Skip to main content

Events & Callbacks Reference

Complete technical reference for all Primer SDK events, callbacks, and instance methods.

Practical Guide Available

For practical examples and implementation patterns, see the Events Guide.

DOM Events

All Primer SDK events are CustomEvents with bubbles: true and composed: true, allowing them to propagate through the DOM and cross shadow DOM boundaries.

Events Overview

Event NameDetail TypeDescription
primer:state-changeSdkStateContextTypeDispatched when SDK state changes (loading, processing, success, error)
primer:methods-updateInitializedPaymentsDispatched when available payment methods are updated
primer:readyPrimerJSDispatched when SDK is fully initialized and ready
primer:card-network-changeCardNetworksContextTypeDispatched when card network is detected or changed
primer:card-submitCardSubmitPayloadTriggerable event to submit the card form programmatically
primer:card-successCardSubmitSuccessPayloadDispatched when card form submission succeeds
primer:card-errorCardSubmitErrorsPayloadDispatched when card form validation errors occur
primer:payment-startundefinedDispatched when payment creation begins
primer:payment-successPaymentSuccessDataDispatched when payment completes successfully with PII-filtered data
primer:payment-failurePaymentFailureDataDispatched when payment fails with error details
primer:vault:methods-updateVaultedMethodsUpdateDataDispatched when vaulted payment methods are loaded or updated
primer:vault:selection-changeVaultSelectionChangeDataDispatched when a vaulted payment method is selected or deselected
primer:vault-submitVaultSubmitPayloadTriggerable event to submit vault payment programmatically
primer:show-other-payments-toggleundefinedTriggerable event to toggle other payment methods visibility
primer:show-other-payments-toggledShowOtherPaymentsToggledPayloadDispatched when other payment methods toggle state changes
primer:dialog-openundefinedDispatched when an overlay dialog opens (redirect payments, 3DS)
primer:dialog-closeundefinedDispatched when an overlay dialog closes (redirect payments, 3DS)

primer:state-change

Dispatched when SDK state changes during the payment lifecycle.

Changed in v0.7.0

The error property has been renamed to primerJsError and the failure property has been renamed to paymentFailure with an updated structure.

Payload Properties:

PropertyTypeDescription
isSuccessfulbooleanWhether the payment operation completed successfully
isProcessingbooleanWhether a payment operation is currently in progress
primerJsErrorError | nullSDK initialization or component error object
isLoadingbooleanWhether the SDK is loading resources or initializing
paymentFailure{ code: string; message: string; diagnosticsId?: string | null; data?: Record<string, unknown> } | nullPayment processing failure with structured error information

Usage Note: Listen to this event to show loading spinners, success messages, or error states.

primer:methods-update

Dispatched when available payment methods are loaded or updated.

Payload Properties:

The event detail is an InitializedPayments instance with the following methods:

MethodReturnsDescription
toArray()InitializedPaymentMethod[]Returns all payment methods as an array
size()numberReturns the count of available payment methods
get<T>(type: T)PaymentMethodByType<T> | undefinedRetrieves a specific payment method by type

Usage Note: Use this event to dynamically render payment methods or check availability.

primer:ready

Dispatched when the Primer SDK is fully initialized and ready for use.

Changed in v0.7.0

The onPaymentComplete callback has been replaced with onPaymentSuccess and onPaymentFailure callbacks. The onVaultedMethodsUpdate callback has been added.

Payload Properties:

The event detail contains the PrimerJS instance with the following properties:

PropertyTypeDescription
onPaymentStart() => voidCallback for payment creation start
onPaymentPrepare(data: PaymentData, handler: PrepareHandler) => voidCallback for payment preparation
onPaymentSuccess(data: PaymentSuccessData) => voidCallback for successful payment completion
onPaymentFailure(data: PaymentFailureData) => voidCallback for payment failure
onVaultedMethodsUpdate(data: VaultedMethodsUpdateData) => voidCallback for vaulted payment methods updates
refreshSession()() => Promise<void>Method to refresh the checkout session
getPaymentMethods()() => PaymentMethodInfo[]Method to retrieve cached payment methods

Usage Note: Use this event to configure callbacks and access PrimerJS instance methods.

primer:card-network-change

Dispatched when card network is detected or changes based on card number input.

Payload Properties:

PropertyTypeDescription
detectedCardNetworkCardNetwork | nullThe detected card network (Visa, Mastercard, etc.)
selectableCardNetworksCardNetwork[]Array of selectable card networks for co-branded cards
isLoadingbooleanWhether card network detection is in progress

CardNetwork Type:

PropertyTypeDescription
displayNamestringHuman-readable card network name
networkstringCard network identifier

Usage Note: Use this event to display card brand logos or network-specific messaging.

primer:card-submit

Triggerable event to submit the card form programmatically from anywhere in your application.

Payload Properties:

PropertyTypeDescription
sourcestring (optional)Identifier for the trigger source (e.g., "custom-button")

Usage Note: Dispatch this event to trigger card form submission when using external submit buttons.

primer:card-success

Dispatched when card form submission completes successfully.

Payload Properties:

PropertyTypeDescription
resultCardSubmitResultSubmission result data

CardSubmitResult Type:

PropertyTypeDescription
successboolean (optional)Whether submission was successful
tokenstring (optional)Payment token generated
analyticsIdstring (optional)Analytics tracking identifier
paymentIdstring (optional)Payment identifier

Usage Note: Use this event to confirm successful card form validation and submission.

primer:card-error

Dispatched when card form validation errors occur.

Payload Properties:

PropertyTypeDescription
errorsInputValidationError[]Array of validation errors

InputValidationError Type:

PropertyTypeDescription
fieldstringField name that failed validation
namestringError name/type
errorstringHuman-readable error message

Usage Note: Use this event to display validation error messages to users.

primer:payment-start

New in v0.7.0

This event provides more granular control over payment flow tracking.

Dispatched when payment creation begins.

Payload Properties:

This event has no detail payload (undefined).

Usage Note: Listen to this event to show loading indicators when the payment flow starts. Use this for UI feedback without coupling to specific payment callbacks.

Example:

document.addEventListener('primer:payment-start', () => {
console.log('Payment creation has started');
// Show loading spinner
});

primer:payment-success

New in v0.7.0

This event provides PII-filtered payment data for safe client-side processing and analytics.

Dispatched when payment completes successfully.

Payload Properties:

PropertyTypeDescription
paymentSummaryPaymentSummaryPII-filtered payment data including last 4 digits, network
paymentMethodTypestringPayment method type identifier (e.g., "PAYMENT_CARD")
timestampnumberUnix timestamp (seconds) when payment succeeded

PaymentSummary Type:

PropertyTypeDescription
last4DigitsstringLast 4 digits of the payment card
expirationMonthstringCard expiration month
expirationYearstringCard expiration year
cardholderNamestringName on the card
networkstringCard network (e.g., "VISA", "MASTERCARD")
isNetworkTokenizedbooleanWhether the card is network tokenized
paymentInstrumentTypestringType of payment instrument
billingAddressobjectBilling address details
threeDSecureAuthenticationobject3DS authentication information
PII Protection

The PaymentSummary object is automatically filtered to remove PII, making it safe for client-side analytics and logging.

Usage Note: Use this event for success analytics, confirmation displays, and updating your UI with payment details. The filtered data is safe for client-side storage and tracking.

Example:

document.addEventListener('primer:payment-success', ((
event: CustomEvent<PaymentSuccessData>,
) => {
const { paymentSummary, paymentMethodType, timestamp } = event.detail;

console.log('Payment succeeded!');
console.log('Card ending in:', paymentSummary.last4Digits);
console.log('Network:', paymentSummary.network);
console.log('Payment method:', paymentMethodType);

// Show success message with safe details
showSuccessMessage(
`Payment completed using ${paymentSummary.network} ending in ${paymentSummary.last4Digits}`,
);
}) as EventListener);

primer:payment-failure

New in v0.7.0

This event provides structured error information for consistent error handling.

Dispatched when payment fails.

Payload Properties:

PropertyTypeDescription
errorobjectStructured error information
error.codestringError code identifier
error.messagestringHuman-readable error message
error.diagnosticsIdstring | null (optional)Diagnostic identifier for support
error.dataRecord<string, unknown> (optional)Additional error context data
paymentSummaryPaymentSummary | undefinedPII-filtered payment data (if payment was created before failure)
paymentMethodTypestringPayment method type identifier
timestampnumberUnix timestamp (seconds) when payment failed

Usage Note: Use this event for error tracking, displaying failure messages to users, and enabling retry logic. The diagnosticsId can be used for support inquiries.

Example:

document.addEventListener('primer:payment-failure', ((
event: CustomEvent<PaymentFailureData>,
) => {
const { error, paymentMethodType, paymentSummary } = event.detail;

console.error('Payment failed:', error.message);
console.error('Error code:', error.code);

if (error.diagnosticsId) {
console.error('Diagnostics ID:', error.diagnosticsId);
}

// Show error message to user
showErrorMessage(`Payment failed: ${error.message}`, {
allowRetry: true,
diagnosticsId: error.diagnosticsId,
});
}) as EventListener);

primer:vault:methods-update

New in v0.7.0

This event allows tracking of vaulted payment methods without directly accessing the vault component.

Updated in v0.9.0

Added cvvRecapture flag to indicate when CVV re-entry is required for vaulted payment methods.

Dispatched when vaulted payment methods are loaded or updated.

Payload Properties:

PropertyTypeDescription
vaultedPaymentsInitializedVaultedPaymentsWrapper class containing vaulted methods
cvvRecapturebooleanWhether CVV re-entry is required (new in v0.9.0)
timestampnumberUnix timestamp (seconds) when updated

InitializedVaultedPayments Methods:

MethodReturnsDescription
get(id)VaultedPaymentMethodSummary | undefinedRetrieves a specific vaulted payment by ID
toArray()VaultedPaymentMethodSummary[]Returns all vaulted payment methods as array
size()numberReturns the count of vaulted payment methods

VaultedPaymentMethodSummary Type:

See the complete VaultedPaymentMethodSummary type definition for all available fields.

Usage Note: Use this event to update your vault UI, track the number of saved payment methods, or react to changes in the user's vaulted payments.

Example:

document.addEventListener('primer:vault:methods-update', ((
event: CustomEvent<VaultedMethodsUpdateData>,
) => {
const { vaultedPayments, cvvRecapture, timestamp } = event.detail;

console.log('Vaulted payment methods updated');
console.log('Total vaulted methods:', vaultedPayments.size());
console.log('CVV recapture required:', cvvRecapture);

// Render vaulted payment methods in UI
const methods = vaultedPayments.toArray();
methods.forEach((method) => {
console.log(`${method.network} ending in ${method.last4Digits}`);
});

// Update UI
updateVaultDisplay(methods, cvvRecapture);
}) as EventListener);

primer:vault:selection-change

This event tracks payment method selection state in the Vault Manager component.

Dispatched when a vaulted payment method is selected or deselected.

Payload Properties:

PropertyTypeDescription
paymentMethodIdstring | nullID of selected payment method, or null when deselected
timestampnumberUnix timestamp (seconds) when selection changed

Usage Note: Use this event to enable/disable custom submit buttons based on selection state. Combine with primer:state-change to track processing state.

Example:

document.addEventListener('primer:vault:selection-change', ((
event: CustomEvent<VaultSelectionChangeData>,
) => {
const { paymentMethodId } = event.detail;

if (paymentMethodId) {
console.log('Payment method selected:', paymentMethodId);
submitButton.disabled = false;
} else {
console.log('Payment method deselected');
submitButton.disabled = true;
}
}) as EventListener);

primer:vault-submit

Triggerable event for programmatic vault payment submission.

Triggerable event to submit vault payment programmatically from anywhere in your application.

Payload Properties:

PropertyTypeDescription
sourcestring (optional)Identifier for the trigger source (e.g., "custom-button")

Usage Note: Dispatch this event to trigger vault payment submission when using external submit buttons. The event must have bubbles: true and composed: true for proper propagation.

Example:

// Trigger vault payment submission from anywhere
document.dispatchEvent(
new CustomEvent('primer:vault-submit', {
bubbles: true,
composed: true,
detail: { source: 'external-checkout-button' },
}),
);

primer:show-other-payments-toggle

Triggerable event for programmatic toggle control.

Triggerable event to toggle the visibility of other payment methods programmatically.

Payload Properties:

This event has no detail payload (undefined).

Usage Note: Dispatch this event to programmatically expand or collapse the other payment methods section. The event must have bubbles: true and composed: true for proper propagation.

Example:

// Toggle other payment methods visibility
document.dispatchEvent(
new CustomEvent('primer:show-other-payments-toggle', {
bubbles: true,
composed: true,
}),
);

primer:show-other-payments-toggled

Tracks toggle state changes in the Show Other Payments component.

Dispatched when the other payment methods toggle state changes.

Payload Properties:

PropertyTypeDescription
expandedbooleantrue when expanded, false when collapsed
timestampnumberUnix timestamp (seconds) when toggle state changed

Usage Note: Use this event to update button labels dynamically or implement custom UI logic based on toggle state.

Example:

document.addEventListener('primer:show-other-payments-toggled', ((
event: CustomEvent<ShowOtherPaymentsToggledPayload>,
) => {
const { expanded } = event.detail;

toggleButton.textContent = expanded
? 'Hide Other Payment Methods'
: 'Show Other Payment Methods';
toggleButton.setAttribute('aria-expanded', String(expanded));
}) as EventListener);

primer:dialog-open

New in v0.13.0

This event fires when overlay dialogs are displayed during payment flows.

Dispatched when an overlay dialog opens. This occurs during:

  • Redirect-based payment methods (popup flow with overlay)
  • 3D Secure authentication challenges

Payload Properties:

This event has no detail payload (undefined).

Usage Note: Listen to this event to disable page interactions or show loading states while a dialog is active.

Example:

document.addEventListener('primer:dialog-open', () => {
console.log('Dialog opened');
// Disable background page interactions
document.body.classList.add('modal-open');
});

primer:dialog-close

New in v0.13.0

This event fires when overlay dialogs are closed during payment flows.

Dispatched when an overlay dialog closes. This occurs when:

  • Payment completes successfully
  • Payment fails
  • User closes or cancels the dialog
  • 3D Secure challenge completes

Payload Properties:

This event has no detail payload (undefined).

Usage Note: Listen to this event to re-enable page interactions. Payment success/failure should be handled via the primer:payment-success and primer:payment-failure events.

Example:

document.addEventListener('primer:dialog-close', () => {
console.log('Dialog closed');
// Re-enable background page interactions
document.body.classList.remove('modal-open');
});

Combined Example:

const checkout = document.querySelector('primer-checkout');

// Track dialog lifecycle
checkout.addEventListener('primer:dialog-open', () => {
disablePageInteractions();
});

checkout.addEventListener('primer:dialog-close', () => {
enablePageInteractions();
});

// Handle payment results separately
checkout.addEventListener('primer:payment-success', (event) => {
console.log('Payment succeeded:', event.detail);
});

checkout.addEventListener('primer:payment-failure', (event) => {
console.log('Payment failed:', event.detail.error.message);
});

PrimerJS Callbacks

Callbacks are set on the PrimerJS instance (accessible via the primer:ready event) to handle payment lifecycle events.

Callbacks Overview

CallbackParametersDescription
onPaymentStartNoneCalled when payment creation begins
onPaymentPreparedata: PaymentData, handler: PrepareHandlerCalled before payment is created, allows validation or abort
onPaymentSuccessdata: PaymentSuccessDataCalled when payment completes successfully
onPaymentFailuredata: PaymentFailureDataCalled when payment fails
onVaultedMethodsUpdatedata: VaultedMethodsUpdateDataCalled when vaulted payment methods update

onPaymentStart

Called when payment creation begins.

onPaymentStart?: () => void;

Usage Note: Use this callback to show loading indicators or disable UI elements during payment processing.

onPaymentPrepare

Called before payment is created, allowing validation or aborting the payment flow.

onPaymentPrepare?: (data: PaymentData, handler: PrepareHandler) => void;

Parameters:

NameTypeDescription
dataPaymentDataContains paymentMethodType being used
handlerPrepareHandlerObject with continuePaymentCreation() and abortPaymentCreation() methods

Usage Note: Use this callback to validate order details or perform pre-payment checks before proceeding.

onPaymentSuccess

New in v0.7.0

Replaces onPaymentComplete for successful payments with PII-filtered data.

Called when payment completes successfully.

onPaymentSuccess?: (data: PaymentSuccessData) => void;

Parameters:

NameTypeDescription
dataPaymentSuccessDataContains PII-filtered payment data and metadata

PaymentSuccessData Structure:

PropertyTypeDescription
paymentSummaryPaymentSummaryPII-filtered payment data including last 4 digits, network
paymentMethodTypestringPayment method type identifier
timestampnumberUnix timestamp (seconds) when payment succeeded

Usage Note: Use this callback to handle successful payments, redirect users to confirmation pages, and track analytics. The paymentSummary object is automatically filtered for PII protection.

Example:

primerCheckout.onPaymentSuccess = (data) => {
const { paymentSummary, paymentMethodType } = data;

console.log('Payment successful!');
console.log(
`Card: ${paymentSummary.network} ending in ${paymentSummary.last4Digits}`,
);

// Redirect to success page
window.location.href = `/order-confirmation?payment=${paymentMethodType}`;
};

onPaymentFailure

New in v0.7.0

Replaces onPaymentComplete for failed payments with structured error information.

Called when payment fails.

onPaymentFailure?: (data: PaymentFailureData) => void;

Parameters:

NameTypeDescription
dataPaymentFailureDataContains error information and context

PaymentFailureData Structure:

PropertyTypeDescription
errorobjectStructured error information
error.codestringError code identifier
error.messagestringHuman-readable error message
error.diagnosticsIdstring | null (optional)Diagnostic identifier for support
error.dataRecord<string, unknown> (optional)Additional error context data
paymentSummaryPaymentSummary | undefinedPII-filtered payment data (if payment was created before failure)
paymentMethodTypestringPayment method type identifier
timestampnumberUnix timestamp (seconds) when payment failed

Usage Note: Use this callback to display error messages to users, enable retry logic, and track payment failures. The diagnosticsId can be shared with support teams for troubleshooting.

Example:

primerCheckout.onPaymentFailure = (data) => {
const { error, paymentMethodType } = data;

console.error('Payment failed:', error.message);

// Display error to user
showErrorNotification({
title: 'Payment Failed',
message: error.message,
diagnosticsId: error.diagnosticsId,
allowRetry: true,
});

// Track failure in analytics
trackPaymentFailure({
errorCode: error.code,
paymentMethod: paymentMethodType,
});
};

onVaultedMethodsUpdate

New in v0.7.0

New callback for tracking changes to vaulted payment methods.

Called when vaulted payment methods are loaded or updated.

onVaultedMethodsUpdate?: (data: VaultedMethodsUpdateData) => void;

Parameters:

NameTypeDescription
dataVaultedMethodsUpdateDataContains vaulted payment methods collection

VaultedMethodsUpdateData Structure:

Updated in v0.9.0

Added cvvRecapture flag to indicate when CVV re-entry is required for vaulted payment methods.

PropertyTypeDescription
vaultedPaymentsInitializedVaultedPaymentsWrapper class containing vaulted methods
cvvRecapturebooleanWhether CVV re-entry is required (new in v0.9.0)
timestampnumberUnix timestamp (seconds) when updated

Usage Note: Use this callback to update your vault UI when payment methods are added, removed, or modified. The InitializedVaultedPayments class provides convenient methods to access vaulted payment data.

Example:

primerCheckout.onVaultedMethodsUpdate = (data) => {
const { vaultedPayments } = data;

console.log(`Loaded ${vaultedPayments.size()} vaulted payment methods`);

// Update UI with vaulted methods
const methods = vaultedPayments.toArray();
renderVaultedPaymentMethods(methods);

// Get specific method by ID
const primaryMethod = vaultedPayments.get('payment-method-id-123');
if (primaryMethod) {
setDefaultPaymentMethod(primaryMethod);
}
};

Example (Headless Vault UI - New in v0.9.0):

// Configure headless vault mode
checkout.options = {
vault: {
enabled: true,
headless: true, // Hide default vault UI
},
};

checkout.addEventListener('primer:ready', (event) => {
const primerJS = event.detail;

primerJS.onVaultedMethodsUpdate = async ({
vaultedPayments,
cvvRecapture,
}) => {
console.log(`Loaded ${vaultedPayments.size()} vaulted payment methods`);
console.log(`CVV recapture required: ${cvvRecapture}`);

// Build custom vault UI
const vaultContainer = document.getElementById('vault-container');
vaultContainer.innerHTML = '';

// Render each vaulted payment method
vaultedPayments.toArray().forEach((method, index) => {
const methodCard = document.createElement('div');
methodCard.className = 'vault-payment-method';
methodCard.innerHTML = `
<input type="radio" name="payment-method" id="method-${index}" value="${method.id}">
<label for="method-${index}">
${method.paymentInstrumentType} •••• ${method.paymentInstrumentData?.last4Digits || '****'}
</label>
`;
vaultContainer.appendChild(methodCard);
});

// Add CVV input if required
if (cvvRecapture) {
const cvvInput = await primerJS.createCvvInput();
const cvvContainer = document.createElement('div');
cvvContainer.className = 'cvv-input-container';
cvvContainer.appendChild(cvvInput);
vaultContainer.appendChild(cvvContainer);
}

// Handle payment submission with custom button
document.getElementById('pay-button').onclick = async () => {
await primerJS.startVaultPayment();
};
};
});

Related:

PrimerJS Instance Methods

Public methods available on the PrimerJS instance (accessible via the primer:ready event).

Methods Overview

MethodReturnsDescription
refreshSession()Promise<void>Synchronizes client-side SDK with server-side session updates
getPaymentMethods()PaymentMethodInfo[]Returns cached list of available payment methods
setCardholderName(name)voidProgrammatically sets the cardholder name field value
vault.createCvvInput()Promise<CvvInput | null>Creates CVV input for CVV recapture (new in v0.11.0)
vault.startPayment()Promise<void>Initiates vault payment (new in v0.11.0)
vault.delete()Promise<void>Deletes a vaulted payment method (new in v0.11.0)
createCvvInput()Promise<HTMLElement>Creates CVV input component for custom vault UI (headless mode)
startVaultPayment()Promise<void>Initiates vault payment processing in headless mode

VaultAPI Namespace

New in v0.11.0

The primerJS.vault namespace provides organized access to vault operations. All vault methods are now grouped under this namespace.

The vault property on PrimerJS provides access to all vault operations:

MethodReturnsDescription
vault.createCvvInput(options)Promise<CvvInput | null>Creates CVV input for CVV recapture
vault.startPayment(id, options?)Promise<void>Initiates vault payment
vault.delete(id)Promise<void>Deletes a vaulted payment method

For complete implementation examples, see the Headless Vault Implementation Guide.

vault.delete()

New in v0.11.0

Programmatically delete vaulted payment methods without using the default vault UI.

Permanently removes a vaulted payment method.

async vault.delete(paymentMethodId: string): Promise<void>

Parameters:

NameTypeDescription
paymentMethodIdstringID of the vaulted payment method to delete

Throws:

  • Error if vault not initialized
  • Error if payment method not found

Example:

try {
await primerJS.vault.delete(methodId);
console.log('Payment method deleted');
} catch (error) {
console.error('Failed to delete:', error);
}

refreshSession()

Synchronizes client-side SDK with server-side session updates.

async refreshSession(): Promise<void>

Use Case: Call this method after updating the checkout session on your server to refresh payment methods or order details.

getPaymentMethods()

Returns the cached list of available payment methods.

getPaymentMethods(): PaymentMethodInfo[]

Use Case: Use this method to check which payment methods are available without waiting for events.

setCardholderName()

New in v0.7.1

Programmatically set the cardholder name value in card payment forms.

Sets the cardholder name field value programmatically.

setCardholderName(cardholderName: string): void

Parameters:

NameTypeDescription
cardholderNamestringThe cardholder name to set

Use Case: Pre-fill the cardholder name from user profile data, auto-complete from previous transactions, or synchronize with external form data to improve checkout UX.

Timing Requirements:

  • Must be called after the primer:ready event has fired
  • Must be called after card hosted inputs have been rendered
  • Calling before initialization will log a warning and fail gracefully

Example:

const checkout = document.querySelector('primer-checkout');

checkout.addEventListener('primer:ready', (event) => {
const primerJS = event.detail;

// Pre-fill cardholder name from user profile
primerJS.setCardholderName('John Doe');
});

createCvvInput()

Deprecated in v0.11.0

This method is deprecated. Use primerJS.vault.createCvvInput() instead. This method will be removed in the next major release.

New in v0.9.0

Create CVV input components for custom vault UI implementations in headless mode.

Creates and returns a CVV input element for collecting CVV/CVC codes when processing vaulted payment methods.

async createCvvInput(
options: CardSecurityCodeInputOptions
): Promise<CvvInput | null>

Parameters:

NameTypeDescription
optionsCardSecurityCodeInputOptionsConfiguration for the CVV input (card network, container, placeholder)

Returns:

TypeDescription
Promise<CvvInput | null>CVV input component or null if vault not available

Usage Context:

  • Required when vault.headless: true and cvvRecapture: true
  • Call this method when onVaultedMethodsUpdate indicates CVV recapture is needed
  • Insert returned element into your custom vault UI
  • Component handles validation, styling, and secure CVV collection
  • Must be called after primer:ready event

Usage Note: This method is designed for headless vault implementations. When using the default vault UI (vault.headless: false), CVV inputs are managed automatically.

Example:

checkout.addEventListener('primer:ready', (event) => {
const primerJS = event.detail;

primerJS.onVaultedMethodsUpdate = async ({
vaultedPayments,
cvvRecapture,
}) => {
// Build custom vault UI
const methods = vaultedPayments.toArray();
renderCustomVaultMethods(methods);

// Add CVV input if required for selected payment method
if (cvvRecapture) {
// Get the selected payment method
const selectedMethod = methods.find((m) => m.isSelected);

if (selectedMethod) {
const cvvInput = await primerJS.createCvvInput({
cardNetwork: selectedMethod.paymentInstrumentData.network,
container: '#cvv-container',
placeholder: 'CVV',
});
if (cvvInput) {
const cvvContainer = document.getElementById('cvv-container');
cvvContainer.innerHTML = ''; // Clear previous CVV input
cvvContainer.appendChild(cvvInput);
}
}
}
};
});

Related:

startVaultPayment()

Deprecated in v0.11.0

This method is deprecated. Use primerJS.vault.startPayment() instead. This method will be removed in the next major release.

New in v0.9.0

Programmatically initiate vault payment flows in headless mode.

Initiates payment processing using a selected vaulted payment method.

async startVaultPayment(): Promise<void>

Returns:

TypeDescription
Promise<void>Resolves when payment processing begins (not completion)

Usage Context:

  • Required when vault.headless: true to trigger payment submission
  • Call this method when user clicks your custom "Pay" button
  • Processes the currently selected vaulted payment method
  • Validates CVV input if CVV recapture is required
  • Payment lifecycle callbacks (onPaymentSuccess, onPaymentFailure) fire normally
  • Must be called after primer:ready event

Error Handling:

The method throws errors in these scenarios:

  • No vaulted payment method is selected
  • CVV is required but not provided or invalid
  • Vault is not enabled or not in headless mode

Usage Note: This method replaces the default vault submit button when using headless mode. Standard payment callbacks still fire for handling success/failure states.

Example:

checkout.addEventListener('primer:ready', (event) => {
const primerJS = event.detail;

// Handle payment submission with custom button
document
.getElementById('custom-pay-button')
.addEventListener('click', async () => {
const payButton = event.target;

try {
// Disable button during processing
payButton.disabled = true;
payButton.textContent = 'Processing...';

// Start vault payment
await primerJS.startVaultPayment();

// Payment processing started
// Success/failure handled by callbacks below
} catch (error) {
console.error('Payment initiation failed:', error);
payButton.disabled = false;
payButton.textContent = 'Pay Now';
}
});

// Handle payment success
primerJS.onPaymentSuccess = (data) => {
console.log('Payment successful:', data.payment.id);
redirectToConfirmation(data.payment.id);
};

// Handle payment failure
primerJS.onPaymentFailure = (data) => {
console.error('Payment failed:', data.error.message);
showErrorMessage(data.error.message);
const payButton = document.getElementById('custom-pay-button');
payButton.disabled = false;
payButton.textContent = 'Pay Now';
};
});

Related:

Type Definitions

Payment Types

PaymentData

interface PaymentData {
paymentMethodType: string;
}

PaymentSuccessData

New in v0.7.0

Provides PII-filtered payment data for safe client-side processing.

interface PaymentSuccessData {
paymentSummary: PaymentSummary;
paymentMethodType: string;
timestamp: number;
}

PaymentFailureData

New in v0.7.0

Provides structured error information for consistent error handling.

interface PaymentFailureData {
error: {
code: string;
message: string;
diagnosticsId?: string | null;
data?: Record<string, unknown>;
};
paymentSummary?: PaymentSummary;
paymentMethodType: string;
timestamp: number;
}

PaymentSummary

PII Protection

All PII fields are automatically filtered from this object for safe client-side usage.

interface PaymentSummary {
last4Digits: string;
expirationMonth: string;
expirationYear: string;
cardholderName: string;
network: string;
isNetworkTokenized: boolean;
paymentInstrumentType: string;
billingAddress: {
firstName?: string;
lastName?: string;
addressLine1?: string;
addressLine2?: string;
city?: string;
state?: string;
countryCode?: string;
postalCode?: string;
};
threeDSecureAuthentication?: {
responseCode: string;
reasonCode?: string;
reasonText?: string;
protocolVersion?: string;
challengeIssued?: boolean;
};
}

VaultedMethodsUpdateData

New in v0.7.0

Provides access to vaulted payment methods collection.

Updated in v0.9.0

Added cvvRecapture flag to indicate when CVV re-entry is required.

interface VaultedMethodsUpdateData {
vaultedPayments: InitializedVaultedPayments;
cvvRecapture: boolean;
timestamp: number;
}

VaultedPaymentMethodSummary

Enhanced in v0.11.0

VaultedPaymentMethodSummary now exposes additional fields for better headless vault implementation:

  • Cards: cardholderName, expirationMonth, expirationYear
  • PayPal: email, firstName, lastName, externalPayerId
  • Klarna: email, firstName, lastName
interface VaultedPaymentMethodSummary {
id: string;
analyticsId: string;
paymentMethodType: string;
paymentInstrumentType: string;
paymentInstrumentData?: {
// Card fields
last4Digits?: string;
network?: string;
cardholderName?: string; // NEW in v0.11.0
expirationMonth?: string; // NEW in v0.11.0
expirationYear?: string; // NEW in v0.11.0
// PayPal fields
email?: string; // NEW in v0.11.0
firstName?: string; // NEW in v0.11.0
lastName?: string; // NEW in v0.11.0
externalPayerId?: string; // NEW in v0.11.0
// ACH fields
accountNumberLastFourDigits?: string;
bankName?: string;
accountType?: string;
};
userDescription?: string;
isSelected?: boolean;
}

VaultSelectionChangeData

Tracks payment method selection state in Vault Manager.

interface VaultSelectionChangeData {
paymentMethodId: string | null;
timestamp: number;
}

VaultSubmitPayload

Payload for triggerable vault payment submission event.

interface VaultSubmitPayload {
source?: string;
}

ShowOtherPaymentsToggledPayload

Tracks toggle state changes in Show Other Payments component.

interface ShowOtherPaymentsToggledPayload {
expanded: boolean;
timestamp: number;
}

Event Payload Types

SdkStateContextType / SdkState

Changed in v0.7.0

The error property has been renamed to primerJsError and the failure property has been renamed to paymentFailure with updated structure.

type SdkStateContextType = SdkState | null;

type SdkState = {
isSuccessful: boolean;
isProcessing: boolean;
primerJsError: Error | null;
isLoading: boolean;
paymentFailure: {
code: string;
message: string;
diagnosticsId?: string | null;
data?: Record<string, unknown>;
} | null;
};

InitializedPayments

class InitializedPayments {
get<T extends RedirectPaymentMethodTypes>(
type: T,
): RedirectPaymentMethod | undefined;

get<T extends (typeof PaymentMethodType)[keyof typeof PaymentMethodType]>(
type: T,
): PaymentMethodByType<T> | undefined;

toArray(): InitializedPaymentMethod[];

size(): number;
}

InitializedVaultedPayments

New in v0.7.0

Wrapper class for accessing vaulted payment methods.

class InitializedVaultedPayments {
get(id: string): VaultedPaymentMethodSummary | undefined;

toArray(): VaultedPaymentMethodSummary[];

size(): number;
}

CardNetworksContextType / CardNetwork

type CardNetworksContextType = {
detectedCardNetwork: CardNetwork | null;
selectableCardNetworks: CardNetwork[];
isLoading: boolean;
} | null;

type CardNetwork = {
displayName: string;
network: string;
};

CardSubmitPayload

interface CardSubmitPayload {
source?: string;
}

CardSubmitSuccessPayload / CardSubmitResult

interface CardSubmitSuccessPayload {
result: CardSubmitResult;
}

interface CardSubmitResult {
success?: boolean;
token?: string;
analyticsId?: string;
paymentId?: string;
[key: string]: unknown;
}

CardSubmitErrorsPayload

interface CardSubmitErrorsPayload {
errors: InputValidationError[];
}

Handler Types

PrepareHandler

interface PrepareHandler {
continuePaymentCreation: () => void;
abortPaymentCreation: () => void;
}

See Also