# Remember Me Components

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

# GoCardless Remember Me Components

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 to integrate the Remember Me components into your checkout flow.

## 1. Prerequisites

### 1.1. Billing Request Setup

Remember Me components require a valid Billing Request ID to function. 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](/docs/api-reference/billing-request).

### 1.2. Requirements

Before implementing Remember Me components, ensure you have:

1. **Active GoCardless Account** with the GoCardless Components upgrade activated
   - Contact your implementation manager to enable this
2. **Public Token** with appropriate scopes

   To generate a public token via the dashboard, go to [https://manage-sandbox.gocardless.com/developers/public-tokens](https://manage-sandbox.gocardless.com/developers/public-tokens) and do the following:

   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_remember_me` scope
   5. Click **Create**

3. **Billing Request** implemented
   - Must have an existing billing request created

## 2. Components

### 2.1. Component Types

GoCardless provides two 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](/images/components/remember-me-return-flow.png)

#### 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](/images/components/remember-me-signup.png)

## 3. Installation

### 3.1. Add GoCardless Components Library

#### React Dependency

The GoCardless Components library requires React as a global variable:

```html
```

#### GoCardless Components

Add the latest version of the GoCardless Components library:

```html
```

To patch the styling of the Signup component of the GoCardless Components library, link the compiled CSS globally in the build:

```html
```

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:

```html
```

```html
```

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

```typescript

interface RememberMeReturnConfigurationParams ;
}

interface MountableComponent 

interface LoadConfigResponse 

enum Environment 

enum Scheme 

interface RememberMeSignupProps ) => void;
}

interface RecognisedCustomerData 

interface CustomerRecognitionResult 

interface VerificationResult 

enum VerificationExitPoint 

export interface RememberMeReturnFlowProps 

declare global ;
  }
}

export ;
```

This provides type safety for the `window.GcComponents` global object and all callback interfaces.

#### Update tsconfig.json

Ensure your `tsconfig.json` includes the types directory:

```json
,
  "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`:

```typescript

export function useGoCardlessComponents() 

      if (attempts >= maxAttempts) 

      // Retry after 100ms
      setTimeout(checkComponentsLoaded, 100);
    };

    checkComponentsLoaded();
  }, []);

  return ;
}
```

#### Using the Hook

```typescript

const CheckoutPage = () =>  = useGoCardlessComponents();

  if (error) ;
  }

  if (!isLoaded) 

  // Proceed with rendering components
  return ;
};
```

### 3.4. Configure Components

Load your configuration before creating components:

```typescript
const config = ;

GcComponents.loadConfig(config);
```

#### Configuration Options

| Property          | Description                                                  | Required |
| ----------------- | ------------------------------------------------------------ | -------- |
| `publicToken`     | Your public token with the `ui_components_remember_me` scope | Yes      |
| `environment`     | `Sandbox` or `Live`                                          | Yes      |
| `scheme`          | Payment scheme (currently only Bacs supported)               | Yes      |
| `enableAnalytics` | Enable usage analytics (default: `true`)                     | No       |

### 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 `` 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:

```html
```

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

```typescript
const CheckoutPage = () =>  else 
  };

  const handleVerificationSuccess = (result) => 
  };

  const handleVerificationExit = (exitPoint) =>  else if (exitPoint === 'verification_failed') 
  };

  const handleError = (error) => ;

  return (
    Checkout
      
    );
};
```

#### ReturnFlow Props

| Prop                         | Type     | Required | Description                                                        |
| ---------------------------- | -------- | -------- | ------------------------------------------------------------------ |
| `billingRequestId`           | string   | Yes      | Unique billing request ID for this transaction                     |
| `defaultEmail`               | string   | No       | Pre-populate email field (e.g., from logged-in session)            |
| `onCustomerRecognitionCheck` | function | No       | Called when customer recognition check completes                   |
| `onVerificationAttempt`      | function | No       | Called when verification is attempted                              |
| `onVerificationExit`         | function | No       | Called when user exits verification flow                           |
| `onError`                    | function | No       | Global error handler                                               |
| `onChange`                   | function | No       | Handles the input change when the payer enters their email address |

#### Callback Data Structures

**onCustomerRecognitionCheck:**

```typescript

}
```

**onVerificationAttempt:**

```typescript

```

**onVerificationExit:**

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

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

```typescript

const CheckoutForm = () =>  = useGoCardlessComponents();
  const componentInstance = useRef(null);
  const [formData, setFormData] = useState();

  // Mount the RememberMeReturnFlow component
  useEffect(() => ;

    const mountComponent = async () =>  = await window.GcComponents.loadConfig(config);

      if (success) ));
          },
          onCustomerRecognitionCheck,
          onVerificationAttempt,
          onVerificationExit,
          onError,
        };

        componentInstance.current =
          window.GcComponents.createRememberMeReturnFlowComponent(
            '#gc-remember-me-return-flow',
            options
          );
        componentInstance.current.mount();
      }
    };

    mountComponent();

    // Cleanup on unmount
    return () => 
    };
  }, [isLoaded, billingRequestId]);

  const handleSubmit = (e) => ;

  return (
    Checkout
      First Name *setFormData()}
          />
        Last Name *setFormData()}
          />
        

      Complete Checkout);
};
```

#### 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 `` with a unique ID
- The component handles email recognition and verification automatically
- After verification, the customer's email is available in the `onVerificationAttempt` callback

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

```typescript
const handleVerificationSuccess = (result: VerificationResult) =>  = 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) ;

      // Update form state with customer data
      setFormData(customerData);
    }

    // Store masked bank account for display
    if (bankAccount) 

    // Mark customer as verified
    setIsVerified(true);
  }
};
```

#### Updating Form Inputs

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

```typescript
// Use useEffect to update form data when verification completes
useEffect(() => ));
  }
}, [verifiedCustomerData]);

// Form inputs automatically reflect the updated state
```

#### Displaying Saved Bank Account

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

```typescript
Account Number:****)}
    setShowBankAccountEdit(true)}>
      Edit Bank Details
    ) : (
  // Show manual bank account input fields
  
  )}
```

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

```typescript

const PaymentConfirmationPage = () => );
  };

  const handleSignupError = (error) => ;

  return (
    Payment Successful!Thank you for your payment.

      
    );
};
```

#### Signup Props

| Prop               | Type     | Required | Description                                         |
| ------------------ | -------- | -------- | --------------------------------------------------- |
| `billingRequestId` | string   | Yes      | Billing request ID for this transaction             |
| `email`            | string   | Yes      | Customer's email address (already validated)        |
| `onSuccess`        | function | No       | Called when customer details are successfully saved |
| `onError`          | function | No       | Called if enrollment fails                          |

#### Callback Data Structures

**onSuccess:**

```typescript

```

## 5. Customisation

### 5.1. Theming

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

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 = ,
};

const config = ;

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:

```typescript
export const defaultTheme: AppearanceVariables = ;
```

## What's next?

  
#### [GoCardless Components](/docs/collect-payments/integration-types/gocardless-components)

Learn about the core GoCardless Components library for setting up mandates.

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

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