Take Payments

Checkout API Setup Guide

Integrate with the Checkout API to take payments with a prebuilt payment flow hosted by Square.

The Checkout API provides a prebuilt solution for taking payments with a secure payment form hosted by Square. This guide provides step-by-step instruction for integrating with the Checkout API.

Web
Mobile Web
Client Side
Languages Supported
Additional Resources

Prerequisites

To use Square Checkout, all of the following must be true:

  • You have a Square account. Create a Square account in minutes if you do not already have one.
  • Your website hosting must support dynamic pages with server-side processing (e.g., code written with PHP, Ruby, ASP, or Java). Hosting solutions that support only HTML pages cannot use Square Checkout at this time.

Assumptions

This guide assumes you have read the Square Checkout Overview to learn about the Checkout data model, requirements, and limitations.

Working example

Our sample code has the following characteristics. These characteristics are not required to use the Checkout API.

  • We use PHP version 5.4+ and have installed the Square Connect v2 PHP SDK. The PHP SDK provides a helpful wrapper for interacting with the Checkout API. We also have SDKs available in other languages.
  • We authorize API calls with a sandbox access token. We use sandbox access tokens for testing purposes only. We strongly recommend using OAuth for authorization in production.

Step 1: Get your application credentials

You need to get your application's sandbox access token from your Application Dashboard.

  1. Go to your Applicaton Dashboard.
  2. Click on the application you want to work with to open the application settings page. Then, find the Sandbox Access Token on the Credentials page. You can also create a new application:
    • Click New Application.
    • Enter a name for your application (e.g., "My Store Checkout") and click Create App.
    • Find the Sandbox Access Token on the Credentials page of your new application's settings.

Step 2: Install the Connect PHP SDK

The Connect PHP SDK provides a helpful wrapper for interacting with our APIs. Though it takes an extra step to install the SDK, it will make interacting with Connect APIs much easier. We will be using the SDK for the rest of this guide.

  1. Follow the Square PHP SDK installation steps to install the SDK. You can clone the SDK directly from Github or you can use Composer, a dependency manager for PHP.
  2. Include the Connect PHP SDK in your file. Remember to change the path depending on where you place the SDK in relation to your other php files.
// Include the Square Connect API resources
require_once(__DIR__ . '/local/path/to/Square/Connect/SDK/autoload.php');

We also have other languages.

Note that using the Connect PHP SDK is optional. As long as you can package and receive JSON messages you can use Square's APIs.

Step 3: Set your application credentials and initialize an API client

  1. Set your application credentials.
//Replace your access token and location ID
$accessToken = 'REPLACE_ME';
$locationId = 'REPLACE_ME';
  1. Create an API client using the PHP SDK.
// Create and configure a new API client object
$defaultApiConfig = new \SquareConnect\Configuration();
$defaultApiConfig->setAccessToken($accessToken);
$defaultApiClient = new \SquareConnect\ApiClient($defaultApiConfig);
$checkoutClient = new SquareConnect\Api\CheckoutApi($defaultApiClient);

Step 5: Create an order for your checkout request

CreateCheckout requests require order information to be packaged as Order objects. We will create an Order object first by creating line items and then by creating the Order object.

Step 5.A: Create line items

Order objects must include at least 1 line item. You can create line items that reference an existing catalog, or you can create an ad-hoc line item.

For now, we will create an ad-hoc line item because it is faster to get started with ad-hoc line items. However, we strongly recommend that you create line items by referencing catalog IDs.

//Create a Money object to represent the price of the line item.
$price = new \SquareConnect\Model\Money;
$price->setAmount(600);
$price->setCurrency('USD');

//Create the line item and set details
$book = new \SquareConnect\Model\CreateOrderRequestLineItem;
$book->setName('The Shining');
$book->setQuantity('2');
$book->setBasePriceMoney($price);

//Puts our line item object in an array called lineItems.
$lineItems = array();
array_push($lineItems, $book);

Step 5.B: Create an order object using your line items

// Create an Order object using line items from above
$order = new \SquareConnect\Model\CreateOrderRequest();

$order->setIdempotencyKey(uniqid()); //uniqid() generates a random string.

//sets the lineItems array in the order object
$order->setLineItems($lineItems);

For more information on adding taxes and discounts to your order, check the Order API Technical Reference.

Step 6: Add code that creates a CreateCheckout request object

  1. First, create a CreateCheckout request object using the PHP SDK:
$checkout = new \SquareConnect\Model\CreateCheckoutRequest();
  1. Set your redirect URL and idempotency key. Then, set the order field as the Order object you created in Step 3.B.
$checkout->setIdempotencyKey(uniqid()); //uniqid() generates a random string.
$checkout->setOrder($order); //this is the order we created in the previous step

Note: We strongly recommend you use the redirect_url field to redirect your customers back to your store after the Checkout flow. If you do not include a redirect URL in your request, Checkout will present a confirmation page on your behalf and your customers will need to navigate back to your page on their own.

Step 7: Send the itemized order to the Square Checkout endpoint

Send your CreateCheckout request and save the result. If successful, the code below will get and print the checkout URL that opens the checkout page. If there's an error, it will print the error response.

try {
    $result = $checkoutClient->createCheckout(
      $locationId,
      $checkout
    );
    //Save the checkout ID for verifying transactions
    $checkoutId = $result->getCheckout()->getId();
    //Get the checkout URL that opens the checkout page.
    $checkoutUrl = $result->getCheckout()->getCheckoutPageUrl();
    print_r('Complete your transaction: ' . $checkoutUrl);
} catch (Exception $e) {
    echo 'Exception when calling CheckoutApi->createCheckout: ', $e->getMessage(), PHP_EOL;
}

Optional: Split transactions with additional recipients

To configure a multi-party transaction, add the additional_recipients field to your transaction request before calling the Charge endpoint. For example:

// Create money object
$amount_money = new \SquareConnect\Model\Money;
$amount_money->setAmount(100);
$amount_money->setCurrency('USD');

// Create a recipient
$recipient = new \SquareConnect\Model\ChargeRequestAdditionalRecipient;
$recipient->setLocationId({RECIPIENT LOCATION ID});
$recipient->setDescription("Charity donation: CA wildfire recovery");
$recipient->setAmountMoney($amount_money);

// Set the new recipient in our additional_recipients field.

//The additional_recipients field expects an array.
$listOfAdditionalRecipients = array($recipient);
$checkout->setAdditionalRecipients($listOfAdditionalRecipients);

You will need to use OAuth and have PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS permission for all of the accounts associated with the location IDs to split the payment. If you are using a personal access token or lack the necessary OAuth permissions on any of the additional recipient accounts, the transaction is declined and Charge returns an error.

To learn more about splitting transactions for multi-party transactions, see the Multi-party Transactions Overview and Multi-party Transactions Setup.

Optional: Pre-populate customer information

Checkout can record shipping information with the transaction. If your Checkout flow collects shipping information and you've already collected the information earlier in the workflow, we recommend pre-populating that data for a more seamless experience for your customer.

Prepolate the customer's email and shipping address by filling the pre_populate_buyer_email and pre_populate_shipping_address fields. The following code samples use the setter functions from the PHP SDK.

  1. Make sure your CreateCheckout request object has ask_for_shipping_address set to true:
$checkout->setAskForShippingAddress(true);
  1. Set the pre_populate_buyer_email.
$customerEmail = "REPLACE_ME_CUSTOMER_CONTACT_INFORMATION_EMAIL";

//Example:
//$customerEmail = "New.Amelia.Earhart@example.com"

$checkout->setPrePopulateBuyerEmail($customerEmail);
  1. Create an Address object and fill it with your previously collected address information, then set that Address object as pre_populate_shipping_address.
//Create Address object
$address = new \SquareConnect\Model\Address;

//Set values for Address object
$address->setAddressLine1($value);
$address->setAddressLine2($value);
$address->setAddressLine3($value);
$address->setLocality($value);
$address->setSublocality($value);
$address->setAdministrativeDistrictLevel1($value);
$address->setPostalCode($value);
$address->setCountry($value);
$address->setFirstName($value);
$address->setLastName($value);
$address->setOrganization($value);

//Set Address object as the pre_populate_shipping_address
$checkout->setPrePopulateShippingAddress($address);

Optional: verify transaction results

We recommend you verify the transaction results on success to make sure that they came from Square. This adds an important layer of security to your integration.

Checkout will send your customer to that URL when payment processing completes (or when it encounters an unrecoverable error) and append URL parameters with information relevant to the transaction:

  • A new transaction ID
  • A checkout ID from Square.
  • The reference ID that you set for your Checkout request.

In order to verify these values, you need to pull the transaction details (e.g., total order amount, credit card status) from Square's systems by querying the TransactionsApi endpoint. For example:

// pull out the transaction ID returned by Square Checkout
$returnedTransactionId = $_GET["transactionId"];

// Create a new API object to verify the transaction
$transactionClient = new \SquareConnect\Api\TransactionsApi($defaultApiClient);

// Ping the Transactions API endpoint for transaction details
try {

  // Get transaction details for this order from the Transactions API endpoint
  $apiResponse = $transactionClient->retrieveTransaction(
    $locationId,
    $returnedTransactionId
  );

} catch (Exception $e) {
  echo "The SquareConnect\Configuration object threw an exception while " .
       "calling TransactionsApi->retrieveTransaction: ",
       $e->getMessage(), PHP_EOL;
  exit;
}

Once you've pulled the transaction details, you can confirm the transaction by:

  • Comparing the processed order total to the expected order total.
  • Comparing the returned checkout ID to the checkout ID you stored earlier for this order number, and
  • Confirming the status for all credit cards involved in the order is CAPTURED.
Prev
< Checkout API Overview

Contact Developer Support, join our Slack channel, or ask for help on Stack Overflow