gpt4 book ai didi

python - Stripe 不在 Python 中抛出充电错误

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:15 27 4
gpt4 key购买 nike

我正在使用 Python 中的 stripe 库进行信用卡收费。我将 customerID 用于收费目的而不是 token ,因为我想重新使用该卡而不需要每次都询问它。成功过程工作得很好,但是,如果我创建错误条件,则永远不会抛出“except”。我正在使用无效的客户 ID 测试失败状态。

服务器日志显示以下错误:“InvalidRequestError: Request req_8949iJfEmeX39p: No such customer: 22”,但这同样没有在 try/except 中处理。

class ChargeCustomerCard(webapp2.RequestHandler):
def post(self):
stripe.api_key = stripeApiKey
customerID = self.request.get("cust")
amount = self.request.get("amt")

try:
charge = stripe.Charge.create(amount=int(amount),currency="usd",customer=customerID,description=customerID)
except stripe.error.CardError, e:
output = {"result":e}
else:
output = {"result":"1"}

self.response.out.write(json.dumps(output))

最佳答案

根据 https://stripe.com/docs/api?lang=python#errors您没有处理 strip 库提供的所有可能的错误/异常。处理财务数据理应更加谨慎,因此您确实至少需要做以下事情:

class ChargeCustomerCard(webapp2.RequestHandler):
def post(self):
stripe.api_key = stripeApiKey
customerID = self.request.get("cust")
amount = self.request.get("amt")

try:
charge = stripe.Charge.create(amount=int(amount),currency="usd",customer=customerID,description=customerID)
except stripe.error.CardError, e:
output = {"result":e}
except Exception as e:
# handle this e, which could be stripe related, or more generic
pass
else:
output = {"result":"1"}

self.response.out.write(json.dumps(output))

或者甚至基于官方文档,更全面的文档如下:

try:
# Use Stripe's library to make requests...
pass
except stripe.error.CardError, e:
# Since it's a decline, stripe.error.CardError will be caught
body = e.json_body
err = body['error']

print "Status is: %s" % e.http_status
print "Type is: %s" % err['type']
print "Code is: %s" % err['code']
# param is '' in this case
print "Param is: %s" % err['param']
print "Message is: %s" % err['message']
except stripe.error.RateLimitError, e:
# Too many requests made to the API too quickly
pass
except stripe.error.InvalidRequestError, e:
# Invalid parameters were supplied to Stripe's API
pass
except stripe.error.AuthenticationError, e:
# Authentication with Stripe's API failed
# (maybe you changed API keys recently)
pass
except stripe.error.APIConnectionError, e:
# Network communication with Stripe failed
pass
except stripe.error.StripeError, e:
# Display a very generic error to the user, and maybe send
# yourself an email
pass
except Exception, e:
# Something else happened, completely unrelated to Stripe
pass

关于python - Stripe 不在 Python 中抛出充电错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36213823/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com