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

ASP.NET Core中Stripe创建客户后获取Source信息及后台自动扣款问题

问题解答:Stripe客户支付方式获取与自动扣款实现

一、获取客户的支付方式信息

你通过Checkout创建客户后,customer.Source返回null是因为Stripe当前推荐使用Payment Methods API(替代旧的Source API),Checkout会将支付方式附加为PaymentMethod而非Source,且默认获取客户时不会返回支付方式列表,需要通过扩展字段获取:

代码示例:获取客户的PaymentMethod

var customerService = new CustomerService();
var customer = customerService.Get(session.CustomerId, new CustomerGetOptions
{
    // 扩展获取支付方式数据
    Expand = new List<string> { "payment_methods.data" }
});

// 遍历客户的支付方式
foreach (var paymentMethod in customer.PaymentMethods.Data)
{
    if (paymentMethod.Card != null)
    {
        // 卡片后四位
        string last4 = paymentMethod.Card.Last4;
        // PaymentMethod唯一标识(格式为pm_xxx)
        string paymentMethodId = paymentMethod.Id;
    }
}

注:tok_visa这类是临时支付令牌,仅在创建支付方式时使用,Checkout完成后会将令牌转换为绑定到客户的PaymentMethod(pm_开头),这才是长期可用的支付方式标识。

二、自动扣款的可行性与实现

自动扣款完全可行,但不建议使用Charge API手动实现,推荐使用Stripe的Subscription(订阅)API,它内置了自动周期扣款、支付失败重试、账单管理等功能,无需手动处理复杂逻辑。

方案1:使用Subscription API实现月付自动扣款

1. 创建月付计划(可在Stripe后台创建或代码创建)

var planService = new PlanService();
var monthlyPlan = planService.Create(new PlanCreateOptions
{
    Amount = amount, // 金额(单位:分,如1000代表$10)
    Currency = "usd",
    Interval = "month", // 周期为月
    Product = new PlanProductOptions { Name = "月度会员" }
});

2. 为客户创建订阅

var subscriptionService = new SubscriptionService();
var subscription = subscriptionService.Create(new SubscriptionCreateOptions
{
    Customer = customerId,
    Items = new List<SubscriptionItemOptions>
    {
        new SubscriptionItemOptions { Plan = monthlyPlan.Id }
    },
    // 处理支付失败:若首次扣款失败,订阅标记为待完成,可后续提醒客户支付
    PaymentBehavior = "default_incomplete"
});

创建后Stripe会自动按每月周期扣款,处理重试、发送账单通知等操作。

方案2:使用Charge API手动扣款(不推荐)

若坚持使用Charge API,无需填充Source字段,只需指定CustomerId,Stripe会自动使用客户的默认支付方式扣款;也可指定具体的PaymentMethodId:

var chargeOptions = new ChargeCreateOptions
{
    Customer = customerId,
    Amount = amount,
    Currency = "usd",
    // 可选:指定具体PaymentMethod(若客户有多个支付方式)
    // PaymentMethod = "pm_xxxxxx", 
    Description = "手动月度扣款"
};

var chargeService = new ChargeService();
var charge = chargeService.Create(chargeOptions);

此方式需自行处理支付失败重试、周期调度等逻辑,维护成本较高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 08:43:38