【发布时间】:2020-11-01 07:00:19
【问题描述】:
我将用户存储在 firebase 实时数据库和条带中以处理付款。经过身份验证的用户可以单击一个按钮,并将被重定向到 Stripe Checkout。付款后,用户会被重定向到应用程序中的success_url。接下来我想更新数据库中的用户对象 - 只需保存支付成功的信息及其 id。
问题:重定向到success_url后,我不知道如何找到完成付款的用户。我想在付款后更新数据库中的用户数据。
想法:我可以将payment_intent 保存在用户配置文件中,因为此信息通过会话发送到客户端。然后,付款完成后,我可以搜索payment_intent 并更新拥有此数据的用户。但这是一个好方法吗?有没有更好的方法找到用户?
我的代码基于 Firebase Cloud Function HTTP 请求。 在 Stripe guidelines 接受付款之后,我为想要付款的用户创建了一个会话:
export const payment = functions.https.onRequest((request, response) => {
cors(request, response, async () => {
response.set("Access-Control-Allow-Headers", "Content-Type");
response.set("Access-Control-Allow-Credentials", "true");
response.set("Access-Control-Allow-Origin", "*");
await stripe.checkout.sessions.create(
{
payment_method_types: ["card"],
line_items: [
{
price_data: {
currency: "usd",
product_data: {
name: "Test"
},
unit_amount: 1000
},
quantity: 1
}
],
mode: "payment",
success_url: "https://example.com/success",
cancel_url: "https://example.com/cancel"
},
function(err: Error, session: any) {
response.send(session);
// the session is sent to the client and can be used to finalise a transaction
}
);
});
});
在客户端,我使用 axios 调用 payment 云函数请求,然后将 sessionId 传递给 Stripe.redirectToCheckout,这将启动结帐重定向:
let sessionId = "";
await axios.post("payment function url request")
.then(response => {
sessionId = response.data.id;
});
const stripe: any = await loadStripe("stripe key");
stripe.redirectToCheckout({
sessionId: sessionId
});
客户在 Stripe Checkout 上完成付款后,会被重定向到指定为 success_url 的 URL,建议在结帐完成时从 stripe 运行 webhook。
它允许触发另一个云功能,该功能向客户端发送有关付款成功的响应response.json({ received: true }):
export const successfulPayment = functions.https.onRequest(
(request, response) => {
const sig = request.headers["stripe-signature"];
let event;
try {
event = stripe.webhooks.constructEvent(
request.rawBody,
sig,
endpointSecret
);
} catch (err) {
return response.status(400).send(`Webhook Error: ${err.message}`);
}
// Handle the checkout.session.completed event
// Should I update the user data in the database here?
if (event.type === "checkout.session.completed") {
const session = event.data.object;
console.log(`Event passed: ${session}`);
}
// Return a response to acknowledge receipt of the event
response.json({ received: true });
// Or how do I use this response to then update the user from the client side?
}
);
我将非常感谢所有的帮助和建议 :)
【问题讨论】:
标签: javascript firebase firebase-realtime-database stripe-payments