简体   繁体   English

如何使用 OAuth2 使用 PHP cURL

[英]How to use OAuth2 using PHP cURL

I've written below code in PHP.我在 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;

?>

But it is giving below error whereas grant_type is already there in request parameter -但它给出了以下错误,而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}

Please help.请帮忙。

Remove client_id and client_secret from CURLOPT_POSTFIELDS as they are sent using Authentication header.从 CURLOPT_POSTFIELDS 中删除 client_id 和 client_secret,因为它们是使用身份验证 header 发送的。

Updated cURL CURLOPT_POSTFIELDS line as mentioned below.更新了 cURL CURLOPT_POSTFIELDS 行,如下所述。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM