Adding Stripe Payments to your Rails application

If you need to process payments, for example charging the user for using your great new website, Stripe is a great contender. An alternative is PayPal, which I will write about later on.

The Stripe APi documentation is great, however I feel that they have mixed the basic with the advanced, a quite common problem.

So therefore, here is the no-nonsense short version.

Basically you have these options

  1. A one-shot charge. If you user returns they will have to type in the CC number again
  2. A one-shot charge, where you save the “tokenized” credit card. Remember, you NEVER want to keep credit card numbers on file. NEVER! But with these tokens (generated by Stripe), you are OK. Save the token in the Users table!
  3. A subscription. Stripe will charge the credit card automatically according to a defined plan. The rest is same as 2) You can query or get notifications when that happen.

Option #2 and #3 should be the most common. #3 is also a natural continuation of #2.

The Stripe API has the following objects

  • Customer
  • Card
  • Payment
  • Plan
  • Subscription

Customer

It is a good idea to create a Stripe Customer as early as possible. This code creates it the first time any module asks the User for its Stripe Customer object (assumes that User model has a ‘stripe_id’ field),

def stripe_customer
  if stripe_id? # do we have a stripe id
    Stripe::Customer.retrieve(stripe_id)  #return a Stripe::Customer object!
  else
    ### create  a new Stripe Customer (valid email must exist!)
    stripe_customer = Stripe::Customer.create(email: email)
    update(stripe_id: stripe_customer.id)   # update User model
    stripe_customer #return a Stripe::Customer object!
  end
end

Note that the Stripe call is synchronous, and will generate an Exception if anything fails.

Next step is to query the user for the Credit Card number. You should create a regular form for this, but the trick is that it is “supercharged” with Stripe-javascript code that modifiees the form, and also handles the submit event.

The sequence will be:

  1. The user fills in the fields and clicks Submit.
  2. The Javascript code intercepts the submit and stops default processing.
  3. The JS-code “tokenizes” the CC code (save it on Stripe server and returns a token)
  4. In a JS-callback, the token is set as a hidden field in the form. You can set other data here too if you like.
  5. The form is submitted as usual

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.