# GoCardless Components

Source: https://docs.gocardless.com/docs/collect-payments/integration-types/gocardless-components

# GoCardless Components

GoCardless Components is a JavaScript library for setting up mandates inside your own checkout — the payer never leaves your site or app. GoCardless handles compliance, payer name verification, and form validation, while you keep full control over the surrounding experience.

Unlike the [Drop-in Flow](/docs/collect-payments/integration-types/javascript-drop-in-flow), which renders as a modal, Components embeds inline in your checkout and offers deeper styling control — with less build effort than fully [Custom Payment Pages](/docs/collect-payments/integration-types/custom-payment-pages). Today, Components supports **Bacs (UK) mandate creation only**.

**Best for:**

- Embedding mandate setup natively in your UI without redirecting customers away
- Bacs-only flows where the primary action is setting up a Direct Debit mandate for recurring collection
- Maintaining brand consistency through the full sign-up journey
- Teams who want more UX control than Hosted Pages, with less build effort than a fully custom API integration

**Out of the box:**

- Embedded UI mounted into any element on your page
- Built-in form validation, error states, and retry behaviour
- Prefill customer details from your existing flow
- Compliant mandate authorisation flow

If you need to collect a payment alongside the mandate or support a non-Bacs scheme, consider [Hosted Pages](/docs/collect-payments/integration-types/gocardless-hosted-pages), [Drop-in Flow](/docs/collect-payments/integration-types/javascript-drop-in-flow), or [Custom Payment Pages](/docs/collect-payments/integration-types/custom-payment-pages) instead.

## 1. Setup

You can skip to [Implementation](#2-implementation) if you already have:

- A merchant account with the GoCardless Components upgrade activated
- A public token scoped for use with UI Components
- A server endpoint capable of fulfilling billing requests via the GoCardless API

### 1.1. Gaining access

Before development, contact your account manager to request access to the GoCardless Components upgrade.

### 1.2. Generating a public token

#### For merchants

Go to [https://manage-sandbox.gocardless.com/developers/public-tokens](https://manage-sandbox.gocardless.com/developers/public-tokens) and:

1. Select **Create public token**
2. Enter a name to identify this token
3. Provide the domain where you will use the component
4. Tick the `ui_components` scope
5. Click **Create**

#### For partner integrators

Generate a public token via the API on behalf of each merchant using their OAuth access token:

```json
POST /public_tokens
Authorization: Bearer 
}
```

> **Info:**
> For security, the public token is validated against the domain provided at creation. During local
>   development, requests from `localhost` are exempt from domain validation.

### 1.3. Setting up a fulfilment endpoint

When a payer completes the Components checkout flow, a callback signals that the billing request is ready to fulfil. You are responsible for calling `POST /billing_requests//actions/fulfil` from your server at that point.

See the [API reference](/docs/api-reference/billing-request#fulfil-a-billing-request) for full details.

Example fulfilment endpoint in Ruby:

```ruby
require 'sinatra'
require 'gocardless_pro'

client = GoCardlessPro::Client.new(
  access_token: 'sandbox_MryMkVSfN5iluYov7jFeHbIy73j2_nt8Mw4AEZIQ',
  environment: :sandbox
)

def validate_session_token(session_token, billing_request_id)
  session_token_client = GoCardlessPro::Client.new(
    access_token: session_token,
    environment: :sandbox
  )
  session_token_client.billing_requests.get(billing_request_id)
end

def fulfil_billing_request(billing_request_id)
  client.billing_requests.fulfil(billing_request_id)
end

post '/fulfil-billing-request/:billing_request_id' do
  billing_request_id = params[:billing_request_id]
  session_token = request.env['HTTP_SESSION_TOKEN']

  begin
    validate_session_token(session_token, billing_request_id)
    fulfil_billing_request(billing_request_id)
  rescue GoCardlessPro::Error => e
    status e.code
    content_type :json
    .to_json
  end
end
```

## 2. Implementation

### 2.1. Add the library to your project

Components requires React as a global variable:

```html
```

Then add the GoCardless Components library:

```html
```

### 2.2. Configure Components

Load your configuration before creating any components:

```javascript
const config = ;

GcComponents.loadConfig(config);
```

| Property            | Description                                                                                                      | Required |
| ------------------- | ---------------------------------------------------------------------------------------------------------------- | -------- |
| `publicToken`       | A public token with the `ui_components` scope, valid in the selected environment                                 | Yes      |
| `scheme`            | The payment scheme — only `bacs` is currently supported                                                          | Yes      |
| `environment`       | `live` or `sandbox`. Defaults to `live`                                                                          | No       |
| `appearance`        | Custom appearance configuration — see [Customisation](#5-customisation)                                          | No       |
| `prefilledCustomer` | Prefill the billing form with customer details — see [Prefilled Customer Details](#6-prefilled-customer-details) | No       |

### 2.3. Select a mount target

Create a `` where you want the component to appear:

```html
```

### 2.4. Create a Billing Component

Use `GcComponents.createBillingComponent(selector, options).mount()` to embed the component:

```javascript
const config = ;

GcComponents.loadConfig(config);

const componentOptions = ,
};

GcComponents.createBillingComponent("#gc-billing", componentOptions).mount();
```

| Callback          | Params                                                 | Trigger                                      | Suggested action                                    |
| ----------------- | ------------------------------------------------------ | -------------------------------------------- | --------------------------------------------------- |
| `onSuccess`       | —                                                      | Billing request fulfilled successfully       | Show a success state or redirect the payer          |
| `onError`         | `error` — object with type, message, metadata          | Error during the flow                        | GoCardless shows an error screen; unmount if needed |
| `onReadyToFulfil` | `billingRequestId` — ID of the ready-to-fulfil request | Payer has submitted all required information | Call your fulfilment endpoint                       |

> **Warning:**
> You must implement `onReadyToFulfil`. The Billing Component waits up to **10 seconds** for the
>   billing request to be fulfilled before timing out and cancelling it.

![Billing Component Form](/images/docs/collect-payments/integration-types/gocardless-components/image.png)

## 3. Testing

Run through the checkout flow end to end and confirm you reach the confirmation screen without errors. Then verify the mandate was created via the GoCardless dashboard or API.

![Successful DD](/images/docs/collect-payments/integration-types/gocardless-components/image-2.png)

## 4. Error handling

### 4.1. Initialisation errors

Render the Error Component if `loadConfig` fails:

```javascript
const  = await GcComponents.loadConfig(config);

if (configSuccess)  else 
```

![Error state](/images/docs/collect-payments/integration-types/gocardless-components/som_wrong.png)

| Error message            | Description                                                                     |
| ------------------------ | ------------------------------------------------------------------------------- |
| `Authentication failed`  | Invalid public token, wrong environment, wrong scope, or mismatched domain      |
| `Missing configuration`  | Required config properties are absent                                           |
| `Scheme not supported`   | The scheme provided is not supported — use `bacs` or `GcComponents.Scheme.Bacs` |
| `HTML element not found` | The selector did not match any element on the page                              |

### 4.2. Checkout errors

When an error occurs during the flow, GoCardless renders an error screen and calls your `onError` callback with a `GoCardlessError` object:

```json
,
  "isUnrecoverableError": false
}
```

| Field                  | Description                                                                    |
| ---------------------- | ------------------------------------------------------------------------------ |
| `type`                 | Error type                                                                     |
| `message`              | Detailed error message                                                         |
| `metadata`             | `subType`, `requestId`, `statusCode`                                           |
| `isUnrecoverableError` | `true` if GoCardless could not offer a retry — provide the payer a way to exit |

| Error                                         | Description                                                                                                                            |
| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `TimeoutError`                                | `onReadyToFulfil` was triggered but the request was not fulfilled within 10 seconds. GoCardless cancels the request and offers a retry |
| `Authentication` (with `SessionTokenExpired`) | Session tokens are valid for 30 minutes. If the token expires mid-flow, the payer must restart                                         |

## 5. Customisation

Pass an `appearance` object in your config to match Components to your brand:

```javascript
const config = ,
  },
};
```

Start with `backgroundColor`, `textFontSize`, `textFontFamily`, `buttonColor`, and `buttonBorderRadius`. All unset variables fall back to GoCardless defaults.

Full default theme:

```json

```

## 6. Prefilled customer details

Pass `prefilledCustomer` in your config to pre-populate the billing form. Bank details cannot be prefilled for security reasons.

```javascript
const config = ,
};
```

![Prefilled form](/images/docs/collect-payments/integration-types/gocardless-components/image-3.png)

## 7. Analytics and data tracking

GoCardless Components collects usage data to improve performance and usability. Data collection is enabled by default and can be disabled:

```javascript
const config = ;
```

| Purpose   | Service              | Cookies                                                                        | Description                                                                         |
| --------- | -------------------- | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
| Analytics | GoCardless / Segment | `ajs_anonymous_id`, `analytics_session_id`, `analytics_session_id.last_access` | Tracks user events (clicks, form interactions) to improve UX. Processed via Segment |

As an integrator, you are responsible for obtaining user consent for data collection, disclosing GoCardless and Segment as third parties, and updating your cookie policy accordingly.

## What's next?

  
#### [Setting Up Mandates](/docs/collect-payments/setting-up-mandates)

Learn how to collect bank account details and create mandates via the API.

  
#### [Integration Types Overview](/docs/collect-payments)

Compare all integration options to find the right fit for your use case.

  
#### [GoCardless Hosted Pages](/docs/collect-payments/integration-types/gocardless-hosted-pages)

The fastest integration — redirect to a GoCardless-hosted checkout.

  
#### [Custom Payment Pages](/docs/collect-payments/integration-types/custom-payment-pages)

Full API control for teams that want complete UX ownership.