
Google Apps ScriptからTwilio Functionsをセキュアに呼び出す
はじめに
Google Apps ScriptからTwilio Functionsをセキュアに呼び出す方法について、ネット上にあまり情報がなかったのでnoteを書きました。
背景
Twilio Functions には、X-Twilio-Signatureというのを利用して外部からの呼出しを認証し、不正なアクセスによる実行を防ぐ機能があります。
X-Twilio-SignatureをFunctionsの呼び出し時にPOSTヘッダーに入れてあげることで、外部から呼び出す際のセキュリティ対策となります。
Node.js や Python での使い方は公式リファレンスにもサンプルが掲載されているのですが、Google Apps Scriptから呼び出す方法は載ってないんですよね。。
今回たまたまこの機能を使う機会があってコードをつくったので、(かなりニッチですが)コードをシェアします。
準備
Twilio Functionsを作成して、そのURLとTwilioのAPIトークンをご用意ください。
GASを作成し、プロジェクトの設定 > 最下部のスクリプトプロパティで、プロパティを『TWILIO_AUTH_TOKEN』、値にTwilioのAPIトークンを入れて保存しておいてください。

サンプルコード
下のコードをGASのスクリプトエディタにコピペしてください。
3行目にはTwilio FunctionsのURLを入力。
5〜9行目にはTwilio Functionsに渡したいデータをオブジェクトにして入れます。(サンプルコードのデータは適当です)
function myFunction() {
// 実行したい Twilio Functions のURL
const url = 'https://xxxxxxx-0000.twil.io/xxxx';
// Functionsに渡したいデータをオブジェクトdataに格納
const data = {
'from': '+810000000000',
'to': '+810000000000',
'url': 'https://handler.twilio.com/twiml/xxxxxx',
};
// プロパティからトークン取得
const prop = PropertiesService.getScriptProperties();
const token = prop.getProperty("TWILIO_AUTH_TOKEN");
// Twilioに投げる
const result = postTwilio(url,token,data);
}
function postTwilio(url,token,data){
// dataのパラメータを並び替えて、URLに連結した文字列strを生成
const str = Object.keys(data).sort().reduce(
(acc, value) => acc + value + data[value], url
);
// 署名を作成してbase64エンコード
const signature = Utilities.base64Encode(
Utilities.computeHmacSignature(
Utilities.MacAlgorithm.HMAC_SHA_1,
str,
token,
Utilities.Charset.US_ASCII
)
);
const headers = {
'X-Twilio-Signature': signature
};
const options = {
"method": "post",
"payload": data,
"headers": headers,
"muteHttpExceptions": true
};
const response = UrlFetchApp.fetch(url, options);
console.log(response.getContentText());
return true;
}
現場からは以上です!
ではまた!