我正在尝试将此请求发送到服务器,但出现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());
}
答案 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.44
到 115.12.3.44:80
也测试过
115.12.3.44
到 http://115.12.3.44
或
google.com
到 http://google.com