Resources

Webhooks API

Set up real-time notifications for completed transactions and updates to product inventories.

What are webhooks?

Webhooks (also known as web callbacks or push APIs) are HTTP calls or snippets of code that are triggered by specific events. With a typical API, you have to make calls at regular time intervals to detect changes to your data. Webhooks replace regular API calls with instant, real-time notifications.

When a trigger event occurs, a webhook collects the event data and sends it as a POST request to a preconfigured URL. For example, a company that works with a manufacturer to print custom images on mugs can use webhooks to send customer images to a manufacturer as soon as a payment is processed.

Webhooks with Square

Square Webhooks support 3 predefined events:

  • PAYMENT_UPDATED — Triggered when a charge is made or refunded through Point of Sale or through API calls to Connect v2 Transaction endpoints.
  • INVENTORY_UPDATED — Triggered when the inventory quantity for a catalog item is updated.
  • TIMECARD_UPDATED — Triggered when an employee clocks in using the Point of Sale app or when a timecard is created in the merchant dashboard.

Notifications for these events also include up to 3 delivery metadata headers:

  • Square-Initial-Delivery-Timestamp — Delivery time of the initial notification delivery as a RFC 339 timestamp.
  • Square-Retry-Number — The number of times Square has resent a notification for the given event (including the current retry) as an integer. The retry number does not include the original notification and is only present when there has been at least one unsuccessful delivery.
  • Square-Retry-Reason — The reason why the last notification delivery failed. The retry reason is only present when there is at least one unsuccessful delivery and has the following possible values:
    • http_timeout — the client server took longer than 10 seconds to respond.
    • http_error — the client server responded with a non-2xx status code.
    • ssl_error — Square could not verify the client SSL certificate.
    • other_error — something unexpected occurred.

Notification delivery SLA

Square makes every effort to deliver Webhook notifications as quickly as possible. In most cases, notifications will arrive within 60 seconds of the associated event.

Applications must acknowledge the notification by responding within 10 seconds with an HTTP 2xx response code. Responding outside the 10 second window, or with a different HTTP status code (including HTTP 3xx), Square will deem delivery unsuccessful.

Unsuccessful deliveries are retried for up to 72 hours after the originating event. After 72 hours have elapsed, the notification is discarded and will not be sent again. Square uses linear backoff to avoid spamming applications and retries notifications according to the following schedule:

Retry attempt Time between attempts Time since webhook event
1 1 minute 1 minute
2 2 minutes 3 minutes
3 4 minutes 7 minutes
4 8 minutes 15 minutes
5 16 minutes 31 minutes
6 32 minutes 63 minutes
7 – 78 60 minutes 2 – 72 hours

How it works — the Square Webhooks API process flow

Consider an application that uses webhooks to send manufacturing requests when customers place orders through a merchant webstore.

Before an application can use webhooks, the following needs to happen:

  • The application backend needs to initialize the webhook listener by subscribing to payment updates.
  • The application needs to have a notification URL and that URL needs to be set in the Application Control Panel.

Here is an example of how the application responds to webhook notifications as customers complete the purchase flow on the merchant webstore:

  1. A customer provides payment information.
  2. The application backend packages and sends a transaction request.
  3. Square processes the transaction, which triggers the PAYMENT_UPDATED notification.
  4. Square Webhooks sends a notification to the listener URL configured in the application control panel.
  5. The webhooks listener receives a JSON message with information on the completed transaction (which includes the transaction ID) and validates the authenticity of the notification.
  6. The webhooks listener uses the transaction information to call Square APIs for more information and then constructs an email message and sends it to manufacturing.

When trigger events occur, Square Webhooks sends a POST request to the notification URL configured in the Application Dashboard. The Square Webhook request body describes:

  • The merchant the event was triggered for.
  • The location where the event occured.
  • The type of webhook event. See WebhookEventType for possible values.
  • PAYMENT_UPDATED notifications also include an entity_id, which is a payment ID you can use to look up more information.

Here is an example of the request body that Square sends to your webhook listener:

{
  "merchant_id": "18YC4JBH91E1H",
  "location_id": "JGHJ0343",
  "event_type": "PAYMENT_UPDATED",
  "entity_id": "Jq74mCczmFXk1tC10GB"
}

Subscribe to Square Webhook notifications

To initialize your webhook listener, you need to subscribe to the events you want notifications for. You only need to do this once. You must subscribe to webhook events programmatically using cURL or custom code in an application.

The quickest way to subscribe to webhook events is to use cURL:

curl -X PUT                                        \
-H "Authorization: Bearer ACCESS_TOKEN"          \
-H "Content-Type: application/json"              \
-d '[EVENT_LIST]'                                \
https://connect.squareup.com/v1/LOCATION_ID/webhooks

  1. Replace ACCESS_TOKEN with the access token for the account being targeted.
  2. Replace LOCATION_ID with a valid location ID for the account being targeted.
  3. Replace EVENT_LIST with a comma-separated list of the notification events you want to subscribe to. EVENT_LIST uses the following syntax:
["PAYMENT_UPDATED", "INVENTORY_UPDATED"]

See WebhookEventType for possible values.

  1. Open the Mac Terminal or Windows Command Prompt. Then, enter the cURL command. If the subscription request is successful, you will receive an array with all the webhook notifications you are now subscribed to.

Subscribe to TIMECARD_UPDATED

To subscribe to the TIMECARD_UPDATED webhook notifications, you need to provide a merchant_id instead of a location_id.

curl -X PUT                                        \
-H "Authorization: Bearer ACCESS_TOKEN"          \
-H "Content-Type: application/json"              \
-d '[EVENT_LIST]'                                \
https://connect.squareup.com/v1/MERCHANT_ID/webhooks

Validate a Square Webhook notification

We recommend validating webhook notifications to confirm they came from Square. While not strictly required, validating the sender adds an extra layer of security and helps avoid man-in-the-middle attacks

All webhook notifications from Square include an X-Square-Signature header. The value of this header is an HMAC-SHA1 signature generated using your webhook notification URL and the body of the request excluding all whitespace.

You can validate the webhook notification by generating the HMAC-SHA1 in your own code and comparing it to the signature of the notification you received. The value of $webhookSignatureKey is the Signature Key assigned by the Square Application Dashboard in the Webhooks settings page for your application.

  1. Get the notification signature:
$notificationSignature = getallheaders()['X-Square-Signature'];
  1. Create a function to validate the signature. The example function below generates an HMAC-SHA1 signature from your notification URL and the notification body, then compares it with the provided signature.
function isValidSignature($notificationBody, $notificationSignature, $notificationUrl, $webhookSignatureKey) {
  # Concatenate your notification URL and the JSON body of the webhook notification
  $stringToSign = $webhookUrl . $notificationBody;

  # Generate the HMAC-SHA1 signature of the string
  #signed with your webhook signature key
  $stringSignature = base64_encode(hash_hmac('sha1', $stringToSign, $webhookSignatureKey, true));

  #Compare HMAC-SHA1 signatures.
  if (hash_equals($stringSignature, $notificationSignature) ) {
    echo "Hashes match!";
  }
  else {
    echo "Hashes do not match."
  }
}

Test your Square Webhooks configuration

When events trigger a webhook, Square sends event information to the notification URL configured for your webhooks listener. For now, we will use webhook.site for demonstration purposes.

  1. In a new tab, go to https://webhook.site and create a subdomain. It will automatically generate a notification URL for you to use. Copy the URL.
  2. Go to the Application Dashboard and click the application you want to work with. Select the Webhooks tab.
  3. Click Enable Webhooks if it is not already enabled.
  4. In the Notification URL field, paste the URL you received from webhook.site.
  5. Click Save.

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