Неустранимая ошибка PHP: Uncaught InvalidArgumentException: неверный формат токена в вендоре / google / apiclient / src / Google / Client.php: 423 - PullRequest
0 голосов
/ 03 октября 2019

Ниже приведен код, используемый для редактирования электронной таблицы Google, но мы получаем проблему, связанную с токеном доступа, дайте мне знать, если у кого-то есть решение этой проблемы. Для идентификатора клиента Outh мы выполняем следующие инструкции: https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/web-php

[29-Sep-2019 04:10:36 UTC] PHP Fatal error: Uncaught InvalidArgumentException: Invalid token format in /home/help4dl9/public_html/doamin.com/wp-content/themes/twentynineteen/google-sheet/vendor/google/apiclient/src/Google/Client.php:423

Здесь функция getClient:


function getClient()
{

$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

$client = new Google_Client();

$client->setApplicationName('APP NAME');

$client->setScopes( 'https://www.googleapis.com/auth/spreadsheets' );

$client->setAuthConfig( __DIR__ . '/credentials.json' );

$client->setAccessType('offline');

$client->setPrompt('select_account consent');

// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = __DIR__ . '/token.json';
if (file_exists($tokenPath)) {
    $accessToken = json_decode(file_get_contents($tokenPath), true);
    $client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
    // Refresh the token if possible, else fetch a new one.
    if ($client->getRefreshToken()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        $authObj = $client->getAccessToken();
        if(array_key_exists("access_token",$authObj)) {
            update_field( 'authentication_code', $authObj['access_token'],'option' ); // Save Token in Theme Option
        }
    } else {
        // Request authorization from the user.
        $authCode = get_field('authentication_code','option');
        // Exchange authorization code for an access token.
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
        $client->setAccessToken($accessToken);
        // Check to see if there was an error.
        if (array_key_exists('error', $accessToken)) {
            throw new Exception(join(', ', $accessToken));
        }
    }
    // Save the token to a file.
    if (!file_exists(dirname($tokenPath))) {
        mkdir(dirname($tokenPath), 0700, true);
    }
    file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}```



1 Ответ

0 голосов
/ 04 октября 2019

Вместо этого следуйте инструкциям PHP Quickstarts for Sheets API без $redirect_uri и get_field:

<?php
require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Sheets API PHP Quickstart');
    $client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}

Убедитесь, что включен API листов и вставьте credentials.json file в нужную папку, как описано в быстрый запуск . Кроме того, всякий раз, когда вы меняете необходимые области, вам нужно вручную удалить файл token.json с вашего диска.

...