Неверный формат токена в клиентском API Google в php - в первый раз он работает нормально, но ошибка после того, как я обновил sh страницу - PullRequest
0 голосов
/ 25 мая 2020

Я получаю следующую ошибку - Неверный формат токена. Код работает нормально в первый раз, но во второй раз, когда страница обновляется, возникает ошибка. Я аутентифицирую лист Google, войдя в учетную запись Gmail. функция fetchAccessTokenWithAuthCode () возвращает пустое значение во второй раз. Функция возвращает данные таблицы Google

//Get spreadsheet data
public function actionGetSpreadsheetData(){
    $arrPost = Yii::$app->request->post();
    $arrParams = Yii::$app->request->queryParams;
    $arrSpreadsheetData = [];
    $arrSpreadsheetGrid = [];
    $googleSheetModel = new GoogleSheet();
    $credentialsPath = $googleSheetModel->getSheetCredentialPath('token.json');
    $client = new \Google_Client();
    $client->setApplicationName('My PHP App');
    $client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
    $client->setAuthConfig('client_secret.json');
    $client->setAccessType('offline');
    if(!empty($arrParams['code']) && !empty($arrPost)):
        $txtAuthCode = $arrParams['code']; 
        $txtSpreadsheetId = $arrPost['GoogleSheet']['txt_spreadsheet_id'];
        // Exchange authorization code for an access token.
        $txtAccessToken = $client->fetchAccessTokenWithAuthCode($txtAuthCode);
        // Store the credentials to disk.
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, json_encode($txtAccessToken));
        //Get Spreadsheet Data
        $range = 'A1:D';
        $arrData = $googleSheetModel->getService()->spreadsheets_values->get($txtSpreadsheetId, $range);
        $arrSpreadsheetData = $arrData->getValues();
        //Getting Spreadsheet Grid
        $arrSpreadsheetGrid = $googleSheetModel->getSpreadSheetGrid($arrSpreadsheetData,$range);
    endif;
    return $this->render('get-spreadsheet-data',[
        'googleSheetModel' => $googleSheetModel,
        'arrSpreadsheetData' => $arrSpreadsheetData,
        'arrSpreadsheetGrid' => $arrSpreadsheetGrid
    ]);
    }

Функция getClient () возвращает объект клиента

public function getClient() {
        $client = new \Google_Client();
        $client->setApplicationName(self::APPLICATION_NAME);
        $client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
        $tokenPath = $this->getSheetCredentialPath(self::CREDENTIALS_PATH);

        $client->setAuthConfig($this->getSheetCredentialPath(self::CLIENT_SECRET_PATH));
        $client->setAccessType('offline');

        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;

    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...