Square eCommerce

Take online payments with Square APIs in 3 steps

Step 1

Create a new Square API application.

Calls to Square’s API are authenticated using application IDs and authorisation tokens (either a personal access token or an OAuth token).

To create a new application, first log in to the Application Dashboard using your Square account.

Then click + New Application and give the application a name.

Note the Application ID, Location ID and Personal Access Token assigned to the application.

Step 2

Add Square Web Payments SDK to your checkout flow.

Square provides an example payment form in the Square Developer documentation site that uses Web Payments SDK to request a valid card token from Square servers and include it in the form data before sending it to your payment processing page. To use the sample form, set appId and locId to the IDs you generated in the previous step:

const appId = '{{ SET THE APPLICATION ID HERE}}'; const locId = '{{ SET THE LOCATION ID HERE}}'; 

The sample form has minimal formatting and only includes the fields required to create a valid card nonce (card number, CVV, expiry date and postcode). You will need to extend the sample form to collect other useful payment information (e.g. charge amount and currency used) and apply styles that make the form match your site. For example:

Step 3

Use Square’s API to charge the card.

The final step is to add code to your payment processing page that initialises a Square API client:

use Square\Models\Currency; use Square\SquareClient; use Square\Environment; // Replace 'XXXXXXXXXX' with an OAuth or your Personal Access Token const SQUARE_ACCESS_TOKEN = 'XXXXXXXXXX'; $client = new SquareClient([ 'accessToken' => SQUARE_ACCESS_TOKEN, 'environment' => Environment::SANDBOX, ]); 

Package the payment information as a CreatePaymentRequest (including the card token retrieved by the payment form in the previous step):

// Package the charge amount and currency as a Money object $sourceId = $_POST[token]; $idempotencyKey = uniqid(); $amountMoney = new Money; $amountMoney->setAmount($_POST['amount']); $amountMoney->setCurrency(Currency::USD); $paymentRequest = new CreatePaymentRequest( $sourceId, $idempotencyKey, $amountMoney ); 

And call the Payments API’s createPayment endpoint in /v2/payments to process the card:

// Create a Payments API client to charge the card using our form info $paymentsApi = $client->getPaymentsApi(); // Call the Payments API to create a payment using that card try { $result = $paymentsApi->createPayment($paymentRequest); } catch (Exception $e) { // Handle the exception } 

The create payment endpoint charges the card associated with the token and provides a response indicating if the card was successfully captured or declined. Successful payments can then be reviewed in the Sales Dashboard for your Square account.

Open your developer account now.