GoCardlessDeveloper Docs
Create a sandbox account

GoCardless Remember Me Components#

View as Markdown

GoCardless Components is a JavaScript component library aimed at providing GoCardless integrators with customisable functionality for creating checkout flows without the need to build their own from scratch using the API.

This document explains how Remember Me works with GoCardless Components, and how to integrate the standalone Remember Me components into your own checkout flow.

Overview#

Remember Me lets returning customers skip re-entering their details. When a customer enters an email address GoCardless has seen before, they verify their identity and their saved details are pre-filled. New customers can opt in to have their details saved for next time.

Using the Billing Request component?

If you're using the Billing Request component, Remember Me is already included and appears automatically — you don't need anything from this page. This page is for custom checkouts that need standalone Remember Me components.

This page covers the standalone ReturnFlow and Signup components for custom checkouts that don't use the Billing Request component. You'll mount and configure these components yourself to integrate Remember Me into your existing checkout flow.

Remember Me currently supports the Bacs scheme only.

1. Prerequisites#

1.1. Billing Request Setup (standalone components only)#

The standalone Remember Me components require a valid Billing Request ID to function. The Billing Request component creates its own, so you can skip this section if you use it. Ensure you can:

  1. Create billing requests via the GoCardless API
  2. Pass billing request IDs to your frontend
  3. Fulfil billing requests from your backend

If you haven't created a billing request yet, see the GoCardless API Documentation.

1.2. Requirements#

The standalone Remember Me components have the same requirements as the main Components library:

  1. Access token with GoCardless Components enabled
    • Remember Me is enabled automatically when you enable GoCardless Components on an access token — there is no separate setup required
    • See Getting an access token for the full setup process
  2. A server endpoint that mints session tokens
  3. Billing Request created and passed to your frontend
    • The standalone components require a billing request ID (see section 1.1 above)

2. Standalone Components#

The rest of this page is only needed if you are using the standalone components. If you use the Billing Request component, you don't need anything else from this page.

2.1. Component Types#

GoCardless provides two standalone Remember Me components:

ReturnFlow Component#

Used at the start of checkout to recognise and verify returning customers who have previously saved their details with GoCardless.

  • Use when: Customer enters checkout flow
  • Purpose: Recognise customers via email and complete verification to pre-fill payment details
  • Recommended location: Top of checkout page, before any form fields

ReturnFlow Component

Signup Component#

Used during checkout to allow new customers to opt-in to saving their details for future use.

  • Use when: New customer completes payment or at any point in the checkout flow as long as the billing request has been created or started.
  • Purpose: Saves customer details for a faster checkout experience in the future
  • Recommended location: Payment confirmation page, below success message or inline during checkout as opt-in checkbox

Signup Component

3. Installation#

3.1. Add GoCardless Components Library#

Add the latest version of the GoCardless Components library:

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

Loading this script attaches GcComponents to the global window object. You don't need to load React or a separate stylesheet.

Load the library with a regular <script src="..."> tag. The Remember Me components are loaded on demand from the same location as this script, so it can't be copied into your own bundle or inlined.

Using the latest version of the GoCardless Components library is advised during the development and testing phases of the integration.

However, for go-live, it is recommended to use a specific version of the GoCardless Components library, by replacing latest with the full version number. Remember Me requires version 2.25.0 or later:

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

3.2. TypeScript Configuration#

If you're using TypeScript, add global type definitions to enable proper type checking for the GoCardless Components library.

Create Global Type Definitions#

Create a file at src/types/global.d.ts with the following content:

type Environment = "sandbox" | "live";
 
// The parts of the billing request that the examples on this page read.
// The full billing request has more fields, see the API reference.
interface BillingRequestResource {
  id: string;
  status?: string;
  resources?: {
    customer?: {
      id?: string;
      email?: string | null;
      given_name?: string | null;
      family_name?: string | null;
      company_name?: string | null;
      phone_number?: string | null;
    };
    customer_billing_detail?: {
      address_line1?: string | null;
      address_line2?: string | null;
      city?: string | null;
      region?: string | null;
      postal_code?: string | null;
      country_code?: string | null;
    };
    customer_bank_account?: {
      account_holder_name?: string;
      account_number_ending?: string;
      branch_code_ending?: string;
      bank_name?: string;
    } | null;
  };
}
 
interface GoCardlessError {
  code: number;
  message: string;
  isUnrecoverable: boolean;
  type?: string;
  requestId?: string;
  errors?: { request_pointer: string; message: string; reason?: string }[];
}
 
interface GcComponentsConfig {
  environment: Environment;
  sessionToken: () => Promise<string>;
  appearance?: Record<string, string>;
  enableAnalytics?: boolean;
  onEvent?: (event: unknown) => void;
  onError?: (error: GoCardlessError) => void;
  locale?: string;
}
 
interface MountedComponent {
  mount: (target: string) => Promise<void>;
  unmount: () => void;
}
 
interface RememberMeSignupConfig {
  billingRequestId: string;
  email: string;
  appearance?: Record<string, string>;
  onSuccess?: (result: { email?: string; phoneNumber?: string | null }) => void;
  onError?: (error: GoCardlessError) => void;
}
 
interface RecognisedCustomerData {
  email: string;
  phoneNumber?: string | null;
}
 
interface CustomerRecognitionResult {
  recognised: boolean;
  customerData?: RecognisedCustomerData;
}
 
interface VerificationResult {
  success: boolean;
  billingRequest?: BillingRequestResource;
  error?: Error;
}
 
type VerificationExitPoint = "user_closed" | "verification_failed" | "verification_success";
 
interface RememberMeReturnFlowConfig {
  billingRequestId: string;
  defaultEmail?: string;
  appearance?: Record<string, string>;
  onChange?: (email: string) => void;
  onCustomerRecognitionCheck?: (result: CustomerRecognitionResult) => void;
  onVerificationAttempt?: (result: VerificationResult) => void;
  onVerificationExit?: (exitPoint: VerificationExitPoint) => void;
  onError?: (error: GoCardlessError) => void;
}
 
interface GcComponentsInstance {
  createComponent(
    name: "remember-me-return-flow",
    config: RememberMeReturnFlowConfig,
  ): MountedComponent;
  createComponent(name: "remember-me-signup", config: RememberMeSignupConfig): MountedComponent;
  unmountAll: () => void;
}
 
interface Window {
  GcComponents: {
    init: (config: GcComponentsConfig) => GcComponentsInstance;
  };
}

This provides type safety for the window.GcComponents global object and makes all the callback interfaces (such as VerificationResult and GoCardlessError) available throughout your project without importing them.

The file has no import or export, so TypeScript treats it as a global declaration file. Don't add one, or the types stop being global.

Update tsconfig.json#

Ensure your tsconfig.json includes the directory containing the file:

{
  "include": ["src"]
}

3.3. Using the useGoCardlessComponents Hook (React)#

For React applications, create a custom hook to detect when the GoCardless Components library has loaded:

Create the Hook#

Create a file at src/hooks/useGoCardlessComponents.ts:

import { useState, useEffect } from "react";
 
export function useGoCardlessComponents() {
  const [isLoaded, setIsLoaded] = useState(false);
  const [error, setError] = useState<Error | null>(null);
 
  useEffect(() => {
    let attempts = 0;
    const maxAttempts = 10;
 
    const checkComponentsLoaded = () => {
      attempts++;
 
      // Check if the global GcComponents library is available
      if (window.GcComponents) {
        setIsLoaded(true);
        return;
      }
 
      if (attempts >= maxAttempts) {
        const err = new Error(
          "GoCardless Components failed to load. Please check your internet connection.",
        );
        setError(err);
        return;
      }
 
      // Retry after 100ms
      setTimeout(checkComponentsLoaded, 100);
    };
 
    checkComponentsLoaded();
  }, []);
 
  return { isLoaded, error };
}

Using the Hook#

import { useGoCardlessComponents } from '../hooks/useGoCardlessComponents';
 
const CheckoutPage = () => {
  const { isLoaded, error } = useGoCardlessComponents();
 
  if (error) {
    return <div>Error: {error.message}</div>;
  }
 
  if (!isLoaded) {
    return <div>Loading GoCardless Components...</div>;
  }
 
  // Proceed with rendering components
  return <div>{/* Your checkout form */}</div>;
};

3.4. Configure Components#

Initialise the library once, then use the returned instance to create the components:

const gc = GcComponents.init({
  environment: "sandbox", // or "live"
  sessionToken: () => fetch("/your-backend/session-token").then((r) => r.text()),
  enableAnalytics: true, // Optional: defaults to true
  onError: (error) => console.error(error),
});

Configuration Options#

PropertyDescriptionRequired
environmentThe environment in which you want to use the components (sandbox or live)Yes
sessionTokenA callback returning a fresh session token (see Prerequisites)Yes

The library also accepts optional appearance, enableAnalytics, onEvent, onError and locale settings. These work the same as for the Billing Request component, see Configure the Library for the full list.

The publicToken and scheme options and the loadConfig method from earlier versions of this page are no longer used. Authentication is handled by the session token, and Remember Me is currently available for the Bacs scheme only.

3.5. 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-return-flow), to select when creating a component.

Example:

<div id="gc-billing-return-flow"></div>
 
<div id="gc-billing-signup"></div>

4. Frontend Implementation#

4.1. Implementing ReturnFlow for Returning Customers#

The ReturnFlow component should be placed at the beginning of your checkout flow to recognise and verify returning customers.

Basic Implementation#

const billingRequestId = "BR123456"; // From your backend
 
const returnFlow = gc.createComponent("remember-me-return-flow", {
  billingRequestId,
  defaultEmail: "", // Optional: pre-fill email if available
  onCustomerRecognitionCheck: (result) => {
    if (result.recognised) {
      console.log("Customer recognised", result.customerData);
      // Customer found - they will be prompted for verification
    } else {
      console.log("Customer not recognised - show standard checkout");
      // Show your normal checkout form
    }
  },
  onVerificationAttempt: (result) => {
    if (result.success) {
      console.log("Verification complete");
      // Pre-fill customer details from result.billingRequest
      // Navigate to confirmation page
    }
  },
  onVerificationExit: (exitPoint) => {
    if (exitPoint === "user_closed") {
      // User cancelled - show manual entry option
      console.log("User cancelled verification");
    } else if (exitPoint === "verification_failed") {
      // Verification failed - offer retry or manual entry
      console.log("Verification failed");
    }
  },
  onError: (error) => {
    console.error("Remember Me error:", error);
    // Fallback to standard checkout
  },
});
 
await returnFlow.mount("#gc-billing-return-flow");

gc is the instance returned by GcComponents.init(...) in Configure Components, and #gc-billing-return-flow is the <div> described in Select where to mount GoCardless Components. mount is asynchronous: it resolves once the component has loaded and been added to the page.

To remove the component, for example when the customer navigates away, call returnFlow.unmount().

ReturnFlow Config#

PropertyTypeRequiredDescription
billingRequestIdstringYesUnique billing request ID for this transaction
defaultEmailstringNoPre-populate email field (e.g., from logged-in session)
onCustomerRecognitionCheckfunctionNoCalled when customer recognition check completes
onVerificationAttemptfunctionNoCalled when verification is attempted
onVerificationExitfunctionNoCalled when user exits verification flow
onErrorfunctionNoCalled on error. Takes priority over the onError passed to GcComponents.init
onChangefunctionNoHandles the input change when the payer enters their email address
appearanceobjectNoAppearance variables for this component, merged on top of the global appearance (see Customisation)

Callback Data Structures#

onCustomerRecognitionCheck:

{
  recognised: boolean,
  customerData?: {
    email: string,
    phoneNumber?: string | null
  }
}

onVerificationAttempt:

{
  success: boolean,
  billingRequest?: BillingRequestResource,
  error?: Error
}

onVerificationExit:

// exitPoint values:
"user_closed" | "verification_failed" | "verification_success";

After a successful verification, onVerificationExit can be called before onVerificationAttempt, because the component confirms the payer details before it calls onVerificationAttempt. Don't rely on the order of the two callbacks. Use onVerificationAttempt to read the customer's details.

4.2. Using ReturnFlow Inside a Form#

The ReturnFlow component can be embedded directly inside your checkout form to provide a seamless experience. The component replaces the email input field and handles customer recognition and verification.

Implementation Example#

import React, { useState, useEffect } from 'react';
import { useGoCardlessComponents } from '../hooks/useGoCardlessComponents';
 
// These types come from the global.d.ts file in section 3.2
interface CheckoutFormProps {
  billingRequestId: string;
  onCustomerRecognitionCheck: (result: CustomerRecognitionResult) => void;
  onVerificationAttempt: (result: VerificationResult) => void;
  onVerificationExit: (exitPoint: VerificationExitPoint) => void;
  onError: (error: GoCardlessError) => void;
}
 
const CheckoutForm = ({
  billingRequestId,
  onCustomerRecognitionCheck,
  onVerificationAttempt,
  onVerificationExit,
  onError,
}: CheckoutFormProps) => {
  const { isLoaded } = useGoCardlessComponents();
  const [formData, setFormData] = useState({
    email: '',
    firstName: '',
    lastName: '',
    // ... other fields
  });
 
  // Mount the Remember Me ReturnFlow component
  useEffect(() => {
    if (!isLoaded || !billingRequestId) return;
 
    const gc = window.GcComponents.init({
      environment: 'sandbox', // or 'live'
      sessionToken: () => fetch('/your-backend/session-token').then((r) => r.text()),
    });
 
    const returnFlow = gc.createComponent('remember-me-return-flow', {
      billingRequestId,
      defaultEmail: formData.email,
      // Sync email changes to form state
      onChange: (email) => {
        setFormData((prev) => ({ ...prev, email }));
      },
      onCustomerRecognitionCheck,
      onVerificationAttempt,
      onVerificationExit,
      onError,
    });
 
    returnFlow.mount('#gc-remember-me-return-flow');
 
    // Cleanup on unmount
    return () => {
      returnFlow.unmount();
    };
  }, [isLoaded, billingRequestId]);
 
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    // Submit form data
  };
 
  return (
    <form onSubmit={handleSubmit}>
      <h2>Checkout</h2>
 
      {/* ReturnFlow component mounts here and replaces email input */}
      <div className="form-group">
        <div id="gc-remember-me-return-flow"></div>
      </div>
 
      <div className="form-row">
        <div className="form-group">
          <label>First Name *</label>
          <input
            type="text"
            name="firstName"
            value={formData.firstName}
            onChange={(e) => setFormData({ ...formData, firstName: e.target.value })}
          />
        </div>
 
        <div className="form-group">
          <label>Last Name *</label>
          <input
            type="text"
            name="lastName"
            value={formData.lastName}
            onChange={(e) => setFormData({ ...formData, lastName: e.target.value })}
          />
        </div>
      </div>
 
      {/* Additional form fields */}
 
      <button type="submit">Complete Checkout</button>
    </form>
  );
};

Key Points#

  • The ReturnFlow component replaces the email input field in your form
  • Use the onChange callback to sync the email value to your form state
  • Mount the component in a dedicated <div> with a unique ID
  • The component handles email recognition and verification automatically
  • After verification, the customer's saved details are available on result.billingRequest in the onVerificationAttempt callback (see the next section)
  • The example calls GcComponents.init inside the effect to keep it self-contained. In your app, initialise the library once and reuse the instance for every component

4.3. Auto-filling Form Inputs After Verification#

When a returning customer successfully verifies their identity, you should auto-fill the form fields with their saved information from the billing request.

Extracting Customer Data#

The onVerificationAttempt callback receives a VerificationResult object containing the billing request with customer data. The customer's details are only available here, after verification succeeds. Before that, the billing request does not contain them (the email, for example, is only available as customerData.email in onCustomerRecognitionCheck):

const handleVerificationSuccess = (result: VerificationResult) => {
  if (result.success && result.billingRequest) {
    const { resources } = result.billingRequest;
    const customer = resources?.customer;
    const billingDetail = resources?.customer_billing_detail;
    const bankAccount = resources?.customer_bank_account;
 
    // Extract and parse customer data
    if (customer && billingDetail) {
      // Parse address line 1 to extract house number and street
      const addressLine1 = billingDetail.address_line1 || "";
      const addressParts = addressLine1.match(/^(\S+)\s+(.+)$/);
 
      // Any of these can be null, so fall back to an empty string
      const customerData = {
        email: customer.email || "",
        // For a business payer, GoCardless returns company_name instead of the
        // names. If your form has a business option, use it to fill that field
        firstName: customer.given_name || "",
        lastName: customer.family_name || "",
        companyName: customer.company_name || "",
        houseNumber: addressParts?.[1] || "",
        flatNumber: billingDetail.address_line2 || "",
        streetName: addressParts?.[2] || addressLine1,
        townCity: billingDetail.city || "",
        postcode: billingDetail.postal_code || "",
        // Often empty for UK addresses
        county: billingDetail.region || "",
      };
 
      // Update form state with customer data
      setFormData(customerData);
    }
 
    // Store masked bank account for display
    if (bankAccount) {
      setMaskedBankAccount(bankAccount);
    }
 
    // Mark customer as verified
    setIsVerified(true);
  }
};

Updating Form Inputs#

Make sure your form inputs are controlled components that respond to state changes:

// Use useEffect to update form data when verification completes
useEffect(() => {
  if (verifiedCustomerData) {
    setFormData((prev) => ({
      ...prev,
      ...verifiedCustomerData,
    }));
  }
}, [verifiedCustomerData]);
 
// Form inputs automatically reflect the updated state
<input
  type="text"
  name="firstName"
  value={formData.firstName}  // This updates automatically
  onChange={handleChange}
/>

Displaying Saved Bank Account#

For verified customers with saved bank accounts, display the masked account details:

{maskedBankAccount ? (
  <div className="masked-account-section">
    <div className="masked-account-info">
      <p><strong>Account Holder:</strong> {maskedBankAccount.account_holder_name}</p>
      <p><strong>Account Number:</strong> ****{maskedBankAccount.account_number_ending}</p>
      {maskedBankAccount.bank_name && (
        <p><strong>Bank:</strong> {maskedBankAccount.bank_name}</p>
      )}
    </div>
    <button type="button" onClick={() => setShowBankAccountEdit(true)}>
      Edit Bank Details
    </button>
  </div>
) : (
  // Show manual bank account input fields
  <div className="bank-account-fields">
    {/* Account number, sort code, etc. */}
  </div>
)}

4.4. Implementing Signup for New Customers#

The Signup component should be shown to new customers during the flow or after successful payment to allow them to opt-in to Remember Me.

Basic Implementation#

<h1>Payment Successful!</h1>
 
<p>Thank you for your payment.</p>
 
<div id="gc-billing-signup"></div>
<p id="signup-confirmation" hidden>Your details have been saved for faster checkout next time</p>
const billingRequestId = "BR123456"; // From your backend
const customerEmail = "[email protected]";
 
const signup = gc.createComponent("remember-me-signup", {
  billingRequestId,
  email: customerEmail,
  onSuccess: (result) => {
    console.log("Customer enrolled in Remember Me:", result);
    signup.unmount();
    document.getElementById("signup-confirmation").hidden = false;
  },
  onError: (error) => {
    console.error("Signup failed:", error);
    // Optional: Show user-friendly message
    // Don't block user from proceeding if signup fails
  },
});
 
await signup.mount("#gc-billing-signup");

gc is the instance returned by GcComponents.init(...) in Configure Components.

Signup Config#

PropertyTypeRequiredDescription
billingRequestIdstringYesBilling request ID for this transaction
emailstringYesCustomer's email address (already validated)
onSuccessfunctionNoCalled when customer details are successfully saved
onErrorfunctionNoCalled if enrollment fails. Takes priority over the onError passed to GcComponents.init
appearanceobjectNoAppearance variables for this component, merged on top of the global appearance (see Customisation)

Callback Data Structures#

onSuccess:

{
  email?: string;
  phoneNumber?: string | null;
}

5. Customisation#

5.1. Theming#

Both components use the GoCardless theme by default. The theme automatically adapts to create a cohesive experience.

The Remember Me components can be customised to fit the UI of your page. This is done through the optional appearance object, which you can pass to GcComponents.init to style every component on the page, or to createComponent to style a single component. When both are set, the component's appearance takes priority.

Example:

const gc = GcComponents.init({
  environment: "sandbox",
  sessionToken: () => fetch("/your-backend/session-token").then((r) => r.text()),
  appearance: {
    backgroundColor: "#bfe6f2",
    inputBorderRadius: "0px",
    wrapperBorderRadius: "0",
    textFontFamily: "Georgia, serif",
    buttonPrimaryColor: "#004d40",
  },
});
 
gc.createComponent("remember-me-return-flow", {
  billingRequestId,
}).mount("#gc-billing-return-flow");
 
gc.createComponent("remember-me-signup", {
  billingRequestId,
  email: customerEmail,
  // Optional: overrides the global appearance for this component only
  appearance: { buttonPrimaryColor: "#00a000" },
}).mount("#gc-billing-signup");

You can modify colours, fonts, borders, padding etc. for a variety of different on-screen elements. We recommend playing around with backgroundColor, textFontFamily, buttonPrimaryColor 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.

Appearance variables are now passed as a flat object, without the variables wrapper used in earlier versions of this page, and some have been renamed (for example buttonColor is now buttonPrimaryColor).

The appearance variables are shared with the Billing Request component. See Customisation for the full list of variables and their default values.

What's next?#