GraphQL: Canceling A Stripe Subscription
Ok so users can upgrade to a Premium account using Stripe Subscriptions. But what if they want to cancel their subscription and downgrade to a Basic account?
This is how you cancel a subscription in Stripe:
So we need a Subscription ID. Where do we get this?
Well, we get this returned to us when we create a subscription. So when we create a subscription, we can store the subscriptionId
as a field on the User
in our database.
This will allow us to find the user’s subscription later, if they want to cancel their subscription.
To do this let’s first clean up our subscription resolver logic. The current resolver updateRole(newRole: Role!, stripeToken: String): User!
has a lot of logic inside of it. Probably too much. It’s handling both creating and canceling subscriptions, along with other auth logic.
We can clean this up by separating the upgrade and downgrade (a.k.a. subscribe/unsubscribe) logic into two separate resolvers:
This lets us keep each one focused.
Each resolver needs to do a few key things to make the full lifecycle of subscribe-to-unsubscribe possible:
upgradeToPremium(stripeToken: String): User!
Create a Customer in Stripe
Subscribe the Customer to a Plan (Subscription)
Update the user in the database
Set the role to
PREMIUM
Save the
subscriptionId
so we can use it later
downgradeToBasic: User!
Grab the
subscriptionId
from the database for our logged in userCancel the Subscription in Stripe using the
subscriptionId
Update the user in the database
Set the role to
BASIC
Set the
subscriptionId
tonull
With this logic, we can both create new subscriptions for our user, as well as cancel an existing one.
Implementation
upgradeToPremium
resolver:
downgradeToBasic
resolver: