[英]How to use firebase cloud function to create Stripe customer
大家好,我是Stripe的新手,所以我有一個關於如何通過Firebase雲功能創建Stripe客戶的問題。 我已經閱讀了Stripe標准集成和一些教程。 本示例教您如何設置Firebase雲功能。 問題在於,無論何時處理費用或輸入金額,該示例都會創建客戶。 Stripe文檔說,可以創建沒有付款信息的客戶用戶。 所以我的想法是,每當我為Firebase創建用戶時,我都會觸發雲功能來同時創建條帶化客戶。 誰能教我如何正確執行此操作,並且還可以向我展示如何更新綁定到該客戶的付款信息。 非常感謝你。
這實際上是一個分為兩部分的問題,但是我認為這比您想象的要容易得多。 這是有關如何解決打字稿中問題的一些指導。
創建客戶
要創建客戶,請通過create-auth-trigger執行以下操作:
export const syncUserToStripe = functions.auth.user().onCreate(async (data, context) =>
const stripe = new Stripe(<stripe-token>); // Initialize the stripe SDK
const stripeCustomer = await stripe.customers.create({
email: data.email
}); // Now you have the stripe customer. Maybe you would like to save the stripeCustomer Id to database/firestore
console.log(`Done syncing firestore user with id: ${data.uid} to Stripe. The stripe id is ${stripeCustomer.id}`);
);
更新付款信息
更新付款是兩步走的火箭。 首先,您需要從客戶端收集數據條令牌。 這很容易通過stripe中的checkout.js
東西來獲得(讓我們安全地收集信用卡)。 實際的實現很容易,但是根據您的前端框架而有所不同。 重要的部分是,一旦有了令牌,就可以在后端更新付款信息,即雲https函數(當您擁有條帶令牌時調用此函數)。代碼的重要部分如下所示:
export async function updateStripePayment(req: Request, res: Response): Promise<any> {
const stripe = new Stripe(<stripe-token>); // Initialize the stripe SDK
// Extract the stripe token from the header
const stripeToken = req.header('StripeToken');
// You also need to get the stripe customer id. Here I will get it from the header, but maybe it makes more sense for you to read it from firestore/realtime db.
const stripeCustomerId = req.header('stripeCustomerId');
// Now you can create a new payment source
const newSource = await stripeAPI.customers.createSource(stripeCustomerId, {source: stripeToken});
// And you can now optionally set it as default
await stripeAPI.customers.update(stripeCustomerId, {default_source: newSource.id});
res.status(200).json(`Sucessfully updated stripe payment info`);
}
一般注意事項
try catch
來捕獲意外錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.