LaunchSchool - An Online School for Developers /

Blog

Stripe Payments in Rails, Part 4 - Plan Discounts With Coupons

This is the fourth article in the “Process Payments with Stripe in Rails” tutorial series:

In this post, we will work on the same code base for this tutorial series. We will implement a coupon option that comes with the subscription service that we covered in part 3 of this series. Note that the coupon functionality runs only with subscriptions, not with simple payments.

We will work on the coupons branch:

1
2
3
4
5
6
7
8
git clone -b coupons git@github.com:gotealeaf/stripe-basics.git
cd stripe-basics
rake db:drop
rake db:create
rake db:migrate
rake db:seed
rails s
open http://localhost:3000

Make sure you follow all the steps in Stripe payments in Rails, Part 3 – Recurring Payments with Stripe before continuing.

Step 1. Create coupon in Stripe dashboard

Go to Stripe dashboard > Subscriptions > Coupons:

The code that we use here will be “50DISCOUNT”.

Step 2. Add the coupon input to Registration form

Create a coupon column in the registration model rails g migration add_coupons_to_registrations coupon:string:

1
2
3
4
5
class AddCouponsToRegistrations < ActiveRecord::Migration
  def change
    add_column :registrations, :coupon, :string
  end
end

In the form we will create the input for the coupon

views/registrations/new.html.haml

1
2
3
4
      - unless @registration.course.plan.blank?
        .field
          = f.label :coupon
          = f.text_field :coupon

This input will be shown only if the course is sold with a subscription plan.

In our registration controller, add it to the permitted params:

1
2
3
def registration_params
  params.require(:registration).permit(:course_id, :full_name, :company, :telephone, :email, :card_token, :coupon)
end

Add the coupon when we create a customer in our Registration model:

models/registration.rb#process_payment

1
2
3
customer_data = {email: email, card: card_token, coupon: coupon}
                    .merge( (course.plan.blank?)? {}: {plan: course.plan})
customer = Stripe::Customer.create customer_data

Step 3. Test the coupon feature

Select “ALL COURSES PLAN” and fill the form with the coupon “50DISCOUNT”:

If you go to the Events in the Stripe Dashboard you can see:

  • How your coupon creation was registered
  • How the new customer is created with the coupon discount

Conclusion

Stripe’s documentation on coupons is a great resource, where you can find more details about this feature.