簡體   English   中英

在 google-api-php-client 庫中創建令牌

[英]Create a token in the google-api-php-client library

我目前在google-api-php-client庫上遇到問題。 當我使用fetchAccessTokenWithAuthCode()方法時,出現嚴重錯誤。 它將來自$httpHandler這應該是一個回調 function $httpHandler = HttpHandlerFactory::build($this->getHttpClient()); 這實際上是一個 object... 以前有人遇到過這個問題嗎? 提前致謝。

    $gClient = new Google_Client();
    $GLOBALS['gClient'] = $gClient; 
    $gClient->setClientId( '' ); //omitted for privacy
    $gClient->setClientSecret( '' ); //omitted for privacy
    $gClient->setApplicationName( 'Mon application' );
    $gClient->setRedirectUri( 'http://localhost/vevweb/wp-admin/admin-ajax.php?action=vm_login_google' );
    $gClient->addScope( 'https://www.googleapis.com/auth/userinfo.email' );

    if( isset( $_GET['code'] ) ) {
                $gClient->authenticate($_GET['code']);//This code return critical error
    }

為什么要使用fetchAccessTokenWithAuthCode為什么不直接使用$client->authenticate($_GET['code']); ? 我認為最好找出標准授權方法出現錯誤的原因,然后切換到其他方法。

oauth2callback.php

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';

// Start a session to persist credentials.
session_start();

// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
    $client = buildClient();
    $auth_url = $client->createAuthUrl();
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
    $client = buildClient();
    $client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
    // Add access token and refresh token to seession.
    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $client->getRefreshToken();    
    //Redirect back to main script
    $redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());    
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

我會檢查你是如何建立你的客戶的

function buildClient(){
    
    $client = new Google_Client();
    $client->setAccessType("offline");        // offline access.  Will result in a refresh token
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $client->setAuthConfig(__DIR__ . '/client_secrets.json');
    $client->addScope([YOUR SCOPES HERE]);
    $client->setRedirectUri(getRedirectUri());  
    return $client;
}

Oauth2Authentication.php中提取的代碼

暫無
暫無

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

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