下記サイトを参考にサービスアカウントを取得した際に
認証キーが入ったjsonファイルをダウンロードします。
hoge.json
{
"type": "xxx",
"project_id": "xxx",
"private_key_id": "xxx",
"private_key": "xxx",
"client_id": "xxx",
"auth_uri": "xxx",
"token_uri": "xxx",
"auth_provider_x509_cert_url": "xxx",
"client_x509_cert_url": "xxx"
}
GoogleカレンダーAPIにて認証を行う際のコード
googleCalendarService.php
$client = new \Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes([
\Google_Service_Calendar::CALENDAR,
\Google_Service_Calendar::CALENDAR_EVENTS,
]);
$client->setAuthConfig(pass/hoge.json); //JSONのファイルパスとJSONファイル
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
$service = new \Google_Service_Calendar($client);
return $service;
jsonファイルの中身はこんな感じ。
GitHubにそのままgitにpushするのはマズイ。
①config配下に設定ファイルを作成
config/google-account.php
return [
'account' => [
'type'=>env('TYPE'),
'project_id'=>env('PROJECT_ID'),
'private_key_id'=>env('PRIVATE_KEY_ID'),
'private_key'=>env('PRIVATE_KEY'),
'client_email'=>env('CLIENT_EMAIL'),
'client_id'=>env('CLIENT_ID'),
'auth_uri'=>env('AUTH_URI'),
'token_url'=>env('TOKEN_URI'),
'auth_provider_x509_cert_url'=>env('AUTH_PROVIDER_X509_CERT_URL'),
'client_x509_cert_url'=>env('CLIENT_X509_CERT_URL'),
],
];
②.envに認証情報を記述
_.env
TYPE=
PROJECT_ID=
PRIVATE_KEY_ID=
PRIVATE_KEY=
CLIENT_EMAIL=g
CLIENT_ID=
AUTH_URI=
TOKEN_URI=
③認証を行う際のコードを修正
googleCalendarService.php
$client = new \Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes([
\Google_Service_Calendar::CALENDAR,
\Google_Service_Calendar::CALENDAR_EVENTS,
]);
$googleDataArray = \Config::get('google-account.account'); //追加
$client->setAuthConfig($googleDataArray);//書き換え
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
$service = new \Google_Service_Calendar($client);
return $service;
補足:json形式に変換するのかと勘違いしてましたが変換は不要です。
型が違う!って怒られちゃいます。
googleCalendarService.php
$g = json_encode($googleDataArray);
$client->setAuthConfig($g);