An introduction to our API

The GoCardless API allows you to manage Direct Debit payments via your own website or software. When a customer signs up for your services they can give you a Direct Debit authorisation online. Your integration can then create and manage payments and subscriptions automatically - there’s no need to manually add a new customer to GoCardless. Our API provides you with full flexibility when it comes to payment creation, and we offer it to all of our merchants at no extra cost.

In this blog post we’ll guide you through the steps needed to use our API, from customer creation to taking your first payment.

Let’s look at how Direct Debit payments work and how the GoCardless API is organised. In order to charge a customer’s bank account, you will first need their authorisation to collect payments via Direct Debit. This can be via our secure online payment pages or, if you’re using GoCardless Pro, you can take complete control of the payment process by hosting the payment pages on your own website.

GoCardless

Using GoCardless the process of creating a new customer is as follows:

  1. You direct your customers to the GoCardless payment page, allowing them to complete the authorisation to take payments from their account.
  2. Once complete, we redirect your customers back to your website. We’ve called this the redirect flow. When the customer is returned to your website, the redirect flow will already have created a customer record on the GoCardless system. Associated with the customer record will be a customer bank account, which itself will be associated with a mandate.
  3. You can now create payments and subscriptions against this mandate.

GoCardless Pro

If you host your own payment pages your clients will never have to leave your website to give you a Direct Debit authorisation.

  1. You use our API to create a customer record, followed by a customer bank account which is linked to the customer.
  2. Next you create a mandate by referencing the customer bank account.
  3. You can now create payments and subscriptions against this mandate.

Example requests

Now that we’ve covered the basics let’s look at the actual requests to the API. In order for you to follow these steps you will need the following:

  • A GoCardless sandbox account, get one here
  • An access token to use the API, create one here

In order to send a HTTP request to our API you will first need to set the URL where you want the request sent to. The base URLs for the GoCardless API are

  • https://api.gocardless.com/ for live
  • https://api-sandbox.gocardless.com/ for sandbox

As we’re using the sandbox we’ll use https://api-sandbox.gocardless.com/ which is then followed by the endpoint you want to send a request to. You will also need to specify if you want to send a POST (sending information) or a GET (requesting information) request and you will need to set the headers. Our API requires several headers to be set:

  • Authorization uses the access token you’ve created in the developer settings, preceded by the word Bearer
  • Accept tells the API that you’re expecting data to be sent in the JSON format. This needs to be application/json.

If you’re sending data to us, for example to create a new payment, you’ll also need to specify the content type:

  • Content-Type specifies the format of the content sent to the API (if any). This needs to be application/json.

An example request to our customers endpoint to list all customers on an account using curl would look like this:

curl https://api-sandbox.gocardless.com/customers \
-H "Authorization: Bearer ZQfaZRchaiCIjRhSuoFr6hGrcrAEsNPWI7pa4AaO" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H "GoCardless-Version: 2015-07-06"

Creating a customer using the redirect flow

To send your customer to the GoCardless payment pages you will need to create a redirect flow. This will be a POST request, and the redirect flow endpoint requires at least two parameters:

  • session_token This is used as an identifier allowing you to link the redirect flow to the respective customer in your integration. You could use the customer's email address or generate a random ID for this - it’s how you will identify this customer when they’re returned to your site after authorising payments
  • success_redirect_url This is the URL we redirect the customer to when they complete the payment pages.
  • description (optional) This will be shown to the customer when they’re on our payment page.

These parameters will need to be send with the request in a JSON blob, wrapped in a redirect_flows envelope:

curl https://api-sandbox.gocardless.com/redirect_flows \
-H "Authorization: Bearer ZQfaZRchaiCIjRhSuoFr6hGrcrAEsNPWI7pa4AaO" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H "GoCardless-Version: 2015-07-06" \
-d '{
  "redirect_flows": {
    "description": "Magazine subscription",
    "session_token": "session_ca853718-99ea-4cfd-86fd-c533ef1d5a3b",
    "success_redirect_url": "http://localhost/success"
  }
}'

The response from the API

{  
   "redirect_flows": {  
      "id": "RE00005H8602K9J5C9V77KQAMHGH8FDB",
      "description": "Magazine subscription",
      "session_token": "session_ca853718-99ea-4cfd-86fd-c533ef1d5a3b",
      "scheme": null,
      "success_redirect_url": "http://localhost/success",
      "created_at": "2016-06-29T13:28:10.282Z",
      "links": {  
         "creditor": "CR000035V20049"
      },
      "redirect_url": "https://pay-sandbox.gocardless.com/flow/RE00005H8602K9J5C9V77KQAMHGH8FDB"
   }
}

The response shows the redirect_url for the newly created redirect flow. An HTTP 303 redirect (or an alternative redirect method) can be used to send your customer to the our payment pages. This should be done immediately, as the redirect link expires after 30 minutes. The customer will then see the GoCardless payment page and can enter their details to authorise a Direct Debit to be set up.

Once the form is complete, we will redirect the customer back to the redirect_uri you originally specified and append the parameter redirect_flow_id like this: http://localhost/success?redirect_flow_id=RE00005H8602K9J5C9V77KQAMHGH8FDB.

In order for the API to know that the customer has been returned safely back to your integration you will need to complete the redirect flow by sending the following request to the API. This is a mandatory step and the customer won’t be set up if this is not completed.

curl https://api-sandbox.gocardless.com/redirect_flows/RE00005QAMHGH8FDB/actions/complete \
-H "Authorization: Bearer ZQfaZRchaiCIjRhSuoFr6hGrcrAEsNPWI7pa4AaO" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H "GoCardless-Version: 2015-07-06" \
-d '{
  "data": {
    "session_token": "session_ca853718-99ea-4cfd-86fd-c533ef1d5a3b"
  }
}'

Notice that the ID of the redirect flow and the required action was appended to the URL, and the session_token (as set by your integration when creating the redirect flow) was sent in the body of the request.

The response from the API

{  
   "redirect_flows": {  
      "id": "RE00005H8602K9J5C9V77KQAMHGH8FDB",
      "description": "Magazine subscription",
      "session_token": "session_ca853718-99ea-4cfd-86fd-c533ef1d5a3b",
      "scheme": null,
      "success_redirect_url": "http://localhost/success",
      "created_at": "2016-06-29T13:49:00.077Z",
      "links": {  
         "creditor": "CR000035V20049",
         "mandate": "MD0000TWJWRFHG",
         "customer": "CU0000X30K4B9N",
         "customer_bank_account": "BA0000TCWMHXH3"
      }
   }
}

The customer’s details have now been saved, and GoCardless will take care of setting up an authorisation to collect payments from their bank account. You’ll use the mandate ID (provided in the links) to create payments and subscriptions, so you’ll want to store that ID in your database. You may find it useful to store the other references to your customer's resources in your database as well.

Creating a payment will be just one more call to the API, using the payments endpoint. A quick look into the developer documentation shows the three required parameters:

  • amount The payment amount, given in pence/cents. So to take £10.00 the value would be 1000
  • currency The currency of the payment you’re taking
  • links[mandate] The mandate that should be charged

Another helpful parameter is charge_date, which specifies when the payment leaves the customer’s bank account. If no charge_date is provided, the payment will be charged on the earliest possible date.

curl https://api-sandbox.gocardless.com/payments \
-H "Authorization: Bearer ZQfaZRchaiCIjRhSuoFr6hGrcrAEsNPWI7pa4AaO" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H "GoCardless-Version: 2015-07-06" \
-d '{
  "payments": {
    "amount": 1000,
    "currency": "GBP",
    "links": {
      "mandate": "MD0000TWJWRFHG"
    }
  }
}
'

The response from the API:

{  
   "payments": {  
      "id": "PM0001G6V7BSN4",
      "created_at": "2016-07-01T09:27:52.352Z",
      "charge_date": "2016-07-06",
      "amount": 1000,
      "description": null,
      "currency": "GBP",
      "status": "pending_submission",
      "amount_refunded": 0,
      "reference": null,
      "metadata":{},
      "links": {  
         "mandate": "MD0000TWJWRFHG",
         "creditor": "CR000035V20049"
      }
   }
}

You have now set up a customer and charged your first payment using the GoCardless API!

The API offers you many more options, allowing you to integrate Direct Debit functionality into your existing website or software.

If you’re using PHP, Java, Ruby or Python you can also make use of our client libraries. To get started, check out our easy "getting started" guide with copy and paste code samples.

Any API-related questions or feedback can be sent to our developer support team at api@gocardless.com.

Interested in joining the GoCardless team?
We're hiring
in Engineering, Support

Getting started with the GoCardless PHP library

This post relates to the Legacy GoCardless API. If you're starting a new integration, you'll need to use the new GoCardless API - for help getting started, check out our guide.

PHP is the web's most popular coding language, used by nearly 40% of websites, so we've made it super simple to integrate with GoCardless using our open-source API library.

In 90% of cases, you'll be wanting to set up pre-authorizations. These are variable Direct Debits, letting you have your customer authorise once through our secure payment pages, after which you'll be able to charge them automatically whenever you need to with just two lines of code.

1. Add the PHP library to your project

First of all, you'll need to sign up for a GoCardless account and enable developer mode. Once you've done that, you'll get your authentication details which you'll be able to copy and paste into your code. This will take about 5 minutes - just follow our guide here.

Next, you'll need to grab the latest version of our library. There are two options for doing this:

  • Download the ZIP file here and add it to your project.
  • Add GoCardless to your composer.json file:
{
    "require": {
        "gocardless/gocardless": ">=0.4.2"
    }
}

We'd recommend storing the extracted GoCardless.php file and the gocardless folder inside a lib/ directory. This makes it easy to organise your code's dependencies.

Next, create a central configuration file. Using this will make it easy to share all the GoCardless setup between different pages, meaning you only have to change your settings in one place. I'll call it gocardless.inc.php:

<?php
  include_once("lib/GoCardless.php");

  // By default, your application will run in the sandbox - here,
  // you can test with no money changing hands. When you're
  // reading to go live, simply uncomment this line.
  // GoCardless::$environment = 'production';

  // Let's add your authentication details for the production and
  // sandbox. You can get them both from your Dashboard - copy them
  // in to replace the examples.
  if (GoCardless::$environment == 'production') {
    $account_details = array(
      'app_id'        => 'INSERT_LIVE_APP_ID',
      'app_secret'    => 'INSERT_LIVE_APP_SECRET',
      'merchant_id'   => 'INSERT_LIVE_MERCHANT_ID',
      'access_token'  => 'INSERT_LIVE_MERCHANT_ACCESS_TOKEN'
    );
  } else {
    $account_details = array(
      'app_id'        => 'INSERT_SANDBOX_APP_ID',
      'app_secret'    => 'INSERT_SANDBOX_APP_SECRET',
      'merchant_id'   => 'INSERT_SANDBOX_MERCHANT_ID',
      'access_token'  => 'INSERT_SANDBOX_MERCHANT_ACCESS_TOKEN'
    );
  }

  GoCardless::set_account_details($account_details);
?>

2. Send the customer to the GoCardless payment pages

Setting up a pre-authorization will allow you to get authorisation from your customer once, and then charge them whenever you need to in the future. To do that, you'll need to send the customer through our secure payment process.

Our API library makes this simple:

<?php
// Bring in the file we made earlier, which includes the GoCardless
// library and all of our configuration
include_once("gocardless.inc.php");

// Provide the details to use to set up the Direct Debit. In
// particular, make sure you set the amount to be higher than
// you'll ever need to collect in a month.
$pre_authorization_details = array(
  "amount" => "10000",
  "interval_length" => 1,
  "interval_unit" => "month"
);

// The GoCardless library puts everything together and
// generates a personalised link to our secure payment pages
$pre_authorization_url = GoCardless::new_pre_authorization_url($pre_authorization_details);

// Now we could put that generated URL behind a link...
echo "<a href='" . $pre_authorization_url . "'>Set up a Direct Debit</a>";
// or we could redirect the user right away...
header("Location: " . $pre_authorization_url);
?>

3. Confirm the setup of the Direct Debit

Once the customer has finished going through our payment flow, we'll send them back to your website, where you'll need to confirm the authorization via our API.

Let's create a file called callback.php. You'll need to set the URL of that as your "redirect URL" in your Dashboard's developer settings:

Setting your redirect URI

<?php
// Let's include our central configuration file again.
include_once("gocardless.inc.php");

// Pull out the required data from the redirect
$confirm_params = array(
  'resource_id'    => $_GET['resource_id'],
  'resource_type'  => $_GET['resource_type'],
  'resource_uri'   => $_GET['resource_uri'],
  'signature'      => $_GET['signature']
);

// We'll add this - it'll come into effect if you implement
// a more advanced integration,
if (isset($_GET['state'])) {
  $confirm_params['state'] = $_GET['state'];
}

GoCardless::confirm_resource($confirm_params);

// If all has gone well, you'll now be able to charge this
// customer. To do this, you'll need to store their
// pre-authorization's ID somewhere - for instance on a
// user's database record.
$pre_authorization_id = $resource_id;
?>

<p><b>Thank you!</b></p>

4. Charge your customer

When you're ready to charge your customer, it's just a few simple lines of code:

<?php
include_once("gocardless.inc.php");

// You'll need to pull our the customer's pre-
// authorization ID which you saved somewhere in
// the previous step.
$pre_authorization_id = fetch_id_from_database();

$pre_auth = GoCardless_PreAuthorization::find($pre_authorization_id);

// Set the details for the payment to collect. We'll
// display the "name" in emails sent to the customer.
$bill_details = array(
  "name" => "Invoice for June 2014",
  "amount" => "25.00"
);

$bill = $pre_auth->create_bill($bill_details);

// It's likely that you'll want to store the bill's ID
// - this is useful for staying up to date on its status
// later.
$bill_id = $bill->id;
?>

What next?

You've now seen how to set up the GoCardless PHP library, create your first Direct Debit and then take a payment. Here's a few things to check out as your next steps:

  • Web hooks allow you to be informed about the progress of a payment or any changes to your customers' Direct Debits - so for example, we'll let you know when money has been successfully collected.
  • Pre-populating information makes it simpler for your customers to pay and increases conversion.
  • Using the "state" parameter lets you pass data through the payment process, and collect it at the other end.

If you have any questions or we can help at all, just get in touch - email us.

Want to find out more or ask questions?
Book a chat with an expert
in Support

How to integrate with the GoCardless API

This post relates to the Legacy GoCardless API. If you're starting a new integration, you'll need to use the new GoCardless API - for help getting started, check out our guide.

What is the GoCardless API?

The GoCardless API is a way for developers to interact via software with GoCardless, allowing you to integrate us into your website, mobile app or desktop software. This means you can build your own customised integration to automate payment collection and reconciliation.

What do you need to do to integrate with the GoCardless API?

Integrating with the GoCardless API is incredibly simple and can be done in minutes with the following 8 simple steps and our easy to use API libraries.

1. Sign up for a merchant account if you haven’t already - it’ll only take a minute to create your account. If you already have a merchant account, just log in to your dashboard.

GoCardless sign up page

2. Log in to your dashboard and enable developer mode. To do this, click 'More…' in the navigation bar, then click 'Developer' and finally, click the 'Enable developer mode' button. We will then create a sandbox environment for you to test in and set you up with your API credentials.


Developer mode

3. Switch to the sandbox. To do this click 'Sandbox' near the top right of the dashboard to switch between the live and sandbox dashboards (to switch back simply click 'Live'). Once you have switched to the sandbox, click 'More…'' then 'Developer' to find your sandbox API credentials.


Sandbox API credentials

4. Download one of our API client libraries for the language you’ll be developing in. These libraries take all the hard work out of using our API, so you’ll only need a few lines of code to get started.

5. Take a look through our developer documentation - use the drop-down list at the top left of the page to select the library you’re using, and we’ll show you code examples for your preferred language.

6. Create a link for a one-off bill, subscription or pre-authorisation using your chosen client library. You’ll use your sandbox credentials to generate the link, so none of the payments you create will be sent to the banking system. The link you generate will take the customer to an online Direct Debit mandate form where they will need to enter their payment details.


Direct Debit mandate form

7. Make a confirmation page on your website (if you'd like to). The customer will be redirected here when they’ve completed the online Direct Debit mandate form. You’ll need to confirm that they’ve reached you successfully and that you’ve received the details of the payment they’ve set up. Our libraries make this simple to do, just read through the confirming payments section of our documentation.


Direct Debit setup successful message

8. Now test it out. Try following the link you’ve generated and set up a sandbox payment to your merchant account. If it all works as expected, you can go back to your live dashboard and get your live API credentials - switch the sandbox credentials for the live ones in your code.

You’re now ready to start taking payments using Direct Debit!

Depending on your needs, you may want to start receiving automatic notifications to your system when the status of a payment changes. We can send webhooks to your server to keep you up-to-date with your payments as they are processed - read through our webhook guide to find out how to add this to your application flow.

If you need any advice on how to integrate GoCardless then please feel free to email us.

Interested in collecting Direct Debits?
Book a chat with an expert