Back

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

Sep 14, 20246 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of GoCardless API integration? You're in for a treat. GoCardless is a powerhouse for handling direct debit payments, and their API is a dream to work with. We'll be using the gocardless/gocardless-pro package, which makes our lives so much easier. Let's get cracking!

Prerequisites

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

  • PHP 7.4 or higher (come on, you're not still on 5.6, right?)
  • Composer installed (because who manually manages dependencies these days?)
  • A GoCardless account with API keys (grab 'em from your dashboard)

Installation

First things first, let's get that package installed:

composer require gocardless/gocardless-pro

Easy peasy, right?

Setting up the GoCardless client

Now, let's initialize our GoCardless client:

<?php require_once 'vendor/autoload.php'; $client = new \GoCardlessPro\Client([ 'access_token' => 'your_access_token_here', 'environment' => \GoCardlessPro\Environment::SANDBOX ]);

Pro tip: Use the sandbox environment while testing. Switch to LIVE when you're ready for the big leagues.

Creating a customer

Time to create our first customer:

$customer = $client->customers()->create([ 'email' => '[email protected]', 'given_name' => 'John', 'family_name' => 'Doe', 'address_line1' => '123 Main St', 'city' => 'London', 'postal_code' => 'SW1A 1AA', 'country_code' => 'GB' ]);

Boom! Customer created. Easy, right?

Setting up a mandate

Now for the fun part - setting up a mandate. This is where we get permission to charge the customer:

$redirectFlow = $client->redirectFlows()->create([ 'description' => 'Wine Club Membership', 'session_token' => 'unique_session_token', 'success_redirect_url' => 'https://example.com/success' ]); // Redirect your customer to $redirectFlow->redirect_url

When they come back:

$completedFlow = $client->redirectFlows()->complete( $redirect_flow_id, ['session_token' => 'unique_session_token'] ); $mandate = $completedFlow->links->mandate;

Creating a payment

Let's charge that card!

$payment = $client->payments()->create([ 'amount' => 1000, // in cents 'currency' => 'GBP', 'links' => [ 'mandate' => $mandate ], 'metadata' => [ 'order_id' => '12345' ] ]);

For recurring payments, check out the subscriptions API. It's super slick!

Handling webhooks

Webhooks are your friends. They'll keep you updated on what's happening:

$webhook = new \GoCardlessPro\Webhook([ 'secret' => 'your_webhook_secret' ]); $events = $webhook->parse( file_get_contents('php://input'), $_SERVER['HTTP_SIGNATURE'] ); foreach ($events as $event) { switch ($event->resource_type) { case 'payments': // Handle payment event break; // Handle other event types } }

Error handling and best practices

Always wrap your API calls in try-catch blocks. GoCardless throws specific exceptions that you can catch and handle:

try { // Your API call here } catch (\GoCardlessPro\Core\Exception\InvalidApiUsageException $e) { // Handle invalid API usage } catch (\GoCardlessPro\Core\Exception\GoCardlessProException $e) { // Handle any other GoCardless Pro exception }

Remember to respect rate limits and log everything. Your future self will thank you!

Testing

Use the sandbox environment to test everything thoroughly. Create test scenarios for successful payments, failed payments, and webhooks. It's better to catch issues now than when real money is involved!

Going live

Ready for prime time? Here's your checklist:

  1. Switch to the live environment
  2. Update your API keys
  3. Update your webhook endpoints
  4. Double-check all your error handling
  5. Monitor your first few live transactions closely

Conclusion

And there you have it! You're now a GoCardless integration ninja. Remember, the GoCardless API docs are your best friend if you get stuck.

Now go forth and process those payments like a boss! 💪💰