API Development 101

Webhooks

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 API calls or snippets of code triggered by predefined events. 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.

Limitations

  • Notifications typically trigger within 60 seconds of the associated event. But, some notifications may take up to 30 minutes to arrive.
  • If Square Webhooks attempts to send a notification and times out or does not receive a response from your server, the notification will drop and it will not resend.

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"
}

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.

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."
  }
}

Learn more

For more detailed information, see the Square Webhooks Technical Reference.

Prev
< Pagination
Next
Getting Started >

Ask for help on Stack Overflow or join our Slack channel