# GoCardless Components

# What are 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 our 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. Today, Components supports **Bacs (UK) mandate creation only**.

Supports: Bacs (UK) Direct Debit mandate setup (no other schemes)

**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

**What you get 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

**Customisation**: Components expose a wide range of appearance variables — colours, fonts, borders, padding, button styling — so you can match it to your brand. If you need to collect a payment alongside the mandate or support a non-Bacs scheme, consider [**<u>Hosted pages</u>**](https://developer.gocardless.com/integration-types/gocardless-hosted-pages/),[ **<u>Drop-in Flow</u>**](https://developer.gocardless.com/integration-types/javascript-drop-in-flow/), or[ **<u>Custom Payment Pages</u>**](https://developer.gocardless.com/integration-types/custom-payment-pages/) instead.

This page explains how you can use the GoCardless Components library to guide a customer through the creation and fulfilment of a billing request.

## 1. Setup

You can skip ahead to [**<u>Implementation</u>**](#2_implementation) if you already have access to the following:

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

### 1.1. Gaining access to the GoCardless Components Upgrade

Before beginning development using GoCardless Components, please ensure you have contacted your account manager to request access to the GoCardless Components upgrade.

### 1.2. Generating a Public Token

In order to use GoCardless Components, you will need to create a Public Token. Generate a public token in the dashboard or create one via the GoCardless API if you are building a Partner integration.

#### 1.2.1 For Merchants

To generate a public token via the dashboard, go to [<u>https://manage-sandbox.gocardless.com/developers/public-tokens</u>](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 be using the GoCardless Component
4. Tick the ui_components scope
5. Click Create

#### 1.2.2 For Partner Integrators

You will need to generate a public token via the API on behalf of each of your merchants. Using their OAuth access token, make the following request to GoCardless:

```json

Authorization: "Bearer oauth_access_token"
POST /public_tokens

{
    "public_tokens": {
        "name": "My Public Token",
        "domain": "example.com",
        "scopes": [
            "ui_components"
        ]
    }
}
```

**<u>Important</u>**

> For security, the public token is validated against the <u>domain</u> provided during its creation. However, during development and testing, requests from localhost will not be subject to this domain validation. This allows you to build and test your integration locally before deploying it to your specified domain.

### 1.3. Setting up an endpoint to fulfil billing requests

When payers complete a checkout flow using GoCardless Components, you will receive a callback indicating that the created billing request is **ready to fulfil**.

In order for the billing request to be fulfilled and the associated mandate to become active, you, as an integrator, are responsible for making the /fulfil request to the GoCardless API upon receiving this callback.

To do this, you should create an endpoint which makes a request to POST /billing_requests/{{billing_request_id}}/actions/fulfil using a read/write access key for your organisation ([<u>see the API reference for more details</u>](https://developer.gocardless.com/api-reference#billing-requests-fulfil-a-billing-request)).

Before proceeding further, please ensure that you have a server set up with an accessible endpoint which can take a billing request ID and fulfil it using the GoCardless API.

Here is an example ruby implementation of a server set up with a /fulfil-billing-request endpoint that takes a billing request ID as a parameter:

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

# Set up the GoCardless client
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

# Define a route for fulfilling a billing request
post '/fulfil-billing-request/:billing_request_id' do
  # Get the billing request ID from the request body
  billing_request_id = params[:billing_request_id]

  # Get session token from the request headers
  session_token = request.env['HTTP_SESSION_TOKEN']

  begin
    # Validate session token
    validate_session_token(session_token, billing_request_id)

    # Fulfil the billing request
    fulfil_billing_request(billing_request_id)
rescue GoCardlessPro::Error => e
    status e.code
    content_type :json
    { success: false, error: e.message }.to_json
  end
end
```

## 2. Implementation

This section will guide you through how to embed Components into your webpage in order to allow customers to successfully set up an active mandate.

### 2.1. Add the GoCardless Components library to your project

#### 2.1.1 React

The GoCardless Components library is reliant on React being available as a **global variable** in order to function correctly.

You can add React as a global variable using the HTML <script> tag:

```html
<script
  crossorigin
  src="https://unpkg.com/react@18/umd/react.production.min.js"
></script>
<script
  crossorigin
  src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"
></script>
```

#### 2.1.2 GoCardless Components

You can find the latest version of GoCardless Components at [<u>https://ui-components.gocardless.com/v1/index.js</u>](https://ui-components.gocardless.com/v1/index.js).

To use GoCardless Components within your project, you will need to insert the library into your app via an HTML <script> tag:

```html
<script src="https://ui-components.gocardless.com/latest/index.js"></script>
```

### 2.2. Configure Components

Before creating and mounting any GoCardless Components into your webpage you first need to load your configuration options.

Your configuration options must include your public token and the scheme you want to use. They may also contain environment and customisation options.

Example:

```javascript
const config = {
  publicToken: YOUR_PUBLIC_TOKEN,
  environment: Environment.Sandbox,
  scheme: GcComponents.Scheme.Bacs,
};

GcComponents.loadConfig(config);
```

The full list of configuration options can be found in the following table:

| **Property Name** | **Description** | **Required?** |
| publicToken | A public token with the ui-components scope, valid in the selected environment | Yes |
| scheme | The payment scheme to use - at the moment only bacs is supported | Yes |
| environment | The environment you want the GoCardless Components to interact with - either live or sandbox. Defaults to live. | No |
| appearance | Custom appearance configuration (see [**<u>Customisation</u>**](#5_customisation)). All appearance variables that are not set in the config will fall back to the GoCardless Components default styling. | No |
| prefilledCustomer | Prefill the GoCardless Components billing form with customer details (see [**<u>Prefilled Customer details</u>**](#5_customisation)). | No |

### 2.3. Select where to mount GoCardless Components

When creating a GC Component, you need to specify where on your webpage it will be mounted.

Create a <div> in your app in the place you want the GC Component to be displayed and give it an intuitive identifier (i.e. gc-billing), to select when creating a component.

Example:

`<div id="gc-billing"></div>`

### 2.4. Create a Billing Component

A Billing component creates a billing request and guides the customer through the necessary steps to set up a mandate.

Billing components collect customer information (customer details, bank account information) to complete required actions for billing request fulfilment.

[<u>For more information about required actions for billing requests, please see our API reference.</u>](https://developer.gocardless.com/api-reference#billing-requests-billing-requests)

Use GcComponents.createBillingComponent(selector, options).mount() to create and mount a billing component onto the page.

Example:

```javascript
const config = {
  publicToken: YOUR_PUBLIC_TOKEN,
  environment: Environment.Sandbox,
  scheme: GcComponents.Scheme.Bacs,
};

// The config should be loaded before any components are created
GcComponents.loadConfig(config);

const componentOptions = {
  onSuccess: () => console.log("Success!"),
  onError: (error: GoCardlessError) => console.log("Error: ", error),
  onReadyToFulfil: (billingRequestId: string) => {
		// This method should call the endpoint from the Setup step to fulfil the billing request via the GoCardless API.
fulfil(billingRequestId);,
}
};
// Selector to identify the div where you want to embed the component
const selector = "#gc-billing";

GcComponents.createBillingComponent(selector, componentOptions).mount();

```

Billing component option callbacks explained:

| **Callback Name** | **Params** | **Trigger** | **Suggested Action** |
| onSuccess | N/A | Billing Component flow is complete and the BillingRequest has been fulfilled. | A success component will be displayed by GoCardless. You can redirect the payer to another success page if you wish. |
| onError | error: Error object containing the error type, message and any metadata | There was an error during the Billing Component flow. | An error component will be displayed by GoCardless and may give the option for the payer to retry. In some error scenarios you may want the payer to exit the flow. You can unmount the component if you wish. More details in [<u>Error Handling</u>](#4_error_handling). |
| onReadyToFulfil | billingRequestId: ID of billing request which is now ready to fulfil | The customer has submitted all the information required to fulfil the billing request. | Fulfil the billing request by calling your billing request fulfil endpoint in your backend service. |

**<u>Important</u>**

> You must implement the **onReadyToFulfil** callback otherwise the created billing request will not be fulfilled. The Billing Component will wait up to **10 seconds** for the billing request to fulfil before timing out and cancelling the billing request.

The mounted billing component will look something like this:

![Billing Component Form](https://images.ctfassets.net/b2dmfxhmyqno/4ijWPPkOy79UGHEm2Jg4Bv/c1148d005266c629ca3d484429a196dc/image.png)

## 3. Testing

After completing the above steps you should be ready to start creating and fulfilling billing requests using GoCardless Components. To make sure everything works as expected you should run through the checkout flow end to end and make sure that you can reach the confirmation screen without encountering any errors.

![Successful DD](https://images.ctfassets.net/b2dmfxhmyqno/1ixODKFBT0zE3UIVeoMS5W/26a80637449d8fe5ce342bf663b0c3c3/image.png)

After confirmation, you can go into the GoCardless dashboard or use the API to verify that the mandate has been set up.

## 4. Error Handling

### 4.1 Initialisation errors

We recommend rendering our Error Component when encountering an error initialising the library.

![Something went wrong](https://images.ctfassets.net/b2dmfxhmyqno/FWoFE1CTyv52mOH7qVB4v/531a11407f00ec297951d6ef9eb53ad2/som_wrong.png)

Example:

```javascript
const { success: configSuccess, error: configError } =
  await GcComponents.loadConfig(config);

if (configSuccess) {
  GcComponents.createBillingComponent(selector, componentOptions).mount();
} else {
  console.error(configError);
  GcComponents.createErrorComponent(selector, componentOptions).mount();
}
```

Common initialisation error messages and their description:

| **Error Message** | **Description** |
| Authentication failed | Authentication failed. Please check that you are using a public token valid in the selected environment, with the ui-components scope and from the domain specified in public token creation. |
| Missing configuration | Some required properties are missing from your config object. Please refer to the table of configuration properties and ensure that all required properties are present in your config |
| Scheme not supports | This means you have attempted to use a scheme that Components does not currently support. Please ensure config.scheme is set to bacs or GcComponents.Scheme.Bacs. |
| HTML element not found | The library was unable to find the element in which to embed the component using your provided selector. Please ensure your selector is valid. |

### 4.2 Troubleshooting checkout errors

When an error occurs during the checkout flow, GoCardless will render an Error Component and call your return onError callback function provided, passing along the GoCardlessError object.

![Something went wrong](https://images.ctfassets.net/b2dmfxhmyqno/FWoFE1CTyv52mOH7qVB4v/531a11407f00ec297951d6ef9eb53ad2/som_wrong.png)

```json
// Example of GoCardlessError object returned in the onError callback

{
  type: "authentication"
  message: "Authentication failed. Please check your configuration",
  metadata: {
    subType: "invalid_api_usage",
    requestId: "1f6f8649-6e40-4b50-936b-a8924dc7d2cb",
    statusCode: "401",
  },
  isUnrecoverableError: false,
}
```

GoCardlessError object description:

| **Error Field** | **Description** |
| type | The error type |
| message | The details error message |
| metadata | Associated metadata for the error including the subType, requestId and statusCode |
| isUnrecoverableError | Returns true if the error was unrecoverable by the GoCardless Component and it could not provide an option for the payer to continue or retry the checkout flow. If this scenario occurs, we recommend you provide the payer with the option to exit the flow. false otherwise. |

Common checkout flow error messages and their description:

| **Error Message** | **Description** |
| TimeoutError | Upon triggering your onReadyToFulfil callback, the Billing Component will wait up to **10 seconds** for the billing request to fulfil before timing out and cancelling the billing request. GoCardless will provide the retry option in this case if it can successfully cancel the original billing request and will ask the payer to try again. |
| Authentication | You may receive this error with the error subType as SessionTokenExpired. GoCardless Components uses session tokens to make requests to the GoCardless API. These session tokens are valid for **30 minutes**. If a session token expires before the user completes the flow they will need to restart. GoCardless will provide the retry option in this case. |

## 5. Customisation

The GC Component can be customised to fit the UI of your page. This is done through the optional appearance parameter provided in the configuration step.

Example:

```javascript
const appearanceVariables = {
  variables: {
    backgroundColor: "#bfe6f2",
    inputBorderRadius: "0px",
    wrapperBorderRadius: "0",
    textFontFamily: "Georgia, serif",
  },
};

const config = {
  publicToken: YOUR_PUBLIC_TOKEN,
  environment: Environment.Sandbox,
  scheme: GcComponents.Scheme.Bacs,
  appearance: appearanceVariables,
};

GcComponents.loadConfig(config);
```

You can modify colours, fonts, borders, padding etc. for a variety of different on-screen elements.

We recommend playing around with backgroundColor, textFontSize, textFontFamily, buttonColor and buttonBorderRadius to get started.

You may notice that GoCardless Components come with some default styling even when no appearance variables are provided. Any appearance variables you add will be applied on top of the default styles.

Full list of appearance variables and their default values:

```json
export const defaultTheme: AppearanceVariables = {
  backgroundColor: "#F9F9F9",

  buttonBorderRadius: "32px",
  buttonColor: "#1C1B18",
  buttonHoverBackgroundColor: "#545048",
  buttonHoverColor: "#faf9f7",
  buttonSubmitTextContent: "Set up this Direct Debit",
  buttonTextColor: "#FAF9F7",
  buttonTextFontSize: "12px",
  buttonTextFontWeight: FontWeight.medium,

  checkboxBackgroundColor: "#DFDFDF",
  checkboxSize: "16px",
  checkboxTextColor: "#1C1B18",
  checkboxTextFontSize: "14px",
  checkboxTextFontWeight: FontWeight.normal,

  dropdownFooterBackgroundColor: "#faf9f7",
  dropdownFooterBorderColor: "#dfddda",
  dropdownHoverBackgroundColor: "#1C1B18",
  dropdownHoverTextColor: "#FFFFFF",
  dropdownPadding: "8px",

  formValidationErrorColor: "#C52F2F",
  formVerticalSpacing: "12px",

  hintTextFontSize: "12px",
  hintTextFontWeight: "600",

  inputBackgroundColor: "#FFFFFF",
  inputBorderColor: "#8C8579",
  inputBorderRadius: "4px",
  inputPadding: "12px",
  inputPlaceholderColor: "#6E685E",
  inputTextColor: "#1C1B18",
  inputTextFontWeight: FontWeight.normal,

  labelTextColor: "#545048",
  labelTextFontSize: "14px",
  labelTextFontWeight: FontWeight.normal,

  linkHoverTextColor: "#1E1751",
  linkTextColor: "#5949CB",
  linkTextFontSize: "12px",
  linkTextFontWeight: FontWeight.normal,

  loadingSpinnerColor: "#1e1a14",

  textColor: "#000000",
  textFontFamily: 'Inter, "Helvetica Neue", Helvetica, Arial, sans-serif',
  textFontSize: "14px",
  textFontWeight: FontWeight.normal,

  wrapperBorderRadius: "8px",
  wrapperMargin: "16px",
};
```

## 6. Prefilled Customer details

The GoCardless Component allows prefilling customer details in the billing form. This is done through the optional prefilledCustomer parameter provided in the configuration step.

For security reasons, we don’t store and prefill any bank details. Only customer and customer billing details could be prefilled.

Here is a configuration example with a full list of prefilledCustomer fields:

```javascript
const prefilledCustomer = {
  firstName: "Components",
  lastName: "Tester",
  email: "components-tester@example.com",
  addressLine1: "65 Goswell Road",
  addressLine2: "",
  city: "London",
  postalCode: "EC1V 7EN",
};

const config = {
  publicToken: YOUR_PUBLIC_TOKEN,
  environment: Environment.Sandbox,
  scheme: GcComponents.Scheme.Bacs,
  prefilledCustomer: prefilledCustomer,
};

GcComponents.loadConfig(config);
```

With the example configuration, these details will be prefilled in the GoCardless Component billing form as shown below:

![Prefilled GC Component Billing Form](https://images.ctfassets.net/b2dmfxhmyqno/1vlBqqp3PHivmSKLLWklOA/decc53ce454c3e9bd84a8407cf5be32e/image.png)

## 7. Analytics and data tracking

GoCardless Components includes analytics and tracking features that allow us to collect usage data. We use this data to improve our products' performance and usability.

### 7.1 Data collection details

| **Purpose** | **Service** | **Cookies** | **Description** |
| **Analytics** | GoCardless | ajs_anonymous_id analytics_session_id analytics_session_id.last_access | We track user events such as clicks and form interactions to understand how users interact with the components. This data helps us improve the user experience and product usability. Data is sent to a third-party analytics provider, Segment, to facilitate processing. |

As an integrator, it is your responsibility to obtain and manage user consent for data collection. We recommend you adhere to the following principles:

- **Explicit Consent:** You must obtain explicit user consent (e.g., via a clear "Accept" button) before enabling non-essential tracking. Note that some data, such as error telemetry, may be considered essential for product functionality and security.
- **Transparency:** Clearly inform users about the data being collected, the purpose of collection, and the third parties involved (GoCardless and Segment). This information should be included in your site's cookie policy or privacy notice.
- **Clear Language:** Use concise and easy-to-understand language without technical jargon.

### 7.2 Configure data collection

Data collection is enabled by default. You can configure this in your configuration when initializing Components.

```javascript
const config = {
  ...
  enableAnalytics: true, // set to false to not send analytics to GoCardless
};

GcComponents.loadConfig(config);
```
