Back

Step by Step Guide to Building a Stripe API Integration in Ruby

Jul 19, 20245 minute read

Introduction

Hey there, fellow Ruby developer! Ready to add some payment magic to your app? Let's dive into integrating Stripe's API. Trust me, it's easier than you might think, and by the end of this guide, you'll be processing payments like a pro.

Prerequisites

Before we jump in, make sure you've got:

  • Ruby 2.5+ installed
  • A Stripe account (if you don't have one, it takes just a minute to sign up)
  • Your Stripe API keys handy

Setting Up the Project

First things first, let's get the Stripe gem installed:

gem install stripe

Now, let's configure those API keys. In your Ruby file or Rails initializer:

require 'stripe' Stripe.api_key = 'your_secret_key_here'

Pro tip: Keep your API keys safe! Use environment variables in production.

Basic API Operations

Creating a Customer

Let's start by creating a customer:

customer = Stripe::Customer.create( email: '[email protected]', name: 'John Doe' )

Adding a Payment Method

Now, let's add a payment method to our customer:

payment_method = Stripe::PaymentMethod.create( type: 'card', card: { number: '4242424242424242', exp_month: 8, exp_year: 2023, cvc: '314', } ) Stripe::PaymentMethod.attach( payment_method.id, customer: customer.id )

Creating a Charge

Time to make it rain:

charge = Stripe::Charge.create( amount: 2000, currency: 'usd', customer: customer.id, payment_method: payment_method.id )

Handling Webhooks

Webhooks are Stripe's way of keeping you in the loop. Here's how to handle them:

post '/webhook' do payload = request.body.read sig_header = request.env['HTTP_STRIPE_SIGNATURE'] event = nil begin event = Stripe::Webhook.construct_event( payload, sig_header, webhook_secret ) rescue JSON::ParserError => e return status 400 rescue Stripe::SignatureVerificationError => e return status 400 end # Handle the event case event.type when 'payment_intent.succeeded' payment_intent = event.data.object puts "PaymentIntent was successful!" # Add other event type handlers here else puts "Unhandled event type: #{event.type}" end status 200 end

Implementing Subscriptions

Creating a Subscription

Let's set up a recurring payment:

subscription = Stripe::Subscription.create( customer: customer.id, items: [ { price: 'price_1234' }, ], )

Updating a Subscription

Need to change things up?

Stripe::Subscription.update( subscription.id, items: [ { id: subscription.items.data[0].id, price: 'price_5678', }, ], )

Canceling a Subscription

All good things must come to an end:

Stripe::Subscription.delete(subscription.id)

Error Handling and Best Practices

Always wrap your Stripe calls in a begin/rescue block:

begin # Stripe API call rescue Stripe::CardError => e # Handle card errors rescue Stripe::RateLimitError => e # Handle too many requests rescue Stripe::InvalidRequestError => e # Handle invalid parameters rescue Stripe::AuthenticationError => e # Handle authentication errors rescue Stripe::APIConnectionError => e # Handle network issues rescue Stripe::StripeError => e # Handle generic errors rescue => e # Handle very unexpected errors end

Use idempotency keys for POST requests to prevent accidental duplicates:

Stripe::Charge.create( { amount: 2000, currency: 'usd', customer: customer.id, }, { idempotency_key: '