概要
GCP(Google Clous Platform)においてプロジェクトを作成し、そのプロジェクト上でGoogle Sheets API(ver.4)を有効な状態でサービスアカウントを作成しました。
作成したサービスアカウントのアクセス権は「オーナー」を与え、.json形式の認証キーを作成しサーバー上に設置を行い、アクセスを行いたいスプレッドシートにサービスアカウント のメールアドレスを共有しました。
その後、PHPを使ってGoogle Sheets APIの呼び出しやスプレッドシートへのアクセスを試そうとしたところ以下のようなエラーに遭遇しています。
現状のエラーメッセージとソースコード、自身で解決するために試そうとしたことを記述しています。どなたか解決方法やアドバイスを頂けませんでしょうか?よろしくお願い致します。
使用言語
PHP ver5.6
現状のエラーメッセージ
- エラーが起きている箇所はソースコード中のfunction api_conect_manage()の例外処理
object(Google\Service\Exception)#101 (8) { ["errors":protected]=> NULL ["message":protected]=> string(98) "{"error":"invalid_scope","error_description":"Invalid OAuth scope or ID token audience provided."}"
ソースコード
//autoload.php読み込み
require_once('path/to/librarydirectory/google-api-php-client--PHP5.6/vendor/autoload.php');
// 宣言
use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;
use Google\Spreadsheet\SpreadsheetService;
// 接続初初期化処理
function api_init(){
//正常処理
try{
//サーバーに設置したjson形式のファイルを読み込み
putenv('GOOGLE_APPLICATION_CREDENTIALS='/path-to-my-jsonkey/download-from-gcp-serviceaccount.json);
//Googleクライアントへの接続準備
$client = new Google_Client();
//サービスアカウントを使った認証方法
$client->useApplicationDefaultCredentials();
//アプリケーション名の設定
$client->setApplicationName("MySpreadsheet");//アプリケーション名はなんでも良い
//アクセストークンが既にある場合はそっちを使う
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
//処理が正常だった場合にサーバー上のログファイルに書き込む。
$this->exception_data_save("api_init()は正常処理です");
return $client;
}catch(Exception $e){
//処理がエラーとなる=例外処理となった場合にサーバー上のログに書きこむ処理
$this->exception_data_save("api_init()例外処理です。ライブラリが正しく読み込めているか確認してください");
var_dump($e);
exit;
return false;
}
return false;
}//function api_init()終了
//API接続処理
function api_conect(){
try{
//サーバーに設置したJson形式の鍵ファイルを読み込み
putenv('GOOGLE_APPLICATION_CREDENTIALS='/path-to-my-jsonkey/download-from-gcp-serviceaccount.json);
$client = new Google_Client();
$client->setApplicationName("MySpreadsheet");
$client->useApplicationDefaultCredentials();
//スコープの設定 解決試行1
$client->setScopes([
\Google_Service_Sheets::SPREADSHEETS,
\Google_Service_Sheets::DRIVE,
//以下のスコープはあっても無くてもエラー内容に変わりがなかった。
"https://spreadsheets.google.com/feeds",
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/spreadsheets',
]);
//トークン関連の処理
$client->refreshTokenWithAssertion();
if ($client->isAccessTokenExpired()) {
$client->refreshTokenWithAssertion();
}
$_SESSION['service_token'] = $client->getAccessToken();
$obj_token = $client->getAccessToken();
$accessToken=$obj_token;
//処理が正常だった場合にサーバー上のログファイルに書き込む。
$this->exception_data_save("api_conect()は正常処理です。");
return $accessToken; //アクセストークンを返す
}catch(Exception $e){
//処理が間違い=例外処理となった場合にサーバー上のログに書き込む処理
$this->exception_data_save("function api_conect()は例外処理です。");
return false;
}
return false;
}//API接続処理終了
//API接続管理処理
function api_conect_manage($sheet_name=NULL,$current_date=NULL,&$input_data=array()){
//function api_init()が正常に動き、api_conect()でアクセストークンが正常に取得できた場合
if(($client=$this->api_init())!==false && ($access_token=$this->api_conect($client))!==false){
// try,catch処理を開始
try{
$serviceRequest = new DefaultServiceRequest($access_token['access_token']);
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new Google_Service_Sheets($client);
$spreadsheetId = 'my spreadsheetId';
$sheetId = 'my sheetID'
//解決2 ->get()部分の引数に$sheetIdを渡してみたがエラーは解決せず
$spreadsheetFeed = $spreadsheetService->spreadsheets->get($spreadsheetId);
//例外処理
}(catch Exeption $e){
//処理が間違い=例外処理となった場合にサーバー上のログに書き込む処理
$this->exception_data_save("api_conect_mange()のtry catch処理は例外処理です。",$input_data);
// # ここで今回のエラーが発生している(Invalid OAuth scope or ID token audience provided)
var_dump($e);
exit;
return false;
}//try,catch終了
}//if分岐終了
}//function api_conect_manage終了
解決のために試したこと
- スコープの追加。function api_conect()のsetScopes()にスコープを追加したり無効にしたりしてテスト行ったがエラー内容に変わりがなかった。(解決1というコメント部分)
- スプレッドシート取得部分の->($spreadsheetId)の引数をsheetIに変更したが、エラーメッセージに変化はなかった。(解決2というコメント部分)
使用しているライブラリ、外部サービス
- google-api-php-client--PHP5.6 v2.11.0
https://github.com/googleapis/google-api-php-client/releases - Google Cloud Platform
https://console.cloud.google.com/
参考にしているページ
php google api client
https://github.com/googleapis/google-api-php-clientMigrate from Sheets API from v3 https://developers.google.com/sheets/api/guides/migration#v4-api_5
PHP QuickStart
https://developers.google.com/sheets/api/quickstart/php