How can I use the Anvil Stripe service to cancel stripe subscriptions

With Anvil, signing up a user for a Stripe subscription is pretty easy.

However, there doesn’t seem to be any documentation on how to cancel this subscription.

Do I basically have to set up a token and then build my Stripe form and do everything manually? Or is there a higher level method that handles this for us?

Best,
Ruben

I apologise for the delay updating our documentation! If you have the Stripe customer ID, you can call anvil.stripe.get_customer() with the customer ID to get an object representing a Stripe customer. You can then call get_subscriptions() to get a list. So the following code will cancel all of a customer’s Stripe subscriptions:

def cancel_all_subscriptions(customer_id):
  customer = anvil.stripe.get_customer(customer_id)
  for subscription in customer.get_subscriptions():
    subscription.cancel()
1 Like

Thank you Meredydd.

This is exactly what I was hoping for.

Best,
Ruben

1 Like

The only thing, however, is that when a subscription is set up.

I only see a ‘subscription_id’ generated, and not a ‘customer_id’.

How can I retrieve the customer_id in order to store it for later use?

I suppose here I will have to generate an ID through anvil.stripe.new_customer(), which requires a token.

So basically I would have to request a token, and no longer have access to the stripe subscription method?

Yes, that is the preferred way to create a Stripe subscription. Generate a token on the client side using anvil.stripe.get_token(), then call anvil.stripe.new_customer() on the server and call new_subscription() on that customer. Here’s a more detailed description, with some sample code:

1 Like