我正在为 subs 集成 Twitch API,并且在获取对中间件函数的 webhook 回调响应时遇到问题,它应该检查标头并验证签名。
我收到了正确的回应!然而,它就停在那里!我检查了路线的顺序,但我不确定我错过了什么
我正在关注https://dev.twitch.tv/docs/eventsub
app.post('/createWebhook/:broadcasterId', (req, res) => {
const createWebHookParams = {
host: "api.twitch.tv",
path: "helix/eventsub/subscriptions",
method: 'POST',
headers: {
"Content-Type": "application/json",
"Client-ID": clientId,
"Authorization": "Bearer " + authToken
}
}
const createWebHookBody = {
"type": "channel.follow",
"version": "1",
"condition": {
"broadcaster_user_id": req.params.broadcasterId
},
"transport": {
"method": "webhook",
"callback": "ngrokURL/notification",
"secret": webhookSecret //
}
}
let responseData = ""
const webhookReq = https.request(createWebHookParams, (result) => {
result.setEncoding('utf8')
result.on('data', (d) => {
responseData = responseData + d
})
.on('end', (result) => {
const responseBody = JSON.parse(responseData) // json
console.log(responseBody)
res.send(responseBody)
})
})
webhookReq.on('error', (e) => {
console.log("Error")
})
webhookReq.write(JSON.stringify(createWebHookBody))
webhookReq.end()
});
// middlewsre ---> // not triggered!!!
app.use(express.json({
verify: verifyTwitchSignature
}));
// making post to receeive the notification.
app.post('/notification', (req, res) => {
console.log("incoming notificatin", req.body)
res.status(200).end();
})
// the middleware verifing the signature
const crypto = require("crypto");
const twitchSigningSecret = process.env.SECRET;
const verifyTwitchSignature = (req, res, buf, encoding)=>{
const messageId = req.header("Twitch-Eventsub-Message-Id");
const timeStamp = req.header("Twitch-Eventsub-Message-Timestamp")
const messageSignature = req.header("Twitch-Eventsub-Message-Signature")
console.log(`Message ${messageId} Signature: `,messageSignature)
if (!twitchSigningSecret){
console.log(`Twitch signing secret is empty`);
throw new Error ("Twitch signing secret is empty.");
}
const computedSignature = "sha256=" + crypto.createHmac("sha256", twitchSigningSecret).update(messageId + timeStamp + buf).digist("hex");
console.log(`Message ${messageId} Computed Signature: `, computedSignature)
if (messageSignature !== computedSignature) {
throw new Error("Invalid Signature.");
}else {
console.log("Verification Successful");
}
}
module.exports = verifyTwitchSignature