0

我有一个看起来像这样的请求;

url = "https://api-3t.sandbox.paypal.com/nvp?METHOD=DoExpressCheckoutPayment&TOKEN=#{transaction.token}
                        &PAYERID=#{transaction.payer_id}&PAYMENTREQUEST_n_PAYMENTACTION=sale"
url = CGI.escape(url)
uri = URI(url)
res = Net::HTTP.get_response(uri)

res.body看起来像这样;TOKEN=EC%2d7UM71457T34680821&TIMESTAMP=2013%2d11%2d03T21%3a19%3a11Z&CORRELATIONID=3b73c396244ff&ACK=Success&VERSION=98&BUILD=8334781

如何从字符串中获取TOKEN和值?ACK不确定params在这里工作吗?有任何想法吗?

4

1 回答 1

2

正文是 URI 编码的,就像 GET(或一些 POST)参数一样。您可以通过执行以下操作手动解压缩它:

require 'uri'

# body takes place of res.body for this example
body = 'TOKEN=EC%2d7UM71457T34680821&TIMESTAMP=2013%2d11%2d03' +    
  'T21%3a19%3a11Z&CORRELATIONID=3b73c396244ff&AC' + 
  'K=Success&VERSION=98&BUILD=8334781'

# First split into key/value pairs, and use inject to start building a hash
results = body.split('&').inject( {} ) do |hash,kv| 

  # Split each key/value pair
  k,v = kv.split('=').map do |uri_encoded_value| 
    # Decode - innermost loop, because it may contain encoded '&' or '='
    URI.decode(uri_encoded_value)
  end

  # Add to hash we are building with inject
  hash[k] = v
  hash
end

=> {"TOKEN"=>"EC-7UM71457T34680821", "TIMESTAMP"=>"2013-11-03T21:19:11Z",
 "CORRELATIONID"=>"3b73c396244ff", "ACK"=>"Success", "VERSION"=>"98", 
 "BUILD"=>"8334781"}

实际上,虽然可以使用类方法URI为您完成几乎所有这些工作(并且比上面更好地处理格式的变化) 。decode_www_form

params = {}
URI.decode_www_form( body ).each do |k,v|
  params[k] = v
end
params
=> {"TOKEN"=>"EC-7UM71457T34680821", "TIMESTAMP"=>"2013-11-03T21:19:11Z",
 "CORRELATIONID"=>"3b73c396244ff", "ACK"=>"Success", "VERSION"=>"98", 
 "BUILD"=>"8334781"}
于 2013-11-03T21:41:59.633 回答