如何在C#中从Stripe Subscription对象获取ProductID及产品信息
C# 从Stripe Subscription对象提取ProductID实现方案
Stripe Subscription对象本身不直接存储ProductID,关联层级为:Subscription -> Items订阅条目集合 -> 单个订阅条目 -> Price价格对象 -> ProductId。
基础实现代码
你现有逻辑获取到订阅对象后,按以下方式取值即可:
// 现有获取订阅的逻辑 var service = new SubscriptionService(); var subscription = service.Get(subscriptionID); // 单产品订阅场景(绝大多数场景默认一个订阅仅关联一个产品):取首个条目的关联ProductID string productId = subscription.Items.FirstOrDefault()?.Price.ProductId; // 多产品订阅场景:提取所有关联的ProductID List<string> allProductIds = subscription.Items .Select(item => item.Price.ProductId) .Where(id => !string.IsNullOrEmpty(id)) .ToList();
常见空值问题处理
如果运行时取到的Price为null,是因为Stripe API默认不会返回嵌套关联对象的完整字段,你需要在调用Get方法时主动指定展开关联字段:
var service = new SubscriptionService(); // 配置展开参数,主动获取订阅条目下的Price对象完整属性 var getOptions = new SubscriptionGetOptions(); getOptions.AddExpand("items.data.price"); var subscription = service.Get(subscriptionID, getOptions); // 再按上述逻辑取ProductID即可 string productId = subscription.Items.FirstOrDefault()?.Price.ProductId;
注意事项
- 请确保你使用的
Stripe.netSDK为最新稳定版本,旧版本字段命名规则可能存在差异 - 如果你的业务允许一个订阅绑定多个产品,不要直接取首个条目,建议遍历所有
Items收集全量ProductID
内容的提问来源于stack exchange,提问作者TampaSportsLover
相关产品推荐
相关产品推荐

