This guide helps you get started with the Checkout SDK on web browsers.

Prerequisite

  • A Mangopay ClientId and API key (get a Sandbox API key for free)
  • A User and their associated Wallet to complete the pay-in
  • A card to register or payment method setup (see Testing - Payment methods for testing information)

Supported browsers: Chrome 117, Firefox 118, Safari 16, or higher

Best practice – Check out our example app and demo

To support you with your integration, be sure to make use of our example app on GitHub, and you can clone our PlayCode demo to experiment with the code and see real-time results.

Installation

You can install the Mangopay Checkout SDK using npm or yarn.

Install with npm:

npm install --save @mangopay/checkout-sdk

Install with yarn:

yarn add @mangopay/checkout-sdk

Install via CDN

If you are using script tags to load files, include the Mangopay SDK script in your HTML:

<script src="https://checkout.mangopay.com/sdk/checkout-sdk.min.js"></script>

Warning – Load script from Mangopay Checkout domain

To maintain PCI compliance, the script must be loaded directly from the Mangopay Checkout domain:

http://checkout.mangopay.com

The script must not be bundled or hosted on other domains. You must reference it directly from our domain.

Content Security Policy (CSP)

Caution - Allow policies if using CSP

If your web page is using the Content-Security-Policy response header, you need to allow the policies below.

PolicyURLs
script-src*.google.com
connect-src

api.mangopay.com

api.sandbox.mangopay.com

*.payline.com

Initialization

Initialize the SDK and specify the configuration options.

Example - Initialization
import { CheckoutSdk } from '@mangopay/checkout-sdk';

const mangopaySdk = await CheckoutSdk.loadCheckoutSdk(elementOrSelector, options);

Initialization parameters

PropertyTypeDescription
elementOrSelector

HTMLElement | String REQUIRED

The container element or the selector of the container element.
options

Object
REQUIRED

The options of the Checkout SDK configuration.

options

The child parameters of the options object parameter:

PropertyTypeDescription
clientId

String REQUIRED

The unique identifier associated with the Mangopay API key, giving access to the Mangopay API.
environmentString

The Mangopay environment.
Allowed values: SANDBOX, PRODUCTION
Default values: SANDBOX

profilingMerchantId

String REQUIRED

The unique identifier associated with your fraud protection package. Contact Mangopay to obtain this value.
amount

String REQUIRED

Information about the debited funds.

The currency (ISO_4217 format) and value (expressed in minor units) of the debited funds.

paymentMethods

Array REQUIRED

The payment methods presented to the user.

Array of objects detailing the type and configuration options for specific payment methods. Each payment method includes configuration options tailored to its specific requirements.

brandingObjectThe custom branding of the payment page (see Customization section below).
localeString | ObjectThe language for the payment page. Specify one of the built-in languages (en, fr) or send an object with custom messages (see Customization section below).
tenantIdString

The Mangopay tenant being used by the platform. Platforms that have contracted with Mangopay’s UK entity must set the value to UK.

Allowed values: EU, UK Default value: EU

Configuration

Configure the MangopayCheckout parameters and delegates.

Example - Vanilla JS

HTML
<body>
    <div id="checkoutForm">
        <div id="container"></div>
    </div>
    <script src="/index.js"></script>
</body>
JavaScript
window.addEventListener('load', async () => {
    const mangopaySdk = await CheckoutSdk.loadCheckoutSdk('#container', options);
    if (!mangopaySdk) {
        throw new Error('Failed to load MangopayCheckoutSdk');
    }

    mangopaySdk.on('error', (event: CustomEvent<ErrorEventDetails>) => console.error(event.detail));

    mangopaySdk.on('tokenizationComplete', (event: CustomEvent<TokenizationCompleteEventDetails>) => {
        // handle tokenization complete
    });

    mangopaySdk.on('paymentComplete', (event: CustomEvent<PaymentCompleteEventDetails>) => {
        // handle payment complete
    });
});

Example - ReactJS

JavaScript
import { MangopayCheckout } from '@mangopay/checkout-sdk-react';

const CheckoutComponent = () => {

  const sdkRef = useRef(null);

  const onTokenizationComplete = () => {
      /* Handle Card/GooglePay/ApplePay token here
             e.g charge customer card using CardId
      */
  };

  const onPaymentComplete = () => {
      /* Handle Card/PayPal payment complete */
  };

  return (
    <MangopayCheckout
      ref={sdkRef}
      options={options}
      disabled={disabled}
      onError={onError}
      onLoaded={onLoaded}
      onChange={onChange}
      onTokenizationComplete={onTokenizationComplete}
      onPaymentComplete={onPaymentComplete}
    />
  )
}

MangopayCheckout parameters

PropertyTypeDescription
refReact.RefObject<MangopayCheckoutForwardedRef>React reference object: import { MangopayCheckoutForwardedRef } from '@mangopay/checkout-sdk-react';
onPaymentCompleteFunction(event)Triggered when the transaction is completed, whatever the outcome (whether successful or failed).
optionsObjectCheckout SDK configuration options
disabledBooleanApplies a disabled state to the Checkout component such that user input is not accepted.
onErrorFunction(event)Triggered when an internal SDK error has occurred.
onLoadedFunction(event)Triggered when the Checkout SDK is loaded.
onChangeFunction(event)Triggered when data exposed by the Checkout SDK is changed.
onTokenizationCompleteFunction(event)

Triggered when:

  • A card tokenization is completed and a CardId is returned.
  • The user authorizes a Google Pay or Apple Pay payment.
onPaymentCompleteFunction(event)Triggered when the transaction is completed, whatever the outcome (whether successful or failed).

Updating options

After the SDK has been initialized you can update the options without needing to fully reinitialize again by using the updateOptions method. Make sure you pass a complete updated options object as specified in the Configuration section.

import { CheckoutSdk } from '@mangopay/checkout-sdk';
const mangopaySdk = await CheckoutSdk.loadCheckoutSdk('#container', options);
// update options
mangopaySdk.updateOptions({...options, amount: {...options.amount, value: updatedValue});

Handling redirection

Warning – Use Mangopay Checkout domain as return URL

When making the pay-in request from your backend, use the Mangopay Checkout URL as the SecureModeReturnURL or ReturnURL (depending on the payment method):

http://checkout.mangopay.com

The user must be returned to this URL after redirection.

Some payment methods (card, Google Pay, PayPal) require or may require the user to be redirected to authorize or complete a transaction.

The Checkout SDK allows you to manage the entire payment flow seamlessly while retaining control over transaction logic in your backend. Once a payment method is selected and payment details are provided, use the options.onCreatePayment function to request the transaction from your backend.

Subsequently, and when necessary for the transaction type, the Checkout SDK seamlessly manages additional redirect actions for 3DS authorization or otherwise validating the payment.

To manage transaction redirects effectively with the SDK:

1

Define onCreatePayment

In your paymentMethods configurations, define an options.onCreatePayment attribute as a function.

2

Within your function:

  • Request a transaction from your server and subsequently, Mangopay.
  • Return the unaltered transaction response object to the SDK.
3

The SDK:

  • Redirects the user to the payment authentication page when necessary.
  • Manages payment provider redirects back to the SDK.
  • Triggers the onPaymentComplete event with the ID and status of the transaction.
  • Confirms the redirect result on your server by invoking the corresponding GET API of the transaction.
  • Presents the payment result to the user.
paymentMethods: [
    {
        type: 'card | paypal | googlepay',
        onCreatePayment: function (event) {
            // 1. implement server-side call to request a transaction.
            // 2. return the card transaction object.
        }
    }
]

Configuring card payments

To configure the card payment method, specify card as the type of the paymentMethods object. For the options, use the following configuration parameters.

options

PropertyTypeDescription
options.supportedCardBrandsArray REQUIRED

The card brands supported.
Allowed values: VISA, MASTERCARD, AMERICAN_EXPRESS, MAESTRO, CB

options.onCreateCardRegistrationFunction REQUIREDUse this attribute to request and return a Card Registration.
options.onCreatePaymentFunction REQUIREDTo handle 3DS redirects for card payments, use this attribute to request and return a pay-in.

Card configuration example

TypeScript

export interface CreatePaymentData {
  Id: string;
  Tag: string;
  CreationDate: string;
  UserId: string;
  CardId: string;
  CardType: string;
  Currency: string;
  PreferredCardNetwork?: 'VISA' | 'MASTERCARD' | 'CB' | 'MAESTRO';
  ProfilingAttemptReference: string;
}

const options = {
    clientId: 'MANGOPAY_CLIENT_ID',
    environment: 'SANDBOX | PRODUCTION',
    amount: {
        value: 1000,
        currency: "EUR"
    },
    paymentMethods: [
        {
            type: 'card',
            onCreateCardRegistration: function (cardType: 'CB_VISA_MASTERCARD' | 'AMEX' | 'MAESTRO') {
                // 1. implement server-side call to create a card registration.
                // 2. return the card registration.
            },
            onCreatePayment: function (event: CreatePaymentData) {
                // 1. implement server-side call to request a card transaction.
                // 2. return the card transaction object.
                // 3. the SDK handles 3DS redirect for you.
            }
        }
    ]
};
const mangopaySdk = await CheckoutSdk.loadCheckoutSdk(elementOrSelector, options);

Card tokenization

In the options for the card payment method, create a function to handle creation of Card Registration event handler in the paymentMethods object:

  • Your onCreateCardRegistration function calls your server, and passes it the card brand of the user.
  • Your server makes a request to Create a Card Registration.
  • In response, your server receives a Card Registration object.
  • In your onCreateCardRegistration function, return the unmodified Card Registration object to the SDK.
  • The SDK tokenizes the card and updates the Card Registration object to create the CardId which is used for payment.
TypeScript
// Vanilla JS
mangopaySdk.on('tokenizationComplete', (event: CustomEvent<TokenizationCompleteEventDetails>) => {
    // handle tokenization complete
});

mangopaySdk.on('paymentComplete', (event: CustomEvent<PaymentCompleteEventDetails>) => {
    // handle payment complete
});

// React.js
const onTokenizationComplete = () => {
    // handle tokenization complete
};

const onPaymentComplete = () => {
    // handle payment complete
};

<MangopayCheckout
    ref={sdkRef}
    options={options}
    onTokenizationComplete={onTokenizationComplete}
    onPaymentComplete={onPaymentComplete}
/>

tokenizationComplete output

REST
{
  "Id": "cardreg_m_01HQ0J6GB3JFZ1NC5EGCJBE4PB",
  "Tag": null,
  "CreationDate": 1708342329,
  "UserId": "user_m_01HP6ZG0XXZ89V34GRZEY9HQCE",
  "AccessKey": "1X0m87dmM2LiwFgxPLBJ",
  "PreregistrationData": "YkgVxL1yNY4ZOfKtqEew_Zj34Eg4_H3r-UyvrLWB_MHYF1OqkWAtDMwDMZ0pSZfliRF4hvSrtJCvT7-9XAi0Xsj7Q1OS-vT4lpHzEztZoLs",
  "RegistrationData": "data=iN_eoipU7i2AEuTss7wuoPRZYTuNVHlTvhc4dEXHczhSWquUg8N2vrbXU91rCDepo0Fw6rcqxRBK8KMWk8xhHGOBEuIr9_d-Xo64K6cr5w-lY2yXbTUOs7e-S6CpTShm",
  "CardId": "card_m_01HQ0J6H02QXH3HATEYW0FMJKP",
  "CardType": "CB_VISA_MASTERCARD",
  "CardRegistrationURL": "https://pci.sandbox.mangopay.com/api/mangopay/vault/tokenize/eyJjbGllbnQiOiJjbGllbnRJZCIsInRva2VuIjoidW5xaXVlVG9rZW4ifQ==",
  "ResultCode": "000000",
  "ResultMessage": "Success",
  "Currency": "EUR",
  "Status": "VALIDATED",
  "ProfilingAttemptReference": "25e5c450-7f00-4805-af04-4330e4dc0cee"
}

Managing cards

You can use the following endpoints to manage cards:

  • View a Card provides key information about the card, including its Fingerprint which can be used as an anti-fraud tool
  • Deactivate or edit a Card allows you to irreversibly set the card as inactive

Warning - End user’s approval needed to save card details

Under no circumstances should card information be kept without the end user’s approval.

If you don’t have the end user’s approval, you need to deactivate the card systematically after use in your implementation.

Requesting card pay-ins

You can use a registered card (CardId) for requests with the following API objects:

In your requests:

  • Ensure that the SecureModeReturnURL parameter is set to https://checkout.mangopay.com
  • Submit the PreferredCardNetwork value if it was received by onCreatePayment

Configuring Apple Pay

Note - Apple Pay integration required

Offering Apple Pay requires additional setup by the platform, including certification and integration. For more information, see the How to process an Apple Pay payment tutorial. 

Caution - Apple Pay on the Web availability

Apple Pay on the Web, using the JavaScript Checkout SDK, is only available on Mac and iOS devices. Apple Pay on the Web also requires additional certification.

To configure the Apple Pay payment method, specify apple_pay as the type of the paymentMethods object. For the options, use the following configuration parameters. 

Apple Pay configuration options

PropertyTypeDescription
paymentRequestObject REQUIREDThe specifications of the payment request.
onCreatePaymentFunction REQUIREDFunction called after the user has successfully authenticated a card for payment from the Apple Pay sheet. Use this attribute to implement backend creation of the Apple Pay PayIn from your server. After creating the pay-in, return the pay-in object to the SDK.

paymentRequest

PropertyTypeDescription
countryCodeString REQUIREDThe platform’s two-letter ISO 3166 country code.
currencyCodeString REQUIREDThe three-letter ISO 4217 code (EUR, GBP, etc) of a supported currency (depends on feature, contract, and activation settings).
merchantCapabilitiesArray REQUIREDInformation about the card types and authentication protocols you support (see Apple Pay documentation).
supportedNetworksArray REQUIRED

The card networks supported by mangopay

Allowed values: VISA, MASTERCARD

totalObject REQUIREDThe line item total for the payment (see Apple Pay documentation).
merchantIdentifierString REQUIREDYour platform’s Apple Pay Merchant ID.
merchantNameString REQUIREDThe name of your platform.
onValidateMerchantFunction REQUIREDUse this attribute to request and return a ApplePay session. Function called when the SDK receives an onvalidatemerchant merchant event from the Apple Pay sheet. The assigned function should implement backend creation of the merchant session object from your server. After creating the session object, return the session object to the SDK.
requiredBillingContactFieldsArray REQUIREDThe billing information to fulfill the order (see Apple Pay documentation).

Requesting the merchant session from your server

Displaying the Apple Pay payment sheet using the Mangopay Checkout SDK works as follows:

  1. You generate the merchant session from your server
  2. The SDK’s onValidateMerchant function calls your server and passes it the static hostname apple-pay-gateway.apple.com as the validation URL. In the China region, use cn-apple-pay-gateway.apple.com.
  3. Your server uses the validation URL to request a session from the Apple Pay server, as described in Requesting an Apple Pay Payment Session.
  4. In the response, your server receives an opaque merchant session object: MerchantSession.
  5. You pass the merchant session object to the completeMerchantValidation method of the SDK (see Apple Pay documentation for more information on this method).
//Define ApplePay Merchant session delegate
const validateApplePayMerchant = (validationURL: string): Promise<ApplePayMerchantSession> => {
	return fetch(
    'https://backend-api-url/get-apple-pay-session',
    method: 'POST',
    body: JSON.stringify({
      validationURL,
      merchantIdentifier: 'merchant.com.example.mystore',
	    displayName: 'MyStore',
	    initiative: 'web',
	    initiativeContext: 'mystore.example.com'
    })
  );
};

Requesting Apple Pay pay-in

To request the payment, use the Create an Apple Pay PayIn endpoint and include the Apple Pay PaymentData.

  1. Set up payment delegate – Assign a delegate function to the onCreatePayment attribute in your Apple Pay options.
  2. Handle payment authorization – After the shopper successfully authorizes a card for payment through the Apple Pay sheet, the SDK will call your onCreatePayment function and pass the PaymentData to it.
  3. Create pay-in – Implement the backend creation of the Apple Pay PayIn on your server using the PaymentData provided.
  4. Return pay-in object – After creating the pay-in, return the pay-in object to the SDK.
interface CreateApplePayPaymentData {
  PaymentData: {
    transactionId: string;
    network: string;
    tokenData: string;
  };
  ProfilingAttemptReference?: string;
}

//Define ApplePay PayIn delegate
const handleCreateApplePayPayIn = (data: CreateApplePayPaymentData): Promise<CreateApplePayPayInResult> => {
	return fetch(
    'https://backend-api-url/create-applepay-payin',
    method: 'POST',
    body: JSON.stringify(data)
  );
};

Apple Pay configuration example

TypeScript
const options = {
  clientId: 'MANGOPAY_CLIENT_ID',
	environment: 'SANDBOX | PRODUCTION',
	paymentMethods: [
		{
      type: 'apple_pay',
      options: {
        paymentRequest: {
          countryCode: 'IE',
          currencyCode: 'EUR',
          merchantCapabilities: ['supports3DS'],
          supportedNetworks: ['visa', 'masterCard'],
          total: {
            label: 'Demo (Card is not charged)',
            type: 'final',
            amount: '20.00',
          },
          merchantIdentifier: 'merchant.com.example.mystore',
          merchantName: 'MyStore',
          onValidateMerchant: validateApplePayMerchant,
          requiredBillingContactFields: ['email']
        },
        onCreatePayment: handleCreateApplePayPayIn
      },
    }
	]
};

// Vanilla JS
const mangopaySdk = await CheckoutSdk.loadCheckoutSdk(elementOrSelector, options);

// React.js
<MangopayCheckout ref={sdkRef} options={options} />

Configuring Google Pay

Note - Google Pay setup required

Offering Google Pay requires additional setup by the platform. For more information, see the How to process a Google Pay payment tutorial. 

Caution - Add Mangopay Checkout to your Google Console

You need to add checkout.mangopay.com along with your domain to the authorized list in the Google Business Console to view the Google Pay payment popup. This allows the Checkout SDK to ensure the Google Pay experience is presented appropriately to your shoppers. Not following this guidance may impact your payment acceptance on Google Pay.

To configure the Google Pay payment method, specify google_pay as the type of the paymentMethods object. For the options, use the following configuration parameters.

Google Pay configuration options

PropertyTypeDescription
merchantInfo.merchantIdString REQUIREDYour Google Pay Business ID, which you can find in Google Pay & Wallet Console.
merchantInfo.merchantNameString REQUIREDYour Google Pay Business Name, which you can find in Google Pay & Wallet Console.
gatewayString REQUIRED

The orchestration used: in this case, whenthen.
Allowed values: whenthen

gatewayMerchantIdString REQUIREDYour Mangopay ClientId.
cardParameters.allowedAuthMethodsArray REQUIRED

The supported authentication methods: PAN_ONLY, meaning the card is registered in the user’s Google account and requires additional authentication; CRYPTOGRAM_3DS, meaning the card is enrolled in the customer’s Google Wallet and authentication is handled by Google, with no 3DS redirection and no liability for the platform.
Allowed values: PAN_ONLY, CRYPTOGRAM_3DS

cardParameters.allowedCardNetworks Array REQUIRED

The card networks supported by Mangopay.

Allowed values: VISA, MASTERCARD

transactionInfoObject REQUIRED

Information about the transaction and its authorization, such as whether the user agrees to the transaction, the total price and price status. For more information on this object parameter, see the Google Pay documentation.

onCreatePaymentFunction REQUIRED

Function called after the user has successfully authorized a card for payment from the Google Pay sheet.

The assigned function should implement backend creation of the Google Pay PayIn from your server. After creating the pay-in, return the pay-in object to the SDK.

button.buttonColorString

The color of the button.

Default value: default

Allowed values:

  • default – A Google-selected default value (currently black but it may change over time).
  • black – A black button suitable for use on white or light backgrounds.
  • white – A white button suitable for use on colorful backgrounds.
button.buttonTypeString

The type of the button, determining the text to display.

Default value: buy

Allowed values:

  • book – The “Book with Google Pay” payment button.
  • buy – The “Buy with Google Pay” payment button.
  • checkout – The “Checkout with Google Pay” payment button.
  • donate – The “Donate with Google Pay” payment button.
  • order – The “Order with Google Pay” payment button.
  • pay – The “Pay with Google Pay” payment button.
  • plain – The Google Pay payment button without the additional text.
  • subscribe – The “Subscribe with Google Pay” payment button.
button.buttonLocaleString

The ISO 639-1 code representing the desired button language.

Default value: The browser or operating system language settings.

Allowed values: en, ar, bg, ca, cs, da, de, el, es, et, fi, fr, hr, id, it, ja, ko, ms, nl, no, pl, pt, ru, sk, sl, sr, sv, th, tr, uk, and zh.

Obtaining Google Pay token

The onTokenizationComplete function is called after the user approves the payment on the Google Pay form. The output contains the paymentData object (see Google Pay documentation) which is needed to request the Google Pay payment via the API from your backend.

Requesting Google Pay pay-in

To request the payment, use the Create a Google Pay PayIn endpoint. Include the Google Pay PaymentData and ensure that the SecureModeReturnURL parameter is set to https://checkout.mangopay.com.

  1. Set up payment delegate – Assign a delegate function to the onCreatePayment attribute in your Google Pay options.
  2. Handle payment authorization – After the shopper successfully authorizes a card for payment through the Google Pay sheet, the SDK will call your onCreatePayment function and pass the PaymentData to it.
  3. Create pay-in – Implement the backend creation of the Google Pay PayIn on your server using the PaymentData provided.
  4. Return pay-in object – After creating the pay-in, return the pay-in object to the SDK.
interface CreateGooglePayPaymentData {
  PaymentData: string;
  ProfilingAttemptReference: string;
}

//Define GooglePay PayIn delegate
const handleCreateGooglePayPayIn = (data: CreateGooglePayPaymentData): Promise<CreateGooglePayPayInResult> => {
	return fetch(
    'https://your-backend-api-url/create-googlepay-payin',
    method: 'POST',
    body: JSON.stringify(data)
  );
};

Google Pay configuration example

const options = {
  clientId: 'MANGOPAY_CLIENT_ID',
	environment: 'SANDBOX | PRODUCTION',
	paymentMethods: [
		{
      type: 'google_pay',
      options: {
        merchantInfo: {
			    merchantId: 'test',
			    merchantName: 'Test',
			  },
				gateway: 'whenthen',
			  cardParameters: {
			    allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],
					allowedCardNetworks: ['VISA', 'MASTERCARD'],
			  },
			  transactionInfo: {
			    totalPrice: '20.00',
			    totalPriceStatus: 'FINAL',
			    currencyCode: 'EUR',
			    countryCode: 'DE', // required for EEA only
			    transactionId: '123456789',
			    totalPriceLabel: '20.00', // required if displayItems is provided
			    displayItems: [
			      {
			        label: 'PS5',
			        type: 'SUBTOTAL',
			        price: '20.00',
			      },
			    ],
			  },
			  paymentData: {
			    emailRequired: true,
			  },
			  onCreatePayment: (paymentData) => handleCreateGooglePayPayIn(paymentData),
        button: {
          buttonLocale: 'fr',
          buttonType: 'book'
        },
      },
    }
	]
};

// Vanilla JS
const mangopaySdk = await CheckoutSdk.loadCheckoutSdk(elementOrSelector, options);

// React.js
<MangopayCheckout ref={sdkRef} options={options} />

Configuring PayPal

Note – PayPal setup required

Offering PayPal requires approval from PayPal and activation. For more information, see the PayPal article.

PayPal configuration options

To configure PayPal, specify paypal as the type of the paymentMethods object. For the options, use the following configuration parameters.

PropertyTypeDescription
options.onCreatePaymentFunction REQUIRED

Use this attribute to request and return a PayPal pay-in.

The assigned function should implement backend creation of the PayPal pay-in from your server.

PayPal configuration example

//Define PayPal PayIn delegate
const createPayPalPayIn = (profilingAttemptReference: string): Promise<CreatePayPalPayInResult> => {
	return fetch(
    'https://your-backend-api-url/create-paypal-payin',
    body: JSON.stringify({ProfilingAttemptReference: profilingAttemptReference})
  );
};

const options = {
    clientId: 'MANGOPAY_CLIENT_ID',
    environment: 'SANDBOX | PRODUCTION',
    amount: {
        value: 1000,
        currency: "EUR"
    },
    paymentMethods: [
        {
	        type: "paypal",
	        options: {
	          //define delegate to call when Paypal button is clicked
	          onCreatePayment: (data) => createPayPalPayIn(data)
	        }
	      }
    ]
};

const mangopaySdk = await CheckoutSdk.loadCheckoutSdk(elementOrSelector, options);

//this event is triggered when redirect/payment is completed
mangopaySdk.on('paymentComplete', (event: CustomEvent<PaymentCompleteEventDetails>) => {
    //  verify payment result
    //  unmount checkout and present payment result.
});

Requesting PayPal pay-in

To request the payment, use the Create a PayPal PayIn endpoint. Ensure that the ReturnURL parameter is set to https://checkout.mangopay.com.

Obtaining browser info for a pay-in

The browserInfo object is required when submitting a pay-in request. To get the required values for the transaction, use the getBrowserInfo function from the Checkout SDK instance. Pass on the values to your server.

//Using checkout-sdk or checkout-sdk-react package from npm.
import { getBrowserInfo } from '@mangopay/checkout-sdk'

//alternatively, if you are using the cdn script
const mangopaySdk = await CheckoutSdk.loadCheckoutSdk('#container', options);
const browserInfo = mangopaySdk.getBrowserInfo();

const payInRequestObj =
{
		...
    browserInfo         : {
        "AcceptHeader"  : browserInfo.AcceptHeader,
        "JavaEnabled"   : browserInfo.JavaEnabled,
        "Language"      : browserInfo.Language,
        "ColorDepth"    : browserInfo.ColorDepth,
        "ScreenHeight"  : browserInfo.ScreenHeight,
        "ScreenWidth"   : browserInfo.ScreenWidth,
        "TimeZoneOffset": browserInfo.TimeZoneOffset,
        "UserAgent"     : browserInfo.UserAgent,
        "JavascriptEnabled": browserInfo.JavascriptEnabled
    }
};

Verifying the payment result

Once the onPaymentComplete event is triggered, verify the status of the relevant Mangopay API object:

Caution – Check payment result from backend

You should confirm the transaction result returned by the Checkout SDK by calling the Mangopay API from your backend.

Verify payment result
//This event is triggered by the SDK when a full payment cycle is complete.
mangopaySdk.on('paymentComplete', (event: CustomEvent<PaymentCompleteEventDetails>) => {

    const { Id } = event.details

    // 1. Verify payment result using the transaction Id.
    // 2. Present payment result to user.
});

Showing and dismissing the loading spinner

When processing a token request, the SDK shows a loading spinner and retains it until the loading state is set to false. This provides a temporary state for the user until the full payment is complete, including calls from your platform’s backend.

The setLoading method handles the loading state for displaying and dismissing the spinner.

import { CheckoutSdk } from '@mangopay/checkout-sdk';
const mangopaySdk = await CheckoutSdk.loadCheckoutSdk('#container', options);
// dismiss the  loader spinner
mangopaySdk.setLoading(false);

Using Card Element

Card Element is a ready-made component that allows you to create your own card payment experience and tokenize card payment details. With Card Element, you can incorporate a custom pay button and have control over the tokenization process.

When using Card Element, you still benefit from card data validation, and the ability to customize the payment form.

Initialize the cardFormElement with your ClientId and select your environment (Sandbox or Production).

import { CheckoutSdk } from '@mangopay/checkout-sdk';

const cardFormElement = await CheckoutSdk.loadCardFormElement(elementOrSelector, options);

cardFormElement-specific options

PropertyTypeDescription
paymentMethodObjectThe payment method used with the card form element. Only 'card' is supported. See Configuring card payments section for details

Vanilla JS usage example

HTML
<body>
    <form novalidate id="checkoutForm">
        <div id="container"></div>
        <button type="submit" id="submitButton">Pay now</button>
    </form>
    <script src="/index.js"></script>
</body>
TypeScript
import { CheckoutSdk } from '@mangopay/checkout-sdk';

window.addEventListener('load', async () => {
    const cardFormElement = await CheckoutSdk.loadCardFormElement('#container', options);
    if (!cardFormElement) {
        throw new Error('Failed to load MangopayCardFormElement');
    }

    const submitButton = document.querySelector('#submitButton');
    if (!submitButton) {
        throw new Error('Submit button is missing.');
    }

    submitButton.addEventListener('click', async (event) => {
        event.preventDefault();
        cardFormElement.disable();
        try {
            cardFormElement.completePayment();
        } finally {
            cardFormElement.enable();
        }
    });

    cardFormElement.on('error', (event: CustomEvent<ErrorEventDetails>) => console.error(event.detail));

    cardFormElement.on('tokenizationComplete', (event: CustomEvent<TokenizationCompleteEventDetails>) => {
        // handle tokenization complete
    });
});

ReactJS usage example

TypeScript
import { CardFormElement } from '@mangopay/checkout-sdk-react';

const CheckoutFormComponent = () => {
    const sdkRef = useRef(null);

    const onTokenizationComplete = () => {
        /* Handle Card token here
               e.g charge customer card using CardId
        */
    };

    return (
        <>
            <form noValidate>
                <CardFormElement
                    ref={sdkRef}
                    options={options}
                    disabled={disabled}
                    onError={onError}
                    onLoaded={onLoaded}
                    onChange={onChange}
                    onTokenizationComplete={onTokenizationComplete}
                />
            </form>
            <button onClick={handleCompletePayment} className="btn pay-btn">
                Pay now
            </button>
        </>
    );
}

Branding

You can customize the appearance of the checkout using the branding object.

TypeScript - Branding example
const options = {
    branding: {
        fontFamily: 'Helvetica Neue',
        fontSize: {
            primary: '14px',
            secondary: '12px',
        },
        borderType: 'square', // 'square' | 'round' | 'bottom'
        colors: {
            primary: '#000000',
            secondary: '#545A61',
            accent: '#4E40EF',
            accentContrast: '#FFFFFF',
            border: '#E6E9EC',
            borderFocused: '#000000',
            error: '#EC0B43',
        },
        borderRadius: '0',
        backgroundColor: '#ffffff',
        textColor: '#000000',
        lineHeight: '48px',
        variables: undefined,
        rules: undefined,
    },
},
};

// Vanilla JS
const mangopaySdk = await MangopaySdkLoader.loadCheckoutSdk('#container', options);

// React.js
<MangopayCheckout ref={sdkRef} options={options} />

Theme variables and rules

You can use the rules and variables objects for further customization.

Variables

Variables are CSS variables that you can declare and use in your theme rules.

TypeScript
{
    theme: {
    ...,
        variables: {
            primaryColor: "#1D3557"
            secondaryColor: "#457B9D"
        }

        rules: {
            PayButton: `
            backgroundColor: var(--primaryColor);
            `
        }
    }
}

Rules

Rules allows you to apply CSS styles to Checkout SDK components. To do so, target components by class names, with or without the CSS class selector prefix (FieldContainer or .FieldContainer), and specify the styles to apply. The feature supports all native CSS properties and nesting.

TypeScript
{
    theme: {
      ...,
        variables: {
            primaryColor: "#1D3557"
            secondaryColor: "#457B9D"
        }

        rules: {
            '.FieldContainer': `
              height: 40px;
              border-radius: 8px;
              backgroundColor: var(--primaryColor);
              
              &:hover {
                backgroundColor: var(--secondaryColor);
              }
          `
        }
    }
}

Localization

Mangopay Checkout SDK has built-in localization support for: DE, EN, ES, FR, NL, PT

TypeScript
const options = {
    locale: 'en', // 'en' | 'fr' | 'es' | 'de' | 'pt' | 'nl' | Object
};

// Vanilla JS
const mangopaySdk = await MangopaySdkLoader.loadCheckoutSdk('#container', options);

// React.js
<MangopayCheckout ref={sdkRef} options={options} />

You can customize labels, placeholder and success and error messages by providing a customLanguage object.

const customLanguage = {
  "card-information.header.label": "Card information",
  "card.number.placeholder": "1234 1234 1234 1234",
  "card.number.aria-label": "Card number",
  "card.number.errors.required": "Card number is required",
  "card.number.errors.min-length": "Minimum number of digits is 13",
  "card.number.errors.invalid-number": "Invalid card number",

  "card.psp.legal.notice": "Processed with Mangopay",
  "card.psp.legal.privacy": "Privacy.",
  "card.save.label": "Save payment details for future use",
  "card.saved-cards.choose-card.label": "Choose card",
  "card.saved-cards.clear-card.label": "Clear",
  "card.saved-cards.saved-card.aria-label": "The card ending in",
  "card.billing-name.placeholder": "Name on card",
  "card.billing-name.aria-label": "Name on card",
  "card.billing-name.errors.required": "Full name is required",
  "card.expiry.placeholder": "MM / YY",
  "card.expiry.aria-label": "Card expiration",
  "card.expiry.errors.required": "Expiration date is required",
  "card.expiry.errors.pattern": "Expiration date format is not valid (MM/YY)",
  "card.expiry.errors.expired": "Your card is expired",
  "card.cvc.placeholder": "CVC",
  "card.cvc.aria-label": "Card CVC",
  "card.cvc.errors.required": "Security code is required",
  "card.cvc.errors.min-length": "Security code is too short",
  "card.cvc.errors.max-length": "Security code is too long",
  "pay-button.label": "Pay",
  "pay-button.aria-label": "Pay",
  "payment-methods.card.label": "Card",
  "payment-methods.show-less.label": "Show less",
  "payment-methods.show-more.label": "Show more",
  "payment-methods.applepay.label": "Apple Pay",
  "payment-methods.applepay.aria-label": "Pay with Apple Pay",
  "payment-methods.googlepay.label": "Google Pay",
  "payment-methods.googlepay.aria-label": "Pay with Google Pay",
  "payment-methods.paypal.label": "PayPal",
  "payment-methods.paypal.aria-label": "Pay with PayPal",
  "payment-methods.paypal.overlay.message": "Don’t see the secure paypal browser? We’ll help you re-launch the window to complete your purchase",
  "payment-methods.paypal.overlay.continue": "Click to Continue",
  "payment-success-state.label": "Payment Succeeded",
  "redirect-note.label": "After submitting your order, you will be securely redirected to complete your purchase.",
  "loading.label": "Processing your payment",

	//errors
  "error.invalid_cvc": "Invalid CVC",
  "error.authorization_required": "Authorization Required",
  "error.contact_card_issuer": "Contact Card Issuer",
  "error.unsupported_card": "Unsupported Card",
  "error.insufficient_funds": "Insufficient Funds",
  "error.unsupported_currency": "Unsupported Currency",
  "error.card_rejected": "Card Rejected",
  "error.expired_card": "Expired Card",
  "error.suspected_fraud": "Suspected Fraud",
  "error.general_decline": "General Decline",
  "error.incorrect_number": "Incorrect Number",
  "error.incorrect_pin": "Incorrect Pin",
  "error.invalid_address": "Invalid Address",
  "error.invalid_card_or_account": "Invalid Card or Account",
  "error.invalid_amount": "Invalid Amount",
  "error.invalid_date": "Invalid Date",
  "error.lost_restricted_or_stolen_card": "Lost, Restricted or Stolen Card",
  "error.blocked_list": "Blocked List",
  "error.not_permitted": "Not Permitted",
  "error.offline_or_online_pin_required": "Offline or Online Pin Required",
  "error.pin_retry_exceeded": "Pin Retry Exceeded",
  "error.processing_error": "Processing Error",
  "error.withdrawal_count_limit_exceeded": "Withdrawal Count Limit Exceeded",
  "error.unknown": "Unknown error",
  "error.fraud": "Fraud",
  "error.three_d_secure": "3DS Failed",
  "error.custom_rule": "Custom Rule",
  "error.payment_cancelled": "Try making your payment again or select a different bank to continue",
  "error.payment_rejected": "The payment was rejected by the institution. Try again, or select another account or institution",
  "error.internal_server_error": "An unexpected error occurred",
  "error.institution_not_responding": "This financial institution is not currently responding to requests. We apologize for the inconvenience",
  "error.authorize.payment-already-authorized": "This payment has been already authorized",
  "error.param_error": "One or several required parameters are missing or incorrect",
  "error.payment_restart": "The payment wasn't successful, please try again",
  "error.ressource_not_found": "The resource does not exist"
};

const options = {
  locale: customLanguage
};

// Vanilla JS
const mangopaySdk = await CheckoutSdk.loadCheckoutSdk('#container', options);

// React.js
<MangopayCheckout ref={sdkRef} options={options} />