Reputation: 1387
I have a request that looks like this ;
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)
and res.body
looks like this; TOKEN=EC%2d7UM71457T34680821&TIMESTAMP=2013%2d11%2d03T21%3a19%3a11Z&CORRELATIONID=3b73c396244ff&ACK=Success&VERSION=98&BUILD=8334781
How can i get the TOKEN
and ACK
values from the string? am not sure params
works here?
Any ideas?
Upvotes: 0
Views: 61
Reputation: 27197
The body is URI-encoded, just like GET (or some POST) params. You could unpack it manually, by doing something like this:
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"}
Actually though URI
can do nearly all of this for you (and deal with variations in the format better than above), with the decode_www_form
class method.
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"}
Upvotes: 2