Back

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

Sep 14, 20247 minute read

Hey there, fellow developer! Ready to dive into the world of GoCardless API integration using Ruby? Buckle up, because we're about to embark on a journey that'll have you processing payments like a pro in no time.

Introduction

GoCardless is a powerhouse when it comes to handling recurring payments and direct debits. Their API is robust, well-documented, and a joy to work with. We'll be using the gocardless_pro gem to make our lives easier and our code cleaner. Let's get started!

Prerequisites

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

  • Ruby (preferably 2.7+)
  • Bundler
  • A GoCardless account with API keys (sandbox is fine for now)

Got all that? Great! Let's move on.

Setting up the project

First things first, let's get our project set up:

mkdir gocardless_integration cd gocardless_integration bundle init

Now, open up that shiny new Gemfile and add:

gem 'gocardless_pro'

Run bundle install, and we're off to the races!

Configuring the GoCardless client

Time to get our GoCardless client up and running. Create a new Ruby file and add this:

require 'gocardless_pro' client = GoCardlessPro::Client.new( access_token: 'your_access_token_here', environment: :sandbox )

Pro tip: Never hardcode your access token. Use environment variables or a secure config management system in a real-world scenario.

Basic API operations

Now for the fun part - let's interact with the API!

Creating a customer

customer = client.customers.create( params: { email: '[email protected]', given_name: 'John', family_name: 'Doe', address_line1: '123 Main St', city: 'London', postal_code: 'SW1A 1AA', country_code: 'GB' } )

Setting up a mandate

mandate = client.mandates.create( params: { scheme: 'bacs', links: { customer: customer.id } } )

Creating a payment

payment = client.payments.create( params: { amount: 1000, # Amount in cents currency: 'GBP', links: { mandate: mandate.id }, metadata: { order_id: '12345' } } )

Handling webhooks

Webhooks are crucial for staying in sync with GoCardless. Here's a quick example using Sinatra:

require 'sinatra' require 'json' post '/webhooks' do payload = JSON.parse(request.body.read) signature = request.env['HTTP_WEBHOOK_SIGNATURE'] begin events = GoCardlessPro::Webhook.parse( request.body.read, signature, 'your_webhook_secret' ) events.each do |event| # Process the event puts "Received event: #{event.action}" end status 200 rescue GoCardlessPro::Webhook::InvalidSignatureError status 498 end end

Error handling and best practices

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

begin # Your API call here rescue GoCardlessPro::InvalidApiUsageError => e puts "Bad request: #{e.message}" rescue GoCardlessPro::ApiError => e puts "API error: #{e.message}" end

Implement exponential backoff for retries, and always respect rate limits. Your future self will thank you!

Testing the integration

Use GoCardless's sandbox environment for testing. It's a playground where you can break things without consequences. Write unit tests for your integration to catch issues early:

require 'minitest/autorun' class GoCardlessIntegrationTest < Minitest::Test def setup @client = GoCardlessPro::Client.new( access_token: 'sandbox_access_token', environment: :sandbox ) end def test_create_customer customer = @client.customers.create( params: { email: '[email protected]', given_name: 'Test', family_name: 'User' } ) assert_equal 'Test', customer.given_name end end

Going live

Ready to take on the real world? Switching to production is as simple as changing the environment:

client = GoCardlessPro::Client.new( access_token: 'your_live_access_token', environment: :live )

Before you go live, double-check everything:

  • Are your API keys secure?
  • Have you tested all error scenarios?
  • Is your webhook endpoint secure and reliable?

Conclusion

And there you have it! You've just built a solid GoCardless integration in Ruby. Remember, the API documentation is your best friend, so don't hesitate to dive deeper.

Keep coding, keep learning, and may your payments always go through smoothly!