首页 > 解决方案 > 将 Rest API 调用从 PHP 转换为 RUBY

问题描述

我正在尝试将帖子连接转换为 walmart api,从 php 转换为 ruby​​,这是 php 版本

$client_id = $data['client_id'];
        $client_secret = $data['client_secret'];
        $url = "https://marketplace.walmartapis.com/v3/token";
        $uniqid = uniqid();
        $authorization_key = base64_encode($client_id.":".$client_secret);
        $code = "";

        $ch = curl_init();
        $options = array(

                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 60,
                CURLOPT_HEADER => false,
                CURLOPT_POST =>1,
                CURLOPT_POSTFIELDS => "grant_type=client_credentials",
                CURLOPT_HTTPHEADER => 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);

这就是我到目前为止所拥有的:

url = "https://marketplace.walmartapis.com/v3/token/"
uniqid = "1234567890a1b"

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"
request["WM_SVC.VERSION"] = "1.0.0"


req_options = {
  use_ssl: uri.scheme == "https",
}

response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
  http.request(request)
end

puts "error " + response.code
puts response.body

现在,我收到 400 错误,所以我发送的某些数据不正确或丢失......比较两者,我没有在 ruby​​ 上为 POST 请求设置 postfields 选项,不确定是否还需要其余部分。 .. 有任何想法吗?

标签: phprubyrest

解决方案


尝试添加这一行:

request.body = 'grant_type=client_credentials'

推荐阅读