Customers API: Cookbook

Save Cards on File

Save cards on file to create a seamless purchase experience for returning customers and enable recurring payments.

Customers API
Payment Form
Transactions API

Before you start

  • You will need an access token. If you are using OAuth, you will need the CUSTOMERS_WRITE to save a card on file and PAYMENTS_WRITE permission to process payments with the saved.
  • You need to have created a Customer object using the Customer API. You can follow The Customer API Setup Guide to create your first Customer object.

Step 1: Generate a nonce with Square Payment Form

Follow the steps in the Payment Form build guide to embed the form and generate a card nonce.

Step 2: Use the nonce to create customer card

Use the Customers API to send the card nonce and the customer ID to the CreateCustomerCard endpoint. It will return a customer card ID in the response (customer_card_id).

$cardNonce = "{NONCE_FROM_STEP_1}";
$customerId = "{YOUR_CUSTOMER_ID}";  // Replace with an existing customer_id

// Create a CustomerCard request object
$body = new \SquareConnect\Model\CreateCustomerCardRequest();

// Set the card nonce value for your request object.

// Send the request to the CreateCustomerCard endpoint

try {
  $result = $customersApi->createCustomerCard($customerId, $body);
} catch (Exception $e) {
  echo 'Error when calling createCustomerCard: ', $e->getMessage(), PHP_EOL;

Step 3: Charge the saved card on file

Once you have saved a card on file, you can use the Transactions API and call the Charge endpoint to process the saved card. If you are using OAuth, you will need the PAYMENTS_WRITE permission.

To charge a saved card, set the customer_card_id and customer_id fields in the ChargeRequest object instead of the card_nonce field.

$customerId = "{YOUR_CUSTOMER_ID}"; // Replace with an existing customer_id
$customerCardId = {SAVED_CARD_ID};  // Replace with an existing customer_id

// The ID of the location to associate the created transaction with.

// An object object from the PHP SDK with the fields to POST for the request.
$body = new \SquareConnect\Model\ChargeRequest();

// Set the customer card ID.

// Set the customer ID.

try {
  $result = $customersApi>charge($locationId, $body);
} catch (Exception $e) {
  echo 'Error when calling TransactionsApi->charge: ', $e->getMessage(), PHP_EOL;

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