且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

OAuth 2.0在php中使用curl

更新时间:2023-02-24 12:33:34

哇,愚蠢的错误,我应该休息一下。

Wow, stupid misstake, I should have a rest.

变量名称不匹配。
我定义:

The variables names doesn't match. I defined:

$client_id = '###.apps.googleusercontent.com';
$client_secret = '###';

但这里我使用了一个不存在的clientID,clientSecret

But here I used an non-existing clientID, clientSecret

curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code' => $code,
'client_id' => $clientID,
'client_secret' => $clientSecret,
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code'
));



修正和运行PHP脚本



Fixed and working PHP script

$client_id = '###.apps.googleusercontent.com';
$redirect_uri = 'http://localhost/phpConnectToDB/csv/refreshFusionTable.php';
$client_secret = '###';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/token");

curl_setopt($ch, CURLOPT_POST, TRUE);

$code = $_REQUEST['code'];

// This option is set to TRUE so that the response
// doesnot get printed and is stored directly in
// the variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code' => $code,
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code'
));

$data = curl_exec($ch);

var_dump($data);

但我不得不说,google提供了一个误导性的错误信息,因为我没有既未定义client_id也未定义client_secret和错误消息:

But I have to say, that google provides a little misleading error message here, because I haven't defined neither client_id nor client_secret and error message was:

{
"error" : "invalid_request",
"error_description" : "Client must specify either client_id or client_assertion, not both"
}