
No License
JavaScript
2022年02月22日
const fs = require('fs');
const { google } = require('googleapis');
const OAuth2 = google.auth.OAuth2;
// OAuthクライアントを初期化
const creds = JSON.parse(fs.readFileSync('creds.json', 'utf-8')).installed;
const oauth2Client = new OAuth2(
creds.client_id,
creds.client_secret,
'urn:ietf:wg:oauth:2.0:oob'
);
// 認証コードを取得するためのURLを取得
const getAuthorizeUrl = () => {
const authorizeUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: [
'https://www.googleapis.com/auth/script.scriptapp',
'https://www.googleapis.com/auth/drive'
],
});
return authorizeUrl;
}
// トークンを取得してJSONファイルに保存
const getToken = () => {
const code = 'getAuthorizeUrlで得たコード';
oauth2Client.getToken(code, (err, token) => {
fs.writeFileSync('token.json', JSON.stringify(token));
});
}
// GAS APIを実行
const callAppsScript = (auth) => {
const scriptId = 'デプロイID';
const script = google.script('v1');
script.scripts.run({
auth: auth,
resource: {
function: 'doSomething',
},
scriptId: scriptId,
}, (err, resp) => {
// GASの関数からの戻り値
console.log(resp.data.response.result);
});
}
// エントリー
const main = () => {
// JSONからトークンを取得してOAuthClientにセットする
const token = JSON.parse(fs.readFileSync('token.json', 'utf-8'));
oauth2Client.setCredentials(token);
// GASの関数を実行
callAppsScript(oauth2Client);
}
main();
No one still commented. Please first comment.
Output