Customers API: Cookbook

Save Cards on File

Customers API

Before you start
Permalink Get a link to this section

  • You will need an access token. If you are using OAuth, you will need CUSTOMERS_WRITE permission to save a card on file and PAYMENTS_WRITE permission to process payments with the saved card. Cards on file are automatically updated on a monthly basis to confirm they are still valid and can be charged.

  • You need to have created a Customer object using the Customers API. You can follow The Customers API Setup Guide to create your first Customer object.

Important

Always ask customers for permission before saving their card information. For example, include a checkbox in your purchase flow that the customer can check to specify that they wish to save their card information for future purchases.

Linking cards on file without obtaining customer permission may result in your application being disabled without notice.

Step 1: Use payment card information to create and verify a nonce
Permalink Get a link to this section

To save a customer card, you will need to create a nonce, which is a secure payment token generated using the Square Payment form or the In-App Payments SDK. You will also need to verify the buyer with Strong Customer Authentication.

  1. Follow the Verify the Buyer When Using a Nonce recipe to verify the buyer as a part of getting your nonce.

  2. Get both the nonce and the verification_token.

Step 2: Save the customer card on file
Permalink Get a link to this section

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 field (customer_card_id).

Important

If you verified the buyer in the process of getting the nonce, you will need to provide the verification_token in your request.


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

// Replace IF you verified the buyer with SCA 
$verificationToken = "{VERIFICATION_TOKEN_FROM_STEP_1}"; 

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

// Set the card nonce value for your request object.
$body->setCardNonce($cardNonce);
$body->setCardNonce($customerId);
// $body->setCardNonce($verificationToken); //uncomment this line if you have the verification token


// Send the request to the CreateCustomerCard endpoint

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