简体   繁体   中英

How to use OAuth2 using PHP cURL

I've written below code in 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 -

{"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.

Updated cURL CURLOPT_POSTFIELDS line as mentioned below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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