使用PHP curl创建正确的授权请求

时间:2017-01-02 05:35:55

标签: php authorization curl

我以此为例:

 Request example 1:
 POST /v1/token HTTP/1.1
 Content-Type: application/x-www-form-urlencoded
 Accept: application/json
 grant_type=client_credentials&client_id=test&client_secret=abc123

我正在使用PHP / Curl来尝试这个。

我试过了:

$url = "someUrl";
$ch = curl_init();

$username = "someUser";
$password = "somePass";

$post = json_encode(array(('grant_type'=>'client_credentials'));

curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch);

但收到错误:“error”:“unsupported_grant_type”

正确的格式是什么?

1 个答案:

答案 0 :(得分:0)

我不知道为什么但这有效:(如果有人愿意解释那会很好)

改变:

   curl_setopt($ch, CURLOPT_POSTFIELDS,$post);

为:

   curl_setopt($ch, CURLOPT_POSTFIELDS,"grant_type=client_credentials");