Stripe Recurring Subscriptions on Rails like a PRO
Estimated reading time 1 hour
Some theory before the action
Stripe has a great API to manage subscription payments, we will take advantage of it to implement recurring subscriptions in Rails 5.
Using the Stripe API allows us to avoid having to store sensitive customer information like (credit card number or cvv), and the APIs are already set up to handle complex cases such as update plans, manage subscriptions, trigger refunds, and more.
We will set up the Stripe API to handle our subscriptions. We also need Stripe to tell us of ongoing payments and the failure of ongoing payments. This will be possible through webhooks, which are endpoints on our application that Stripe will use to send us details of transactions when changes happen via Stripe.
Our TO-DO list
- We'll create plans locally and on Stripe
- We'll list our plans and select one of them
- We'll subscribe to a selected plan
- We'll implement Stripe webhooks to listen and register events locally
NOTE: We'll create plans, subscriptions and customers locally since we need to have that data in our application we also want to send that data to Stripe so we can manage it through the Stripe API.
NOTE: It's important to say that we are not going to store any credit card information in our systems.
Lets get started with the code
Generating the Plan model
Let's create the plans table & model. Feel free to add more columns to match your own business requirements.
rails generate model plan payment_gateway_plan_identifier:string name:string \ price:monetize interval:integer interval_count:integer \ status:integer description:text
Let's add the Stripe customer
id to our users table. In case you don't know, we need a Stripe customer in order to associate it to a Stripe plan.
NOTE: I assume that you have a User model already in your application
We need a Subscription model in order to track subscriptions locally, off course we will also create those subscriptions on Stripe.
rails generate model subscription user:references \ plan:references start_date:date end_date:date \ status:integer payment_gateway:string payment_gateway_subscription_id:string
In order to subscribe to a plan, we need to list all the active plans, here is the controller.
Select a plan
Display all the plans information and a link to the subscription page.
Display a form with credit card details information like Card number, CVC, Expiration Month and Year.
Using Stripe JS will allow us to get the payment errors (if any).
Here we will use jQuery and Stripe JS (V2) in order to generate the Stripe Token and validate the card information. In case there are no eerors the form will submit to our backend API.
We will insert the Stripe JS (V2) script tag so we can generate the
payment_gateway_token, which is going to be needed to create a Stripe subscription.
Basically a Stripe Token is a key that represent our credit card information.
NOTE: I'm using Rails 5.x encrypted credentials to get the stripe public key content
Basically this controller will use a service that takes care of processing the payment (we will see the service object later).
We need a wrapper between our application and the Stripe library. We are going to create a class to delegate all the Stripe methods. It's going to be worth, trust me!
We are going to consume the Stripe Client methods through another class. Why? First. This will help us a lot in case we like to switch to another payment gateway. Second. The code is going to be extremily easy to test with this design. Another reason is because handling exceptions in this way it's pretty nice since every level has its own exceptions.
All of our payment gateway services will inherit from this class. Why? Because it defines the client which will be used in all of our payment gateway services.
Implementing Service: Create Subscription Service class
Testeable code rocks that's why we will build a service to delegate the subscription creation. As you can see our service doesn't know anything about Stripe. It just works!
Implementing Service: Create Customer Service class
Again, we create another service to delegate the customer creation.
Implementing Service: Create Plan Service class
We'll delegate the Stripe plan creation to the
Implementing Service Error class
Let's create the
ServiceError class and it's childrens, which will help us to handle OUR OWN application exceptions, it is a good idea to raise our own exceptions, here is why: Imagine you want to switch to another platform like Braintree... without this implementation you will end up findining the places where you rescue Stripe exceptions and change them to Braintree exceptions (not so cool). This approach will facilitate our lifes since we will not need to take care about changing library specific errors all over our code. (We will talk more about this later).
We'll setup Stripe webhooks to listen for subscriptions changes, this will allow us to register/track subscriptions changes locally in our application. For example, you can send emails or create online notifications or anything similar to inform a user about subscription changes.
We'll use the StripeEvent gem it will allow us to receive Stripe events in our application.
Routes so far
Gemfile so far
Registering events locally is a great idea, reasons: First, because requesting info to an external API is slow. Second, in case you want to do analytics with the data this will help you a lot. Third, you can customize the data. For now let's create a simple event model it will save all the event payload in a JSONB column.
rails generate model event payment_gateway_event_data:jsonb
Setting up this gem is pretty straightforward, we will tell StripeEvent which events are of our interests, for now we will only handle one event (invoice payment failed), but you can handle ALL of them if you want.
Implementing Service: Get Event Service class
This class returns the Stripe event, we are paranoid that's why we want to verify the event from Stripe.
Handling Events: Invoice Payment Failed class
Our invoice payment failed class will handle the Stripe event, we'll build the class in such way that is it going to create the event locally. But you can do a lot here... For instance you can send emails, broadcast an action cable channel, or anything like that.
This class creates an event locally using the webhook information AND the verified information, we are paranoid that's why we want to verify the event from Stripe.
Here is a list of really important things to keep in mind while implementing webhooks:
- Always verify the data that comes from the webhook requests
- In case you don't plan to verify the events from Stripe, NEVER allow access to paid services in your application because "hacking" this webhook endpoints is extremily easy.
We have learned how to implement subscriptions with Stripe, we also learned how to design elegant services classes, we finally learned how to implement Stripe webhooks.
Tips and advice
Make sure to let your users know that you are not storing credit card information in your systems. Automated testing is really important since you are dealing with real money, but I'm not covering that in this post since it's a large subject. Webhook testing can be done with ngrok.
Final thoughts and next steps
As you can see implementing subscriptions with Stripe is pretty simple, the documentation is extremily detailed Stripe API Reference make sure to take a look whenever you need to look example responses.