这是我的代码
$data = array(
'grant_type' => 'Password',
'username' => 'username',
'password' => 'pwd',
'DeviceId' => ''
);
$url = "http://test/sync/oauth/token";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
print_r($response);`
我认为是正确的,但是服务器还给我这个错误
错误:对网址http://test/sync/oauth/token的调用失败并显示状态 400,回复{"错误":" unsupported_grant_type"},curl_error, curl_errno 0
错误在哪里?
答案 0 :(得分:1)
好吧,在浪费了我几个小时并进行了大量测试之后 我想出了一个解决方案,希望对您的案件有帮助
Tip : Dont Concatenate the Post Arguments into a string and add it in Array just use it sepratlely so with that you dont even need to add the Custom_HEADERS => Content-Type : application/x-www-form-urlencoded
有人说您需要将application / x-www-form-urlencoded添加为Content-Type,然后它才能工作,但我的解决方案可以正常工作 继承人的工作代码
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_URL, 'YOUR_TOKEN_URL_HERE');
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array(
'Username' => 'YOUR_USERNAME',
'Password' => 'YOUR_PASSWORD',
'grant_type' => 'password'
)));
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
echo $result;
此代码也非常适合Laravel Bearer令牌和其他代码
希望您的情况对我的回答有所帮助 快乐编码:)!
答案 1 :(得分:0)
OAuthAuthorizationServerHandler 的默认实现只接受表单编码(即application / x-www-form-urlencoded)而不接受JSON编码(application / JSON)
您的请求的ContentType应为 application / x-www-form-urlencoded 并将正文中的数据传递为: grant_type =密码&安培;用户名=用户名和安培;密码=密码 即不是JSON格式。
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
答案 2 :(得分:0)
对于那些需要它的人...... 这是解决方案:
$data = array(
'grant_type' => 'password',
'username' => 'username',
'password' => 'password',
'DeviceId' => ''
);
$url_token = "http://test/sync/oauth/token";
try {
$oauth = new OAuth('username','password');
$signature = $oauth->fetch ($url_token,$data,'POST');
$response_info = $oauth->getLastResponseInfo();
header("Content-Type: {$response_info["content_type"]}");
$token = $oauth->getLastResponse();
$token = json_decode($token, true);
$authorization_token = $token['access_token'];
} catch(OAuthException $E) {
echo "Response: ". $E->lastResponse . "\n";
}
return $authorization_token;