Jacob Ruiz

View Original

GraphQL: Adding Subscription Pricing With Stripe

Problem

We want to allow users to purchase a Premium subscription to our app, to be billed monthly.

Solution

We can use Stripe to:

  • Tokenize the user’s payment method on the client.

  • Accept the token on our backend

  • Create a Customer in Stripe

  • Subscribe that Customer to our Product

Implementation

Stripe Dashboard

  • Create a new Product

  • Create a new Pricing Plan for that Product

    • We’ll need the Plan ID (eg. plan_FLyf9o01u2bJZU)

GraphQL

Schema

Update our updateRole mutation to accept a stripeToken

updateRole(newRole: Role!, stripeToken: String): User!

Resolver

updateRole needs to do a series of things, in order:

1. Create a Customer in Stripe

See this content in the original post

2. Create a Subscription in Stripe for that Customer

See this content in the original post

3. Update the user’s role in the database

See this content in the original post

4. Reset the cookie so the JWT includes the new role

See this content in the original post

5. Return the updated user from our resolver

See this content in the original post

Putting it all together

Here’s the code for the resolver in full. It’s pretty long-winded in it’s first iteration, but it gets the job done. Later we’ll want to add more code to handle different cases.

See this content in the original post