繁体   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