How to identify a Google OAuth2 user?

后端 未结 6 952
误落风尘
误落风尘 2020-11-27 10:48

I used Facebook login to identify users. When a new user comes, I store their userID in my database. Next time they come, I recognized their Facebook ID and I know which use

6条回答
  •  遥遥无期
    2020-11-27 11:19

    I inserted this method into google-api-php-client/src/apiClient.php:

    public function getUserInfo() 
    {
        $req = new apiHttpRequest('https://www.googleapis.com/oauth2/v1/userinfo');
        // XXX error handling missing, this is just a rough draft
        $req = $this->auth->sign($req);
        $resp = $this->io->makeRequest($req)->getResponseBody();
        return json_decode($resp, 1);  
    }
    

    Now I can call:

    $client->setAccessToken($_SESSION[ 'token' ]);
    $userinfo = $client->getUserInfo();
    

    It returns an array like this (plus e-mail if that scope has been requested):

    Array
    (
        [id] => 1045636599999999999
        [name] => Tim Strehle
        [given_name] => Tim
        [family_name] => Strehle
        [locale] => de
    )
    

    The solution originated from this thread: https://groups.google.com/forum/#!msg/google-api-php-client/o1BRsQ9NvUQ/xa532MxegFIJ

提交回复
热议问题