iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 8
1
Microsoft Azure

白眼狼的30天Azure跳槽計畫系列 第 8

Day [8] Azure Functions-使用 LINE Messaging API

建立LINE 官方帳號

今天開始透過Azure Functions 使用 LINE Messaging API 部署程式處理來自Line官方帳號的事件
首先前往 LINE Developers官網登入後申請官方帳號

https://ithelp.ithome.com.tw/upload/images/20200920/20108281vPUhqAG52L.jpg

填寫官方帳號基本資訊建立帳號後,記得啟用Webhook選項如下圖:
https://ithelp.ithome.com.tw/upload/images/20200923/20108281sZL8XPv6vm.jpg

安裝LINE Messaging API SDK for nodejs

接下來我們要開始使用Azure Functions 來部署LINE Messaging API程式來處理用戶的Webhook Event
首先終端機前往前幾天已經建立好了 lineWebhook 專案路徑後(可參考Day [5] Azure Functions - 使用CLI 建構本地專案)
輸入 npm install @line/bot-sdk --save

$ npm install @line/bot-sdk --save

https://ithelp.ithome.com.tw/upload/images/20200920/20108281LtOzMHLH9S.jpg

即可在functions專案中使用LINE Messaging API,我們先修改index.ts程式來測試使用LINE Messaging API
channelSecret, channelAccessToken資訊可在line官方帳號設定畫面中取得

import { AzureFunction, Context, HttpRequest } from "@azure/functions"
import { WebhookEvent, validateSignature } from "@line/bot-sdk"

export const LINE = {
    channelSecret: "<YOUR_CHANNEL_SECRET>",
    channelAccessToken: "<YOUR_CHANNEL_ACCESS_TOKEN>"
};

const lineWebhook: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
    const signature: string = req.headers["x-line-signature"]
    if (validateSignature(JSON.stringify(req.body), LINE.channelSecret, signature)) {
        const events = req.body.events as Array<WebhookEvent>
        for (const event of events) {
            context.log(event)
        }
    }

    context.res = { status: 200, body: 'ok' };
};

export default lineWebhook;

修改將functions部署至Azure 步驟可參考: Day [7] Azure Functions-將函式部署至Azure
在終端機輸入:

$ npm run build:production
$ func azure functionapp publish lineWebhook

https://ithelp.ithome.com.tw/upload/images/20200923/201082814Ll3v3Wtot.jpg
部署成功後將 lineWebhook url 填入官方帳號的Webhook settings-Webhook URL 如下圖:
https://ithelp.ithome.com.tw/upload/images/20200923/201082819ae9oCnd6V.jpg

設定後加入line官方帳號好友輸入訊息測試
https://ithelp.ithome.com.tw/upload/images/20200923/20108281zKzsbpwG9a.png
輸入後可登入Microsoft Azure入口,進入Functions服務點選該函式->監視->記錄資料流,可看到來自lineWebhook的事件資訊即測試成功。
https://ithelp.ithome.com.tw/upload/images/20200923/20108281N3IdL6L47R.jpg


上一篇
Day [7] Azure Functions-將函式部署至Azure
下一篇
Day [9] Azure Functions-Line Chatbot實作(ㄧ)
系列文
白眼狼的30天Azure跳槽計畫30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言