stripe webhooks stripe签名的编写单元测试



我正在尝试为Stripe-webhook编写单元测试。问题是我也在验证stripe-signature,但它按预期失败了。

有没有一种方法可以在测试中用模拟数据将正确的签名传递给webhook?

这是我试图处理的webhook路线的开始

// Retrieve the event by verifying the signature using the raw body and secret.
let event: Stripe.Event;
const signature = headers["stripe-signature"];
try {
event = stripe.webhooks.constructEvent(
raw,
signature,
context.env.stripeWebhookSecret
);
} catch (err) {
throw new ResourceError(RouteErrorCode.STRIPE_WEBHOOK_SIGNATURE_VERIFICATION_FAILD);
}
// Handle event...

我正在尝试处理的当前测试,我使用的是Jest:

const postData = { MOCK WEBHOOK EVENT DATA }
const result = await request(app.app)
.post("/webhook/stripe")
.set('stripe-signature', 'HOW TO GET THIS SIGNATURE?')
.send(postData);

Stripe现在在其节点库中公开了一个函数,他们建议该函数用于创建测试签名:

测试Webhook签名

您可以使用stripe.webhooks.generateTestHeaderString模拟来自Stripe:的webhook事件

const payload = {
id: 'evt_test_webhook',
object: 'event',
};
const payloadString = JSON.stringify(payload, null, 2);
const secret = 'whsec_test_secret';
const header = stripe.webhooks.generateTestHeaderString({
payload: payloadString,
secret,
});
const event = stripe.webhooks.constructEvent(payloadString, header, secret);
// Do something with mocked signed event
expect(event.id).to.equal(payload.id);

参考:https://github.com/stripe/stripe-node#webhook-签署

在诺兰的帮助下,我能够使签名生效。如果其他人需要帮助,我就是这么做的:

import { createHmac } from 'crypto';
const unixtime = Math.floor(new Date().getTime() / 1000);
// Calculate the signature using the UNIX timestamp, postData and webhook secret
const signature = createHmac('sha256', stripeWebhookSecret)
.update(`${unixtime}.${JSON.stringify(postData)}`, 'utf8')
.digest('hex');
// Set the stripe-signature header with the v1 signature
// v0 can be any value since its not used in the signature calculation
const result = await request(app.app)
.post("/webhook/stripe")
.set('stripe-signature', `t=${unixtime},v1=${signature},v0=ff`)
.send(postData);

如果你在ruby中,你可以做:

Stripe::Webhook::Signature.generate_header(
Time.now,
Stripe::Webhook::Signature.compute_signature(
Time.now,
payload,
secret
)
)

最新更新