简体   繁体   English

使用 Stripe 和 Django 进行定期付款

[英]Recurring payments using Stripe and Django

I'm still pretty new to Django and am trying to set up recurring payments via Stripe.我对 Django 还是很陌生,我正在尝试通过 Stripe 设置定期付款。 I'm using Django 2.0 and have successfully set up a single charge test case.我正在使用 Django 2.0 并成功设置了单次充电测试用例。 However, I'm unfamiliar with how to create recurring payments, and require it for the project I'm working on.但是,我不熟悉如何创建定期付款,并且我正在从事的项目需要它。

For the single payment, I have the following:对于单笔付款,我有以下内容:

Views观点

stripe.api_key = settings.STRIPE_SECRET_KEY

def checkout(request):
    """Stripe check out"""

    new_tier = models.PaymentTier(
        level = "Tier 3",
        year = 2018
    )

    if request.method == "POST":
        token = request.POST.get("stripeToken")
    try:
        charge = stripe.Charge.create(
            amount = 2000,
            currency = "usd",
            source = token,
            description = "Tier 3 subscription for Elite Fitness"
        )

        new_tier.charge_id = charge.id

    except stripe.error.CardError as ce:
        return False, ce

    else:
        new_tier.save()
        return redirect("thank_you_page")



def payment_form(request):
    """Render stripe payment form template"""

    context = {"stripe_key": settings.STRIPE_PUBLIC_KEY}
    return render(request, "stripe-template.html", context)




def thank_you_page(request):
    """Successful payment processed"""

    return render(request,'thank_you_page.html')

stripe-template.html条纹模板.html

<form action="checkout/" method="POST"> {% csrf_token %}
    <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
        data-key={{stripe_key}} # Make sure to wrap the variable name with double {}
        data-amount="2000"
        data-name="company name here"
        data-description="Elite Fitness Subscription"
        data-image="picture.png"
        data-currency="usd">
    </script>
</form>

I've had a difficult time finding anything online which covers recurring payments specifically.我很难在网上找到任何专门涵盖定期付款的内容。 If anybody knows how to set them up (even through dj-stripe or pinax ) any help will be very greatly appreciated.如果有人知道如何设置它们(即使通过dj-stripepinax ),我们将不胜感激。

You should take a look at the Billing Quickstart -documentation.您应该查看Billing Quickstart文档。 It outlines step by step how to setup a subscription (or recurring payment).它逐步概述了如何设置订阅(或定期付款)。 The gist of it is, you first create a product , then create a plan with that product, create a customer for whom you want to bill repeatedly, then attach that plan as a subscription to the customer.它的要点是,您首先创建一个产品,然后使用该产品创建一个计划创建一个您想要重复计费的客户,然后将该计划作为订阅附加到该客户。

您需要创建一个计划,指定经常性付款价格和持续时间,然后使用订阅在计划中注册您的 Stripe 客户。

As of 2020 it's actually recommended to use PaymentIntents for this.从 2020 年开始,实际上建议为此使用PaymentIntents Stripe has an excellent guide for how to do this in their docs now that walks through the whole flow and covers things like 3D-secure as well.现在,Stripe 在他们的文档中对如何执行此操作提供了出色的指南,其中介绍了整个流程并涵盖了 3D 安全等内容。

For a longer treatment on the topic specific to Django, see this article: How to Create a Subscription SaaS Application with Django and Stripe有关特定于 Django 的主题的详细说明,请参阅此文章:如何使用 Django 和 Stripe 创建订阅 SaaS 应用程序

In 2022 I would suggest using the latest Stripe Checkout and Stripe Checkout session API .在 2022 年,我建议使用最新的Stripe CheckoutStripe Checkout session API In your view you can create a new checkout session, and redirect straight to it (no JS required).在您看来,您可以创建一个新的结帐 session,并直接重定向到它(不需要 JS)。 Something roughly like this:大致是这样的:

def checkout(request):
    session = stripe.checkout.Session.create(
        success_url=redirect_url + "?stripe=success",
        cancel_url=redirect_url + "?stripe=cancel",
        mode="subscription",
        # `client_reference_id` will come back in the webhook,
        # making it easier to look up the associated object
        client_reference_id=obj.uuid,
        payment_method_types=["card"],
        line_items=[
            {
                "price": subscription_price_id,
                "quantity": 1,
            }
        ],
    )
    return HttpResponseRedirect(session.url, status=303)

Depending on your app, you'll probably also want to use the Customer Portal sessions (like Checkout sessions, but let's existing customers upgrade/cancel/etc.) and a webhook endpoint (if you need to do something when subscriptions are created or cancelled).根据您的应用程序,您可能还希望使用客户门户会话(如结帐会话,但让现有客户升级/取消/等)和网络钩子端点(如果您需要在创建或取消订阅时执行某些操作). A little bit longer writeup about that in Django Forge docs and the Stripe billing quickstart is also a good link still (updated to use these APIs, just not specific to Django).Django Forge 文档Stripe billing quickstart中写了更长一点的文章,这也是一个很好的链接(更新为使用这些 API,只是不特定于 Django)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM