pythonstripe-payments

Cancelling Stripe subscription after a set period of time


I want a subscription to cancel itself after a year. What's the go to way of implementing this?

checkout_session = stripe.checkout.Session.create(
                    payment_method_types=["card"],
                    mode="subscription",
                    customer=stripe_customer_id,  # Use existing customer ID
                    line_items=[
                        {
                            "price": product.stripe_recurring_price_id,  # Recurring subscription price
                            "quantity": 1,
                        },
                        {
                            # First month extra fees
                            "price_data": {
                                "currency": "myr",
                                "product": "PRODUCT_ID",  # One time charge
                                "unit_amount": 4000,  # RM40 in cents
                                "recurring": None,  # No recurring charges for this item
                            },
                            "quantity": 1,
                        },
                    ],
                    metadata=metadata,
                    # TODO: Add cancellation for subscription after 12 months
                    success_url=YOUR_DOMAIN + "success?success=true",
                    cancel_url=YOUR_DOMAIN + "success?canceled=true",
                )
                return JsonResponse(
                    {"id": checkout_session.id, "url": checkout_session.url}
                )

I'm using "stripe.checkout.Session.create" instead of "stripe.Subscription.create" because there's an extra fee for the first month. This was the only solution I had. If there's another solution then do share.

Basically, I need to be able to set the subscription to last a year and cancels itself after a year. The subscription should not last for more than a year.


Solution

  • You can schedule the Subscription to cancel after a period of time by setting cancel_at field[1].

    While you can't set this at Checkout Session creation API as this field isn't available[2]. What you can do is after the Checkout Session is completed you make an update on the Subscription creation and set that field with the timestamp after an year[3]:

    [1] https://docs.stripe.com/api/subscriptions/create#create_subscription-cancel_at

    [2] https://docs.stripe.com/api/checkout/sessions/create#create_checkout_session-subscription_data

    [3] https://docs.stripe.com/api/subscriptions/update#update_subscription-cancel_at