【问题标题】:How to re-write this cURL request in Guzzle 6?如何在 Guzzle 6 中重写这个 cURL 请求?
【发布时间】:2019-10-24 06:38:45
【问题描述】:

示例代码(由 Channel Advisor 提供):

https://developer.channeladvisor.com/authorization/updating-access-token/php-updating-access-token

<?php
$endpoint = "https://api.channeladvisor.com/oauth2/token";
$refresh_token="{{REFRESH_TOKEN}}";
$application_id= "{{APPLICATION_ID}}";
$shared_secret="{{SHARED_SECRET}}";
$url = $endpoint;
$client_id = base64_encode("$application_id:$shared_secret");
$body = "grant_type=refresh_token&refresh_token=$refresh_token";
$length = strlen($body);
$headers = array(
    "Authorization: Basic $client_id",
    "Content-Type: text/plain",
    "Cache-Control: no-cache",
    "Content-Length: $length"
);
echo "URL:".$url."\n";
echo "Body:$body\n";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
print_r($httpcode);
echo"\n";
$json = json_decode($result, true);
var_dump($json);
?>

尝试重写为 Guzzle HTTP 请求:

我的问题是我是否正确设置了基本身份验证?

    $accessToken = {{ACCESS_TOKEN}};
    $refresh_token = {{ACCESS_TOKEN}};
    $application_id = {{APPLICATION_ID}};
    $shared_secret = {{SHARED_SECRET}};
    $base_uri = "https://api.channeladvisor.com/oauth2/token";
    $client_id = 'Basic ' . base64_encode("$application_id:$shared_secret");

          $client = new Client(
            ['headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
                'Authorization' => $client_id
            ]
        ]
    );

    $result = $client->request('POST', $base_uri, [
        'query' => [
            'grant_type' => 'refresh_token',
            'refresh_token' => $refresh_token
        ],
    ]);

    $body = $response->getBody();
    // Implicitly cast the body to a string and echo it
    echo $body;

【问题讨论】:

  • 是的,你是对的。你的问题基本上是什么?

标签: php laravel curl


【解决方案1】:

您正在发送POST 请求,那么我猜您应该发送 FORM 数据,而不是 QUERY 数据。

$response = $client->request('POST', $base_uri, [
    'form_params' => [
        'grant_type' => 'refresh_token',
        'refresh_token' => $refresh_token
    ],
]);

【讨论】:

  • 谢谢这个答案是正确的。我没有正确设置变量,所以其中一些没有通过。菜鸟失误。
猜你喜欢
  • 2018-10-22
  • 2015-10-30
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2017-01-13
  • 2015-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多