Google Api,如何将access_token传递给API调用

时间:2018-05-14 06:16:10

标签: php google-api google-oauth google-analytics-api google-api-php-client

我正在尝试使用Google分析API。我在开发者控制台中创建了一个帐户,我使用OAuth2授予​​对用户数据的访问权限。所以我有我的refresh_token。但现在,我想在GA中获取我可以访问的帐户的所有profilesID。我按照Google的官方教程进行操作,我收到了此错误:

{
"error": {
    "errors": [{
        "domain": "global",
        "reason": "required",
        "message": "Login Required",
        "locationType": "header",
        "location": "Authorization"
    }],
    "code": 401,
    "message": "Login Required"
}

}

我看到我错过了凭证,但我不知道如何在此次通话中通过access_token。这是我的代码:

$client = new Google_Client();
    $client->setApplicationName("APP_NAME");
    $client->setAuthConfig(GA_KEYS_JSON);

    $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
    $analytics = new Google_Service_Analytics($client);

    // Get the list of accounts for the authorized user.
    $accounts = $analytics->management_accounts->listManagementAccounts();
    $items = $accounts->getItems();

    var_dump($items);die();

有什么想法吗?

4 个答案:

答案 0 :(得分:0)

请看这里:https://developers.google.com/api-client-library/php/auth/web-app#exchange-authorization-code

function jsonToCsvConvertor(JSONData, reportTitle) {
    //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
    var arrData = typeof JSONData !== 'object' ? JSON.parse(JSONData) : JSONData,                    
        csv = '',
        row,
        key1,
        i,
        subGridData;

    //Set Report title in first row or line                    
    csv += reportTitle + '\r\n\n';

    row = '';                        
    for (key1 in arrData[0]) {                         
        if(key1 !== 'subGridOptions' && key1 !== '$$hashKey'){
            row += key1 + ',';
        }
    }                                  
    csv += row + '\r\n';

    for (i = 0; i < arrData.length; i++) {
        row = '';
        subGridData = '';                                        
        for (key1 in arrData[i]) {
            if(key1 !== 'subGridOptions' && key1 !== '$$hashKey'){
                row += '"' + arrData[i][key1] + '",';
            }
            else if(key1 === 'subGridOptions'){
                //csv += row + '\r\n';
                subGridData = writeSubGridData(arrData[i][key1].data);                                
            }                     
        }
        csv += row + '\r\n';
        csv = subGridData ? csv + subGridData + '\r\n' : csv;
    }
    if (csv === '') {
        console.log('Invalid data');
    }
    return csv;     
}
//Generates subgrid Data to exportable form
function writeSubGridData(subgridData){
    var j,
        key2,             
        csv = '',
        row = '';
    for (key2 in subgridData[0]){
        if(key2 !== '$$hashKey'){
        row += key2 + ',';  
        }                                
    }
    csv = row + '\r\n';
    for (j=0; j < subgridData.length ; j++){
        row = '';                                    
        for(key2 in subgridData[j]){
            if(key2 !== '$$hashKey'){                                
                row += '"' + subgridData[j][key2]+ '",';
            }
        }
        csv += row + '\r\n';
    }
    return csv;
}

jsonToCsvConvertor(exportData, 'New-Report');

并刷新访问令牌:https://developers.google.com/api-client-library/php/auth/web-app#offline

答案 1 :(得分:0)

好的,我找到了一个解决方案,但可能还有另一种提高效率并使用Google_Client类的方式。

public function generateToken($refresh_token)
{
    $data = [
        "client_id" => "ClientID",
        "client_secret" => "SecretID",
        "refresh_token"=> "RefreshToken",
        "grant_type"=> "refresh_token"
    ];

    $url = "https://www.googleapis.com/oauth2/v4/token";
    $res = post_request($url, $data);
    $res = json_decode($res, true); 
    return $res["access_token"];
}

答案 2 :(得分:0)

  

$客户端 - &GT; fetchAccessTokenWithRefreshToken($客户端 - &GT; getRefreshToken());

当您可以提供刷新令牌时,

可用于获取新的访问令牌。

以下是从我的示例项目中删除的一些代码。 Google analytics v3

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));
}

oauth2authncation.php

require_once __DIR__ . '/vendor/autoload.php';
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    $client = getOauth2Client();
    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }
return $client;
}
/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Scopes will need to be changed depending upon the API's being accessed.
 * Example:  array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
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;
}
/**
 * Builds the redirect uri.
 * Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
 * Hostname and current server path are needed to redirect to oauth2callback.php
 * @return A redirect uri.
 */
function getRedirectUri(){
    //Building Redirect URI
    $url = $_SERVER['REQUEST_URI'];                    //returns the current URL
    if(strrpos($url, '?') > 0)
        $url = substr($url, 0, strrpos($url, '?') );  // Removing any parameters.
    $folder = substr($url, 0, strrpos($url, '/') );   // Removeing current file.
    return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}
/**
 * Authenticating to Google using Oauth2
 * Documentation:  https://developers.google.com/identity/protocols/OAuth2
 * Returns a Google client with refresh token and access tokens set. 
 *  If not authencated then we will redirect to request authencation.
 * @return A google client object.
 */
function getOauth2Client() {
    try {

        $client = buildClient();

        // Set the refresh token on the client. 
        if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
            $client->refreshToken($_SESSION['refresh_token']);
        }

        // If the user has already authorized this app then get an access token
        // else redirect to ask the user to authorize access to Google Analytics.
        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

            // Set the access token on the client.
            $client->setAccessToken($_SESSION['access_token']);                 

            // Refresh the access token if it's expired.
            if ($client->isAccessTokenExpired()) {              
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                $client->setAccessToken($client->getAccessToken()); 
                $_SESSION['access_token'] = $client->getAccessToken();              
            }           
            return $client; 
        } else {
            // We do not have access request access.
            header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
        }
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

答案 3 :(得分:0)

我使用Google_Client()类找到了更好的解决方案:

$client->refreshToken($theRefreshTokenYouHadStored);

所以不需要执行POST请求来获取新的令牌,所有这些都是隐式地使用了refreshToken()方法。

非常感谢您的所有贡献!