Google 登录网站:读取用户的 phone 号码

Google sign-in for websites: read user's phone number

我想通过 Google 在我的网站上登录来获取用户的 phone 号码。在“使用 Google 登录”按钮的 JavaScript 中,我包括范围 'https://www.googleapis.com/auth/user.phonenumbers.read' 以允许读取用户的 phone 号码。也许我需要使用 'https://www.googleapis.com/auth/contacts.readonly' 而不是这个范围。无论如何,如何在 PHP 或 JavaScript 中获取已登录用户的 phone 号码?当用户单击登录按钮时,由于范围 Google 确实会请求共享 phone 号码的权限。在 Google API 控制台 -> 编辑应用程序注册 -> 范围中,我包含了这个 phone 数字范围。另外,我在 Google 项目中启用了 People API。我已经安装

composer require google/apiclient

我从前端收到登录用户的 ID 令牌。我的 PHP 是:

<?php
require_once 'vendor/autoload.php';

$id_token = $_POST['idtoken'];

$client = new Google_Client(['client_id' => '349001386451-bpovja3t7soabdu3cbhnig12fqlr20o0.apps.googleusercontent.com']);
$payload = $client->verifyIdToken($id_token);
if ($payload) {
  $userid = $payload['sub'];
  echo "Userid: $userid";
} else {
  echo "Invalid ID token";
}

(以上代码已从https://developers.google.com/identity/sign-in/web/backend-auth编辑)
我是这个的新手。我有我的客户端 ID、客户端密码和用户的 ID 令牌。我可以在上面的代码中显示 userid,如何显示 phone 号码?


编辑: 我下载了 client_secret.json 并尝试了 另一种方法:

index.php

<?php
require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google\Client();
$client->setAuthConfig('client_secret.json');

$client->setScopes(array('https://www.googleapis.com/auth/user.phonenumbers.read', 'https://www.googleapis.com/auth/contacts.readonly', 'profile'));

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
  $service = new Google_Service_PeopleService( $client );
  $optParams = ['personFields' => 'phoneNumbers'];
  $profile = $service->people->get( 'people/me', $optParams );
  var_export($profile);
  var_export( $profile->getPhoneNumbers() );
} else {
  $redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . '/testing/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

--

oauth2callback.php

<?php
require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google\Client();
$client->setAuthConfigFile('client_secret.json');
$client->setRedirectUri('https://' . $_SERVER['HTTP_HOST'] . '/testing/oauth2callback.php');
$client->addScope(Google_Service_PeopleService::USER_PHONENUMBERS_READ);

if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . '/testing/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

但是当我 运行 index.php 时出现错误:

"error": { "code": 403, "message": "The caller does not have permission to request "people/me". Request requires one of the following scopes: [profile]."

但我确实在 index.php

中包含了 profile 范围

我使用此处给出的新的第三种方法成功获得 phone 号码:
https://developers.google.com/people/api/rest/v1/people/get?apix=true&apix_params=%7B%22resourceName%22%3A%22people%2Fme%22%2C%22personFields%22%3A%22phoneNumbers%22%7D

我复制了这个 link 中给出的 JavaScript 代码,删除了除一个之外的所有范围,替换了 YOUR_API_KEYYOUR_CLIENT_ID,运行 它在我的服务器,在 Firefox 中,它工作正常!

<script src="https://apis.google.com/js/api.js"></script>
<script>
  /**
   * Sample JavaScript code for people.people.get
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/guides/code_samples#javascript
   */

  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/user.phonenumbers.read"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("YOUR_API_KEY");
    return gapi.client.load("https://people.googleapis.com/$discovery/rest?version=v1")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.people.people.get({
      "resourceName": "people/me",
      "personFields": "phoneNumbers"
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "YOUR_CLIENT_ID"});
  });
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>

但它只读取 Google 帐户的“关于我”中添加的 phone 个数字:https://myaccount.google.com/profile
而不是用于密码重置的 phone 个 Google 帐户。我其实很想要这个号码不知道可不可以

用于密码重置的phone号码will not be possible访问:

It has been determined that we will not return the account recovery phone number. The account recovery phone number is only intended for specific usage like recovery the account when locked out. In the interest of protecting user privacy this will not be returned in the 3rd party API.