Card Payments
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);
-
Get a new Card object
const card = await payments.card();
This creates a new Card instance with all of the behaviors and properties needed to take a card payment.
-
Attach the Card instance to a DOM element
Attach the Card instance to an empty DOM element on your page. The payment card form renders into the empty element, turning it into a secure payment card form.
await card.attach('#card');
-
Get the payment token
Get the payment form token from the Card instance when the buyer completes the form by calling the tokenize method.
const tokenResult = await card.tokenize(); if (tokenResult.status === 'OK') { const token = tokenResult.token; } else { console.error(tokenResult.errors); }
If the payment card information is valid, it returns a one-time-use token which you can use to create a Payment using the Payments API CreatePayment endpoint to charge a customer. Otherwise, it will return an error that you can present to the customer.
<!-- Provide a target element for the Card form -->
<form id="payment-form">
<div id="card-container"></div>
<button id="card-button" type="button">Pay</button>
</form>
<!-- Configure the Web Payments SDK and Card payment method -->
<script type="text/javascript">
async function main() {
const payments = Square.payments(APPLICATION_ID, LOCATION_ID);
const card = await payments.card();
await card.attach('#card-container');
async function eventHandler(event) {
event.preventDefault();
try {
const result = await card.tokenize();
if (result.status === 'OK') {
console.log(`Payment token is ${result.token}`);
}
} catch (e) {
console.error(e);
}
};
const cardButton = document.getElementById('card-button');
cardButton.addEventListener('click', eventHandler);
}
main();
</script>
#
Payments
Returned by Square.payments(appId, locationId)
.
Use this object to instantiate Payment methods. Learn more on the Payments page.
Methods
const payments = Square.payments(appId, locationId);
#
Card
The credit or debit card payment method
An object that has the methods to create and set up a single card payment.
Created by payments.card()
.
Note: The Card payment method automatically infers whether to display the postal code field and prompt based on the issuing country of the buyer payment card.
Methods
const payments = Square.payments(appId, locationId);
const card = await payments.card();
await card.attach('#card');
const form = document.querySelector('#card-payment');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const result = await card.tokenize(); // the card nonce
});