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.
Before we jump in, make sure you've got:
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.
Let's start by creating a customer:
customer = Stripe::Customer.create( email: '[email protected]', name: 'John Doe' )
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 )
Time to make it rain:
charge = Stripe::Charge.create( amount: 2000, currency: 'usd', customer: customer.id, payment_method: payment_method.id )
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
Let's set up a recurring payment:
subscription = Stripe::Subscription.create( customer: customer.id, items: [ { price: 'price_1234' }, ], )
Need to change things up?
Stripe::Subscription.update( subscription.id, items: [ { id: subscription.items.data[0].id, price: 'price_5678', }, ], )
All good things must come to an end:
Stripe::Subscription.delete(subscription.id)
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: '