首页 > 解决方案 > 条带源创建失败

问题描述

我看到一个与 Stripe 相关的奇怪错误,因为我无法使用我的实时 API 密钥创建源。

  1. 在我的应用程序中创建客户后,在 Stripe 上创建了一个客户(即实时 API 密钥正在工作)

  2. 使用测试Stripe API 密钥时,我可以添加卡片并进行收费

  3. 当我在我的网站上使用我的实时API 密钥时,即使我将有效的源传递给函数,customer.sources.create() 调用也会失败。

     stripe_customer_id = cus_IoiFADFAADFASDF (made up value for this post, but is a valid one in my environment that has been generated by Stripe)
    
     source = src_1ILfdf3asdfasdfasdfadsf (made up value for this post, but is a valid one in my environment that has been generated by Stripe)
    
     customer = stripe.Customer.retrieve(stripe_customer_id)
    
     stripe_card_response = customer.sources.create(source=source) #THIS IS THE LINE OF CODE THAT FAILS
    

我已经确认我传递给这些函数的 stripe_customer_id 和源变量已被填充。它们填充了从 Stripe 发送给我的值。

不幸的是,Stripe 不会返回任何可识别的错误。换句话说,当我在我的代码中经历以下异常时,只有最后一个被命中,这是一个通用的全部捕获。

except stripe.error.CardError as e:
except stripe.error.RateLimitError as e:
except stripe.error.InvalidRequestError as e:
except stripe.error.AuthenticationError as e:
except stripe.error.APIConnectionError as e:
except stripe.error.StripeError as e:
except Exception as e: #this is where the error falls as it doesn't relate to any of the others

500 错误返回以下内容

    raise AttributeError(*err.args)
AttributeError: sources

谢谢你的帮助!

标签: pythonstripe-payments

解决方案


问题是,当您检索客户时,默认情况下不会返回其来源

如果您在检索客户时扩展请求,您的代码应该可以按预期工作:

customer = stripe.Customer.retrieve(stripe_customer_id,
  expand=['sources']
)

stripe_card_response = customer.sources.create(source=source)

“检索、就地变异然后保存”模式是 Stripe 正在远离的一种模式,转而支持客户服务。相反,您可以执行以下操作,这意味着您无需检索客户并免于扩展sources

source = stripe.Customer.create_source(
  stripe_customer_id
  source=source
)

推荐阅读