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
2. Create a Subscription in Stripe for that Customer
3. Update the user’s role in the database
4. Reset the cookie so the JWT includes the new role
5. Return the updated user from our resolver
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.