close

目標

使用node.js裡的套件googleapis來完成google API的存取測試

1. 安裝套件

npm install googleapis

2. 申請Google Developer

連到Google Developers開立Developer權限囉!

3. 建立憑證

花了些時間看了GOOGLE提供的幾種OAUTH的方法,最後由於應用的方式,所以選擇了"Using OAuth 2.0 for Installed Applications"

device-auth-decision-installedapp


詳細文檔請參考文件https://developers.google.com/identity/protocols/OAuth2InstalledApp

建立憑證的方式,首先先登入Google Developers Console,在左邊的欄位有 "API和憑證",裡面有各憑證點下去,然後建立一個新的用戶端ID

googleCertificate


建立完成後會得到用戶端ID以及用戶端密碼,如下圖所示

google-clientinfo


裡面主要需要注意的是redirect URI的設定,根據Google文檔,"Using OAuth 2.0 for Installed Applications"有三個redirect URL可供輸入根據應用,我選用了"urn:ietf:wg:oauth:2.0:oob"

* http://localhost
* urn:ietf:wg:oauth:2.0:oob
      This value signals to the Google Authorization Server that the authorization code should be returned in the title bar of the browser, with the page text prompting the user to copy the code and paste it in the application (as shown in the screenshot above). This is useful when the client (such as a Windows application) cannot listen on an HTTP port without significant client configuration.
* urn:ietf:wg:oauth:2.0:oob:auto
      This is identical to urn:ietf:wg:oauth:2.0:oob, but the text in the confirmation page won't instruct the user to copy the authorization code, but instead will simply ask the user to close the window.

完成步驟2,3後,接著使用程式來確認API存取方法

4. 執行Sample code來取得access Token

基本上,貼上程式碼應該就可以執行了

var readline = require('readline');
var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var CLIENT_ID = '256637951185-p1b226vo2mfem77mbuiccj74eefj3m2v.apps.googleusercontent.com',
    CLIENT_SECRET = 'YOUR CLIENT SECRET',
    REDIRECT_URL = 'urn:ietf:wg:oauth:2.0:oob',
    SCOPE = ['https://www.googleapis.com/auth/drive',
        'https://www.googleapis.com/auth/plus.me',
    ];  
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var auth = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
var url = auth.generateAuthUrl({scope: SCOPE});
var getAccessToken = function(code) {
    auth.getToken(code, function(err, tokens) {
        if (err) {
            console.log('Error while trying to retrieve access token', err);
            return;
        }   
        auth.credentials = tokens;
        console.log(tokens);
    }); 
};
console.log('Visit the url: ', url);
rl.question('Enter the code here:', getAccessToken);

程式裡有看到伊個scope的定義,那主要是在宣告取得的token可以允許什麼樣的服務。這些服務需要先由使用者確認後才可以提供。 scope的list可由google文件中找到

https://developers.google.com/gdata/faq#AuthScopes

http://hayageek.com/google-oauth-scope-list/

google建議根據不同的使用情境,存放不同的tokens,當然程式的難度也不同~_~。這裡要注意的是,即使你的scope內有宣告使用什麼服務,但是同時在Google Developer Console裡的api也要啟動,不然沒法使用

這程式主要的目的在使用之前得到的註冊資訊,取得access token。首先,先開啟瀏覽器,存取console上提示的那個位置,存取時google會詢問你是否允許你的APP存取你的GOOGLE DRIVE

Visit the url:  https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.file%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fplus.me&response_type=code&client_id=256637951185-p1b226vo2mfem77mbuiccj74eefj3m2v.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob
Enter the code here:4/jh7L4h6mD_OxJyB0KKai_km1QMHm0RaMBmPyIf7a6y8.QtMk-xqQ7OodgrKXntQAax3w2JV6mgI

確認開放存取後會回傳一個網頁,如下所示

google-authconfirm


把這個碼貼回剛剛的console理就可以得到access_token了

{ access_token: 'ya29.bwFW-1vQBf7r87keGzBUpTe8GvhbwpoIBD9Pjm4_gIsuRbeMwn5Uax8QWZcD8ndiL9mgPHkmJ5i-Kw',
  token_type: 'Bearer',
  id_token: 'eyJhbGciOiJSUzI1NiIsImtpZCI6IjhkOGJkMTA4N2Y2NDA1ZTIwZmRiZTJkZDhkODgyMzEwYTM1MzYzZjMifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTExMzUzNzM3NzYwMDM4NDYxNzQ1IiwiYXpwIjoiMjU2NjM3OTUxMTg1LXAxYjIyNnZvMm1mZW03N21idWljY2o3NGVlZmozbTJ2LmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiYXRfaGFzaCI6IjdhRV81R2w4aElDbUoxMGxLemptY3ciLCJhdWQiOiIyNTY2Mzc5NTExODUtcDFiMjI2dm8ybWZlbTc3bWJ1aWNjajc0ZWVmajNtMnYuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJpYXQiOjE0MzEyNTI0MzYsImV4cCI6MTQzMTI1NjAzNn0.UV5cVGquA-qnS4HmUWXTz-8ITahfcMWzyPrx9ONaVcKrMdV6smD9Bq84pV3V6A4G8mBUTnQKhrY_Sx9yEE7X5htmbj5ZY3z3horqaN7IvcQXrAeILRV_FX2aZf7yVDDQoTxoveQ4PIE77A486kmdb4wP4WmiwKKBtBJ1dof3Faw',
  refresh_token: '1/Hn9VqLfVumXrnFKb-Dpms0j7i2wMfNWJ_wqz-1dtrQAMEudVrK5jSpoR30zcRFq6',
  expiry_date: 1431255903675 }

5. 執行程式碼進行檔案下載測試

終於取得access_token後,將access_token存在程式裡,開始做Google Drive檔案下載的動作

首先,先參考GOOGLE文件,知道怎麼下載 https://developers.google.com/drive/web/manage-downloads

var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var CLIENT_ID = '256637951185-p1b226vo2mfem77mbuiccj74eefj3m2v.apps.googleusercontent.com',
    CLIENT_SECRET = 'YOUR CLIENT SECRET',
    REDIRECT_URL = 'urn:ietf:wg:oauth:2.0:oob',
    SCOPE = ['https://www.googleapis.com/auth/drive',
        'https://www.googleapis.com/auth/plus.me',
    ];  
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);

var tokens = { 
    access_token: 'ya29.bwEit2Xce8VpIWbZtpjTFpoHW10gLCkjuV4jrbs4bNGxPIWGhEugQV20EmQBVGpc8bx1r4alsXciHA',
    token_type: 'Bearer',
    id_token: 'eyJhbGciOiJSUzI1NiIsImtpZCI6IjhkOGJkMTA4N2Y2NDA1ZTIwZmRiZTJkZDhkODgyMzEwYTM1MzYzZjMifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTExMzUzNzM3NzYwMDM4NDYxNzQ1IiwiYXpwIjoiMjU2NjM3OT
UxMTg1LXAxYjIyNnZvMm1mZW03N21idWljY2o3NGVlZmozbTJ2LmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiYXRfaGFzaCI6ImI5WHhlMG9GdHNpNWhNbGViSHo4dFEiLCJhdWQiOiIyNTY2Mzc5NTExODUtcDFiMjI2dm8ybWZlbTc3bWJ1aWNjajc0ZWVmaj
NtMnYuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJpYXQiOjE0MzEyNjMwMjksImV4cCI6MTQzMTI2NjYyOX0.v3DqpRgmyNsDPLdb1SlVDdZ6fejvpE3Tfk5MLl_-YD7wu9AZ6Y0vOMop-pNiTXYz2Q_sPynUAJn-ToG_uZA2We_RWFywgOPpKb2Wq9DyK1cXVu
HZEYNLOu6UTIytPaI3e4nm_I6KCZIBDx_lc6KE6RA0SyloOFpSH-JpnaPpj44',
    refresh_token: '1/TgOhZcbvVBvjSK3dnYDd0lGmzsJH4EFALL8zQJkNx1990RDknAdJa_sgfheVM0XT',
    expiry_date: 1431266494150
}
oauth2Client.setCredentials(tokens);
var drive = google.drive({version: 'v2',auth: oauth2Client});
function getList() {
    drive.files.list({}, function(err, result) {
        console.log(result.items.length + ' items');
        for (item in result.items) {
            console.log(result.items[item].title, result.items[item].id);
        }   
    }); 
};
var request = require('request');
var fs = require('fs');
function download(fileId) {
    var file = fs.createWriteStream("./bbbb.mp3");
    var getDown = "https://www.googleapis.com/drive/v2/files/" + fileId + "?alt=media";
    request.get({
        url: getDown,
        encoding: null, // Force Request to return the data as Buffer
        headers: {
            Authorization: 'Bearer ' + tokens.access_token
        }   
    }, function(err, res) {
        if (err) {
            console.log(err);
        }   
    }).pipe(file);
}

//getList();
download('0B9i2kpb09evneWV0SklvYlJCRjQ');

上面程式只是範例,所以可以看到我直接調用download,並把指定的檔案ID帶入。如要先確定檔案ID,可以先執行getList,就會列出你的Google Drive裡有的檔案。 抓下檔案後,做一下簡單的md5sum檢查檔案跟server上放的一樣,一切正確!

補充資料

* Google APIs Explorer 可以確認API參數,更可以在裡面直接玩API!好用!

https://developers.google.com/apis-explorer/#p/

* Google Drive Rest API

https://developers.google.com/drive/v2/reference/files/list

* Using OAuth 2.0 to Access Google APIs 裡面列了google有提供的OAUTH方式

https://developers.google.com/identity/protocols/OAuth2

Youtube 取得影片方法

youtube download 無法使用youtube data API達成,但可以經由parsing 來達成,使用別人寫好的模組來存取即可

https://github.com/fent/node-ytdl-core

但可以經由youtube data API取得video id,如經由youtube.playlistItems.list取得playlist中所有items的影片id

client_secret安全嗎?

若選擇的是Installed Applications型別的應用,如Google網頁上講的。不用管安全性...

https://developers.google.com/identity/protocols/OAuth2InstalledApp

When creating a client ID, you specify that your application is an Installed application. This results in a different value for the redirect_uri parameter.
The client ID and client secret obtained from the Developers Console are embedded in the source code of your application. In this context, the client secret is obviously not treated as a secret.
The authorization code can be returned to your application in the title bar of the browser or to an http://localhost port in the query string.
arrow
arrow
    文章標籤
    node.js googleapis
    全站熱搜

    Perry Wu 發表在 痞客邦 留言(0) 人氣()