簡體   English   中英

通過 PHP 獲取 Google Api:獲取用戶個人資料

[英]Google Api via PHP : Get user profile

我已經通過 Google API 添加了網站登錄(使用 google php api 客戶端),但我不確定我是如何獲取用戶個人資料的。

獲取身份驗證的代碼是:

$client = new Google_Client();
$client->setClientId(ClientIDGoesHere);
$client->setClientSecret(ClientSecretGoesHere);
$client->setScopes(Google_Service_Gmail::GMAIL_READONLY);

$redirectUrl = 'http://AReference.ngrok.io/performGoogleLogin.php';
$client->setRedirectUri($redirectUrl);

$oauth = $client->getOAuth2Service();

我從這個網站嘗試了以下內容,但它說沒有找到 userinfo:

$userProfile = $oauth->userinfo->get();

我收到以下錯誤:注意:未定義的屬性:Google\\Auth\\OAuth2::$userinfo in googleLogin.php on line 23

我追求的是 given_name、family_name、電子郵件、性別、圖片(很高興擁有)

OP 和@user9156598,這是對我有用的解決方案。

$oauth = new Google_Service_Oauth2($googleClient->GetClient());
$userProfile = $oauth->userinfo->get();
$output = "<p>Name: " .  $userProfile['name'] . '</p>';
$output = $output . "<p>Family Name: " .  $userProfile['familyName'] . '</p>';
$output = $output . "<p>Given Name: " .  $userProfile['givenName'] . '</p>';
$output = $output . "<p>Gender: " .  $userProfile['gender'] . '</p>';
$output = $output . "<p>Email Address: " .  $userProfile['email'] . '</p>';
$output = $output . "<p>Verified Email Address: " .  $userProfile['verifiedEmail'] . '</p>';
$output = $output . "<p>Picture: " .  $userProfile['picture'] . '</p>';
print($output);

谷歌客戶端構造函數:

    $this->m_client = new Google_Client();
    $this->m_client->setApplicationName("Local Social Meetups");
    $this->m_client->setClientId(GOOGLE_CLIENT_ID);
    $this->m_client->setClientSecret(GOOGLE_CLIENT_SECRET);

    $this->m_client->setIncludeGrantedScopes(true);
    $this->m_client->setAccessType('offline');
    $this->m_client->setApprovalPrompt("force");
    $this->m_client->setIncludeGrantedScopes(true);

    // Set the scope of information that the application has access to.  In
    // this case it's just the users profile.
    $scopes = array(
        Google_Service_Oauth2::USERINFO_PROFILE,
        Google_Service_Oauth2::USERINFO_EMAIL
    );
    $this->m_client->setScopes($scopes);

    // The redirection Url that is used by Google after authentication.
    $this->m_client->setRedirectUri(GOOGLE_REDIRECT_URL);

    if (isset($_SESSION['googleAccessToken']))
    {
        $this->m_client->setAccessToken($_SESSION['googleAccessToken']);
    }

    $this->m_oauth = $this->m_client->getOAuth2Service();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM