如何解决枪口中的授权承载问题

时间:2019-07-25 13:52:08

标签: php laravel curl guzzle

我正在尝试将此请求发送到服务器,但出现401错误 问题可能出在代码的哪一部分?

“狂饮版本6.3”

try {
        $urlDoPayment = 'https://api.example.com/v1/pay';
        $client = new Client();
        try {
            $response = $client->request('POST', $urlDoPayment, [
                \GuzzleHttp\RequestOptions::JSON => [
                    'form_params' => [
                        'amount' => 100,
                        'returnUrl' => "https://example.com/payment/verify",
                        'payerIdentity' => "",
                        'payerName' => "",
                        'description' => "",
                        'clientRefId' => ""
                    ],
                    'headers' => [
                        'Content-Type' => 'application/json',
                        'Authorization' => 'Bearer MY_TOKEN',
                        'Accept' => 'application/json'
                    ]
                ]
            ]);
            $statusCode = $response->getStatusCode();
            $content = $response->getBody();
            dd($content);
        } catch (GuzzleException $e) {
            dd($e->getMessage());
        }

    } catch (\Exception $exception) {
        dd($exception->getCode());
    }

3 个答案:

答案 0 :(得分:1)

请求中的headers嵌套在请求选项的错误部分。如果令牌有效,那应该至少可以解决401错误。

尝试:

$response = $client->request('POST', $urlDoPayment, [
    \GuzzleHttp\RequestOptions::JSON => [
        'form_params' => [
            'amount' => 100,
            'returnUrl' => "https://example.com/payment/verify",
            'payerIdentity' => "",
            'payerName' => "",
            'description' => "",
            'clientRefId' => ""
        ],
        // headers should not be here
    ], // json post body params end
    'headers' => [
        'Content-Type' => 'application/json',
        'Authorization' => 'Bearer MY_TOKEN',
        'Accept' => 'application/json'
    ]
]);

答案 1 :(得分:0)

使用此代码解决了这个问题

$response = $client->request('POST', $urlDoPayment, [
                'json' => [
                    'amount' => 100,
                    'returnUrl' => "http://example.com/payment/verify",
                    'payerIdentity' => "",
                    'payerName' => "",
                    'description' => "",
                    'clientRefId' => ""
                ],
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer MY_TOKEN',
                    'Accept' => 'application/json'
                ]
            ]);

答案 2 :(得分:0)

我怀疑问题出在未定义的端口或协议上。标题内容对我来说不是问题。我通过更改解决了同样的问题:

115.12.3.44115.12.3.44:80

也测试过

115.12.3.44http://115.12.3.44

google.comhttp://google.com