Google 官方提供了一個 Node.js 用戶端函式庫 googleapis,讓開發者能便捷地訪問 Google 的各項 API,並支援 OAuth2 後台登入授權。
安裝
此庫透過 npm 發布,安裝 googleapis 及其依賴:
$ npm install googleapis
完整的 API 支援列表可參考 https://developers.google.com/apis-explorer 。
使用範例
例一:透過 Google 短網址取得完整網址
var google = require('googleapis');
var urlshortener = google.urlshortener('v1');
var params = { shortUrl: 'https://goo.gl/xKbRu3' };
// 取得短網址對應的原始長網址
urlshortener.url.get(params, function (err, response) {
console.log('Long url is', response.longUrl);
});
例二:登入授權(OAuth2)
此範例整合 OAuth2 認證,能取得使用者的訪問 Token,並在需要時刷新 Token 以防止工作階段過期:
var google = require('googleapis');
var plus = google.plus('v1');
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
// 透過 token 交換取得權杖,或直接設定:
oauth2Client.setCredentials({
access_token: 'ACCESS TOKEN HERE',
refresh_token: 'REFRESH TOKEN HERE'
});
plus.people.get({ userId: 'me', auth: oauth2Client }, function(err, response) {
// 處理 err 與 response
});
完整的登入授權範例可參考官方 GitHub 上的 oauth2.js。
例三:檔案上傳
以下示範把本地檔案上傳到 Google Drive,善用串流(stream)能讓大檔案的處理更有效率:
var fs = require('fs');
var drive = google.drive({ version: 'v2', auth: oauth2Client });
drive.files.insert({
resource: {
title: 'testimage.png',
mimeType: 'image/png'
},
media: {
mimeType: 'image/png',
body: fs.createReadStream('awesome.png') // 使用讀取串流
}
}, callback);
問題解答
若遇到任何問題,可到 Stack Overflow 提問;若發現程式漏洞,則可到 GitHub 上提交 Issue。透過這個官方函式庫,開發者能以一致的介面輕鬆整合 Google 各項服務,並借助 OAuth2 完成安全的後台授權。