如何使用 PHP cURL 使用 OAuth2

How to use OAuth2 using PHP cURL

我在 PHP 中写了下面的代码。

<?php
$user = "AB123456";
$api_secret = "ghjfvnvbvnmvmnnbvbnvnbvbnv3345vbnvbnvnbv3bv2bnv";
$redirect_url = "https://ant.aliceblueonline.com/plugin/callback";
$code = "azvUgu6BPhIbe4yAQALBl";
$url = "https://ant.aliceblueonline.com/oauth2/token?client_id=".$user."&client_secret=".$api_secret."&grant_type=authorization_code&code=".$code."&redirect_uri=".$redirect_url."&authorization_response=".$redirect_url;


$session = curl_init();
curl_setopt($session, CURLOPT_URL, $url);
curl_setopt($session, CURLOPT_URL, $url);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($session, CURLOPT_POST, 1);
curl_setopt($session, CURLOPT_POSTFIELDS, array("client_id=" => $user, "client_secret" => $api_secret, "grant_type" => "authorization_code", "code" => $code, "redirect_uri" => $redirect_url));
$headers = array('Content-Type: application/x-www-form-urlencoded','Authorization: Basic '.base64_encode($user.":".$api_secret));
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
$r = curl_exec($session);
curl_close($session);

echo $r;

?>

但它给出了以下错误,而 grant_type 已经存在于请求参数中 -

{"error":"invalid_request","error_description":"The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed","error_hint":"Request parameter \"grant_type\"\" is missing","status_code":400}

请帮忙。

从 CURLOPT_POSTFIELDS 中删除 client_id 和 client_secret,因为它们是使用身份验证 header 发送的。

更新了 cURL CURLOPT_POSTFIELDS 行,如下所述。

curl_setopt($session, CURLOPT_POSTFIELDS, "grant_type=authorization_code&code=".$code."&redirect_uri=".$redirect_url);