Search code examples
reactjsauthenticationgoogle-developers-console

How to get the user's phone number using react-google-login?


I'm actually using this React library (https://www.npmjs.com/package/react-google-login) to authenticate with Google.
As for the basic profile and email scopes, this works fine. On my client app on Google Cloud Platform, I've correctly enabled the People API (https://developers.google.com/people) and added the correct scope to the scope list, in React (https://www.googleapis.com/auth/user.phonenumbers.read). I've also ensured that my phone number on my Google Profile was made public even if I don't know if that could matter. After doing all this, the consent screen is working fine asking me to allow the app to access my phone number.

However after login, I can only see the data linked to profile and email scopes. In the library I can see that they made some object properties as shown in the code below inside the library itself :

  function handleSigninSuccess(res) {
    /*
      offer renamed response keys to names that match use
    */
    const basicProfile = res.getBasicProfile()
    const authResponse = res.getAuthResponse(true)
    res.googleId = basicProfile.getId()
    res.tokenObj = authResponse
    res.tokenId = authResponse.id_token
    res.accessToken = authResponse.access_token
    res.profileObj = {
      googleId: basicProfile.getId(),
      imageUrl: basicProfile.getImageUrl(),
      email: basicProfile.getEmail(),
      name: basicProfile.getName(),
      givenName: basicProfile.getGivenName(),
      familyName: basicProfile.getFamilyName()
    }
    onSuccess(res)
  }

\

So the problem is that I don't know if I even receive the phone data or if I just can't read it because I don't know how to call the phone data inside the response, in terms of variables name in React. Anyone has an idea ?


Solution

  • The library you're using seems to be using Google Identity which does not include a method to obtain the user's phone number, just their basic profile.

    You can get the user's phone number with the people api but this is not in the scope of this library. You'd have to make your own method to get the the authenticated user profile with the phoneNumbers field. Enabling the people api and requesting authorization are just the first steps.

    https://developers.google.com/people/api/rest/v1/people/get