PaymentClient Class

The entry point for interacting with Meta Pay.

Examples

The following is an example of how to use PaymentClient.

First create a payment request. The PaymentRequest contains the payment details that should appear to the customer, and the options and configurations to create a payment response for the payment partner to process the transaction.

function buildPaymentRequest(): PaymentRequest 
{
  return
  {
    paymentDetails:
    {
     total: {label: 'Board Game', amount: {value: '19.99', currency: 'USD'}},
    },
    paymentOptions:
    {
      requestPayerName: true,
      requestPayerEmail: false,
      requestPayerPhone: false,
      requestShipping: false,
      allowOfferCodes: false
    },
    paymentConfiguration:
    {
      mode: 'TEST',
      partnerId: 'TEST_PARTNER_ID',
      partnerMerchantId: '<your merchant id>',
      acquirerCountryCode: 'US',
      supportedContainers: {
        'basic-card-v1': {}, // no configurations, use {}
      },
      containerContext: '<a unique identifier for the payment>',
    },
  };
}

Next create the PaymentClient and determine whether Meta Pay is available in the browser environment that your customer is using. If Meta Pay is available, display the Meta Pay button and attach the method to invoke when the customer clicks the button.

const paymentClient = new window.metapay.PaymentClient('1.0');

window.onload = async function ()
{
  const availability = await paymentClient.getAvailability();
  
  if (availability === 'AVAILABLE')
  {
    // display the Meta Pay button
    await paymentClient.renderButton
    (
      '#btn_container',
      buildPaymentRequest,
      responsePromise => onMetaPayClick(responsePromise),
      {theme: 'light'}
    );

    async function onMetaPayClick(responsePromise)
    {
      const response = await responsePromise;

      try
      {
        // process payment by sending response.container to partner
        // ...

        // dismiss the Meta Pay interface with a successful signal
        await response.complete(PaymentComplete.success);
      }
      catch (err)
      {
        // error handling
        // ...
  
        // dismiss the Meta Pay interface with a failure signal
        await response.complete(PaymentComplete.fail);
      }

      // more code
      // ...
    };
  }
  else
  {
    console.log('Meta Pay is not available');
  }
};

Proactive Checkout Flow

In some contexts e.g. when a user with existing payment method on file is entering checkout within a Meta family of app e.g. Facebook or Instagram, the SDK can initiate a more streamlined checkout experience proactively. The following diagram illustrates how this works:

In some user contexts initiating a checkout at page load is not the right user experience e.g. if the user is on a product detail page with a "Buy with MetaPay" button they haven't yet expressed intent to purchase. Handle these non-checkout scenarios by setting the uxFlags property of the PaymentConfiguration object e.g. paymentConfig.uxFlags = ['DISABLE_PROACTIVE_CHECKOUT']

Constructors

PaymentClient(clientVersion: string): PaymentClient

Creates an PaymentClient.

PropertyTypeDescriptionRequired

clientVersion

string

The version of the JavaScript SDK for Meta Pay that the client code uses.

Yes

Methods

getAvailability

getAvailability(paymentConfig: PaymentConfiguration): Promise<string>

Before you display the Meta Pay button on your site, call getAvailability to determine whether Meta Pay is available in the browser environment that your customer is using. This check ensures you only offer the Meta Pay experience where it is supported. If Meta Pay is available, display the Meta Pay button.

This method returns an Availability or an PaymentError.

ParameterTypeDescription

paymentConfig

PaymentConfiguration

Configuration details for the payment request and information such as the merchant and payment partner.

renderButton

renderButton(container: string, providePaymentRequest: () => PaymentRequest, onResponse: (responsePromise: Promise<PaymentResponse>) => void, _options?: ThemeOptions): Promise<void>

After verifying availability of Meta Pay, use this method to render a Meta Pay button in the web page. The button will be styled using styles and CDN resources per the _options parameter. This method will attach load and click listeners to support launching the Meta Pay payment sheet when the user clicks the button using the paymentRequest provided to the method. After the user has completed interaction with the payment sheet, the onResponse promise will be invoked with a payment response.

Additionally, the PaymentRequest returned from providePaymentRequest and onResponse function may be used to automatically initiate display of the payment sheet to create a more streamlined checkout experience for eligible Meta Pay users.

To respond to user interactions while the payment sheet is open please set onPaymentDetailsChanged and onPaymentConsent event handlers on the PaymentClient instance.

Note: If load and click listeners attached to the button rendered by this method are removed or modified, the payment sheet may not function properly.

PropertyTypeDescriptionRequired

containerSelector

string

A DOM selector string identifying the container element into which the styled Meta Pay button should be inserted.

Yes

providePaymentRequest

function:() => PaymentRequest

A function called when the payment sheet is launched which must return a valid PaymentRequest (not a promise) that will be rendered in the payment sheet. This function should reflect the current state of checkout and may be called more than once.

Yes

onResponse

responsePromise: Promise<PaymentResponse>) => void

A function invoked when the customer completes their interaction with the payment sheet providing a promise with the result of the interaction.

Yes

_options?

ThemeOptions

Style options for the Meta Pay button.

No

[deprecated] preparePaymentSheet

preparePaymentSheet(paymentConfig: PaymentConfiguration): Promise<PaymentSheetStatus>

This method is deprecated, please use renderButton.

Use this method to prepare a Meta Pay payment sheet. Call this method in response to a customer action such as a button click so that the payment sheet can create user interface components such as a popup window.

After you call preparePaymentSheet, call getPaymentResponse to provide the payment request details.

If you call getPaymentResponse without calling preparePaymentSheet first, the SDK attempts to initiate the payment sheet. However, getPaymentResponse might fail if there is no customer action first.

This method returns an PaymentSheetStatus or an PaymentError.

ParameterTypeDescription

paymentConfig

PaymentConfiguration

Configuration details for the payment request and information such as the merchant and payment partner.

getPaymentResponse

getPaymentResponse(request: PaymentRequest): Promise<PaymentResponse>

This method creates a Meta Pay interface. The customer can select a payment method and provide information such as name and shipping information if requested in the PaymentOptions of the request.

This method returns an PaymentResponse.

ParameterTypeDescription

request

PaymentRequest

The request to pay for a transaction by using a customer's Meta Pay account.

attemptProactivePayment

attemptProactivePayment(request: PaymentRequest): Promise<PaymentResponse>

Similar to getPaymentResponse, this method creates a Meta Pay experience. However, you can call this method when you render the Meta Pay button. On supported platforms, this can provide a more streamlined checkout experience for customers.

This method returns an Promise<PaymentResponse>. If proactive checkout is not supported, the promise will be rejected with an error.

ParameterTypeDescription

request

PaymentRequest

The request to pay for a transaction by using a customer's Meta Pay account.

Events

onPaymentConsent

An optional event handler that allows a merchant to attempt to authorize a payment before the payment sheet is closed.

When you use this event handler the payment sheet interface waits until the promise returned from the handler is resolved. If the event returns a PaymentAuthorizationResult with authorizationState of ERROR the message appears to the customer and the customer can choose to update or change the payment method.

onPaymentConsent Example

// before you call paymentClient.renderButton() attach a consent handler
paymentClient.onPaymentConsent = paymentConsentHandler;

async function paymentConsentHandler(paymentResponse)
{
  try
  {
    console.log('payment response received');

    // submit paymentResponse to payment processor for authorization
    return Promise.resolve({authorizationState: 'SUCCESS'});
  }
  catch (error)
  {
    return Promise.reject
    ({
       authorizationState: 'ERROR',
       error:
       {
         reason: 'INVALID_PAYMENT_DATA',
         message: 'We were unable to process payment. Please try again with a different card.'
       },
    });
  }
}

onPaymentDetailsChanged

An optional event handler that allows the merchant to update the initial FBPaymentRequest in response to changes that the customer makes in the payment sheet. It may also be used to display errors to the customer should any changes cause the transaction to be deemed invalid by the merchant. This callback is responsible for updating paymentDetails.total and/or paymentDetails.summaryItems in response to customer changes to the sheet. The callback must be implemented when the initial payment request is provided with the following scenarios:

  • paymentOptions.requestShipping is true
  • paymentOptions.shippingType is PICKUP
  • paymentOptions.requestBilling is true and tax values need to be recalculated for the total.
  • paymentOptions.allowOfferCodes is true. The handler should modify the total and summary values to correspond to the changes linked to the customer-selected offer code.

The callback must return a Promise<PaymentDetailsUpdate>.

ParameterTypeDescription

event

PaymentDetailsChangedEvent

The event representing a change on the Meta Pay payment sheet.

onPaymentDetailsChanged Example

// before you call paymentClient.renderButton() attach a handler
paymentClient.onPaymentDetailsChanged = paymentDetailsChangedHandler;

async function paymentDetailsChangedHandler(event)
{	
  // Create an PaymentDetailsUpdate object
  let update = {
  	paymentDetails: event.paymentDetails,
  	errors: [],
  }
  if (event.changeTypes.length != 0) {
  	// Modify the FBPaymentDetailsUpdate object based on 
  	// the incoming FBPaymentDetailsChangedEvent
  	// ...
  }
  
  return Promise.resolve(update);
}