我正在尝试在WooCommerce Webhook API和我的节点之间创建一个集成。js后端。然而,我真的不知道应该如何使用这个秘密来验证请求。
机密:一个可选的密钥,用于生成请求正文的HMAC-SHA256哈希,以便接收方可以验证webhook的真实性。
X-WC-Webhook-Signature:有效负载的Base64编码的HMAC-SHA256哈希。
Nodejs后端:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
router.post('/', function (req, res) {
var secret = 'ciPV6gjCbu&efdgbhfgj&¤"#&¤GDA';
var signature = req.header("x-wc-webhook-signature");
var hash = CryptoJS.HmacSHA256(req.body, secret).toString(CryptoJS.enc.Base64);
if(hash === signature){
res.send('match');
} else {
res.send("no match");
}
});
来源:https://github.com/woocommerce/woocommerce/pull/5941
WooCommerce REST API源
哈希和签名不匹配。怎么了?
更新:<代码>控制台。log返回以下值:
哈希
:pU9kXddJPY9MG9i2ZFLNTu3TXZA 85pnwfPqmr0dg0=
签名:PjKImjr9Hk9MmIdUMc pEmCqBoRXA5f3Ac6tnji7exU=
哈希(不带.toString(CryptoJS.enc.Base64))
:a54f645dd7493d8f4c1bd8b66452cd4eedd35d903efbce699f07cfa8caf4760d
签名需要根据正文而不是它包含的JSON进行检查。i、 e.请求的原始字节。身体
const rawBodySaver = (req, res, buf, encoding) => {
if (buf && buf.length) {
req.rawBody = buf.toString(encoding || 'utf8');
}
};
app.use(bodyParser.json({ verify: rawBodySaver }));
app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use(bodyParser.raw({ verify: rawBodySaver, type: '*/*' }));
import crypto from 'crypto'; //Let's try with built-in crypto lib instead of cryptoJS
router.post('/', function (req, res) {
const secret = 'ciPV6gjCbu&efdgbhfgj&¤"#&¤GDA';
const signature = req.header("X-WC-Webhook-Signature");
const hash = crypto.createHmac('SHA256', secret).update(req.rawBody).digest('base64');
if(hash === signature){
res.send('match');
} else {
res.send("no match");
}
});
我希望下面能节省一些时间。
// Make sure to add a WISTIA_SECRET_KEY in your Environment Variables
// See https://docs.pipedream.com/environment-variables/
const secret = process.env.SELF_AUTOMATE_KEY;
const signature = event.headers["x-wc-webhook-signature"];
const body = steps.trigger.raw_event["body_b64"];
const clean_Body = body.replace("body_b64: ", "");
//const body = steps.trigger.raw_event;
console.log(event.headers["x-wc-webhook-signature"]);
console.log("Print Body", clean_Body);
if (process.env.SELF_AUTOMATE_KEY === undefined) {
$end("No WISTIA_SECRET_KEY environment variable defined. Exiting.")
}
if (!("x-wc-webhook-signature" in event.headers)) {
$end("No x-wc-webhook-signature header present in the request. Exiting.")
}
// Once we've confirmed we have a signature, we want to
// validate it by generating an HMAC SHA-256 hexdigest
const crypto = require('crypto');
const hash = crypto.createHmac('sha256',
secret).update(JSON.stringify(clean_Body), 'base64').digest('base64');
console.log(hash);
// $end() ends the execution of a pipeline, presenting a nice message in the "Messages"
// column in the inspector above. See https://docs.pipedream.com/notebook/code/#end
if (hash !== signature) {
$end("The correct secret key was not passed in the event. Exiting!")
}