电子表格库php中的“访问令牌无效”错误

时间:2017-04-04 10:22:00

标签: php cakephp google-sheets

我需要在cakephp中通过google驱动器上传电子表格。我使用google-api-php-client生成访问令牌,php-google-spreadsheet-client访问sheet.Code如下:

function test() {
    require_once '../vendors/google-api-php-client-2.1.1/vendor/autoload.php';
    $client = new \Google_Client();
    $client->setApplicationName("spreadsheet");
    $client->setDeveloperKey("//My developerkey");
    $client = new Google_Client();
    $client->setAuthConfig('client_id.json');
    if( !isset($_GET['code']) ) {

        $client->addScope(Google_Service_Drive::DRIVE);
        $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/test' );
        $auth_url = $client->createAuthUrl();
        header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    } else {

        $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/test' );
        $auth_url = $client->createAuthUrl();
        $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
        $client->setAccessToken($token);

        $serviceRequest = new Google\Spreadsheet\DefaultServiceRequest($token['access_token']);
        Google\Spreadsheet\ServiceRequestFactory::setInstance($serviceRequest);
        $spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
        $spreadsheetFeed = $spreadsheetService->getSpreadsheetFeed();
        $spreadsheet = $spreadsheetFeed->getByTitle('Test');
    }

但我收到访问令牌无效的错误,如下图所示:

enter image description here

我做错了什么?

2 个答案:

答案 0 :(得分:1)

嗨,这可能会有所帮助,首先请在Google上创建您的开发者帐户并生成访问令牌客户端ID等。然后按照以下步骤操作。

先决条件

要运行此快速入门,您需要:

安装了命令行界面(CLI)和JSON扩展的PHP 5.4或更高版本。     Composer依赖关系管理工具。     访问互联网和Web浏览器。     Google帐户。

第1步:启用Google表格API

使用此向导在Google Developers Console中创建或选择项目并自动启用API。单击继续,然后转到凭据。 在“将凭据添加到项目”页面上,单击“取消”按钮。 在页面顶部,选择OAuth许可屏幕标签。选择电子邮件地址,如果尚未设置,请输入产品名称,然后单击“保存”按钮。 选择“凭据”选项卡,单击“创建凭据”按钮,然后选择“OAuth客户端ID”。 选择应用程序类型“其他”,输入名称" Google表格API快速入门",然后单击“创建”按钮。 单击“确定”关闭生成的对话框。 单击客户端ID右侧的file_download(下载JSON)按钮。 将此文件移动到您的工作目录并将其重命名为client_secret.json。

第2步:安装Google客户端库

运行以下命令以使用composer安装库:

php composer.phar require google/apiclient:^2.0

有关替代安装选项,请参阅库的安装页面。 第3步:设置示例

在工作目录中创建名为quickstart.php的文件,并复制以下代码:

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


define('APPLICATION_NAME', 'Google Sheets API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/sheets.googleapis.com-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-php-quickstart.json
define('SCOPES', implode(' ', array(
  Google_Service_Sheets::SPREADSHEETS_READONLY)
));

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(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfig(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } 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);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }
  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);

// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range = 'Class Data!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();

if (count($values) == 0) {
  print "No data found.\n";
} else {
  print "Name, Major:\n";
  foreach ($values as $row) {
    // Print columns A and E, which correspond to indices 0 and 4.
    printf("%s, %s\n", $row[0], $row[4]);
  }
}

第4步:运行示例

使用以下命令运行示例:

php quickstart.php

第一次运行示例时,它会提示您授权访问:

Browse to the provided URL in your web browser.

If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization.
Click the Accept button.
Copy the code you're given, paste it into the command-line prompt, and press Enter.

More about google sheets

答案 1 :(得分:0)

在面对Google电子表格的大量问题后,我终于做到了这一点。在您的开发人员控制台中创建web_service帐户并以.json格式下载其凭证,其类似于

{
      "type": "service_account",
      "project_id": "rank********er",
      "private_key_id": "*****************************",
      "private_key": "-----BEGIN PRIVATE KEY-----\nkey here\n",
      "client_email": "rank***@appspot.gserviceaccount.com",
      "client_id": "1066978********************",
      "auth_uri": "https://accounts.google.com/o/oauth2/auth",
      "token_uri": "https://accounts.google.com/o/oauth2/token",
      "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
      "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/ra*******r%40appspot.gserviceaccount.com"
    }

然后在您要使用Google电子表格的类/文件中使用此代码。在使用电子表格之前,您需要将该表格共享给json文件中给出的客户端电子邮件。

<?php
include dirname(__DIR__) . "/vendor/autoload.php";

use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;

$credential = dirname(__FILE__) . "/client_secret.json";
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $credential);
$client = new \Google_Client;
$client->useApplicationDefaultCredentials();

$client->setApplicationName("Some App");
$client->setScopes([
    'https://www.googleapis.com/auth/drive',
    'https://spreadsheets.google.com/feeds'
    ]);

if ($client->isAccessTokenExpired()) {
    $client->refreshTokenWithAssertion();
}
$accessToken = $client->fetchAccessTokenWithAssertion()["access_token"];

$serviceRequest = new DefaultServiceRequest($accessToken);
ServiceRequestFactory::setInstance($serviceRequest);

$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
$spreadsheetFeed = $spreadsheetService->getSpreadsheetFeed();
$spreadsheet = $spreadsheetFeed->getByTitle('Spreadsheet Name');
$worksheet = $spreadsheet->getWorksheetFeed()->getEntries()[0];

$listFeed = $worksheet->getListFeed();
$cellFeed = $worksheet->getCellFeed();
$entries = $listFeed->getEntries();

foreach ($listFeed->getEntries() as $entry) {
    $proxy = $entry->getValues();
    $proxy['status'] = $status_message;
    $entry->update($proxy);
}

根据您的名称更改标题/应用名称。您可以通过composer安装以下库来使用上面的代码行。

"google/apiclient":"^2.0",
"asimlqt/php-google-spreadsheet-client": "3.0.*",

供参考使用:https://github.com/asimlqt/php-google-spreadsheet-client