我正在测试Google OAuth 2.0。我有我的客户ID,客户密码和验证码。现在,我想获取访问权限并刷新令牌。
但是,我可以从PHP做到这一点。但是在使用Javascript时出现无效授予错误。
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
</head>
<body>
<a href='#' onClick='getaccessToken();'> Get your access Token </a>
<pre id="response"> </pre>
<script>
function getaccessToken() {
$.ajax({
type: 'POST',url: "https://accounts.google.com/o/oauth2/token",contentType: 'application/x-www-form-urlencoded',dataType: 'json',data: {
client_id: 'MY CLIENT ID',client_secret: 'MY SECRET',code: 'MY AUTH CODE',redirect_uri: 'http://localhost:8888/google-api.html',grant_type: 'authorization_code'
},success: function (data) {
$('#response').html(data);
},error: function (e) {
$('#response').html(e.responseText);
}
});
}
</script>
</body>
</html>
基本上,我正在尝试将以下PHP Curl POST请求转换为Ajax
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"https://accounts.google.com/o/oauth2/token");
curl_setopt($ch,CURLOPT_POST,TRUE);
curl_setopt($ch,CURLOPT_HTTPHEADER,[ 'Content-Type: application/x-www-form-urlencoded']);
curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query([
'code' => $code,'client_id' => $client_id,'client_secret' => $client_secret,'redirect_uri' => $redirect_uri,'grant_type' => 'authorization_code',]));
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($ch);
curl_close ($ch);
注意:堆栈溢出中类似类型的问题有很多视图,但仍未得到解答。天才的开发人员请提供您的意见。我也被困了三天。