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 and Personal Access Token assigned to the application.


Step 2

Add Square’s payment form to your checkout flow.

Square provides an example payment form in the Square Developer documentation site that uses Square’s SqPaymentForm JavaScript object to request a valid card nonce from Square servers and include it in the form data before sending it to your payment processing page. To use the sample form, set applicationID to the applicationID you generated in the previous step:

var applicationId = '{{ SET THE APPLICATION ID HERE}}';

The sample form has minimal formatting and only includes the fields required to create a valid card nonce (card number, CVV, expiration 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 nonce retrieved by the payment form in the previous step):

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

$paymentRequest = new CreatePaymentRequest(
    $sourceId,
    $idempotencyKey,
    $amountMoney
);

And calls the Transaction API’s createPayment endpoint to process the card:

// Create a PaymentsApi client to charge the card using our form info
$paymentsApi = $client->getPaymentsApi();

// Call the PaymentsApi to create a payment using that card
try {
  $result = $paymentsApi->createPayment($paymentRequest);
} catch (Exception $e) {
  // Handle the exception
}

The create payment endpoint runs the card information included in the nonce object 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.