我正在尝试使用PayPal API。以下是Curl用法的参考:https://developer.paypal.com/docs/api/orders/v2/
在谷歌上搜索后,我发现了一个显示类似错误的链接:但没有给出修复提示。https://www.paypal-community.com/t5/REST-APIs/Request-is-not-well-formed-syntactically-incorrect-or-violates/td-p/2090480
我在PHP和Laravel中有以下代码
$client = new GuzzleHttpClient();
$response = $client->request('POST', $uri, [
'headers' => [
'Accept' => 'application/json',
'Accept-Language' => 'en_US',
'Content-Type' => 'application/json',
'Authorization' => "Bearer " . $this->token
],
'form_params' => [
"intent" => "CAPTURE",
"purchase_units" => [
"amount" => [
"currency_code" => "USD",
"value" => "100.00"
]
]
]
]
);
当我运行代码时,我得到以下错误
GuzzleHttp\Exception\ClientException客户端错误:
POST https://api.sandbox.paypal.com/v2/checkout/orders
导致400 Bad Request
响应:{"名称":"INVALID_REQUEST","消息":"请求为格式不正确、语法不正确或违反架构&"debug_id(截断…(
更新1-根据答案修改了代码,但仍然存在相同的错误消息
$response = $client->request('POST', $uri, [
'headers' => [
'Accept' => 'application/json',
'Accept-Language' => 'en_US',
'Content-Type' => 'application/json',
'Authorization' => "Bearer " . $this->token
],
'form_params' => [
"intent" => "CAPTURE",
"purchase_units" => [
[
"amount" => [
"currency_code" => "USD",
"value" => "100.00"
]
]
]
]
]
);
下面的代码适用于我。
$client = new GuzzleHttpClient();
$response = $client->request('POST', $uri, [
'json' => [
"intent" => "CAPTURE",
"purchase_units" => [
[
"amount" => [
"currency_code" => "USD",
"value" => "100.00"
]
]
]
],
'headers' => [
'Accept' => 'application/json',
'Accept-Language' => 'en_US',
'Content-Type' => 'application/json',
'Authorization' => "Bearer " . $this->token
]
]
);
该文件称:
purchase_units:array(包含purchase_unit对象(一组采购单位。每个购买单位在客户和商家之间建立一个合同。每个购买单元代表客户打算从商家购买的全部或部分订单。
您现在的purchase_units是purchase_unit,而不是purchase_nit的数组,请尝试将form_params更改为
[
"intent" => "CAPTURE",
"purchase_units" => [
[
"amount" => [
"currency_code" => "USD",
"value" => "100.00"
]
]
]
]
'form_params' => [
PayPal REST API不使用表单参数。
您需要发送一个"json"数据对象。请参阅GuzzleHttp客户端文档。