首页 > 解决方案 > 为 stripe webhooks stripe-signature 编写单元测试

问题描述

我正在尝试为 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...

而我正在尝试处理的当前测试,我正在使用 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);

标签: node.jsunit-testingstripe-payments

解决方案


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-signing


推荐阅读