且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

条纹不会在 Python 中引发充电错误

更新时间:2023-11-12 11:52:34

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

According to https://stripe.com/docs/api?lang=python#errors you're not handling all the possible errors/exceptions that the stripe library supplies. And dealing with financial data rightfully deserves even more caution so you really need to do at least something like:

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))

或者甚至基于官方文档,一个更全面的像:

Or even based on the official documentation, a more comprehensive one like:

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