node.js - 为 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);
解决方案
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);
推荐阅读
- c++ - 在运行时猜测函数的返回类型
- node.js - Sequelize:将日期存储在 JSON 列中,并将它们与 where 子句中的日期进行比较
- python-3.x - 如何在 x 轴上设置带有日期的图表
- wordpress - 有没有办法配置 nginx 在 Google PageSpeed Insight 上获得更多分数?
- c# - 如何设置对象在游戏对象方向上的速度?
- java - 当按钮每秒都在改变颜色时,如何让我按下的按钮停止而其他按钮继续切换颜色?
- datagridview - 无法刷新绑定到 DataTable 的 DataGridView
- java - 如何将xml文件生成为循环方法?
- postgresql - 按天自动分区 - PostgreSQL
- javascript - JavaScript 对象原型中的函数在被另一个模块导入时未定义