Authentication overview

GoCardless provides an API for programmatically managing bank payments, including Direct Debits, Instant Bank Pay, and Open Banking services. Authentication is a prerequisite for all API requests, ensuring that only legitimate applications can interact with a user's GoCardless account and initiate financial operations. The system employs standard security practices to protect sensitive data and prevent unauthorized access.

The core of GoCardless API authentication involves identifying the calling application and verifying its permissions to perform requested actions. This process is critical for maintaining the integrity of payment transactions and customer data. GoCardless adheres to regulatory standards such as PSD2 and GDPR, which necessitate strong authentication mechanisms for financial service providers.

Supported authentication methods

GoCardless primarily supports two methods for authentication, catering to different interaction patterns with its API:

  1. API Keys: Used for direct API requests from your server to GoCardless. This method authenticates your application to create, read, update, and delete resources.
  2. Webhook Signature Verification: Used to verify the authenticity and integrity of webhook events sent by GoCardless to your application. This ensures that incoming notifications are genuinely from GoCardless and have not been tampered with.

API Keys

API keys are long, randomly generated strings that serve as secret tokens for authenticating your application. When making an API request, you include your API key in the Authorization header as a Bearer token. GoCardless then verifies this token against its records to grant access. Each API key is associated with a specific environment (sandbox or live) and a set of permissions.

The use of Bearer tokens is a common practice in RESTful API authentication, as described in RFC 6750 for OAuth 2.0 Bearer Token Usage. While GoCardless's API keys function similarly, they are typically managed directly within the GoCardless developer dashboard rather than being obtained through an OAuth flow for server-to-server communication.

Webhook Signature Verification

Webhooks enable GoCardless to notify your application of events in real-time. To ensure the security of these notifications, GoCardless sends a unique signature with each webhook event. Your application must verify this signature using a shared secret (the webhook secret) to confirm that the event originated from GoCardless and its payload has not been altered.

This verification process is crucial for preventing spoofing and ensuring that your application processes only legitimate events. Many API providers, such as Stripe's webhook signing, employ similar mechanisms to secure webhook endpoints.

Authentication methods comparison

Method When to Use Security Level
API Key (Bearer Token) Making direct API calls from your server to GoCardless (e.g., creating a mandate, fetching payment status). High. Requires secure storage and transmission over HTTPS.
Webhook Signature Verification Receiving and processing real-time event notifications from GoCardless securely. High. Protects against tampering and spoofing of event data.

Getting your credentials

To obtain the necessary credentials for authenticating with the GoCardless API, follow these steps:

  1. Create a GoCardless Account: If you don't already have one, sign up for a GoCardless account. You can start with a sandbox account for testing.
  2. Access the Developer Dashboard: Log in to your GoCardless dashboard. Navigate to the 'Developers' section or similar area that provides API access settings. The exact navigation may vary slightly, but it's typically under settings or a dedicated developer menu.
  3. Generate API Keys: Within the developer section, you will find an option to generate new API keys. You can typically create separate keys for your sandbox and live environments. When generating, you'll usually be prompted to give the key a descriptive name and potentially select specific permissions or roles for that key. Ensure you note down your API key immediately upon generation, as it often won't be displayed again for security reasons.
  4. Set up Webhooks and Secret: If you plan to use webhooks, you'll need to configure your webhook endpoint in the GoCardless dashboard. When setting up a webhook, GoCardless will provide a webhook secret. This secret is vital for verifying the authenticity of incoming webhook events. Just like API keys, store this secret securely.

For detailed, up-to-date instructions on credential generation, refer to the official GoCardless API reference documentation.

Authenticated request example

This example demonstrates how to make an authenticated API request to GoCardless using an API key in Python. This request retrieves a list of mandates associated with your account in the sandbox environment. The GoCardless Python SDK simplifies this process considerably.


import gocardless_pro

# Replace with your actual GoCardless API key
# It's recommended to load this from environment variables or a secure configuration system.
ACCESS_TOKEN = "gcl_prod_sandbox_YOUR_API_KEY_HERE"

# Initialize the GoCardless client for the sandbox environment
client = gocardless_pro.Client(
    access_token=ACCESS_TOKEN,
    environment='sandbox'
)

try:
    # Fetch mandates. This request will be authenticated using the provided access_token.
    mandates = client.mandates.list()

    print("Successfully fetched mandates:")
    for mandate in mandates.records:
        print(f"  Mandate ID: {mandate.id}, Status: {mandate.status}, Reference: {mandate.reference}")

except gocardless_pro.errors.GoCardlessProError as e:
    print(f"Error fetching mandates: {e.message}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

In this example, the ACCESS_TOKEN variable holds your API key. The gocardless_pro.Client constructor then uses this token to authenticate all subsequent API calls made through that client instance. For production environments, ensure you use your live API key and set the environment to 'live'.

Webhook verification example (Node.js)

This Node.js example illustrates how to verify a webhook signature using the GoCardless Node.js SDK. This code would typically be part of your webhook endpoint handler.


const gocardless = require('gocardless-pro');
const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const PORT = process.env.PORT || 3000;

// Replace with your actual webhook secret
// Load this from environment variables for production
const WEBHOOK_SECRET = 'YOUR_WEBHOOK_SECRET_HERE';

// Use raw body parser to get the raw request body for signature verification
app.use(bodyParser.raw({ type: 'application/json' }));

app.post('/webhook', (req, res) => {
    const signature = req.headers['webhook-signature'];
    const requestBody = req.body;

    if (!signature) {
        return res.status(400).send('Webhook-Signature header missing');
    }

    try {
        // Verify the webhook signature
        const events = gocardless.Webhooks.parseAndVerify(
            requestBody.toString(), // Raw body as string
            signature,
            WEBHOOK_SECRET
        );

        console.log('Webhook events received and verified:', events);

        // Process the events (e.g., update database, trigger actions)
        events.forEach(event => {
            console.log(`Event ID: ${event.id}, Resource: ${event.resource_type}, Action: ${event.action}`);
            // Implement your event handling logic here
        });

        res.status(200).send('Webhook received and processed');

    } catch (error) {
        console.error('Webhook signature verification failed:', error.message);
        return res.status(498).send('Invalid signature'); // 498 Invalid Token
    }
});

app.listen(PORT, () => {
    console.log(`Webhook server listening on port ${PORT}`);
});

The gocardless.Webhooks.parseAndVerify method handles the cryptographic verification using the provided requestBody, signature header, and your WEBHOOK_SECRET. If the verification fails, an error is thrown, indicating a potentially malicious or tampered webhook event.

Security best practices

Implementing strong security measures for your GoCardless integration is paramount to protect sensitive financial data and ensure compliance. Adhere to these best practices:

  • Secure Credential Storage: Never hardcode API keys or webhook secrets directly into your application's source code. Instead, store them in environment variables, secure configuration files, or a dedicated secret management service (e.g., AWS Secrets Manager, Google Secret Manager, Azure Key Vault). Restrict access to these secrets to authorized personnel and systems only. For additional guidance, consult Google Cloud's secrets management best practices.
  • Use HTTPS Everywhere: Always communicate with the GoCardless API and receive webhooks over HTTPS. This encrypts data in transit, protecting your API keys and sensitive payment information from eavesdropping.
  • Principle of Least Privilege: Grant API keys only the minimum necessary permissions required for your application's functionality. For example, if your application only needs to create mandates, do not give it permissions to cancel them or manage payouts. Regularly review and adjust permissions as your application evolves.
  • Rotate API Keys and Webhook Secrets: Periodically rotate your API keys and webhook secrets. This practice limits the window of exposure if a credential is compromised. Establish a regular rotation schedule (e.g., quarterly or biannually).
  • Implement Webhook Signature Verification: Always verify the signature of incoming webhook events. This is a critical step to ensure that events are genuinely from GoCardless and have not been altered in transit, protecting your system from forged requests.
  • Error Handling and Logging: Implement robust error handling for API requests and webhook processing. Log authentication failures and suspicious activity, but avoid logging sensitive data like API keys or full request bodies in plain text. Monitor these logs for anomalies.
  • Isolate Environments: Use separate API keys and webhook secrets for your development, staging, and production environments. Never use production credentials in non-production environments. GoCardless provides a dedicated sandbox environment for testing without affecting live accounts.
  • Client-Side Security: Do not expose your API keys or webhook secrets directly in client-side code (e.g., in web browsers or mobile apps). All API calls requiring these credentials should originate from your secure backend server.
  • Stay Updated: Keep your GoCardless SDKs and any related security libraries up to date to benefit from the latest security patches and features.