用户在我的安卓应用程序中授权。我正在将用户的令牌和其他信息发送到我的服务器。在此服务器上,我想为用户实现一些逻辑。
我想要的正是这个流程。
我按照此链接中的步骤快速入门.php在服务器上获取用户的日历。
但是我收到以下错误:
谷歌 OAuth 异常",消息"无法 JSON 解码令牌"
出于这个原因,我尝试了这个解决方案。但我犯了同样的错误。因此,作为第三个选项,我自己创建了 json 格式,就像在这个解决方案中一样,如下所示。
$access_token = '{
"access_token":'.$access_token.',
"token_type":"Bearer",
"expires_in":3600,
"id_token":'.$id_token.',
"refresh_token":" ",
"created":'. time() .'
}';
如您所见,我不知道如何交换刷新令牌。我搜索了如何获取刷新令牌并看到了这个问题。并在我的代码中实现了这个解决方案,但没有任何变化。
编辑4:我试图根据android应用程序的这个答案获取访问令牌并将其发送到应用程序服务器。我像以前一样使用代码:
GoogleSignInAccount acct = result.getSignInAccount();
code = acct.getServerAuthCode();//sending this code to AsyncTask to get access token
我获取访问令牌的函数:
private void getAccessToken()throws GoogleAuthException, IOException{
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
List<String> scopes = new LinkedList<String>();
scopes.add("https://www.googleapis.com/auth/calendar");
scopes.add("https://www.googleapis.com/auth/calendar.readonly");
scopes.add("https://www.googleapis.com/auth/urlshortener");
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, jsonFactory, client_id, client_secret, scopes).build();
try{
GoogleTokenResponse res = flow.newTokenRequest(code).execute();
accessToken = res.getAccessToken();
}catch(IOException e){
}
在 php 服务器端,我更改了用户示例.php文件,如下所示,因为我现在有访问令牌:
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setAccessType("offline");
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/urlshortener");
$service = new Google_Service_Urlshortener($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
$client->setAccessToken('{"access_token":"'. $access_token .'","token_type":"Bearer","expires_in":3600,"created":'. time() .'}');
if ($client->getAccessToken() && isset($_GET['url'])) {
$url = new Google_Service_Urlshortener_Url();
$url->longUrl = $_GET['url'];
$short = $service->url->insert($url);
$_SESSION['access_token'] = $client->getAccessToken();
但是现在我得到以下错误:
致命错误:未捕获的异常"Google_Service_Exception",在第 110 行的 C:''wamp''www''google-php''src''Google''Http''REST.php 中显示消息"调用 POST https://www.googleapis.com/urlshortener/v1/url:(403) 权限不足"
正如我在OP中提到的,在开始使用GoogleAuthorizationCodeFlow获取访问令牌后,我遇到了权限不足的错误。然后我尝试将日历范围添加到GoogleApiClient.Builder(this)
但是我收到错误,例如如果我添加Auth.GOOGLE_SIGN_IN_API
则无法添加范围,因为我已将Auth.GOOGLE_SIGN_IN_API
添加到GoogleApiClient.Builder。所以这次我尝试将范围添加到GoogleSignInOptions.Builder,它现在可以工作了。我能够同时获得刷新令牌和访问令牌。下面的代码解决了我的问题:
GoogleSignInOptions gso = state.getGso();
if(gso == null){
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(new Scope("https://www.googleapis.com/auth/calendar"))
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.requestServerAuthCode(getString(R.string.server_client_id), false)
.requestProfile()
.build();
}