Search code examples
pythondjangostripe-payments

Automatically create a free trial Stripe checkout


We use Stripe for our checkout and have a free trial enabled. So when a user comes to the site to enable the free trial they just enter their email in the checkout.

What I would like is to tie the start of the free trial with creating an account on my site. Since I get the user's email with account creation I would like to create the free trial programmatically and remove that step. Is that possible?

Here is my code to create the checkout session.

def create_checkout_session(request, app_type):
    subscription_plan_duration = SubscriptionPlanDuration.objects.filter().first()

    user_subscription = UserSubscription.objects.create(
                            subscription_plan_duration_id = subscription_plan_duration.id,
                            user_id = request.user.id,
                            app_type = app_type,
                            is_active = False #True - change for 3.
                        )
    
    discount_coupon = DiscountCoupon.objects.filter(subscription_plan_duration_id = subscription_plan_duration.id).first()

    checkout_session = stripe.checkout.Session.create(
        line_items=[
                {
                    'price': subscription_plan_duration.price_id,
                    'quantity': 1,
                },
            ],
        metadata={ 
            "user_subscription_id": user_subscription.id
        },
        mode="subscription",
        # discounts=[{
        #     'coupon': discount_coupon.coupon_id,
        # }],
        subscription_data={
            "trial_period_days": 30,
            "trial_settings": {
                "end_behavior": {
                    "missing_payment_method": "cancel"
                }
            }
        },
        payment_method_collection="if_required",
        allow_promotion_codes=True,
        success_url=settings.APP_END_POINT + '/stripe/success',
        cancel_url=settings.APP_END_POINT + '/stripe/cancel-subscription/' + app_type
    )

    return redirect(checkout_session.url)

Solution

  • If you don't want the customer to have to go through the Checkout Session, you can create a Subscription via the API instead : https://docs.stripe.com/api/subscriptions/create

    Note though that you need to have a Customer already created as it's a required field in https://docs.stripe.com/api/subscriptions/create#create_subscription-customer