Skip to main content

Payment Element

Introduction

The Payment Element is a web element that incorporates:

The Card Element is always included in the Payment Element. Apple Pay and Google Pay buttons are displayed if they are supported by the user's browser. The Payment Element provides extensive customization options, allowing you to modify the elements' appearance to match your brand's style, ensuring a professional and cohesive user experience during the payment process.

Step 1: Prepare the page

Add the following script element to your page's html to include the Payment Elements SDK in your site:

<head>
<script src="https://sandbox-cdn.pci.getfwd.com/sdk/forward.js"></script>

Your webpage also needs an element where it can be mounted. This is typically achieved by defining a <div> and assigning it a unique identifier.

<div id="payment-form" />

Step 2: Create a Payment Element

The Forward class can be accessed through the window object. To instantiate a Payment Element, you can call the createPaymentElement static class helper with the following:

  • apiKey: Your public key.
  • clientSecret: The client_secret of the payment intent.
  • googlePayMerchantId: (optional) The merchant ID provided by Google after registering for Google Pay - Google Pay Details. The Google Pay button will not display if this is not provided.
// <script>
const paymentElement = await window.Forward.createPaymentElement({
apiKey: 'pk_123948342832',
clientSecret: 'pi_123948342832_secret_123948342832',
googlePayMerchantId: '12345678901234567890',
});

Step 3: Mount the Payment Element

After creating an instance of the Payment Element, you can add it to the page by using the mount method.

Provide the element selector where you want the form to be placed as well as the following callbacks as arguments to the mount method:

  • onChange: (optional) This callback is invoked whenever the Card Element form contents change.
  • onReady: This callback is invoked when the user has entered a fully ready card with no errors. It receives a tokenize function that your application can call to tokenize the card.
  • onCancel: (optional) This callback is invoked when the user prematurely closes the Apple Pay or Google Pay pop-up window.
  • onSuccess: This callback is invoked when the card is successfully tokenized. It receives a token representing a PaymentMethod id, which can be utilized to process payments on your backend.
  • onError: This callback is invoked when an error occurs during the tokenization process. It receives an error object that contains information about the error.
info

Your onSuccess callback MUST return a Promise that sends the token to your server to process the payment. If the payment is successful, the Promise should be resolved. If the payment fails, the Promise should be rejected with an error message.

note

onChange and onReady are only applicable when the user interacts with the Card Element. onCancel is specific to the Apple Pay and Google Pay buttons.

The mount method returns a function that you can use to remove the Payment Element from the page.

// <script>
const unmountPaymentElement = paymentElement.mount('#payment-form', {
onChange: (event) => {
if (!event.ready) {
console.log('Credit card input is incomplete');
// Disable submit/pay button and show error message
}
console.log(event);
},
onReady: (tokenize) => {
console.log('Credit card form is ready');
// Enable submit/pay button and call `tokenize` on click
tokenize({billingDetails: {address: {postalCode: '12345'}}});
},
onSuccess: async ({ token }) => {
console.log(token);
// Send token to your server to process payment, the token is a payment method id
// Resolve promise or throw error
},
onError: (error) => {
console.log(error);
},
onCancel: () => {
console.log('User closed Apple Pay or Google Pay pop-up window');
},
});

// Remove the Payment Element from the page
unmountPaymentElement();

onChange Event

onChange messages contain information about the correctness of the form fields or any encountered errors. The event object follows the structure of the PaymentChangedEvent type:

type PaymentChangedEvent = {
ready: boolean;
empty?: boolean;
errors?: string[];
payment_method_type: 'card';
card: {
last_four_digits?: string;
first_six_digits?: string;
brand?: string;
exp_month?: string;
exp_year?: string;
wallet?: 'apple_pay' | 'google_pay';
};
billing_details?: {
address: {
country: string;
postal_code: string;
};
};
};

onReady Event

The onReady callback is invoked when the user has entered a fully ready card with no errors. It receives a tokenize function that your application can call to tokenize the card.

// The signature of the returned function is:
type Tokenize = (options?: TokenizeOptions) => Promise<PaymentMethod>;
type TokenizeOptions = {
billingDetails?: PaymentMethodBillingDetails; // Added for backwards compatibility
pineappleDetails?: {
authToken: string;
gatewayId: string;
};
};

type PaymentMethodBillingDetails = {
address?: {
city?: string;
country?: string;
state?: string;
addressLine1?: string;
addressLine2?: string;
postalCode?: string;
};
email?: string;
name?: string;
phone?: string;
};

Apple Pay Payment Request

You can customize the Apple Pay payment request by specifying applePayPaymentRequest on mount.

applePayPaymentRequest is an object that may contain any subset of the properties of an ApplePayPaymentRequest.

// <script>
paymentElement.mount('#payment-button', {
onSuccess: async ({ token }) => { ... },
onError: (error) => { ... },
applePayPaymentRequest: {
total: {
label: 'COMPANY, INC.',
type: 'final',
amount: '38.06',
},
}
});

You may also subsequently update the Apple Pay payment request by calling the setApplePayPaymentRequest method (prior to the user clicking the Apple Pay button):

// <script>
paymentElement.setApplePayPaymentRequest({
total: {
label: 'COMPANY, INC.',
type: 'final',
amount: '38.06',
}
});

Google Pay Payment Data Request

You can customize the Google Pay payment data request by specifying googlePayPaymentDataRequest on mount.

googlePayPaymentDataRequest is an object that may contain any subset of the properties of a Google Pay PaymentDataRequest.

// <script>
paymentElement.mount('#payment-button', {
onSuccess: async ({ token }) => { ... },
onError: (error) => { ... },
googlePayPaymentDataRequest: {
transactionInfo: {
countryCode: "US",
currencyCode: "USD",
totalPriceStatus: "FINAL",
totalPrice: "100.00",
},
}
});

You may also subsequently update the Google Pay payment data request by calling the setGooglePayPaymentDataRequest method (prior to the user clicking the Google Pay button):

// <script>
paymentElement.setGooglePayPaymentDataRequest({
transactionInfo: {
countryCode: "US",
currencyCode: "USD",
totalPriceStatus: "FINAL",
totalPrice: "100.00",
}
});

Appearance

The Payment Element can be customized to match your brand's style. You can adjust the appearance of the form using additional optional attributes of the mount options object.

Style

You can customize the appearance of the Card Element form using the style attribute of the mount options object. The style attribute provides a way to adjust various attributes, each of which corresponds to an internal CSS variable. You can use any valid CSS string as the value for these attributes to achieve the desired customization.

export type Style = {
inputHeight?: string; // Height of input elements.
inputPaddingLeft?: string; // Padding applied to input elements.
inputBackgroundColor?: string; // Background color of input elements.
borderWidth?: string; // Input border.
borderColor?: string; // Default border color.
borderRadius?: string;
focusBorderColor?: string; // Color of border on focus.
focusBoxShadow?: string; // Box shadow on input element on focus.
errorColor?: string; // Border and text on error.
hoverBorderColor?: string; // Border color on hover.
textColor?: string; // Default text color applied to input and labels elements.
fontFamily?: string; // Font family used for label elements, input elements and error messages.
fontSize?: string; // Font size applied to input elements.
fontStyle?: string; // Font style applied to label elements, input elements and error messages.
fontVariant?: string; // Font variant applied to label elements, input elements and error messages.
fontWeight?: string; // Font weight applied to text of input elements.
labelFontWeight?: string; // Font weight of the input element label.
labelFontSize?: string; // Font size of the input element label.
lineHeight?: string; // Line height applied to input element text.
letterSpacing?: string; // Letter spacing applied to all text in the iframe.
placeholderColor?: string; // Placeholder color of input elements.
backgroundColor?: string; // Background color of iframe container.
};

Labels

By default, the Card Element form includes labels for each of the input fields. However, if you prefer not to have any labels on your form, you can disable them by setting the showLabels option to false.

Apple Pay button

You may adjust Apple Pay button styling by specifying applePayButtonOptions.

export type ApplePayButtonOptions: {
buttonstyle?: 'black' | 'white' | 'whiteWithOutline';
}

Google Pay button

You may also adjust Google Pay button styling by specifying googlePayButtonOptions.

See the Google Pay ButtonOptions documentation for more information.

export type GooglePayButtonOptions {
buttonType?: 'book' | 'buy' | 'checkout' | 'donate' | 'order' | 'pay' | 'plain' | 'subscribe';
buttonColor?: 'default' | 'black' | 'white';
buttonSizeMode?: 'static' | 'fill';
buttonRootNode?: HTMLDocument | ShadowRoot;
buttonLocale?: string;
}

Example of no labels and adjusting style and Apple Pay and Google Pay buttons

paymentElement.mount('#payment-form', {
onReady: (tokenize) => { ... },
onSuccess: async ({ token }) => { ... },
onError: (error) => { ... },
style: {
textColor: 'red',
borderWidth: '2',
borderColor: 'gray',
backgroundColor: 'green',
inputBackgroundColor: 'white',
},
showLabels: false,
applePayButtonOptions: {
buttonstyle: "white-outline",
},
googlePayButtonOptions: {
buttonType: "checkout",
},
});

Apple Pay Payment

If the user submitted payment information using the Apple Pay Button, the onSuccess callback is provided with both a token and an applePayPayment object.

See the ApplePayPayment documentation for more information.

Google Pay Payment

If the user submitted payment information using the Google Pay Button, the onSuccess callback is provided with both a token and a googlePayPayment object.

See the Google Pay PaymentMethodData documentation for more information.