Alk*_*lko 12 unit-testing node.js stripe-payments
我正在尝试为 Stripe webhooks 编写单元测试。问题是我也在验证,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...
Run Code Online (Sandbox Code Playgroud)
我正在尝试处理当前的测试,我正在使用 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);
Run Code Online (Sandbox Code Playgroud)
Ula*_*ach 19
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);
Run Code Online (Sandbox Code Playgroud)
参考: https: //github.com/stripe/stripe-node#webhook-signing
在诺兰的帮助下,我成功地完成了签名。如果其他人需要帮助,这就是我所做的:
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);
Run Code Online (Sandbox Code Playgroud)