Broadleaf Microservices
  • v1.0.0-latest-prod

Amazon Payment Services React Hooks

The Broadleaf Amazon Payment Services React SDK provides several hooks for implementors to make use of.

useConsumeTokenResponse

Produces a callback to use to consume the response from APS for a tokenization request. The data can still be an unparsed string.

Parameters

Parameter Type Required? Description

amazonPaymentServicesClient

Amazon Payment Services Client

✅

The client needed to make API requests

defaultLanguage

string

✅

The default language code

handleSubmitPayment

(paymentRequest: PaymentRequest) ⇒ void PaymentRequest.

✅

Callback method to handle submission of the payment request.

paymentNameTemplate

string

❌

Template used to compile the payment’s name: ’${cardType}

${maskedAccountNumber} ${expMonth}/${expYear}'`

selectedAddress

Address

✅

The currently selected billing address

selectedInstallment

SelectedInstallment

✅

The currently selected installment plan.

useInstallments

boolean

✅

Response

Parameter Type Required? Description

consumeTokenResponse

( data: string, cart: Cart ) ⇒ Promise<{ responseCode?: string; signatureMatched?: boolean; success?: boolean; }> Cart.

✅

The callback method to use to handle consuming the APS token response.

isProcessing

boolean

✅

Whether the token is being processed.

tokenError

ApiError

✅

The API Error if the request to process the token fails.

Example

import { AmazonPaymentServicesClient } from '@broadleaf/amazon-payment-services-api';
import { useConsumeTokenResponse } from '@broadleaf/amazon-payment-services-react';
import type { ClientOptions } from '@broadleaf/commerce-core';

const options: ClientOptions = {
  applicationToken,
  baseHost,
  locale: currentLocale,
  preview,
};
const amazonPaymentServicesClient = new AmazonPaymentServicesClient(options);
const { consumeTokenResponse, isProcessing, tokenError } = useConsumeTokenResponse({
  amazonPaymentServicesClient,
  defaultLanguage: 'en',
  selectedAddress,
  selectedInstallment,
  useInstallments,
  setProcessing,
  handleSubmitPayment,
  paymentNameTemplate: '${cardType}|${maskedAccountNumber}'
});

useConsumeTokenServiceResponse

Provides a callback to consume the response from APS after submitting a request to create a token service (i.e., APS saved payment). This will use the merchant reference to determine the id of an existing PaymentAccount in Broadleaf to retrieve and update with the token name.

See useCreateTokenService for the initial request.

Parameters

Parameter Type Required? Description

amazonPaymentServicesClient

Amazon Payment Services Client

✅

The client needed to make API requests

authState

AuthState

✅

Important information about the authentication state of the user.

customerClient

Customer Client

✅

The client needed to make API requests against Customer APIs.

previewOptions

PreviewOptions

❌

Options passed to the HTTP request call to customize the request for sandbox previews.

Response

Parameter Type Required? Description

consumeTokenServiceResponse

( tokenServiceResponse: TokenServiceResponse ) ⇒ Promise<{ account?: PaymentAccount; signatureMatched?: boolean; responseCode?: string; responseMessage?: string; success?: boolean; }>

✅

The callback to use to consume the token service response.

isProcessing

boolean

✅

Whether the token is being processed.

error

ApiError

❌

The API Error if the request to process the token service response fails.

Example

import { useMemo } from 'react';
import { useAuth } from '@broadleaf/auth-react';
import { AmazonPaymentServicesClient } from '@broadleaf/amazon-payment-services-api';
import { useConsumeTokenServiceResponse } from '@broadleaf/amazon-payment-services-react';
import { CustomerClient } from '@broadleaf/commerce-customer';
import type { AuthState } from '@broadleaf/payment-js';
import type { ClientOptions } from '@broadleaf/commerce-core';

const { isAuthenticated, isLoading, getAccessToken, user } = useAuth();
const { csrMode, csrAnonymous } = useCsrContext();
const authState = useMemo<AuthState>(() => {
  const customerEmail = user?.email_address;
  const customerId = user?.customer_id;
  return {
    isAuthenticated,
    isAuthenticating: isLoading,
    getAccessToken,
    customerEmail,
    customerId,
    isCsr: csrMode,
    isAnonymousCsr: csrAnonymous,
  };
}, [csrAnonymous, csrMode, getAccessToken, isAuthenticated, isLoading, user]);
const options: ClientOptions = {
  applicationToken,
  baseHost,
  locale: currentLocale,
  preview,
};
const amazonPaymentServicesClient = new AmazonPaymentServicesClient(options);
const customerClient = new CustomerClient(options);
const {
  consumeTokenServiceResponse,
  error: tokenServiceResponseError,
  isProcessing,
} = useConsumeTokenServiceResponse({
  amazonPaymentServicesClient,
  authState,
  customerClient,
});

useCreateTokenService

Provides a callback to submit the request to create a token service (i.e., APS saved payment). This requires a plain form submission with full redirect to APS. Because of which a PaymentAccount should be created on Broadleaf’s side prior to the submission and linked to the submission. This is so that the payment information that isn’t sent to APS can be stored and retrieved when APS responds with the token name.

See useConsumeTokenServiceResponse for consuming the response.

Parameters

Parameter Type Required? Description

accessCode

✅

The APS access code for their APIs.

amazonPaymentServicesClient

Amazon Payment Services Client

✅

The client needed to make API requests

authState

AuthState

✅

Important information about the authentication state of the user.

checkoutUrl

string

✅

APS checkout submission URL.

customerClient

Customer Client

✅

The client needed to make API requests against Customer APIs.

defaultLanguage

string

✅

The language code for the request.

merchantIdentifier

string

✅

The caller’s merchant identifier.

previewOptions

PreviewOptions

❌

Options passed to the HTTP request call to customize the request for sandbox previews.

Response

Parameter Type Required? Description

handleCreateTokenService

(data: PaymentAccountFormData) ⇒ Promise<void>. PaymentAccountFormData

✅

The callback method ot use to handle making the create token request.

error

ApiError

❌

The API Error if the request to failed.

Example

import { useMemo } from 'react';
import { useAuth } from '@broadleaf/auth-react';
import { AmazonPaymentServicesClient } from '@broadleaf/amazon-payment-services-api';
import { useCreateTokenService } from '@broadleaf/amazon-payment-services-react';
import { CustomerClient } from '@broadleaf/commerce-customer';
import type { AuthState } from '@broadleaf/payment-js';
import type { ClientOptions } from '@broadleaf/commerce-core';

const { isAuthenticated, isLoading, getAccessToken, user } = useAuth();
const { csrMode, csrAnonymous } = useCsrContext();
const authState = useMemo<AuthState>(() => {
  const customerEmail = user?.email_address;
  const customerId = user?.customer_id;
  return {
    isAuthenticated,
    isAuthenticating: isLoading,
    getAccessToken,
    customerEmail,
    customerId,
    isCsr: csrMode,
    isAnonymousCsr: csrAnonymous,
  };
}, [csrAnonymous, csrMode, getAccessToken, isAuthenticated, isLoading, user]);
const options: ClientOptions = {
  applicationToken,
  baseHost,
  locale: currentLocale,
  preview,
};
const amazonPaymentServicesClient = new AmazonPaymentServicesClient(options);
const customerClient = new CustomerClient(options);
const { handleCreateTokenService, error: createTokenServiceError } =
  useCreateTokenService({
    amazonPaymentServicesClient,
    authState,
    accessCode: 'accessCode',
    checkoutUrl: 'https://sbcheckout.PayFort.com/FortAPI/paymentPage',
    customerClient,
    defaultLanguage: 'en',
    merchantIdentifier: '123abc',
  });

useFetchInstallments

Hook to use to fetch a list of Installments available.

Parameters

Parameter Type Required? Description

apsClient

Amazon Payment Services Client

✅

The client needed to make API requests

cartState

CartState

✅

Important information about the cart state.

defaultLanguage

string

✅

The language code for the request.

Response

Parameter Type Required? Description

refetch

(props: AmazonPaymentServicesInstallmentsRequest) ⇒ Promise<void> AmazonPaymentServicesInstallmentsRequest

✅

Method to resend the request.

installments

Array of AmazonPaymentServicesInstallments

❌

The resulting installments.

loadingInstallments

boolean

✅

Whether the request in process.

error

ApiError

❌

The API Error if the request to failed.

Example

import { AmazonPaymentServicesClient } from '@broadleaf/amazon-payment-services-api';
import { useFetchInstallments } from '@broadleaf/amazon-payment-services-react';
import type { CartState } from '@broadleaf/payment-js';
import type { ClientOptions } from '@broadleaf/commerce-core';

import { useCartContext } from '@app/cart/contexts';

const cartState = useCartContext();
const options: ClientOptions = {
  applicationToken,
  baseHost,
  locale: currentLocale,
  preview,
};
const amazonPaymentServicesClient = new AmazonPaymentServicesClient(options);
const { installments, loadingInstallments, error } = useFetchInstallments({
  apsClient,
  cartState,
  defaultLanguage: 'en'
});

useInstallments

Hook to use to perform various operations useful to fetch, display, and track which installment the user has selected during checkout.

Parameters

Parameter Type Required? Description

apsClient

Amazon Payment Services Client

✅

The client needed to make API requests

cartState

CartState

✅

Important information about the cart state.

defaultLanguage

string

✅

The language code for the request.

Response

Parameter Type Required? Description

availableInstallmentBanks

✅

List of the banks/issuers of the available installments

availablePlans

Array of PlanDetails

✅

List of PlanDetails from the available installments

bank

string

❌

Selected bank’s issuer code

setBank

(bank?: string) ⇒ void;

✅

Method to set bank

error

ApiError

❌

The API Error if the request to failed.

installments

Array of AmazonPaymentServicesInstallments

❌

The resulting installments.

loadingInstallments

boolean

✅

Whether the request in process.

selectedPlan

PlanDetail

❌

The plan selected by the user

setSelectedPlan

(plan?: PlanDetail) ⇒ void

✅

Method to set selectedPlan.

selectedInstallment

SelectedInstallment

❌

The installment selected by the user.

setSelectedInstallment

(installment?: SelectedInstallment) ⇒ void

✅

Method to set selectedInstallment

Example

import { AmazonPaymentServicesClient } from '@broadleaf/amazon-payment-services-api';
import { useInstallments } from '@broadleaf/amazon-payment-services-react';
import type { CartState } from '@broadleaf/payment-js';
import type { ClientOptions } from '@broadleaf/commerce-core';

import { useCartContext } from '@app/cart/contexts';

const cartState = useCartContext();
const options: ClientOptions = {
  applicationToken,
  baseHost,
  locale: currentLocale,
  preview,
};
const amazonPaymentServicesClient = new AmazonPaymentServicesClient(options);
const {
  availableInstallmentBanks,
  availablePlans,
  bank,
  setBank,
  installments,
  loadingInstallments,
  error,
  selectedPlan,
  setSelectedPlan,
  selectedInstallment,
  setSelectedInstallment
} = useInstallments({
  apsClient,
  cartState,
  defaultLanguage: 'en'
});

useSignatureRequest

Hook to use to get a callback to send a request to use the Broadleaf API to generate a signature for the payment request.

Parameters

Parameter Type Required? Description

amazonPaymentServicesClient

Amazon Payment Services Client

✅

The client needed to make API requests

Response

Parameter Type Required? Description

requestSignature

(request: SignatureRequestProps) ⇒ Promise<string | undefined>. SignatureRequestProps

✅

Callback method to send the signature request.

error

ApiError

❌

The API Error if the request to failed.

Example

import { AmazonPaymentServicesClient } from '@broadleaf/amazon-payment-services-api';
import { useSignatureRequest } from '@broadleaf/amazon-payment-services-react';
import type { ClientOptions } from '@broadleaf/commerce-core';

const options: ClientOptions = {
  applicationToken,
  baseHost,
  locale: currentLocale,
  preview,
};
const amazonPaymentServicesClient = new AmazonPaymentServicesClient(options);
const { requestSignature, error } = useSignatureRequest({
  amazonPaymentServicesClient,
});

useSubmitTokenRequest

Provides a callback to submit the payment data to Amazon’s API. The endpoint requires a form submission instead of JSON, so this callback will create a hidden form in a new frame and submit that to prevent the screen from flashing from a redirect.

It’s important to note that it’s up to the user to handle the response from APS with an endpoint that can then communicate with the original web page that hosts the form. One option for that would be using Web Sockets to push the response to the browser then call useConsumeTokenResponse.

Parameters

Parameter Type Required? Description

accessCode

string

✅

APS API access token.

amazonPaymentServicesClient

Amazon Payment Services Client

✅

The client needed to make API requests

checkoutUrl

string

✅

APS checkout submission URL.

defaultLanguage

string

✅

The default language code

merchantIdentifier

string

✅

The caller’s merchant identifier.

merchantReference

string

✅

Reference for the merchant to use to identify the token.

Response

Table 1. Hook Response
Parameter Type Required? Description

handleSubmit

(data: SubmitData) ⇒ Promise<void>.

✅

error

ApiError

❌

The API Error if the request to failed.

SubmitData is a combination of Address, CardFormData, and the following fields:

+ .Submit Data

Parameter Type Required? Description

issuer_code

string

✅

Identifies the card issuer.

plan_code

string

✅

Identifies the plan.

number_of_installment

string

❌

Identifies the optional installment.

Example

import { AmazonPaymentServicesClient } from '@broadleaf/amazon-payment-services-api';
import { useSubmitTokenRequest } from '@broadleaf/amazon-payment-services-react';
import type { ClientOptions } from '@broadleaf/commerce-core';

const options: ClientOptions = {
  applicationToken,
  baseHost,
  locale: currentLocale,
  preview,
};
const amazonPaymentServicesClient = new AmazonPaymentServicesClient(options);
const { handleSubmit, error } = useSubmitTokenRequest({
  amazonPaymentServicesClient,
  accessCode: 'AbC123',
  defaultLanguage: 'en',
  merchantIdentifier: '123abc',
  merchantReference: Math.floor(Date.now() / 1000),
  checkoutUrl: 'https://sbcheckout.PayFort.com/FortAPI/paymentPage',
});

useVerifySignature

Hook to use to get a callback method to hit the Broadleaf signature verification API.

Parameters

Parameter Type Required? Description

amazonPaymentServicesClient

Amazon Payment Services Client

✅

The client needed to make API requests

Response

Parameter Type Required? Description

verifySignature

(request: Record<string, string | string[]>) ⇒ Promise<boolean | undefined>

✅

Callback method to use to send the verification request. Should include all fields from the token service request against the APS API except token_name.

error

ApiError

❌

The API Error if the request to failed.

Example

import { AmazonPaymentServicesClient } from '@broadleaf/amazon-payment-services-api';
import { useVerifySignature } from '@broadleaf/amazon-payment-services-react';
import type { ClientOptions } from '@broadleaf/commerce-core';

const options: ClientOptions = {
  applicationToken,
  baseHost,
  locale: currentLocale,
  preview,
};
const amazonPaymentServicesClient = new AmazonPaymentServicesClient(options);
const { verifySignature, error: verifySigError } = useVerifySignature({
  amazonPaymentServicesClient,
});