Reputation: 128
i was away from Ruby for a while...now, i need to recreate a php api connection (curl) on ruby, to add it to my rails app, but all im getting is a Net::HTTPMovedPermanently message
here is the original php version:
$url = "https://marketplace.walmartapis.com/v3/token";
$uniqid = uniqid();
$authorization_key = base64_encode($client_id.":".$client_secret);
$code = "";
$ch = curl_init();
$options = array(
"WM_SVC.NAME: Walmart Marketplace",
"WM_QOS.CORRELATION_ID: $uniqid",
"Authorization: Basic $authorization_key",
"Accept: application/json",
"Content-Type: application/x-www-form-urlencoded",
),
);
curl_setopt_array($ch,$options);
$response = curl_exec($ch);
$code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
if($code == 201 || $code == 200)
{
$token = json_decode($response,true);
return $token['access_token'];
}
}
And this is my Ruby version so far:
require 'net/http'
require 'base64'
client_id = "id"
client_secret = "secret"
url = "https://marketplace.walmartapis.com/v3/token/"
uniqid = "1234567890abc"
uri = URI(url)
request = Net::HTTP::Post.new(uri)
request['WM_SVC.NAME'] = 'Walmart Marketplace'
request['WM_QOS.CORRELATION_ID'] = uniqid
request.basic_auth(client_id, client_secret)
request['Accept'] = 'application/json'
request['Content-Type'] = 'application/x-www-form-urlencoded'
http = Net::HTTP.new(uri.host)
response = http.request(request)
puts response
What im missing?
Update...
i've changed some things based on curl-to-ruby web, and is at follows...now im getting a 400 error
require 'net/http'
require 'uri'
client_id = "foo"
client_secret = "bar"
url = "https://marketplace.walmartapis.com/v3/token"
uniqid = "1234567890abc"
uri = URI.parse(url)
request = Net::HTTP::Post.new(uri)
request["WM_SVC.NAME"] = "Walmart Marketplace"
request["WM_QOS.CORRELATION_ID"] = uniqid
request.basic_auth(client_id, client_secret)
request["Accept"] = "application/json"
request.content_type = "application/x-www-form-urlencoded"
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, req_options) do |http|
http.request(request)
end
puts response.code
puts response.body
i created a new question to clear out whats working so far, and the missing fields comparing to php
Upvotes: 1
Views: 92
Reputation: 774
It looks like the resource you are trying to access has been moved. The HTTPMovedPermanently reponse is a form of HTTPRedirection. Your code should make another request to the new location.
This is the example directly from the Net::HTTP documentation:
def fetch(uri_str, limit = 10)
# You should choose a better exception.
raise ArgumentError, 'too many HTTP redirects' if limit == 0
response = Net::HTTP.get_response(URI(uri_str))
case response
when Net::HTTPSuccess then
response
when Net::HTTPRedirection then
location = response['location']
warn "redirected to #{location}"
fetch(location, limit - 1)
else
response.value
end
end
Upvotes: 2