Skip to content

Instantly share code, notes, and snippets.

@jirawatee
Last active February 6, 2025 04:28
Show Gist options
  • Save jirawatee/67ef7365978e3d64c6e84c75db55aa46 to your computer and use it in GitHub Desktop.
Save jirawatee/67ef7365978e3d64c6e84c75db55aa46 to your computer and use it in GitHub Desktop.
x-line-signature validation
const functions = require("firebase-functions");
const request = require("request-promise");
const LINE_HEADER = {
"Content-Type": "application/json",
Authorization: "Bearer YOUR-CHANNEL-ACCESS-TOKEN"
}
const LINE_MESSAGING_API = "https://api.line.me/v2/bot/message";
// 1. Copy your Channel Secret from LINE Developers Console then paste is as a value
const LINE_CHANNEL_SECRET = "YOUR-CHANNEL-SECRET";
// 2. Import crypto dependency for HMAC creating
const crypto = require('crypto');
exports.LineBotReply = functions.https.onRequest((req, res) => {
if (req.method === "POST") {
// 3. Generate Signature by HMAC-SHA256 algorithm using LINE Channel Secret and request body(Buffer)
const signature = crypto.createHmac('SHA256', LINE_CHANNEL_SECRET).update(req.rawBody).digest('base64').toString();
// 4. Compare your signature and header's signature
if (signature !== req.headers['x-line-signature']) {
return res.status(401).send('Unauthorized');
}
reply(req.body);
}
return res.status(200).send(req.method);
})
const reply = bodyPayload => {
return request.post({
uri: `${LINE_MESSAGING_API}/reply`,
headers: LINE_HEADER,
body: JSON.stringify({
replyToken: bodyPayload.events[0].replyToken,
messages: [{ type: "text", text: JSON.stringify(bodyPayload) }]
})
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment