【问题标题】:how to get user email after access token generate in PHP在 PHP 中生成访问令牌后如何获取用户电子邮件
【发布时间】:2021-03-20 17:30:43
【问题描述】:

我已经使用 PHP Oauth 2.0 使用以下代码成功生成了访问令牌和刷新令牌,我想将刷新令牌和用户电子邮件存储在我的数据库中。我有刷新令牌,但不确定如何获取用户电子邮件。

<?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);

回复 enter image description here

【问题讨论】:

    标签: php oauth-2.0 google-oauth


    【解决方案1】:

    我不使用 Google APK,但您可以使用普通的 API 请求:

    GET:https://www.googleapis.com/oauth2/v3/userinfo?access_token={access_token}

    回复:

    {
      "sub": "116289810291163096502",
      "name": "John Smith",
      "given_name": "John",
      "family_name": "Smith",
      "picture": "https://lh3.googleusercontent.com/a-/AOh10GhaIqIxRM0PbSwNMA7hFltGP7P1CzvUbCtcpyDHqg=s96-c",
      "email": "john.smith@example.com",
      "email_verified": true,
      "locale": "en",
      "hd": "example.com"
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-22
      • 2022-01-19
      • 2013-02-12
      • 2016-09-18
      • 2021-05-14
      • 2020-10-10
      • 2018-07-14
      • 2018-09-05
      • 2021-01-05
      相关资源
      最近更新 更多