调用Stripe API时出现KeyError与AttributeError问题求助
解决Stripe API访问Customer扩展属性报错的问题
问题原因
Stripe API默认返回的Customer对象仅包含核心基础属性,文档中「More attributes」下列出的subscriptions、cash_balance、tax等属于关联资源或可选返回字段,不会在默认的Customer.retrieve请求中返回。Python SDK返回的对象是动态映射API响应的,只有实际返回的字段才能通过属性访问,未返回的字段直接访问就会触发KeyError或AttributeError。
解决方案
方案1:使用expand参数主动展开属性
在调用Customer.retrieve时,通过expand参数指定需要一并返回的扩展属性,这样就能直接访问这些字段:
import stripe import os from flask import ... stripe.api_key = os.environ['STRIPE_KEY'] # 展开需要的属性 customer = stripe.Customer.retrieve( 'cus_*******', expand=['subscriptions', 'cash_balance', 'tax'] ) # 现在可以正常访问这些属性 print(customer.subscriptions) print(customer.cash_balance) print(customer.tax.location)
方案2:单独调用对应API获取关联资源
如果只需要某一类关联资源(比如订阅),可以直接调用对应的列表API,更灵活:
# 获取指定客户的所有订阅 subscriptions = stripe.Subscription.list(customer='cus_*******') print(subscriptions)
补充说明
- Stripe的API设计遵循按需返回原则,避免不必要的数据传输,所以非核心字段需要主动请求。
- 可以通过
print(dict(customer))查看API响应的原始数据,确认哪些字段实际被返回,避免访问不存在的属性。
内容的提问来源于stack exchange,提问作者Krabs
相关产品推荐
相关产品推荐

