Implementation
This page will guide you through the complete integration of the Checkout SDK into your e-shop.
A single call to useCheckout() covers the entire payment flow — from rendering the form to handling Apple Pay or Google Pay and card payments.
Installation
The Checkout SDK can be added to the project in two ways — using a dependency manager or by loading it from Comgate CDN.
Dependency manager
Use this option if you manage dependencies with npm, yarn or pnpm and build the project using a bundler (Vite, Webpack, Next.js, …).
The @comgate/checkout-js package contains only the loader — the SDK itself is downloaded dynamically at runtime. Even so, we recommend regularly checking for new versions and updating the package so that you don't miss important fixes and improvements.
- npm
- yarn
- pnpm
npm install @comgate/checkout-js
yarn add @comgate/checkout-js
pnpm add @comgate/checkout-js
Comgate CDN
If you do not want to use dependency managers, the SDK can be loaded directly from the Comgate CDN.
After loading, the library is available globally as window.comgateCheckoutJs.
- <body>
- <head>
<!DOCTYPE html>
<html lang="cs">
<head>
<meta charset="UTF-8">
<title>Comgate Checkout example - script in body</title>
<!-- ... metas ... -->
</head>
<body>
<!-- ... content ... -->
<script src="https://checkout.comgate.cz/sdk/@3"></script>
<script>
if (window.comgateCheckoutJs) {
const comgateLoaderVersion = comgateCheckoutJs.getLoaderVersion();
console.log(comgateLoaderVersion.version);
}
</script>
</body>
</html>
We recommend loading the Checkout SDK within the <body> element, ideally inserting the scripts just before the closing </body> tag.
<!DOCTYPE html>
<html lang="cs">
<head>
<meta charset="UTF-8">
<title>Comgate Checkout example - script in head</title>
<!-- ... metas ... -->
<script src="https://checkout.comgate.cz/sdk/@3" defer></script>
</head>
<body>
<!-- ... content ... -->
<script>
// nutné vyčkat na event DOMContentLoaded
document.addEventListener('DOMContentLoaded', () => {
if (!window.comgateCheckoutJs) {
console.log('Loader not found.');
return;
}
const comgateLoaderVersion = comgateCheckoutJs.getLoaderVersion();
console.log(comgateLoaderVersion.version);
});
</script>
</body>
</html>
Working with versions
For production deployment we recommend using a fixed major version. Comgate guarantees backward compatibility within the same major version, so fixes and improvements reach users automatically.
- CDN: Use the major version in the URL (e.g.
/sdk/@3) - NPM: Use the
versionparameter in the configuration ofuseCheckout(),preloadComgateCheckout()orprefetchComgateCheckout()— you can pass a string or an imported constant.
- CDN
- NPM
<!-- Fixed major version in URL — recommended for production -->
<script src="https://checkout.comgate.cz/sdk/@3"></script>
<!-- Specific patch version — not recommended - suitable for testing/development -->
<script src="https://checkout.comgate.cz/sdk/v/3.0.1"></script>
// VERSION_3 = '3'
// VERSION_PREFERRED = VERSION_3 (currently recommended version)
import { useCheckout, VERSION_3, VERSION_PREFERRED } from '@comgate/checkout-js';
// using the constant:
useCheckout({ version: VERSION_3, /* ... */ });
// or a plain string:
useCheckout({ version: '3', /* ... */ });
We strongly discourage locking to a specific patch version (e.g. 3.0.1).
Preparing HTML
After installing the library, the next step is to prepare the HTML structure. Before calling useCheckout(), prepare container elements on the page for the individual payment methods you plan to use.
Apple Pay and Google Pay
For each method, prepare an empty <div> into which the SDK will render the native button. The buttons automatically adapt to the container dimensions — so you determine the size with your own element style. Also assign a unique ID to each element.
Each mountPoint (Apple Pay, Google Pay and card) must correspond to exactly one element in the DOM. If the selector finds multiple elements, the SDK will throw an error. Therefore use a selector with an ID (e.g. '#cg-applepay-box') or pass a direct reference to a specific HTMLDivElement.
The element must be in the DOM at the time useCheckout() is called. In frameworks (Vue, React, Angular…) therefore always call useCheckout() only after the component is mounted into the DOM — typically inside onMounted (Vue) or useEffect (React). The SDK tolerates a short delay caused by the framework render cycle, but do not rely on this as a substitute for correct lifecycle integration.
<div id="cg-applepay-box" style="width: 240px; height: 45px;"></div>
<div id="cg-googlepay-box" style="width: 240px; height: 45px;"></div>
Recommended dimensions
When implementing both methods, choose unified dimensions that satisfy both services. Below are minimum and recommended sizes — Google Pay has stricter minimums:
| Type | Apple Pay min. | Google Pay min. | Recommended | |
|---|---|---|---|---|
| Desktop | logo only (plain) | 100 × 30 px | 140 × 40 px | 160 × 45 px |
| with text | 140 × 30 px | 240 × 40 px | 240 × 45 px | |
| Mobile | logo only (plain) | 100 × 30 px | 140 × 40 px | 160 × 50 px |
| with text | 140 × 30 px | 240 × 40 px | 240 × 50 px |
Don't forget the viewport meta tag: <meta name="viewport" content="width=device-width, initial-scale=1">.
Card form
To pay via the card form, you need to prepare a container element on the page — <div> with any ID, which you reference in the configuration using mountPoint (CSS selector, e.g. '#cg-card-box', or a direct reference to HTMLDivElement).
The SDK automatically looks for additional elements from the element ID:
${id}-ibox→ here the SDK inserts the secure iframe with the card fields (the element is required and must be placed inside the main div)${id}-button→ wrapper for<button>, the SDK attaches it to the payment (can also be outside the container)
Card input fields run in an isolated iframe — sensitive data never leaves the secured environment → PCI-DSS compliance.
- In the container
- Outside the container
The button can be placed inside the container, ideally below the iframe with the card fields:
<div id="cg-card-box">
<div id="cg-card-box-ibox"><!-- iframe with card fields --></div>
<div id="cg-card-box-button">
<button type="button">Pay by card</button>
</div>
</div>
The button does not have to be only inside the container — it can be placed anywhere on the page, as long as the <div> has the correct ID:
<div id="cg-card-box">
<div id="cg-card-box-ibox"></div>
</div>
<!-- button anywhere else on the page -->
<div id="cg-card-box-button">
<button type="button">Pay by card</button>
</div>
CSS Style
The SDK automatically inserts the default styles of the card container when mounting — there is no need to add any custom CSS. The customization options are described in the section Appearance customization — Card form.
Loading state (before SDK loads)
Until the SDK manages to load and start, the container will be displayed as an empty space. If you want to display a loading spinner instead of empty space, it is possible — see details below in the section Card form loading state.
The loading state is optional — if you don't mind the empty space before loading, there is no need to implement anything.
But first implement the SDK and only then add your own styles or loading spinner.
Implementation
Once you have the HTML elements ready, you can proceed to the actual initialization of the SDK.
The useCheckout() function is your main (and actually only) entry point. You call it with a configuration object, it does everything needed — loads modules, renders the UI — and returns a Promise with instances of individual modules.
Simplified process flow: Your backend / cloud app creates a payment on the Comgate Merchant API, which returns transId. You pass this ID along with checkoutId (obtained in the client portal during Checkout SDK activation) to your frontend in the call to useCheckout(). The SDK initializes the payment methods, renders the buttons and forms, and once the customer pays, it calls your callback.
The Core module is implemented as a singleton. The instance is created on the first call to useCheckout() and remains active until the page is closed / reloaded.
Further calls to useCheckout() do not create a new Core module instance, but only update the passed callbacks (such as onPaid or onCancelled). Previously passed callbacks are replaced and only the callbacks passed in the last call to useCheckout() remain active.
When leaving the payment page, you must call destroy() on the Apple Pay, Google Pay and card module instances — otherwise they remain active in memory and may cause conflicts during subsequent payment processing. More information is in the section Cleaning up instances.
- Standard implementation
- Complete example
import { useCheckout } from '@comgate/checkout-js';
const COMGATE_CHECKOUT_ID = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
const COMGATE_TRANSACTION_ID = 'XXXX-XXXX-XXXX';
const GOOGLE_PAY_MERCHANT_ID = 'BCR3D****ZEY1LKS';
const CHECKOUT_BOX_GOOGLE_PAY = '#cg-googlepay-box';
const CHECKOUT_BOX_APPLE_PAY = '#cg-applepay-box';
const CHECKOUT_BOX_CARD = '#cg-card-box';
useCheckout({
checkoutId: COMGATE_CHECKOUT_ID,
core: {
transactionId: COMGATE_TRANSACTION_ID,
locale: 'en',
onPaid: (payload) => { console.log('Paid', payload); },
onCancelled: (payload) => { console.log('Cancelled', payload); },
onPending: (payload) => { console.warn('Repeat the payment', payload); },
onError: (payload) => { console.error('Error', payload); },
onPaymentStarted: () => { document.body.classList.add('loading'); },
onPaymentStopped: () => { document.body.classList.remove('loading'); },
},
// if you don't want ApplePay, omit this key
applepay: {
mountPoint: CHECKOUT_BOX_APPLE_PAY,
},
// if you don't want GooglePay, omit this key
googlepay: {
mountPoint: CHECKOUT_BOX_GOOGLE_PAY,
payment: {
// Merchant ID assigned to you by Google after registering with Google Pay Business Console.
// Not required for testing, but mandatory for production deployment.
// DIY
googlePayMerchantId: GOOGLE_PAY_MERCHANT_ID
}
},
// if you don't want card, omit this key
card: {
mountPoint: CHECKOUT_BOX_CARD,
},
})
.then((result) => {
console.log('Checkout result', result);
if (result.applepay && !result.applepay.success) {
document.querySelector(CHECKOUT_BOX_APPLE_PAY).style.display = 'none';
}
if (result.googlepay && !result.googlepay.success) {
document.querySelector(CHECKOUT_BOX_GOOGLE_PAY).style.display = 'none';
}
if (result.card && !result.card.success) {
document.querySelector(CHECKOUT_BOX_CARD).style.display = 'none';
}
})
.catch((error) => {
console.error('Unexpected error', error);
});
import { useCheckout } from '@comgate/checkout-js';
const COMGATE_CHECKOUT_ID = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
const COMGATE_TRANSACTION_ID = 'XXXX-XXXX-XXXX';
const GOOGLE_PAY_MERCHANT_ID = 'BCR3D****ZEY1LKS';
useCheckout({
checkoutId: COMGATE_CHECKOUT_ID,
core: {
transactionId: COMGATE_TRANSACTION_ID,
locale: 'en',
onPaid: (payload) => {
// Payment successful — redirect to the thank-you page
window.location.href = '/thank-you?id=' + payload.transactionId;
},
onCancelled: (payload) => {
// Payment cancelled — redirect to the cancellation page
window.location.href = '/payment-cancelled';
},
onPending: (payload) => {
// Attempt failed — display a message, the payer can try again
document.getElementById('error-msg').textContent =
'Payment did not go through (' + payload.message + '). Please try again.';
},
onError: (payload) => {
// Critical error — display an error message
document.getElementById('error-msg').textContent =
'An error occurred: ' + payload.message;
console.error('Checkout SDK error:', payload);
},
onPaymentStarted: () => {
document.getElementById('loading-overlay').style.display = 'flex';
},
onPaymentStopped: () => {
document.getElementById('loading-overlay').style.display = 'none';
},
},
applepay: {
mountPoint: '#cg-applepay-box',
ui: { type: 'pay', color: 'black' },
actions: {
// onButtonClick => onButtonClickHandler,
onButtonClick: (moduleId) => {
console.log('Apple Pay clicked', moduleId);
// payment starts only after the function completes / Promise resolves
// you can, for example, also stop processing
// more in the documentation for onButtonClick below
},
},
},
googlepay: {
mountPoint: '#cg-googlepay-box',
ui: { type: 'pay', color: 'black' },
payment: { googlePayMerchantId: GOOGLE_PAY_MERCHANT_ID },
actions: {
// onButtonClick => onButtonClickHandler,
onButtonClick: (moduleId) => {
console.log('Google Pay clicked', moduleId);
// payment starts only after the function completes / Promise resolves
// you can, for example, also stop processing
// more in the documentation for onButtonClick below
},
},
},
card: {
mountPoint: '#cg-card-box',
actions: {
// onButtonClick => onButtonClickHandler,
onButtonClick: (moduleId) => {
console.log('Card Button clicked', moduleId);
// payment starts only after the function completes / Promise resolves
// you can, for example, also stop processing
// more in the documentation for onButtonClick below
},
},
// change of card form appearance for entering card data
appearance: {
version: 1, // increase by 1 on every change
variables: {
colorText: '#111827',
colorBackground: '#ffffff',
colorPrimary: '#0891b2',
colorDanger: '#dc2626',
colorPlaceholder: '#9ca3af',
borderColor: '#e5e7eb',
borderRadius: '4px',
fontFamily: 'Arial, sans-serif',
fontSize: '14px',
spacing: '8px',
},
rules: {
label: { color: '#374151', fontWeight: 'bold', fontSize: '12px' },
input: { backgroundColor: '#ffffff', borderColor: '#e5e7eb', color: '#111827', paddingBlock: '6px', paddingInline: '8px' },
inputFocus: { borderColor: '#0891b2' },
inputInvalid: { borderColor: '#dc2626' },
error: { color: '#dc2626', fontSize: '11px' },
},
},
},
})
.then((result) => {
if (result.applepay && !result.applepay.success) {
document.getElementById('cg-applepay-box').style.display = 'none';
}
if (result.googlepay && !result.googlepay.success) {
document.getElementById('cg-googlepay-box').style.display = 'none';
}
if (result.card && !result.card.success) {
document.getElementById('cg-card-box').style.display = 'none';
console.warn('Card not available:', result.card.error);
}
})
.catch((error) => {
console.error('Unexpected SDK error:', error);
});
onButtonClickHandler
function onButtonClickHandler(moduleId) {
console.log("onButtonClick", moduleId);
// Checkout waits for this function to complete before starting the payment.
// The function should be short — Google Pay and Apple Pay require
// the payment to occur immediately after a physical click.
// With too long a delay they will reject the payment.
// A) Function returns nothing → payment continues (most common case)
// B) Promise.resolve() → payment continues
// return Promise.resolve();
// C) Promise.reject() → payment stops, the customer must click again
// (The SDK does not notify the customer — this logic is the e-shop's responsibility)
// return Promise.reject();
// D) Unresolved Promise → Checkout waits for resolve or reject
// Behaves like case B or C depending on what the Promise ends with
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// resolve(); // continue
// // reject(); // stop
// }, 2000);
// });
// Note: any other return value (e.g. false, true, a number)
// is ignored and behaves the same as case A.
}
Initialization result
The useCheckout() function returns Promise<TUseCheckoutResult>. The result contains the state of the entire initialization and of individual modules.
Response structure
interface TUseCheckoutResult {
success: boolean;
core: TUseCheckoutModuleResult<CheckoutCore>;
applepay?: TUseCheckoutModuleResult<ModuleApplePay>;
googlepay?: TUseCheckoutModuleResult<ModuleGooglePay>;
card?: TUseCheckoutModuleResult<ModuleCard>;
}
interface TUseCheckoutModuleResult<T> {
success: boolean;
error?: string;
instance: T | null;
}
How to interpret the result
After successful resolution of the Promise, useCheckout() returns an object of type TUseCheckoutResult. The object contains an overall success flag and a separate initialization result for each module you included in the configuration — that is, for each key (applepay, googlepay, card) that you passed to useCheckout(). Modules that you omitted in the configuration will not be present in the result.
| Situation | result.success | result.[module].success | What to do |
|---|---|---|---|
| All OK | true | true for all | Payment methods are ready, no action needed. |
| Some module failed (AP/GP/card unavailable, element not found…) | false | false for the affected module | The Promise resolves. Check result.[module].error — find out the cause. Hide or disable the unavailable payment method. |
Critical error (invalid checkoutId, Core failed, network issue) | – | – | The Promise rejects — the resulting object is not created at all. Handle in the catch block. |
The module key (applepay, googlepay, card) is present in the result only if you included the given module in the configuration. If, for example, you did not pass the applepay key, result.applepay will be equal to undefined.
Module result properties
Each module returns a TUseCheckoutModuleResult<T> object with three properties:
| Property | Type | Description |
|---|---|---|
success | boolean | true — the module was loaded, the device supports it and the UI was rendered into the specified mount point. false — initialization failed, see error. |
error | string | undefined | Description of the failure cause, present only when success: false. Examples: "Apple Pay is not available on this device", "Element \"#cg-applepay-box\" not found", ... |
instance | T | null | Reference to the module instance. When success: true it contains the active instance. When success: false it can be null (the module was not even created) or contain a partially initialized instance. |
Processing example
import { useCheckout } from '@comgate/checkout-js';
try {
const result = await useCheckout({
checkoutId: COMGATE_CHECKOUT_ID,
core: { transactionId: COMGATE_TRANSACTION_ID, onPaid, onCancelled, onPending, onError },
applepay: { mountPoint: '#cg-applepay-box' },
googlepay: { mountPoint: '#cg-googlepay-box', payment: { googlePayMerchantId: GP_MERCHANT_ID } },
card: { mountPoint: '#cg-card-box' },
});
// Core is always successful if the Promise did not end with an exception
console.log('Core initialized', result.core.instance);
// Check result.success for a quick overview of whether everything went well
if (!result.success) {
console.warn('Some module failed to initialize');
}
// Apple Pay — may be unavailable on the device
if (result.applepay?.success) {
console.log('Apple Pay ready');
} else if (result.applepay) {
console.warn('Apple Pay unavailable:', result.applepay.error);
document.getElementById('cg-applepay-box').style.display = 'none';
}
// Google Pay — may be unavailable on the device
if (result.googlepay?.success) {
console.log('Google Pay ready');
} else if (result.googlepay) {
console.warn('Google Pay unavailable:', result.googlepay.error);
document.getElementById('cg-googlepay-box').style.display = 'none';
}
// Card form
if (result.card?.success) {
console.log('Card form rendered');
} else if (result.card) {
console.warn('Card form unavailable:', result.card.error);
}
} catch (error) {
// Critical error — SDK failed to initialize
console.error('Checkout initialization failed:', error);
}
Cleaning up instances
If your application uses client-side routing (Vue Router, React Router, Next.js App Router, etc.), you must call destroy() on all modules when leaving the payment page. Without this, old Apple Pay, Google Pay and card form instances remain in memory, may react to future events and cause conflicts during further payment processing.
The destroy() method removes the rendered UI (iframe, buttons), disconnects event listeners and releases the module's resources. It is available on the applepay, googlepay and card module instances. destroy() is not called on the Core instance — Core is a singleton and its lifecycle is managed by the SDK itself.
const result = await useCheckout({ /* ... */ });
// When leaving the payment page, call destroy on all modules:
function cleanup() {
result.applepay?.instance?.destroy();
result.googlepay?.instance?.destroy();
result.card?.instance?.destroy();
// => destroy is not called on CORE
}
// Vue 3
onUnmounted(() => cleanup());
// React
useEffect(() => {
return () => cleanup();
}, []);
After calling destroy(), the module instance cannot be used again — for a new payment, you must call useCheckout() again.
Use only the functions and methods described in this documentation. The SDK contains internal elements that are not intended for public use. Their use is not supported and may lead to SDK malfunction.
Additional features
Some SDK features work automatically in the background, others can be optionally controlled. The most important ones are described below.
3D Secure
When paying by card, the customer's bank may require additional verification using 3D Secure. 3D Secure is fully handled by the SDK — no additional implementation is necessary.
If the bank requires additional verification (3D Secure), the SDK automatically chooses the most suitable display method:
- iframe modal — if the bank's verification page can be displayed in an iframe, the SDK displays it directly on the page. If the iframe fails to load, the SDK switches to a redirect.
- New window (popup) — if the bank does not allow display in an iframe, the SDK opens a new window. If the popup is blocked by the browser, the SDK switches to a redirect.
- Redirect — fallback method for both scenarios above. The customer is redirected to the bank's page.
In the case of a redirect, the customer is returned after completing the verification to one of the URLs set in the client portal:
- Paid URL — payment successful,
- Cancelled URL — payment cancelled,
- Pending URL — the customer can repeat the payment.
Click to Pay
Click to Pay support is being intensively worked on. The feature will be available in one of the future SDK versions.
Click to Pay will allow customers to pay with a saved card without having to enter the card number again. After implementation, it will be an automatic part of the card form — without the need for additional configuration.
Debug mode
By passing debug: true in the configuration, you activate extended logging to the browser console. The SDK writes color-coded messages with the prefix [ComgateCheckout], which help with problem diagnostics.
useCheckout({
checkoutId: COMGATE_CHECKOUT_ID,
debug: true, // enables extended logging
core: { /* ... */ },
card: { mountPoint: '#cg-card-box' },
});
Do not use debug mode in production — the output may contain sensitive information about the initialization process.
Version information
For diagnostics and logging, you can find out the version of the loader and individual loaded modules.
The loader version is available via the exported getLoaderVersion() function:
import { getLoaderVersion } from '@comgate/checkout-js';
const { version, revision } = getLoaderVersion();
console.log('Loader:', version, revision);
Versions of individual modules are available via the global object window.comgate.checkout after initialization is complete. Each module (Core, Apple Pay, Google Pay, Card) exposes a version() method:
// Module versions are available after useCheckout() resolves
await useCheckout({ /* ... */ });
const checkout = window.comgate?.checkout;
console.log('Core version: ', checkout?.core?.version());
console.log('Apple Pay version: ', checkout?.applepay?.version());
console.log('Google Pay version:', checkout?.googlepay?.version());
console.log('Card version: ', checkout?.card?.version());
The version() values of modules are only available if the given module was successfully loaded. If the module was not included in the configuration or its loading failed, the corresponding property (checkout.applepay etc.) will not be present.
SDK preloading
| Function | Priority | Use |
|---|---|---|
prefetchComgateCheckout() | Low (prefetch) | The customer may pay — cart, product page. |
preloadComgateCheckout() | High (preload) | The customer will definitely pay — order summary, payment step. |
preloadComgateCheckout()
Preloads SDK scripts into the browser cache via <link rel="preload">. The scripts are not executed — they are only stored so that the subsequent useCheckout() call is faster.
Suitable for pages where you know the customer will soon proceed to the payment step (e.g. order summary).
- NPM
- CDN
import {
preloadComgateCheckout,
MODULE_APPLEPAY,
MODULE_GOOGLEPAY,
MODULE_CARD
} from '@comgate/checkout-js';
preloadComgateCheckout({
checkoutId: 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx',
modules: [MODULE_APPLEPAY, MODULE_GOOGLEPAY, MODULE_CARD],
version: '3',
onPreload: (result) => {
console.log('Preload completed:', result.preloaded);
},
})
.then((result) => {
if (result.success) {
console.log('All modules preloaded:', result.preloaded);
}
});
const {
preloadComgateCheckout,
MODULE_APPLEPAY,
MODULE_GOOGLEPAY,
MODULE_CARD
} = window.comgateCheckoutJs;
preloadComgateCheckout({
checkoutId: 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx',
modules: [MODULE_APPLEPAY, MODULE_GOOGLEPAY, MODULE_CARD],
version: '3',
onPreload: (result) => {
console.log('Preload completed:', result.preloaded);
},
})
.then((result) => {
if (result.success) {
console.log('All modules preloaded:', result.preloaded);
}
});
Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
checkoutId | string | Yes | – | UUID v4 assigned by Comgate. Identifies your e-shop. Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx. |
modules | TModuleType[] | Yes | – | Modules to preload. Allowed values: MODULE_APPLEPAY ('applepay'), MODULE_GOOGLEPAY ('googlepay'), MODULE_CARD ('card'), MODULE_CORE ('core'). Must contain at least one module (other than core). Core is always included automatically. |
version | string | No | '3' | SDK version. We recommend a fixed major version (e.g. '3'). Allowed values: '2', '3', or specific semver ('2.x.x', '3.x.x'). Version 1 is not supported. |
debug | boolean | No | false | Enables extended logging to the browser console. |
onPreload | (payload: TPreloadComgateCheckoutResult) => void | No | undefined | Alternative callback called after preloading is complete. The payload is identical to the return value of the Promise. |
The onPreload parameter is an alternative to handling the result via .then(). Both variants can be combined — the callback is always called first.
Return value Promise<TPreloadComgateCheckoutResult>
| Attribute | Type | Description |
|---|---|---|
checkoutId | string | Passed checkoutId. |
success | boolean | true if all requested modules were successfully loaded into the cache. |
preloaded | TModuleType[] | Array of names of successfully preloaded modules (e.g. ['core', 'applepay', 'googlepay']). |
error | { [key in TModuleTypeExtended]?: Error } | Error details for individual modules. The key is the module name ('core', 'applepay', 'googlepay', 'card', 'loader'), the value is an Error instance. Present only if some module failed. |
Error states
The Promise rejects if:
checkoutIdis not a valid UUID v4modulesis not an array or does not contain any module (other than core)- Any of the requested modules failed to preload
In case of rejection, the payload is identical to TPreloadComgateCheckoutResult, but success is false and the error field contains the details.
prefetchComgateCheckout()
Inserts a <link rel="prefetch"> for SDK scripts into the page. The browser downloads them with low priority in idle time — unlike preloadComgateCheckout(), the download will not block the current rendering or compete with critical resources.
Suitable for pages where the customer may proceed to payment, but it is not yet certain (e.g. product page, cart before summary).
- NPM
- CDN
import {
prefetchComgateCheckout,
MODULE_APPLEPAY,
MODULE_GOOGLEPAY,
MODULE_CARD
} from '@comgate/checkout-js';
prefetchComgateCheckout({
checkoutId: 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx',
modules: [MODULE_APPLEPAY, MODULE_GOOGLEPAY, MODULE_CARD],
version: '3',
onPrefetch: (result) => {
console.log('Prefetch completed:', result.prefetched);
},
})
.then((result) => {
if (result.success) {
console.log('All modules prefetched:', result.prefetched);
}
});
const {
prefetchComgateCheckout,
MODULE_APPLEPAY,
MODULE_GOOGLEPAY,
MODULE_CARD
} = window.comgateCheckoutJs;
prefetchComgateCheckout({
checkoutId: 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx',
modules: [MODULE_APPLEPAY, MODULE_GOOGLEPAY, MODULE_CARD],
version: '3',
onPrefetch: (result) => {
console.log('Prefetch completed:', result.prefetched);
},
})
.then((result) => {
if (result.success) {
console.log('All modules prefetched:', result.prefetched);
}
});
Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
checkoutId | string | Yes | – | UUID v4 assigned by Comgate. Identifies your e-shop. Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx. |
modules | TModuleType[] | Yes | – | Modules to prefetch. Allowed values: MODULE_APPLEPAY ('applepay'), MODULE_GOOGLEPAY ('googlepay'), MODULE_CARD ('card'), MODULE_CORE ('core'). Must contain at least one module (other than core). Core is always included automatically. |
version | string | No | '3' | SDK version. We recommend a fixed major version (e.g. '3'). Allowed values: '2', '3', or specific semver ('2.x.x', '3.x.x'). Version 1 is not supported. |
debug | boolean | No | false | Enables extended logging to the browser console. |
onPrefetch | (payload: TPrefetchComgateCheckoutResult) => void | No | undefined | Callback called after prefetching is complete. The payload is identical to the return value of the Promise. |
The onPrefetch parameter is an alternative to handling the result via .then(). Both variants can be combined — the callback is always called first.
Return value Promise<TPrefetchComgateCheckoutResult>
| Attribute | Type | Description |
|---|---|---|
checkoutId | string | Passed checkoutId. |
success | boolean | true if all requested modules were successfully prefetched. |
prefetched | TModuleType[] | Array of names of successfully prefetched modules (e.g. ['core', 'applepay', 'googlepay']). |
error | { [key in TModuleTypeExtended]?: Error } | Error details for individual modules. Present only if some module failed. |
Configuration reference
Complete overview of all configuration parameters that can be passed to useCheckout(). Each payment method has its own set of settings — only checkoutId and the core object are required.
TUseCheckoutConfig
| Attribute | Type | Required | Description |
|---|---|---|---|
checkoutId | string | Yes | UUID v4 assigned by Comgate. Identifies your e-shop. |
version | string | No | SDK version. Default '3'. We recommend a fixed major version (e.g. '3'). Allowed values: '2', '3', or specific semver ('3.x.x'). Version 1 is not supported. |
core | TUseCheckoutCore | Yes | SDK core configuration — callbacks, transaction ID, localization. |
applepay | TUseCheckoutApplePay | No | Enables the Apple Pay module. If the key is missing, the module will not be loaded. |
googlepay | TUseCheckoutGooglePay | No | Enables the Google Pay module. If the key is missing, the module will not be loaded. |
card | TUseCheckoutCard | No | Enables the card form module. If the key is missing, the module will not be loaded. |
TUseCheckoutCore
| Attribute | Type | Required | Default | Description |
|---|---|---|---|---|
transactionId | string | Yes | – | Payment ID in the format XXXX-XXXX-XXXX. Obtained when creating a payment via the API. |
locale | string | No | 'en' | Language of SDK texts. Supported values: cs, sk, en, de, es, fr, hr, hu, it, no, pl, ro, si, sl, sv, bg, da, el, et, lt, lv, nl, pt, fi, vi, uk, ru. |
redirectMode | string | No | 'top' | Redirect target on 3D Secure fallback: 'self' (current window), 'parent' (parent frame), 'top' (main window). |
onPaid | (payload) => void | Yes | – | Called after a successful payment. See Payload onPaid. |
onCancelled | (payload) => void | Yes | – | Called after a payment is cancelled. See Payload onCancelled. |
onPending | (payload) => void | Yes | – | Called after an unsuccessful attempt; the payment remains active. See Payload onPending. |
onError | (payload) => void | Yes | – | Called on an unexpected SDK error. See Payload onError. |
onPaymentStarted | () => void | No | – | Called when payment processing starts (displaying the loader). |
onPaymentStopped | () => void | No | – | Called after payment processing is complete (hiding the loader). |
On onPaymentStarted, do not remove HTML elements from the page — use CSS (display: none or overlay).
Callbacks — payload reference
All callbacks receive a payload object. Each payload contains the attribute service ('card' | 'applepay' | 'googlepay'), which identifies the payment method.
onPaid(payload)
| Attribute | Type | Description |
|---|---|---|
transactionId | string | Transaction ID |
price | number | Paid amount |
currency | string | Currency (ISO 4217, e.g. CZK, EUR) |
status | 'PAID' | 'AUTHORIZED' | Payment state |
service | string | Payment method |
onCancelled(payload)
| Attribute | Type | Description |
|---|---|---|
status | 'CANCELLED' | Payment state |
message | string | Reason for cancellation |
scope | string | Error area |
service | string | Payment method |
declineStatusCode | string? | Decline code (optional) |
onPending(payload)
| Attribute | Type | Description |
|---|---|---|
status | 'PENDING' | Payment state |
message | string | Error description |
scope | string | Error area |
service | string | Payment method |
declineStatusCode | string? | Decline code (optional) |
onPending does not mean a definitive failure — only an unsuccessful attempt. The payment remains active and the customer can repeat the operation.
onError(payload)
| Attribute | Type | Description |
|---|---|---|
message | string | Error description |
scope | string | Error area |
critical | boolean | true = critical error, the SDK cannot be used further |
canRepeat | boolean? | true = the customer can repeat the payment |
service | string | Payment method |
declineStatusCode | string? | Decline code (optional) |
Distinguishing the payment method
onPaid: (payload) => {
switch (payload.service) {
case 'card': console.log('Card payment'); break;
case 'applepay': console.log('Apple Pay payment'); break;
case 'googlepay': console.log('Google Pay payment'); break;
}
}
TUseCheckoutApplePay
| Attribute | Type | Required | Description |
|---|---|---|---|
mountPoint | string | Yes | CSS selector of the button container (e.g. '#cg-applepay-box'). |
ui | object | No | Button visual settings — details see Apple Pay. |
actions | object | No | { onButtonClick } — see onButtonClickHandler. |
payment | object | No | { provider, providerId } — details see Apple Pay. |
TUseCheckoutGooglePay
| Attribute | Type | Required | Description |
|---|---|---|---|
mountPoint | string | Yes | CSS selector of the button container (e.g. '#cg-googlepay-box'). |
ui | object | No | Button visual settings — details see Google Pay. |
actions | object | No | { onButtonClick } — see onButtonClickHandler. |
payment | object | No | { googlePayMerchantId, provider, providerId } — details see Google Pay. |
TUseCheckoutCard
| Attribute | Type | Required | Description |
|---|---|---|---|
mountPoint | string | HTMLDivElement | Yes | CSS selector or direct reference to the DOM element (must be a <div> with a non-empty id). The SDK derives selectors for sub-elements (#${id}-ibox, #${id}-button) from the id. |
actions | object | No | { onButtonClick } — see onButtonClickHandler. |
appearance | object | No | Customization of the appearance of the fields inside the iframe — details see Card form. |
SDK behavior based on the presence of elements in the container:
- Finds
#{id}-ibox→ inserts the iframe with the card fields. - Finds
#{id}-button→ connects the button to the payment flow. - Does not find
#{id}-button→ the payment can be started manually by callingprocess()on the module instance.