我设置了一些要监听的事件,正如 stripe 解释的 webhooks 使用一样,这是我的代码(端点函数):
const stripeEvents = async (ctx:any) => {
const endpointSecret = 'whsec_...';
// Now you have the verified event, and you can parse it as JSON
if(ctx.request.hasBody){
let event;
try {
// Parse the request body as JSON
const sig = ctx.request.headers.get('stripe-signature');
const body = await ctx.request.body({ type: "text" }).value;
event = await stripe.webhooks.constructEvent(body, sig!, endpointSecret);
} catch (err) {
ctx.response.status = 400;
console.log('Error : ' + err.message);
}
// Handle the event
switch (event.type) {
case 'invoice.paid':
const invoicePaid = event.data.object;
console.log('invoice url : ' + invoicePaid.hosted_invoice_url);
invoicePdf.push(invoicePaid.hosted_invoice_url);
// Then define and call a function to handle the event invoice.paid
break;
case 'charge.updated':
const updatedcharge = event.data.object;
console.log('receipt url : ' + updatedcharge.receipt_url);
receiptUrlArray.push(updatedcharge.receipt_url);
// ... handle other event types
break;
default:
console.log(`Unhandled event type ${event.type}`);
}
ctx.response.status = 200;
} else {
ctx.response.status = 400;
}
}
我在控制台中得到 switch 默认情况,它返回“未处理的事件类型 customer.created”。之后,在我的代码流中,代码被阻止,所以我无法到达我想监听的事件。但是,我在 CLI 中仍然收到此事件的 200 响应,在我的仪表板中也是如此。
为什么此时代码执行被阻塞?它阻止结帐会话的创建以及其余事件的发生,这是主框架:
const customer = await stripe.customers.create({
name: 'bla',
email: 'balbla',
description: 'bla',
});
console.log('customer created ! ');
const lineItems = [];
for (let i = 0; i < labelProduitsArray.length; i++) {
console.log(`Turn in the loop ${i}`);
lineItems.push({
price_data: {
currency: 'eur',
product_data: {
name: labelProduitsArray[i],
},
unit_amount: 300,
},
quantity: quantityProduitsArray[i],
},);
}
console.log(lineItems);
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: lineItems,
mode: 'payment',
success_url: 'http://localhost:80/OBV/success',
cancel_url: 'http://localhost:80/OBV/cancel',
invoice_creation: {
enabled: true,
},
shipping_options: [
{
shipping_rate_data:{
type: 'fixed_amount',
fixed_amount:{
amount: shipping_rate,
currency: 'eur'
}
},
display_name: carrier_service_name,
delivery_estimate:{
minimum:{
unit: 'hour',
value: 48
},
maximum:{
unit: 'hour',
value: 72
}
}
}
]
});
console.log(' -- Im Here -- ');
ctx.response.status = 303;
ctx.response.redirect(session.url);
最后这是控制台结果,停留在 console.log(lineItems):
好吧,我找到了一个解决方案,虽然看起来很奇怪,但我不知道它是否来自使用 webhooks + 本地测试,问题来自于重定向到结账页面的按钮。
此按钮没有使用 href 直接重定向到结帐页面,而是重定向到一个函数端点,我们将其称为“first func”,它对数据执行一些操作,然后重定向到最终呈现结帐页面的结帐函数.
这项工作是在服务器端完成的。通过向按钮提供 href 并直接指向结帐端点功能,我能够访问结帐页面,但我在 webhooks 显示 404 错误时遇到了一些麻烦。
因此,我必须让用“first func”编写的重定向语句指向结帐功能,就像最初完成的那样,但同时在按钮上提供指向结帐页面的直接链接。
它有效,我现在可以检索我想要的所有数据。但两次重定向到同一页面并不直观......
我也收到此消息:[未捕获的应用程序错误]:Http - 连接在消息完成之前关闭
但我认为这一切都是由于测试环境+本地主机,我会看到...