Gem of the Week: Stripe
August 25, 2016 Jamey Alea 0 Comments
As a developer, e-commerce is unavoidable. It’s a huge part of tons of web apps and it can be daunting at first because a bug in your e-commerce functionality is absolutely sure to net you lost money and angry customers. Naturally, deciding on a payment processor is an important choice. Ease of development and usability for business are both big factors. Paypal, while certainly fairly ubiquitous, has a lot of issues, especially on the business side when it comes to fees and ease of accessing your own money. Personally, I’ve had better luck using Stripe and conveniently for us, Stripe is extraordinarily easy to develop with and comes with a nifty little gem for quick integration in Rails.
After you add the ‘stripe’ gem to your Gemfile, there is a little bit of configuration required. Let’s assume you already have a Stripe account (but if you don’t, signing up for one at stripe.com is pretty painless). Create a file in your app’s config/initializers folder called stripe.rb. Here’s a basic way you can set up the configuration.
if Rails.env.production? Rails.configuration.stripe = { :publishable_key => "your_live_publishable_key", :secret_key => "your_live_secret_key" } else Rails.configuration.stripe = { :publishable_key => "your_test_publishable_key", :secret_key => "your_test_secret_key" } end Stripe.api_key = Rails.configuration.stripe[:secret_key]
Obviously, you have to fill in the actual API keys from your Stripe account. When you’re logged in, find them by viewing your account settings, where there should be a tab called API keys.
Particularly for the live production keys, it’s much safer not to copy the keys directly into the initializer file, so you’ll want to use environment variables (ie, ENV[‘stripe_live_publishable_key’]) in this file instead.
This configuration is really convenient because it knows what environment you’re working in and automatically adjusts what Stripe configuration you’re working with. That means you can test in development and staging without worrying about messing with real Stripe data, but when you deploy to your production server, it will automatically bring Stripe live without you having to do anything else.
One thing that’s nice about Stripe is that it can support as little or as much customization as you need. I’m just going to go over a really simple implementation using Checkout, which is a ready-made payment form that Stripe provides. Checkout is the easiest and fastest way to get Stripe up and running in your app, but if you need more customization and feel comfortable writing your own Javascript, a lot more possibilities open up.
Inside a rails form_tag, you’ll want to include this script, provided by Checkout:
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22https%3A%2F%2Fcheckout.stripe.com%2Fcheckout.js%22%20class%3D%22stripe-button%22%0A%20%20%20%20data-key%3D%22%3C%25%3DRails.configuration.stripe%5B%3Apublishable_key%5D%20%25%3E%22%0A%20%20%20%20data-name%3D%22Your%20Site%E2%80%99s%20Name%22%0A%20%20%20%20data-description%3D%22your%20description%20of%20the%20charge%20(which%20will%20show%20up%20in%20your%20stripe%20dashboard)%22%0A%20%20%20%20data-amount%3D%221000%22%3E%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" />
Let’s analyze this for a second. The data-key option is your publishable key, which you are able to grab from the initializer we set up earlier. The data-amount option is important – that’s an integer which represents how much the customer will be charged, in cents. There are lots of other options you specify here. Data-image lets you specify an icon that will appear in the form. Data-zip-code and data-billing-address default to false, but if you set them to true, the form will also prompt for, collect and validate the user’s postal code and billing address. You can set what currency you’re using with data-currency, but it defaults to USD. Changing data-label gives you control over what the button on the form says instead of the default “Pay with Card.” More options can be found in the Checkout documentation, but as you can see, even when using the premade Checkout implementation, you get a lot of control over configuration.
Okay, now remember how I said that you had to put that script tag inside of a rails form_tag? That allows you to consume the information gleaned from this form inside your controller to actually make charges to Stripe. Inside a controller action that corresponds with the form_tag that holds the checkout script, create a Stripe customer like this:
customer = Stripe::Customer.create( :email => params[:stripeEmail], :source => params[:stripeToken] )
These params come from the Checkout form – stripeEmail is the email that the user entered, while stripeToken is the important bit, a token created and passed back to you by Stripe based on accurate billing information. This means you can save customer information for later use without ever having to keep any sensitive credit card info on your servers by storing the customer’s id.
You still haven’t actually charged them any money, though. Using this customer, you can create a charge.
charge = Stripe::Charge.create( :customer => customer.id, :amount => 1000, :description => ‘Example charge from a customer’, :currency => 'usd' )
What if you don’t need to save any customer details to reference again later? Can’t you just skip the customer step? You sure can, by substituting
:source => params[:stripeToken]
for the customer param when you create the charge.
Oh no, what if that was a mistake? Refund the money back to your customer.
refund = Stripe::Refund.create(:charge => charge)
Not too hard, right? By the way, you can always go to your Stripe dashboard and see records of all these charges and refunds. Just make sure you’re viewing the proper environment (test or live) by checking the slider at the top left of your dashboard.
Testing your Checkout form is easy. Just use the test credit card number 4242424242424242 with any 3-digit CVC and an expiration date in the future and you should see a successful charge to your test environment.
That’s about all you need for really basic Stripe usage but as I said before, Stripe is great because it can get about as complicated as your app needs it to. For a great start on more custom Stripe integrations, forms and recurring payments, I’ll refer you to this really helpful episode of Railscasts – Billing with Stripe. Or for more detailed documentation, see the gem itself on Github and the API docs on Stripe’s website.
(This article was originally published on Uptime.)