大家好!![](https://zoearth1024moon99nas.direct.quickconnect.to/plugins/editors-xtd/zoearth_insert_emoticons_btn/imgs/756d.gif)
![](https://zoearth1024moon99nas.direct.quickconnect.to/plugins/editors-xtd/zoearth_insert_emoticons_btn/imgs/756d.gif)
PHP 要呼叫 Google Api 其實程序還蠻繁瑣的
要寫的東西不少
還需要研究文件之類
所以盡量使用API 會節省時間
(通常老闆也沒這麼多時間等你慢慢寫...
)
![](https://zoearth1024moon99nas.direct.quickconnect.to/plugins/editors-xtd/zoearth_insert_emoticons_btn/imgs/f218.gif)
所以我看到這API
覺得相當不錯
分享給大家看看
我這邊使用的目標是
"排程把 WEB上圖片 丟到 google drive 上然後替換網站上圖片來節省流量"
注意!
這作法雖然可行
但是 google drive 圖片存取有流量限制
大網站可不能這樣搞...
可以看看裡面提供的範例
在這邊
比較不一樣的是
因為我不可能人在電腦前
這樣每一次要上傳WEB上圖片我都要登入授權
所以必須改成 "長期授權" 模式
所以在原本的 $client 是這樣定義
$client = new Google_Client(); $client->setAuthConfig($oauth_credentials); $client->setRedirectUri($redirect_uri); $client->addScope("https://www.googleapis.com/auth/drive"); $service = new Google_Service_Drive($client);
這邊需要改成
//$client_id : 這是 google api 的 client_id //$client_secret : 這是 google api 的 client_secret $client = new Google_Client(); $client->setClientId($client_id); $client->setClientSecret($client_secret); $client->addScope("https://www.googleapis.com/auth/drive"); $client->setAccessToken($token); //這是要使用的 drive 的帳號 $service_account_name = 'zoearthmoon@gmail.com'; //這是 google api 建立的憑證 $key = file_get_contents( __DIR__.'/drive upload IMG-000000000000.p12'); $cred = new Google_Auth_AssertionCredentials( $service_account_name, array('https://www.googleapis.com/auth/drive'), $key ); $client->setAssertionCredentials($cred); //$refresh_token : 這是 google api 登入後取得的資料 //$token : 這是 google api 登入後取得的資料 if ($client->getAuth()->isAccessTokenExpired()) { $client->refreshToken($refresh_token); $token = $client->getAccessToken(); $client->setAccessToken($token); }
且要注意的是
這都需要先去 google api 上建立 API 與產生憑證
然後第一次需要先用 OAuth 網頁登入取得 token
這比較複雜以後有機會再說 ![](https://zoearth1024moon99nas.direct.quickconnect.to/plugins/editors-xtd/zoearth_insert_emoticons_btn/imgs/5ff6.gif)
![](https://zoearth1024moon99nas.direct.quickconnect.to/plugins/editors-xtd/zoearth_insert_emoticons_btn/imgs/5ff6.gif)
總之
給大家參考囉
留言板
歡迎留下建議與分享!希望一起交流!感恩!