5

我需要获取 Google 验证令牌才能与 Google API 一起使用,但我的代码不起作用。

$client_id = '495225261106.apps.googleusercontent.com';
$client_secret = urlencode('MY_SECRET_CDE');
$redirect_uri = urlencode('http://MYPAGE.net/test.php');
//$grant_type = urlencode('authorization_code'); //it does not work either.
$grant_type = 'authorization_code';

$post_string = "code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp6&client_id={$client_id}&client_secret={$client_secret}&redirect_uri={$redirect_uri}&grant_type={$grant_type}";

//echo_key_value('post_string',$post_string);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);   // Execute the HTTP command
$errmsg = curl_error($ch); 

if($errmsg) echo $errmsg;

输出是:

{"error":"invalid_grant"}
4

3 回答 3

1

在使用 postfields 之前,您不必输入“ curl_setopt($ch, CURLOPT_POST, true); ”吗?我的工作正常,除此之外,我没有在我的秘密上使用 urlencode,它是一样的

于 2011-07-07T15:49:33.950 回答
1

您可能会发现通过官方客户端库之一使用 Google API 更容易,尤其是 OAuth 的东西。

这是 PHP 的链接:http ://code.google.com/p/google-api-php-client/

以及带有库的 OAuth 2.0 文档的链接(带有一些很好的示例代码):http ://code.google.com/p/google-api-php-client/wiki/OAuth2

于 2011-09-02T19:21:05.807 回答
0

设置说明

  • 转到 Google Developers Console
    https://console.developers.google.com/project选择您的项目或创建一个新项目(然后选择它)
  • 为您的项目启用 API 在左侧边栏中,展开 APIs & auth > APIs 搜索“驱动器”单击“驱动器 API”单击蓝色的“启用 API”按钮
  • 为您的项目创建服务帐户 在左侧边栏中,展开 APIs & auth > Credentials 单击蓝色的“添加凭据”按钮
  • 选择“服务帐户”选项
  • 选择“提供新的私钥”复选框 选择“JSON”密钥类型选项
  • 单击蓝色的“创建”按钮,您的 JSON 密钥文件将生成并下载到您的机器(它是唯一的副本!)
  • 打开 json 文件并将你的私钥保存到一个名为 rsa 的文件中

记下您的服务帐户的电子邮件地址(也可在 JSON 密钥文件中找到) 使用上述电子邮件与您的服务帐户共享一个(或多个文档)

基于来自(一个很棒的文档)的信息 https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority

有关可能的 API 范围集列表 https://developers.google.com/identity/protocols/googlescopes#sheetsv4

对于纯粹基于 bash 的解决方案

#!/bin/bash

client_email='your client email'
scope='https://www.googleapis.com/auth/spreadsheets.readonly'

jwt1=`echo -n '{"alg":"RS256","typ":"JWT"}' | openssl base64 -e`

exp=$(($(date +%s)+3600))
iat=$(date +%s)

jwt2=`echo -n '{\
"iss":"'"$client_email"'",\
"scope":"'"$scope"'",\
"aud":"https://accounts.google.com/o/oauth2/token",\
"exp":'$exp',\
"iat":'$iat'}' | openssl base64 -e`

jwt3=`echo -n "$jwt1.$jwt2" | tr -d '\n' | tr -d '=' | tr '/+' '_-'`

jwt4=`echo -n "$jwt3" | openssl sha -sha256 -sign rsa | openssl base64 -e`

jwt5=`echo -n "$jwt4" | tr -d '\n' | tr -d '=' | tr '/+' '_-'`

echo $jwt3
echo $jwt5

curl -H -vvv "Content-type: application/x-www-form-urlencoded" -X POST "https://accounts.google.com/o/oauth2/token" -d \
"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=$jwt3.$jwt5"

对于基于 javascript nodejs 的解决方案,请参见

https://gist.github.com/cloverbox/5ce51a1d8889da9045c5b128a3a2502f

于 2018-09-07T05:46:53.510 回答