我目前有一个谷歌云功能(如下),它从条带支付接收 webhook 并将其中一些数据写入 firestore。然而我的问题是它似乎挂起大约 3 分钟并最终完成。
const Stripe = require("stripe");
const admin = require("firebase-admin");
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: "2023-10-16",
});
if (admin.apps.length === 0) {
admin.initializeApp();
}
const db = admin.firestore();
async function webhook(request, response) {
const sig = request.headers["stripe-signature"];
let event;
try {
event = stripe.webhooks.constructEvent(
request.rawBody,
sig,
process.env.WEBHOOK_SECRET
);
} catch (err) {
console.error("⚠️ Webhook signature verification failed.", err.message);
return response.status(400).send(`Webhook Error: ${err.message}`);
}
switch (event.type) {
case "checkout.session.completed":
handlepaymentCompletion(event.data.object);
break;
default:
// Unexpected event type
return response.status(400).end();
}
// Return a response to acknowledge receipt of the event
response.json({ received: true });
}
// handle sub created
async function handlepaymentCompletion(payment) {
try {
const lineItems = await stripe.checkout.sessions.listLineItems(
payment?.id,
{
limit: 100,
}
);
console.log(lineItems.data);
// // Transform line items data
// const itemsToSave = lineItems.data.map((item) => ({
// amount: item.amount_total,
// currency: item.currency,
// description: item.description,
// active: item.price.active,
// created: item.price.created,
// product: item.price.product,
// }));
/// Assuming there's only one item
const item = lineItems.data[0];
// Construct the data object for Firestore
const data = {
amount: item.amount_total,
currency: item.currency,
description: item.description,
active: item.price.active,
created: payment.created,
product: item.price.product,
paymentIntentId: payment.payment_intent,
};
const customer_id = payment.customer;
// Query for the client document with the matching `stripeCusId`
const clientQuerySnapshot = await db
.collection("productionClients")
.where("stripeCustId", "==", customer_id)
.get();
if (!clientQuerySnapshot.empty) {
const clientId = clientQuerySnapshot.docs[0].id;
// Reference to the invoicePayments sub-collection
const invoicePaymentsRef = db
.collection("productionClients")
.doc(clientId)
.collection("invoicePayments");
// Example: Here's how you could add a new invoice payment document
invoicePaymentsRef.add(data);
console.log("Invoice payment updated successfully.");
} else {
console.log("No client found with the specified Stripe customer ID.");
}
} catch (error) {
console.error("Error updating user:", error);
// Optionally handle the error
}
}
module.exports = webhook;
我添加了额外的日志记录,看起来挂起的地方是查询与条带中的 customer_id 匹配的客户端文档。
该集合中有 4 个项目,因此无论如何它都不是一个大集合或索引问题。
我看不出还有什么其他问题。
任何人都可以阐明吗?
你错过了
await
add()
返回的承诺:
await invoicePaymentsRef.add(data);
在函数返回之前,所有承诺或其他异步工作都必须等待或以某种方式完全解决,否则您将得到像这样无法解释的行为。
参见: