GoCardlessDeveloper Docs
Create a sandbox account

GoCardless Components#

View as Markdown

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, 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.

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, Drop-in Flow, or Custom Payment Pages instead.

1. Setup#

You can skip to 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 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:

POST /public_tokens
Authorization: Bearer <oauth_access_token>
 
{
  "public_tokens": {
    "name": "My Public Token",
    "domain": "example.com",
    "scopes": ["ui_components"]
  }
}

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/{billing_request_id}/actions/fulfil from your server at that point.

See the API reference for full details.

Example fulfilment endpoint in 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
    { success: false, error: e.message }.to_json
  end
end

2. Implementation#

2.1. Add the library to your project#

Components requires React as a global variable:

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

Then add the GoCardless Components library:

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

2.2. Configure Components#

Load your configuration before creating any components:

const config = {
  publicToken: YOUR_PUBLIC_TOKEN,
  environment: Environment.Sandbox,
  scheme: GcComponents.Scheme.Bacs,
};
 
GcComponents.loadConfig(config);
PropertyDescriptionRequired
publicTokenA public token with the ui_components scope, valid in the selected environmentYes
schemeThe payment scheme — only bacs is currently supportedYes
environmentlive or sandbox. Defaults to liveNo
appearanceCustom appearance configuration — see CustomisationNo
prefilledCustomerPrefill the billing form with customer details — see Prefilled Customer DetailsNo

2.3. Select a mount target#

Create a <div> where you want the component to appear:

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

2.4. Create a Billing Component#

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

const config = {
  publicToken: YOUR_PUBLIC_TOKEN,
  environment: Environment.Sandbox,
  scheme: GcComponents.Scheme.Bacs,
};
 
GcComponents.loadConfig(config);
 
const componentOptions = {
  onSuccess: () => console.log("Success!"),
  onError: (error) => console.log("Error: ", error),
  onReadyToFulfil: (billingRequestId) => {
    fulfil(billingRequestId);
  },
};
 
GcComponents.createBillingComponent("#gc-billing", componentOptions).mount();
CallbackParamsTriggerSuggested action
onSuccessBilling request fulfilled successfullyShow a success state or redirect the payer
onErrorerror — object with type, message, metadataError during the flowGoCardless shows an error screen; unmount if needed
onReadyToFulfilbillingRequestId — ID of the ready-to-fulfil requestPayer has submitted all required informationCall your fulfilment endpoint

Billing Component Form

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

4. Error handling#

4.1. Initialisation errors#

Render the Error Component if loadConfig fails:

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();
}

Error state

Error messageDescription
Authentication failedInvalid public token, wrong environment, wrong scope, or mismatched domain
Missing configurationRequired config properties are absent
Scheme not supportedThe scheme provided is not supported — use bacs or GcComponents.Scheme.Bacs
HTML element not foundThe 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:

{
  "type": "authentication",
  "message": "Authentication failed. Please check your configuration",
  "metadata": {
    "subType": "invalid_api_usage",
    "requestId": "1f6f8649-6e40-4b50-936b-a8924dc7d2cb",
    "statusCode": "401"
  },
  "isUnrecoverableError": false
}
FieldDescription
typeError type
messageDetailed error message
metadatasubType, requestId, statusCode
isUnrecoverableErrortrue if GoCardless could not offer a retry — provide the payer a way to exit
ErrorDescription
TimeoutErroronReadyToFulfil 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:

const config = {
  publicToken: YOUR_PUBLIC_TOKEN,
  environment: Environment.Sandbox,
  scheme: GcComponents.Scheme.Bacs,
  appearance: {
    variables: {
      backgroundColor: "#bfe6f2",
      inputBorderRadius: "0px",
      wrapperBorderRadius: "0",
      textFontFamily: "Georgia, serif",
    },
  },
};

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

Full default theme:

{
  "backgroundColor": "#F9F9F9",
  "buttonBorderRadius": "32px",
  "buttonColor": "#1C1B18",
  "buttonHoverBackgroundColor": "#545048",
  "buttonHoverColor": "#faf9f7",
  "buttonSubmitTextContent": "Set up this Direct Debit",
  "buttonTextColor": "#FAF9F7",
  "buttonTextFontSize": "12px",
  "buttonTextFontWeight": "medium",
  "checkboxBackgroundColor": "#DFDFDF",
  "checkboxSize": "16px",
  "checkboxTextColor": "#1C1B18",
  "checkboxTextFontSize": "14px",
  "checkboxTextFontWeight": "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": "normal",
  "labelTextColor": "#545048",
  "labelTextFontSize": "14px",
  "labelTextFontWeight": "normal",
  "linkHoverTextColor": "#1E1751",
  "linkTextColor": "#5949CB",
  "linkTextFontSize": "12px",
  "linkTextFontWeight": "normal",
  "loadingSpinnerColor": "#1e1a14",
  "textColor": "#000000",
  "textFontFamily": "Inter, \"Helvetica Neue\", Helvetica, Arial, sans-serif",
  "textFontSize": "14px",
  "textFontWeight": "normal",
  "wrapperBorderRadius": "8px",
  "wrapperMargin": "16px"
}

6. Prefilled customer details#

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

const config = {
  publicToken: YOUR_PUBLIC_TOKEN,
  environment: Environment.Sandbox,
  scheme: GcComponents.Scheme.Bacs,
  prefilledCustomer: {
    firstName: "Components",
    lastName: "Tester",
    email: "components-tester@example.com",
    addressLine1: "65 Goswell Road",
    addressLine2: "",
    city: "London",
    postalCode: "EC1V 7EN",
  },
};

Prefilled form

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:

const config = {
  publicToken: YOUR_PUBLIC_TOKEN,
  environment: Environment.Sandbox,
  scheme: GcComponents.Scheme.Bacs,
  enableAnalytics: false,
};
PurposeServiceCookiesDescription
AnalyticsGoCardless / Segmentajs_anonymous_id, analytics_session_id, analytics_session_id.last_accessTracks 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?#