如何从Stripe Setup模式会话中获取用户支付方式?
问题
已知Stripe Checkout的Session ID,会话采用setup模式且表单已嵌入页面,如何获取用户输入的支付方式?
已编写如下代码:
// Get the session object Stripe.Checkout.SessionService sessionService = new(); Stripe.Checkout.Session session = await sessionService.GetAsync(id);
根据Stripe官方文档,需从Session对象中获取setup_intent键值(即会话创建的SetupIntent ID),但Stripe.Checkout.Session类无setup-intent属性,仅有的SetupIntent属性为对象且值为null。求该场景下的实现示例。
解决方案
问题出在默认调用GetAsync时,Stripe.NET不会自动展开关联的SetupIntent对象,必须在请求中指定扩展字段来获取完整的关联资源。
具体实现步骤及代码示例如下:
- 构建
SessionGetOptions实例,添加Expand参数指定要展开的字段为setup_intent - 将该选项传入
GetAsync方法,获取包含完整SetupIntent数据的Session对象 - 通过
session.SetupIntent拿到SetupIntent实例,从中提取支付方式ID,再进一步获取支付方式详情
// 创建Session获取选项,指定展开setup_intent字段 var getOptions = new Stripe.Checkout.SessionGetOptions { Expand = new List<string> { "setup_intent" } }; // 带选项请求Session数据 var sessionService = new Stripe.Checkout.SessionService(); var session = await sessionService.GetAsync(id, getOptions); // 提取支付方式信息 if (session.SetupIntent != null && !string.IsNullOrEmpty(session.SetupIntent.PaymentMethodId)) { string paymentMethodId = session.SetupIntent.PaymentMethodId; // 获取完整支付方式详情 var paymentMethodService = new Stripe.PaymentMethodService(); var paymentMethod = await paymentMethodService.GetAsync(paymentMethodId); // 示例:提取卡片后四位、品牌信息 string cardLast4 = paymentMethod.Card.Last4; string cardBrand = paymentMethod.Card.Brand; }
关键说明
- Stripe API默认仅返回顶层资源的基础字段,关联的子资源需要通过
Expand参数主动请求展开 - 指定
Expand = new List<string> { "setup_intent" }后,Stripe会返回完整的SetupIntent对象,此时session.SetupIntent不再为null - 拿到
PaymentMethodId后,可通过PaymentMethodService获取支付方式的详细信息,用于后续业务逻辑处理
内容的提问来源于stack exchange,提问作者Jonathan Wood
相关产品推荐
相关产品推荐

