为什么不使用PHP中的Google_Oauth2Service接收电子邮件地址?

问题描述 投票:1回答:2

有人知道我如何获得用户的电子邮件地址吗?

我的代码在下面:

require_once("sm/google/Google_Client.php");
    require_once("sm/google/contrib/Google_PlusService.php");
    require_once("sm/google/contrib/Google_Oauth2Service.php");   
    include_once("ErrorReporting.php");   



    $objError = new ErrorReporting();   
    $client = new Google_Client();

    $client->setApplicationName("myproject");
    //$client->setHttpClient($httpClient);


    // Visit https://code.google.com/apis/console?api=plus to generate your
    // client id, client secret, and to register your redirect uri.
    $client->setClientId(GOOGLE_CLIENT_ID);
    $client->setClientSecret(GOOGLE_CLIENT_SECRET);
    $client->setRedirectUri($callbackurl);
    $client->setDeveloperKey(GOOGLE_API_KEY);
    $client->setAccessType("online");
    $client->setApprovalPrompt("auto");
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
    $oauth2Service  = new Google_Oauth2Service($client); 
    $plus = new Google_PlusService($client);



$userinfo = $oauth2Service->userinfo;
print_r($userinfo->get());


    if (isset($_GET['code'])) {


        try {
            $client->authenticate();
        } catch(Exception $e) {  
            $objError->reportError("Error! while authenticate through google",$e ,'dev');
        }

        $token = $client->getAccessToken();

        try {
        $userProfile = $plus->people->get("me");
        print_r($userProfile);
            exit();
        }  catch(Exception $e) {  

            //echo $e;
            $objError->reportError("Error! while login through google",$e ,'dev');
        }

        $id = $userProfile['id'];

        return array(
                'user' => $id,
                'network' => 'google',
                'userprofile' => $userProfile,
                'token' => $token,
                'loginUrl' => null,
                'logoutUrl' => null
        );
    } else {
        $authUrl = $client->createAuthUrl();
        return array(
                'user' => 0,
                'network' => 'google',
                'userprofile' => $userProfile,
                'token' => null,
                'loginUrl' => $authUrl,
                'logoutUrl' => null
        );
    }
}

所以不确定如何使用Google oauth2service获取电子邮件地址。当我尝试访问它时,屏幕上没有出现错误,但没有添加电子邮件地址。我查看了contrib / Google_Oauth2Service.php类文件,但没有找到get()方法,因此不确定在这里我缺少什么。

以下两行代码未返回任何电子邮件信息:

$userinfo = $oauth2Service->userinfo;
    print_r($userinfo->get());

我的PHP版本是5.3

我的Google_Oauth2Service.php文件如下所示:

    <?php
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */


  /**
   * The "userinfo" collection of methods.
   * Typical usage is:
   *  <code>
   *   $oauth2Service = new Google_Oauth2Service(...);
   *   $userinfo = $oauth2Service->userinfo;
   *  </code>
   */
  class Google_UserinfoServiceResource extends Google_ServiceResource {

    /**
     * (userinfo.get)
     *
     * @param array $optParams Optional parameters.
     * @return Google_Userinfo
     */
    public function get($optParams = array()) {
      $params = array();
      $params = array_merge($params, $optParams);
      $data = $this->__call('get', array($params));
      if ($this->useObjects()) {
        return new Google_Userinfo($data);
      } else {
        return $data;
      }
    }
  }

  /**
   * The "v2" collection of methods.
   * Typical usage is:
   *  <code>
   *   $oauth2Service = new Google_Oauth2Service(...);
   *   $v2 = $oauth2Service->v2;
   *  </code>
   */
  class Google_UserinfoV2ServiceResource extends Google_ServiceResource {

  }

  /**
   * The "me" collection of methods.
   * Typical usage is:
   *  <code>
   *   $oauth2Service = new Google_Oauth2Service(...);
   *   $me = $oauth2Service->me;
   *  </code>
   */
  class Google_UserinfoV2MeServiceResource extends Google_ServiceResource {

    /**
     * (me.get)
     *
     * @param array $optParams Optional parameters.
     * @return Google_Userinfo
     */
    public function get($optParams = array()) {
      $params = array();
      $params = array_merge($params, $optParams);
      $data = $this->__call('get', array($params));
      if ($this->useObjects()) {
        return new Google_Userinfo($data);
      } else {
        return $data;
      }
    }
  }

/**
 * Service definition for Google_Oauth2 (v2).
 *
 * <p>
 * Lets you access OAuth2 protocol related APIs.
 * </p>
 *
 * <p>
 * For more information about this service, see the
 * <a href="https://developers.google.com/accounts/docs/OAuth2" target="_blank">API Documentation</a>
 * </p>
 *
 * @author Google, Inc.
 */
class Google_Oauth2Service extends Google_Service {
  public $userinfo;
  public $userinfo_v2_me;
  /**
   * Constructs the internal representation of the Oauth2 service.
   *
   * @param Google_Client $client
   */
  public function __construct(Google_Client $client) {
    $this->servicePath = '';
    $this->version = 'v2';
    $this->serviceName = 'oauth2';

    $client->addService($this->serviceName, $this->version);
    $this->userinfo = new Google_UserinfoServiceResource($this, 

    $this->serviceName, 'userinfo', json_decode('{"methods": {"get": {"id": "oauth2.userinfo.get", "path": "oauth2/v2/userinfo", "httpMethod": "GET", "response": {"$ref": "Userinfo"}, "scopes": ["https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"]}}}', true));
        $this->userinfo_v2_me = new Google_UserinfoV2MeServiceResource($this, $this->serviceName, 'me', json_decode('{"methods": {"get": {"id": "oauth2.userinfo.v2.me.get", "path": "userinfo/v2/me", "httpMethod": "GET", "response": {"$ref": "Userinfo"}, "scopes": ["https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"]}}}', true));


  }
}



class Google_Tokeninfo extends Google_Model {
  public $access_type;
  public $audience;
  public $email;
  public $expires_in;
  public $issued_to;
  public $scope;
  public $user_id;
  public $verified_email;
  public function setAccess_type( $access_type) {
    $this->access_type = $access_type;
  }
  public function getAccess_type() {
    return $this->access_type;
  }
  public function setAudience( $audience) {
    $this->audience = $audience;
  }
  public function getAudience() {
    return $this->audience;
  }
  public function setEmail( $email) {
    $this->email = $email;
  }
  public function getEmail() {
    return $this->email;
  }
  public function setExpires_in( $expires_in) {
    $this->expires_in = $expires_in;
  }
  public function getExpires_in() {
    return $this->expires_in;
  }
  public function setIssued_to( $issued_to) {
    $this->issued_to = $issued_to;
  }
  public function getIssued_to() {
    return $this->issued_to;
  }
  public function setScope( $scope) {
    $this->scope = $scope;
  }
  public function getScope() {
    return $this->scope;
  }
  public function setUser_id( $user_id) {
    $this->user_id = $user_id;
  }
  public function getUser_id() {
    return $this->user_id;
  }
  public function setVerified_email( $verified_email) {
    $this->verified_email = $verified_email;
  }
  public function getVerified_email() {
    return $this->verified_email;
  }
}

class Google_Userinfo extends Google_Model {
  public $birthday;
  public $email;
  public $family_name;
  public $gender;
  public $given_name;
  public $hd;
  public $id;
  public $link;
  public $locale;
  public $name;
  public $picture;
  public $timezone;
  public $verified_email;
  public function setBirthday( $birthday) {
    $this->birthday = $birthday;
  }
  public function getBirthday() {
    return $this->birthday;
  }
  public function setEmail( $email) {
    $this->email = $email;
  }
  public function getEmail() {
    return $this->email;
  }
  public function setFamily_name( $family_name) {
    $this->family_name = $family_name;
  }
  public function getFamily_name() {
    return $this->family_name;
  }
  public function setGender( $gender) {
    $this->gender = $gender;
  }
  public function getGender() {
    return $this->gender;
  }
  public function setGiven_name( $given_name) {
    $this->given_name = $given_name;
  }
  public function getGiven_name() {
    return $this->given_name;
  }
  public function setHd( $hd) {
    $this->hd = $hd;
  }
  public function getHd() {
    return $this->hd;
  }
  public function setId( $id) {
    $this->id = $id;
  }
  public function getId() {
    return $this->id;
  }
  public function setLink( $link) {
    $this->link = $link;
  }
  public function getLink() {
    return $this->link;
  }
  public function setLocale( $locale) {
    $this->locale = $locale;
  }
  public function getLocale() {
    return $this->locale;
  }
  public function setName( $name) {
    $this->name = $name;
  }
  public function getName() {
    return $this->name;
  }
  public function setPicture( $picture) {
    $this->picture = $picture;
  }
  public function getPicture() {
    return $this->picture;
  }
  public function setTimezone( $timezone) {
    $this->timezone = $timezone;
  }

 public function getTimezone() {
    return $this->timezone;
  }
  public function setVerified_email( $verified_email) {
    $this->verified_email = $verified_email;
  }
  public function getVerified_email() {
    return $this->verified_email;
  }
}

谢谢

php google-oauth google-login
2个回答
0
投票

我注意到您身上的几件事情可能会给您带来一些悲伤。您的操作顺序似乎相反。您不应该这样称呼:

$userinfo = $oauth2Service->userinfo;
print_r($userinfo->get());

在此之前:

$client->authenticate();

此外,您应该将代码与客户端一起发送。

所以,这样的事情应该会为您提供适当的输出:

if (isset($_GET['code'])) {

$code = $_GET['code'];
    try {
        $client->authenticate($code);
    } catch(Exception $e) {  
        $objError->reportError("Error! while authenticate through google",$e ,'dev');
    }
$userinfo = $oauth2Service->userinfo;
print_r($userinfo->get());
}

尝试一下,然后让我们知道您是否处在正确的轨道上。另外,Google Plus已被弃用,因此,我建议您不再使用这些库。


0
投票

我不知道您如何使用它,但是我已经尝试使用Google v1-masterapiclient分支,并且能够获取用户的电子邮件地址

$client = new Google_Client();

$client->setApplicationName('Login to Test Project');
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setClientSecret(GOOGLE_CLIENT_SECRET);
$client->setRedirectUri(GOOGLE_REDIRECT_URL);
$client->addScope(['email', 'profile']);

if (isset($_GET['code'])) {
    try {
        $token = $client->authenticate($_GET['code']);
        $Oauth = new Google_Service_Oauth2($client);
        $info = $Oauth->userinfo->get();
        print_r($info);
    } catch (Exception $exception) {
        print_r($exception->getMessage());
    }    
} else {
    $authUrl = $client->createAuthUrl();
    header('Location: '.$authUrl);
}

请共享您的composer.json文件,以便我尝试使用您的配置以提供更好的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.