带有“服务帐户密钥”身份验证且没有 google/apiclient

时间:2021-04-30 17:38:59

标签: php google-sheets-api

Google docs 仅包含带有 google/apiclient php 库的示例。但是该库包含 14888 个 php 文件。这对于一个带有我需要的“服务帐户密钥”身份验证的 google sheet api 请求来说太多了。

是否有针对某处“服务帐户密钥”身份验证的原生 http google sheet api 请求的示例?

2 个答案:

答案 0 :(得分:1)

我相信你的目标如下。

  • 您希望在不使用 googleapis for PHP 的情况下从服务帐户检索访问令牌。
  • 您希望通过检索到的访问令牌使用 Sheets API。

为了实现您的目标,示例脚本如下。

示例脚本:

在使用此脚本之前,请使用您的服务帐户值设置 $private_key$client_email 变量。另外,作为使用 Sheets API 的示例脚本,请设置 $spreadsheetId$range。在这种情况下,例如,请使用服务帐户的电子邮件在您的 Google Drive 上共享您的 Google 电子表格。这样,服务帐户就可以看到您的电子表格。请注意这一点。

<?php

$private_key = "-----BEGIN PRIVATE KEY-----\n###-----END PRIVATE KEY-----\n"; // private_key of JSON file retrieved by creating Service Account
$client_email = "###"; // client_email of JSON file retrieved by creating Service Account
$scopes = ["https://www.googleapis.com/auth/spreadsheets.readonly"];  // This is a sample scope.

$url = "https://www.googleapis.com/oauth2/v4/token";
$header = array("alg" => "RS256", "typ" => "JWT");
$now = floor(time());
$claim = array(
    "iss" => $client_email,
    "sub" => $client_email,
    "scope" => implode(" ", $scopes),
    "aud" => $url,
    "exp" => (string)($now + 3600),
    "iat" => (string)$now,
);
$signature = base64_encode(json_encode($header, JSON_UNESCAPED_SLASHES)) . "." . base64_encode(json_encode($claim, JSON_UNESCAPED_SLASHES));
$b = "";
openssl_sign($signature, $b, $private_key, "SHA256");
$jwt = $signature . "." . base64_encode($b);
$curl_handle = curl_init();
curl_setopt_array($curl_handle, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => array(
        "assertion" => $jwt,
        "grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer"
    ),
]);
$res = curl_exec($curl_handle);
curl_close($curl_handle);
$obj = json_decode($res);
$accessToken = $obj -> {'access_token'};

print($accessToken . "\n");  // You can see the retrieved access token.


// The following script is for a sample for using the access token.
$spreadsheetId = '###';  // Please set the Spreadsheet ID.
$range = 'Sheet1';
$curl_test = curl_init();
curl_setopt($curl_test, CURLOPT_URL, 'https://sheets.googleapis.com/v4/spreadsheets/' . $spreadsheetId .'/values/'. $range);
curl_setopt($curl_test, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $accessToken));
curl_setopt($curl_test, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl_test);
print($response);
  • 运行此脚本时,会从服务帐户中检索访问令牌,作为示例,使用 Sheets API 检索 $spreadsheetId 的“Sheet1”的值。

参考:

答案 1 :(得分:1)

尽管这不能回答您的问题(这可能对其可能会遇到此 14888 文件问题的其他人有用),但请注意,您还可以通过指定在作曲家中使用哪些服务来减少类的数量。 json 文件。

在您的情况下,您需要使用以下内容;

{
    "require": {
        "google/apiclient": "^2.7"
    },
    "scripts": {
        "post-update-cmd": "Google\\Task\\Composer::cleanup"
    },
    "extra": {
        "google/apiclient-services": [
            "Sheets"
        ]
    }
}

参考:https://packagist.org/packages/google/apiclient

相关问题