繁体   English   中英

如何使用 PHP 在谷歌 oauth 2.0 api 中获取刷新令牌

[英]how to get Refresh token in google oauth 2.0 api with PHP

我正在使用生成访问令牌并且它工作成功,因为访问令牌的时间很短,只有 1 小时,我想获取用户的刷新令牌并存储在数据库中,以便我可以随时获取访问令牌需要。

下面是我在两个文件中的代码。

文件 Oauth.php

 <?php 
 require  'vendor/autoload.php';
 // Refer to the PHP quickstart on how to setup the environment:

 $client = new Google_Client();
 $client->setAccessType('offline');
 $client->setAuthConfigFile('client_secret.json');  //file downloaded earlier
 $client->addScope("https://www.googleapis.com/auth/calendar");
 $auth_url = $client->createAuthUrl();
 header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); //redirect user to Google

第二个文件 get_token.php

 <?php 
require  'vendor/autoload.php';
// Refer to the PHP quickstart on how to setup the environment:
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
$client->setAccessToken($access_token);
?>

Response I am getting like this https://www.xxxxxxxxxxxxxxxxxxx.com/google_calendar/get_token.php?code=4/0AY0e-g7ZauFJQPlzm1KsNpeuTF8S_5alcpjX8TA9LN0GVJd2cD0gAAiDPU56j2C9sVKIfg&scope=https://www.googleapis.com/auth/calendar

提前致谢

当你得到谷歌返回的访问令牌时,响应正文中是什么? 刷新令牌应该在基于 OAuth 2.0 标准的初始响应中传回,您需要将此令牌存储在安全的地方。 当您需要刷新访问令牌时,您需要将这个存储的刷新令牌与请求一起传递(可能在查询字符串中作为参数),然后 Google 会将新的访问令牌发回给您。 通读谷歌文档,因为这应该详细解释! 在此处输入图像描述 在此处输入图像描述 正如你在我从上面的谷歌 OAuth 得到的响应中看到的那样,第二张图片是你应该得到的响应,重复你请求访问令牌的过程,看看你是否得到了像我在图片中得到的响应,您会注意到响应正文中的 refresh_token 。

我用以下方法做到了这一点

<?php 
require  '../vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig('client_secret_234rcontent.com.json');
$client->addScope('https://www.googleapis.com/auth/calendar');
$client->setRedirectUri('https://' . $_SERVER['HTTP_HOST'] . 
 '/google_calendar2/oauth2callback.php');
 // offline access will give you both an access and refresh token so that
 // your app can refresh the access token without user interaction.
 $client->setAccessType('offline');
 // Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access, you can omit this.
$client->setPrompt('consent');
$client->setApprovalPrompt("consent");
$client->setIncludeGrantedScopes(true);   // incremental auth
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));

重定向 uri 代码

<?php
require  'vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfigFile('client_secret_2344056t4.apps.googleusercontent.com.json');
$client->setRedirectUri('https://' . $_SERVER['HTTP_HOST'] . 
'/google_calendar2/oauth2callback.php');
$client->addScope('https://www.googleapis.com/auth/calendar');
$credentials=$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
// $refresh_token = $credentials['refresh_token'];
print_r($credentials);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM