You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Stripe CheckoutSession中自动设置客户的default_payment_method?

在Stripe CheckoutSession创建时自动设置默认支付方式

问题描述

我正在尝试为Stripe客户设置默认支付方式,想确认是否可以在创建CheckoutSession的过程中自动设置default_payment_method。目前使用的CheckoutForm代码如下:

import { addDoc, doc, onSnapshot, collection, setDoc } from "firebase/firestore"; 
import { httpsCallable } from "firebase/functions";
import { auth, firestore, functions } from "../../firebase";
import { getStripe } from "./initializeStripe";

export async function createCheckoutSession(uid) {

  const stripePK = await getStripe();
  
  const docRef = await addDoc(collection(firestore, "customers", `${uid}`, "checkout_sessions"), {
    price: "price_12431",
    success_url: window.location.origin,
    cancel_url: window.location.origin,
  })

  // 等待扩展将CheckoutSession关联到文档
  onSnapshot(doc(firestore, "customers", `${uid}`, "checkout_sessions", docRef.id), (doc) => {
    const { sessionId } = doc.data();
    if(sessionId) stripePK.redirectToCheckout({sessionId: sessionId});
  });
}

我想要修改的是客户详情页中的「默认支付方式」字段(该字段支持手动选择已保存的支付方式)。

解决方案

可以实现自动设置,需要结合Stripe配置与Firebase扩展逻辑调整,具体步骤如下:

  • 启用支付方式保存
    在创建CheckoutSession的Firestore文档中,添加payment_intent_data.setup_future_usage字段,用户完成支付后,支付方式会自动保存到对应Stripe客户名下。修改后的代码示例:

    const docRef = await addDoc(collection(firestore, "customers", `${uid}`, "checkout_sessions"), {
      price: "price_12431",
      success_url: window.location.origin,
      cancel_url: window.location.origin,
      // 配置保存支付方式
      payment_intent_data: {
        setup_future_usage: "on_session" // 可选值:on_session(用户在场时复用)/ off_session(自动扣费)
      }
    })
    
  • 自动设为默认支付方式

    • 首次保存支付方式:Stripe默认会将用户首次通过Checkout保存的支付方式设为客户的默认支付方式,无需额外配置。
    • 后续支付场景:如果需要将后续使用的支付方式更新为默认,可通过监听Checkout完成事件实现。示例Firebase云函数代码:
    const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
    
    exports.updateDefaultPaymentMethod = functions.firestore
      .document('customers/{uid}/checkout_sessions/{sessionId}')
      .onUpdate(async (change, context) => {
        const session = change.after.data();
        // 仅在会话完成且关联支付意向时执行
        if (session.status === 'completed' && session.payment_intent) {
          const paymentIntent = await stripe.paymentIntents.retrieve(session.payment_intent);
          // 更新客户默认支付方式
          await stripe.customers.update(session.customer, {
            default_payment_method: paymentIntent.payment_method
          });
        }
      });
    
  • 关键注意事项

    • 确保Firebase扩展已正确关联用户与Stripe客户(通常扩展会自动完成此映射)。
    • 根据业务场景选择setup_future_usage的取值:on_session适用于需要用户确认的后续支付,off_session适用于订阅自动扣费等无需用户在场的场景。
    • 测试时使用Stripe提供的测试卡号(如4242 4242 4242 4242),确保支付流程正常完成。

内容的提问来源于stack exchange,提问作者Maksym Davydov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 15:20:25