Usage
-
Initialize the Square Payments object
Initialize the Square Payments object with your application ID and the ID of the seller location where the payment is taken.
const payments = Square.payments(APPLICATION_ID, LOCATION_ID);
-
Create a PaymentRequest with the total amount
Create a new PaymentRequest using the desired options. At the minimum, you need to provide the total amount, the countryCode, the currencyCode, and requestShippingContact. If requestShipping Contact is true, you must include an
afterpay_shippingcontactchanged
callback. Note: The amount field is formatted for display, including decimal places. When creating a payment with the Payments API, the amount must be formatted as the payment amount in the smallest unit of currency. For example, $5.79 would be 579 cents.const paymentRequest = payments.paymentRequest({ countryCode: 'US', currencyCode: 'USD', total: { amount: '5.79', label: 'Total' }, requestShippingContact: true, }); paymentRequest.addEventListener( 'afterpay_shippingaddresschanged', function (contact) { return { shippingOptions: [ { id: 'FREE', amount: '0.00', label: 'Free', taxLineItems: [ { id: 'taxItem1', label: 'Taxes', amount: '3.50', }, ], total: { amount: '9.29', label: 'Total', }, }, ], }; }, );
The PaymentRequest is created by the SDK with payment request options that your application provides in a paymentRequestOptions object that you declare.
-
Create an AfterpayClearpay object
Get a new AfterpayClearpay object with your PaymentRequest.
const afterpayClearpay = await payments.afterpayClearpay(paymentRequest);
This creates a new AfterpayClearpay instance with all of the behaviors and properties needed to take an Afterpay/Clearpay payment.
-
Get the one-time payment token from the AfterpayClearpay object
Get the payment token from the AfterpayClearpay object when the buyer completes the form by calling the tokenize method.
const tokenResult = await afterpayClearpay.tokenize(); if (tokenResult.status === 'OK') { const token = tokenResult.token; } else { console.error(tokenResult.errors); }
If the Afterpay/Clearpay information is valid, the tokenResult will include an
'OK'
, status as well as a one-time-use token which can be used to make a call to the Payments API CreatePayment endpoint to charge a customer. If the Afterpay/Clearpay information is not valid, it will return an error that you can present to the customer.