在 django/python 中创建条带电荷的正确方法

Emm*_*osu 3 python django stripe-payments

我目前正在将 Stripe 集成到 django 项目中。我使用代码示例遵循了stripe 网站上的教程,但我不确定它们是否已准备好生产。这是应用程序中最微妙的部分,我想确保它做得对。目前,我有一些与此类似的东西。

if new_order_form.is_valid():
    new_order = new_order_form.save(commit=False)
    new_order.total = 10
    new_order.order_number = generate_order_number(8)
    try:
      charge = stripe.Charge.create(
          amount=1000, # new_order.total * 100
          currency="usd",
          source=token,
          description="Example charge"
      )
      new_order.charge_id = charge.id
    except stripe.error.CardError, e:
      # The card has been declined
      pass

    new_order.save()
    return HttpResponseRedirect('/thanks/')
return redirect(request, 'new_order.html' context)
Run Code Online (Sandbox Code Playgroud)

编辑: 我的担忧是:

  • 会不会有卡被收取两次费用的情况?
  • 是否会出现订单创建并保存
    但收费不成功的情况?
  • 应该在哪里创建和保存订单?

小智 5

这是我们在项目中使用的内容,希望对您有所帮助!!

try:
    charge = stripe.Charge.create(
      amount={{amount}}, 
      currency="usd",
      customer={{customer}},
      description={{description}},
      metadata={{this.id}}
  )
except stripe.error.CardError as e:
    # Problem with the card
    pass
except stripe.error.RateLimitError as e:
    # Too many requests made to the API too quickly
    pass
except stripe.error.InvalidRequestError as e:
    # Invalid parameters were supplied to Stripe API
    pass
except stripe.error.AuthenticationError as e:
    # Authentication Error: Authentication with Stripe API failed (maybe you changed API keys recently)
    pass
except stripe.error.APIConnectionError as e:
    # Network communication with Stripe failed
    pass
except stripe.error.StripeError as e:
    # Stripe Error
    pass
else:
    #success
Run Code Online (Sandbox Code Playgroud)