创建条纹订阅Python

时间:2019-05-21 16:06:23

标签: python django stripe-payments

我正在尝试创建条带订阅,然后向客户收取该订阅的费用。我的条纹交易在仪表板中显示为“未完成”,因为未付款。

前端正在使用预制的条纹信用卡表单成功地使用stripe.js创建令牌,但是我不确定用于创建订阅和收费的后端python代码是否正确。

订阅应立即收费:

  

“ collection_method”:“自动收费”,

...
    if request.method == "POST":
        try:
            token = request.POST['stripeToken']

            #Create Stripe Subscription Charge
            subscription = stripe.Subscription.create(
              customer=user_membership.stripe_customer_id,
              items=[
                {
                  "plan": selected_membership.stripe_plan_id,
                },
              ],
            )

            #Charge Stripe Subscription
            charge = stripe.Charge.create(
              amount=selected_membership.stripe_price,
              currency="usd",
              source=token, # obtained with Stripe.js
              description=selected_membership.description,
              receipt_email=email,
            )

            return redirect(reverse('memberships:update_transactions',
                kwargs={
                    'subscription_id': subscription.id
                }))

        except stripe.error.CardError as e:
            messages.info(request, "Oops, your card has been declined")

...

1 个答案:

答案 0 :(得分:1)

听起来您的客户没有附属卡,因此在创建订阅时不会支付订阅费用!

如果您已经创建了客户,则应该执行以下操作:

# add the token to the customer
# https://stripe.com/docs/api/customers/update?lang=python

stripe.Customer.modify(
  user_membership.stripe_customer_id, # cus_xxxyyyyz
  source=token # tok_xxxx or src_xxxyyy
)

# create the subscription

subscription = stripe.Subscription.create(
 customer=user_membership.stripe_customer_id,
 items=[
 {
   "plan": selected_membership.stripe_plan_id,
 },
])

# no need for a stripe.Charge.create, as stripe.Subscription.create will bill the subscription
相关问题