Last active
January 17, 2024 03:54
-
-
Save letswritetw/55682f4261cb2929f33888ad5319fa34 to your computer and use it in GitHub Desktop.
line-signature
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const lineConfig = { | |
channelAccessToken: 'XXXXXXXXXXX', | |
channelSecret: 'XXXXXXXXXXX' | |
}; | |
const crypto = require('crypto'); | |
const channelSecret = lineConfig.channelSecret; | |
app.post('/webhook', line.middleware(lineConfig), (req, res) => { | |
// 給 LINE 的 body 要是 string | |
const body = JSON.stringify(req.body); | |
// 取得 LINE 的簽名 | |
const signature = crypto.createHmac('SHA256', channelSecret).update(body).digest('base64'); | |
// 取得 headers 中的 X-Line-Signature | |
const headerX = req.get('X-Line-Signature'); | |
// 比對 signature, headers ,二者相等時才代表是由 LINE server 發來的訊息 | |
if(signature === headerX) { | |
// webhook event | |
const event = req.body.events[0]; | |
// 是加入好友時 | |
if(event.type === 'follow') handleFollow(event); | |
// 是封鎖時 | |
else if(event.type === 'unfollow') handleUnFollow(event); | |
// 是訊息時 | |
else if(event.type === 'message') handleMessage(event); | |
// 是 postback 時 | |
else if(event.type === 'postback') handlePostback(event); | |
} | |
res.send('webhook') | |
}); | |
function handleFollow() { | |
// 加入好友時要做的事 | |
} | |
function handleUnFollow() { | |
// 被封鎖時要做的事 | |
} | |
function handleMessage() { | |
// 收到訊息時要做的事 | |
} | |
function handlePostback() { | |
// 收到 postback 時要做的事 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment