Integration
This guide walks you through embedding the Google Pay button on your page. The flow is:
- Load the component script.
- Add a container element.
- Define event handlers.
- Build the
paymentDataobject. - Call
init(options).
For a copy-paste-ready end-to-end snippet, jump to the Full Example.
Step 1: Add the Google Pay Component script
Include the component bundle in the <head> of your HTML page.
Sandbox / Test:
<script src='https://test-pay.dnapayments.com/components/google-pay/google-pay-component.js'></script>
Production:
<script src='https://pay.dnapayments.com/components/google-pay/google-pay-component.js'></script>
The script exposes window.DNAPayments.GooglePayComponent.
Step 2: Create the container element
<div id='google-pay-btn-container' style='width: 100%; height: 46px;'></div>
Apply the desired width and height to the container: the button takes the container's dimensions.
Step 3: Define event handlers
The component is event-driven. Provide callbacks via the events object passed to init(). The full list is in the Events section. The most common four are shown here.
function onClick() {
console.log('Google Pay button has been clicked');
}
function onError(error) {
// error is { code, message }, see the Handling Error Codes page
console.error('Google Pay error:', error);
}
function onCancel() {
console.log('Payment was cancelled by the user');
}
function onPaymentSuccess(result) {
console.log('Payment processed successfully', result);
// redirect to a success page, persist invoiceId, etc.
}
const events = {
onClick,
onError,
onCancel,
onPaymentSuccess,
};
Step 4: Build paymentData
paymentData carries the order details. Top-level fields and nested structures are described in paymentData reference.
const paymentData = {
amount: 24,
currency: 'GBP',
invoiceId: 'YOUR_INVOICE_ID',
description: 'Shoes',
paymentSettings: {
terminalId: 'YOUR_TERMINAL_ID',
callbackUrl: 'https://example.com/callback',
failureCallbackUrl: 'https://example.com/failure-callback'
},
customerDetails: {
accountDetails: { accountId: 'uuid000001' },
billingAddress: {
firstName: 'John', lastName: 'Doe',
addressLine1: 'Fulham Rd',
postalCode: 'SW6 1HS', city: 'London', country: 'GB'
},
email: 'example@email.com',
mobilePhone: '+441234567890'
},
orderLines: [{
name: 'Running shoe',
quantity: 1,
unitPrice: 24,
taxRate: 20,
totalAmount: 24,
totalTaxAmount: 4,
imageUrl: 'https://www.example.com/logo.png',
productUrl: 'https://www.example.com/AD6654412.html'
}]
};
Step 5: Initialize the button
Pass the container, paymentData, events and your access token to init():
async function renderGooglePay() {
window.DNAPayments.GooglePayComponent.init({
containerElement: document.getElementById('google-pay-btn-container'),
paymentData,
events,
token: 'YOUR_ACCESS_TOKEN',
});
}
window.addEventListener('load', renderGooglePay);
The OAuth token endpoint returns an object (access_token, expires_in, token_type, ...). Pass only the access_token string to the component. See Authentication for the token flow and the scopes required for the seamless component.
API reference
The component exposes the following functions on window.DNAPayments.GooglePayComponent:
| Method | Description |
|---|---|
init(options) | Render the button and return the component instance. |
create(...) | ⚠️ Deprecated: use init() instead. |
init(options)
const component = await window.DNAPayments.GooglePayComponent.init(options);
Renders the Google Pay button into containerElement and returns the initialized component instance.
options fields
| Property | Type | Required | Description |
|---|---|---|---|
containerElement | HTMLElement | ✅ | DOM node where the button is rendered. |
events | object | ✅ | Event handler map: see Events. |
paymentData | object | ✅ | Payment request: see paymentData reference. Must include at least amount, currency and paymentSettings.terminalId. |
token | string | ✅ | OAuth2 access token (the access_token string returned by Authentication). |
environment | string | - | Either 'sandbox' or 'production'. Optional, defaults to the environment baked into the bundle. |
cardBrands | string[] | - | Restrict accepted card networks on top of the terminal-configured list. Defaults to ['VISA', 'MASTERCARD']. Allowed values: 'VISA', 'MASTERCARD', 'AMEX', 'DISCOVER', 'INTERAC', 'JCB'. |
create(...) (deprecated)
create() is kept for backwards compatibility and will be removed in a future version. Use init(options) instead.
Migration:
// Before: positional arguments
window.DNAPayments.GooglePayComponent.create(
container, paymentData, events, token, cardBrands
);
// After: single options object
window.DNAPayments.GooglePayComponent.init({
containerElement: container,
paymentData, events, token, cardBrands
});
Events
The component emits the following events. All handlers are attached via the events map passed to init().
| Event | Signature | Fires when |
|---|---|---|
onClick | () => void | The user taps the Google Pay button, before the Google Pay sheet is shown. |
onLoad | () => void | Fires after the button has been rendered and mounted into containerElement. |
onBeforeProcessPayment | async () => void, async () => { paymentData?, token? } | Fires after the user authorizes the payment in the Google Pay sheet but before the component executes it on the backend. The handler may return refreshed paymentData / token: this is the canonical CMS pattern where the order (and invoiceId) is created server-side at this moment. Locked fields (amount, currency, delivery address) must match the init() values, otherwise the component fires 1010. See Deferred values via onBeforeProcessPayment. |
onPaymentSuccess | (result) => void | The payment has been processed successfully (and the 3-D Secure step, if any, has been confirmed). See onPaymentSuccess payload. |
onCancel | () => void | The user dismissed the Google Pay sheet. |
onError | (error) => void | Any error during initialization or processing. See onError payload and Handling Error Codes. |
Deferred values via onBeforeProcessPayment
onBeforeProcessPayment fires after the customer authorizes the payment in the Google Pay sheet and before the component sends it to the DNA Payments backend. The handler can return { paymentData, token } to swap in server-side values (typically invoiceId and a freshly issued access token):
const events = {
onBeforeProcessPayment: async () => {
const { invoiceId, token } = await fetch('/api/create-order-and-token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ amount: paymentData.amount, currency: paymentData.currency })
}).then(r => r.json());
return {
paymentData: { ...paymentData, invoiceId },
token
};
}
};
Locked fields (amount, currency, delivery address) must match the values passed at init(). Returning a paymentData whose locked fields differ fires 1010 PAYMENT_DATA_MISMATCH. Use onBeforeProcessPayment to add server-side fields, not to change the displayed total. If the cart amount can change, re-initialize the component instead.
onPaymentSuccess payload
{
id: string,
reference: string,
success: boolean
}
The object may include additional fields when applicable.
onError payload
{
code: number,
message: string,
additionalInfo?: any
}
additionalInfo carries the underlying cause when available (the original exception, or the response body from the DNA Payments backend), useful for logging and debugging. See Handling Error Codes for the full list of code values.
paymentData reference
The most commonly used fields of paymentData:
| Field | Required | Description |
|---|---|---|
amount | ✅ | Total transaction amount as a decimal number. |
currency | - | ISO 4217 currency code (e.g. 'GBP'). Defaults to 'GBP'. |
invoiceId | - | Your internal order / invoice identifier. |
description | - | Human-readable description shown on receipts. |
paymentSettings.terminalId | ✅ | Your DNA Payments terminal ID. |
paymentSettings.callbackUrl | - | Server-to-server success callback. |
paymentSettings.failureCallbackUrl | - | Server-to-server failure callback. |
customerDetails.accountDetails.accountId | - | Stable customer ID on your side. |
customerDetails.email | - | Customer email. The SDK auto-fills this from the Google Pay wallet identity when missing. |
customerDetails.mobilePhone | - | Customer phone. Same fallback as email. |
customerDetails.billingAddress | - | Billing address object (firstName, lastName, addressLine1, postalCode, city, country, ...). |
customerDetails.deliveryDetails.deliveryAddress | - | Shipping address object (same shape as billingAddress). |
orderLines | - | Array of line items (name, quantity, unitPrice, taxRate, totalAmount, totalTaxAmount, imageUrl, productUrl). |