还加入了帕特里克的答案加入,我建议使用快递连同它的机身的解析器。 下面是一个完整的例子。这适用于Express 4.x,Node 8.x(写作时的最新版本)。
请替换YOUR_WEBHOOK_SECRET_HERE
并在authorizationSuccessful
函数中做一些事情。
// Imports
const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const app = express();
// The GitHub webhook MUST be configured to be sent as "application/json"
app.use(bodyParser.json());
// Verification function to check if it is actually GitHub who is POSTing here
const verifyGitHub = (req) => {
if (!req.headers['user-agent'].includes('GitHub-Hookshot')) {
return false;
}
// Compare their hmac signature to our hmac signature
// (hmac = hash-based message authentication code)
const theirSignature = req.headers['x-hub-signature'];
const payload = JSON.stringify(req.body);
const secret = 'YOUR_WEBHOOK_SECRET_HERE'; // TODO: Replace me
const ourSignature = `sha1=${crypto.createHmac('sha1', secret).update(payload).digest('hex')}`;
return crypto.timingSafeEqual(Buffer.from(theirSignature), Buffer.from(ourSignature));
};
const notAuthorized = (req, res) => {
console.log('Someone who is NOT GitHub is calling, redirect them');
res.redirect(301, '/'); // Redirect to domain root
};
const authorizationSuccessful =() => {
console.log('GitHub is calling, do something here');
// TODO: Do something here
};
app.post('*', (req, res) => {
if (verifyGitHub(req)) {
// GitHub calling
authorizationSuccessful();
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Thanks GitHub <3');
} else {
// Someone else calling
notAuthorized(req, res);
}
});
app.all('*', notAuthorized); // Only webhook requests allowed at this address
app.listen(3000);
console.log('Webhook service running at http://localhost:3000');
似乎并没有为我工作 – ditoslav 2015-10-19 13:09:42
非常重要的一提的是GitHub的hookshot *必须*有它的Content-Type设置为'应用程序/ json'。您将在webhook配置页面上找到这些设置。 https://github.com/MY_ORG/MY_REPO/settings/hooks/HOOK_ID#delivery-response – 2017-07-02 22:32:24
像@MrClean的状态,使用application/json! – Mattis 2017-08-29 11:17:55