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

如何通过Stripe API识别用户的默认支付卡片?

解决Stripe API识别用户默认支付卡片的问题

先修正当前代码的核心问题

你现在的addCard方法仅取回了Token信息,但没有将卡片关联到对应Stripe Customer账户——这是后续管理卡片、识别默认的前提。必须先把Token绑定到Customer,客户名下才会有可管理的卡片列表。

修正后的添加卡片代码

async addCard(req: Request, token: string) {
  // 获取当前用户对应的Stripe Customer
  const customer = await this.getCardCustomer(req.user);
  
  // 将Token对应的卡片添加到该Customer名下
  const addedCard = await stripe.customers.createSource(customer.id, {
    source: token
  });

  // 可选:如果要将新卡片设为默认支付方式,添加以下代码
  await stripe.customers.update(customer.id, {
    invoice_settings: {
      default_payment_method: addedCard.id
    }
  });

  return addedCard;
}

识别默认卡片的实现思路

调用stripe.customers.retrieve获取客户详情时,客户对象的invoice_settings.default_payment_method字段存储着默认支付方式的ID。只需将卡片列表中的每个卡片ID与这个默认ID对比,就能标记出默认卡片。

修正后的获取卡片并识别默认的代码

async getCards(req: Request) {
  const customer = await this.getCardCustomer(req.user);
  
  // 调用retrieve时展开关联的支付方式,确保拿到完整卡片列表
  const customerDetails = await stripe.customers.retrieve(customer.id, {
    expand: ['sources.data'] // 旧版Sources API用这个;新版Payment Methods换成'payment_methods.data'
  });

  // 获取默认支付方式ID
  const defaultPaymentId = customerDetails.invoice_settings.default_payment_method;

  // 整理卡片数据,同时标记默认卡片
  const cardList = (customerDetails.sources.data || []).map(card => ({
    id: card.id,
    brand: card.brand,
    last4: card.last4,
    expMonth: card.exp_month,
    expYear: card.exp_year,
    isDefault: card.id === defaultPaymentId // 核心判断逻辑
  }));

  return {
    cards: cardList,
    defaultPaymentId: defaultPaymentId
  };
}

额外说明(推荐新规范)

Stripe目前推荐使用Payment Methods API替代旧的Sources API,新项目建议调整实现:

  1. 前端用Stripe的Payment Element或Card Element直接创建PaymentMethod,而非Token
  2. 后端通过stripe.paymentMethods.attach将PaymentMethod关联到Customer
  3. 识别默认的逻辑一致:依然通过customer.invoice_settings.default_payment_method匹配ID

对于Apple Pay支付方式,在PaymentMethod对象中card.wallet.type会显示为apple_pay,可用来区分普通信用卡和Apple Pay支付方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:20:17