• Design
  • Shotty
  • Blog
  • Reading
  • Photos
Menu

Jacob Ruiz

Product Designer
  • Design
  • Shotty
  • Blog
  • Reading
  • Photos
graphql-notes@2x.png

GraphQL: Canceling A Stripe Subscription

July 2, 2019

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:

stripe.subscriptions.del(
  'sub_F4Pm39d98MmCJG',
  function(err, confirmation) {
    // asynchronously called
  }
);

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:

upgradeToPremium(stripeToken: String): User!
downgradeToBasic: User!

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 user

  • Cancel the Subscription in Stripe using the subscriptionId

  • Update the user in the database

    • Set the role to BASIC

    • Set the subscriptionId to null

With this logic, we can both create new subscriptions for our user, as well as cancel an existing one.

Implementation

upgradeToPremium resolver:

downgradeToBasic resolver:

← Summer - Joe HisaishiGraphQL: Adding Subscription Pricing With Stripe →
shotty-skinny2x.jpg

Shotty - Faster Access To Your Screenshots on Mac

Shotty is an award-winning Mac app I created to give you instant access to all your recent screenshots, right from the menu bar. You can even add annotations on-the-fly. Stop wasting time digging through Finder for your screenshots. I promise it’ll change your workflow forever (just read the App Store reviews!).



Most popular

information-architecture

Information Architecture: The Most Important Part of Design You're Probably Overlooking

Follow @JacobRuizDesign