与 PayPal 连接:获取状态 4​​00(错误请求)

Connect With PayPal : Get status 400 (Bad Request)

在根据访问代码获取访问令牌期间,我面临来自 PayPal 的 400 错误请求响应。我通过以下参考 link https://developer.paypal.com/docs/connect-with-paypal/integrate/#1-create-the-app

我完全遵循了 5 个步骤,但在第 1 步遇到了问题。 6. 请参阅下面的代码:

请求部分:

$curl = curl_init();

$base_token = "{client_id:secret}";

$data = array(
    CURLOPT_URL => "https://api.sandbox.paypal.com/v1/oauth2/token",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => array(
        'grant_type' => 'authorization_code',
        'code' => '{authorization_code}'
    ),
    CURLOPT_HTTPHEADER => array(
        "Authorization: Basic ".$base_token,
    ),
);
curl_setopt_array($curl,$data );
$response = curl_exec($curl);
curl_close($curl);

响应部分:

stdClass Object (
    [name] => Bad Request
    [debug_id] => 5837077aa8787
    [message] => java.lang.IllegalArgumentException
    [details] => Array
        (
        )
)

将数组传递给 CURLOPT_POSTFIELDS 会将内容类型设置为 multipart/form-data。这是错误的。

您需要将查询字符串传递给 CURLOPT_POSTFIELDS。

CURLOPT_POSTFIELDS => http_build_query(array(
        'grant_type' => 'authorization_code',
        'code' => '{authorization_code}'
    )),

解决问题见我下面的代码:

$base_token = '{client_id:secret}';

$curl = curl_init();

$data = array(
    CURLOPT_URL => "https://api.sandbox.paypal.com/v1/oauth2/token",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_POSTFIELDS => http_build_query(array(
        'grant_type'=>'authorization_code',
        'code'=> $request->code,
    )),
    CURLOPT_HTTPHEADER => array(
        "Content-Type: application/x-www-form-urlencoded",
    ),
    CURLOPT_USERPWD => $base_token
);

curl_setopt_array($curl, $data);

$response = curl_exec($curl);
curl_close($curl);