Guzzle request Google API - fantasy0107/notes GitHub Wiki
laravel 預設就有裝
安裝
composer require google/apiclient:^2.0
keyword
token/access token
expire time
refresh token
scope
前置
- google cloud platform 控制台
- 專案是否有啟用 API ex: photo api
- 這個 API 可以用 憑證 還是 API金鑰
- refresh token ? google 的不會過期
- 相關 API 文件 - 知道需要傳過去和回傳的格式是什麼 ex: PHOTO API 回傳格式
- 收費
google php client 相關需要用到的
//用 refresh token 去更新 access token
$client->refreshToken($googleClientToken['refresh_token']);
// 取得 accessToken 可能會沒有 refresh_token
$client->getAccessToken()
參考資料
- Photos Library API Endpoints
- Google Client Services
- invalid_grant
- 範例
- 和socialite 一起使用
- 使用 server API keys
- guzzle 連線
google developer 控制台 - 憑證在哪個專案底下要看那個專案有開啟哪些 API 那些 API才能用
The Google Auth server issued Refresh tokens never expire
The Google Auth server issued Refresh tokens never expire — that's the whole point of the refresh
tokens. The refresh token will expire (or I should say become unauthorized) when the user revokes
access to your application.
範例
新增 updatetoken
上傳檔案後會回傳這個讓你可以透過 updatetoken 去操作相片
...
$goooglePhotoUploadUrl = 'https://photoslibrary.googleapis.com/v1/uploads';
$guzzleClient = new Client;
// 取得 binary file
$fileRealPath = $file->getRealPath();
$content = file_get_contents($fileRealPath);
// request for google updatetoken
$res = $guzzleClient->request(
'POST',
$goooglePhotoUploadUrl,
[
'headers' => [
'Content-type' => 'application/octet-stream',
'X-Goog-Upload-File-Name' => 'test.jpeg',
'X-Goog-Upload-Protocol' => 'raw',
'Authorization' => $dodoGconfig['token_type'].' '.$dodoGconfig['access_token']
],
'body' => $content
]
);
$updateToken = $res->getBody()->getContents();
dd($updateToken);
...
新增相簿
...
$time = time();
$res = $guzzleClient->request(
'POST',
$goooglePhotoCreateAlbumUrl,
[
'headers' => [
'Content-type' => 'application/octet-stream',
'Authorization' => $dodoGconfig['token_type'].' '.$dodoGconfig['access_token']
],
'json' => [
'album' => [
'title' => "$time"
]
]
]
);
...
將相片丟到相簿
...
$googlePathToUploadUrl = 'https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate';
$res = $guzzleClient->request(
'POST',
$googlePathToUploadUrl,
[
'headers' => [
'Content-type' => 'application/json',
'Authorization' => $dodoGconfig['token_type'].' '.$dodoGconfig['access_token']
],
'json' => [
'albumId' => $albumId,
'newMediaItems' => [
[
'description' => 'fromLaravel',
'simpleMediaItem' => [
'uploadToken' => $updateToken
]
]
]
]
]
);
...
問題
- 手動建立的相簿不能透過 API 加相片進去 但 API 建立的相簿卻可以加相片進去