[英]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
提前致谢
我用以下方法做到了这一点
<?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.