Table of Contents

Webhooks in Sonar: Basic PHP Example

Read Time: 2 mins

If you have not read the article How to: Using Webhooks in Sonar, we highly recommend that you start there.

Below is an example of a very simple Webhook receiver that you could host on a server to get Webhooks from Sonar. This example simply outputs the JSON data to a file in /tmp.

<?php
$output_dir = "/tmp/webhook-output";
$output_path = "$output_dir/{$_SERVER['REMOTE_ADDR']}_" . date("YmdHis") . ".json"; // set output path

if ($_SERVER['REQUEST_METHOD'] != "POST" ) {
header("Content-type: text/plain");
echo "This is only intended to be accessed via webhook POST";
exit;
}

header("Content-type: application/json"); // send response header to Sonar
echo json_encode(array("response" => "received")); // send arbitrary response body to Sonar

$json_raw = file_get_contents("php://input"); // receive raw POST input from Sonar

$json_array = json_decode($json_raw); // convert raw JSON string into a php array
$json_formatted = json_encode($json_array,JSON_PRETTY_PRINT); // convert array back to "pretty-printed" string

file_put_contents($output_path, $json_formatted); // output string to file

A screenshot of what it might look like from the Sonar-instance side can be found below:

This is what was received when the user was changed from Joe Blow to a Sales Agent (role_id was moved from 13 to 14):

{
"event": "user.updated",
"current": {
"id": 10,
"name": "Joe Blow",
"enabled": true,
"role_id": 14,
"language": "en",
"username": "joe",
"created_at": "2020-06-03T19:44:15+00:00",
"updated_at": "2020-07-09T16:19:16+00:00",
"public_name": "Joe Blow",
"super_admin": false,
"email_address": "joeblow@sonar.softwar",
"mobile_number": null,
"is_sonar_staff": false,
"completed_setup": true
},
"original": {
"id": 10,
"name": "Joe Blow",
"enabled": true,
"role_id": 13,
"_version": "1594311410815998",
"language": "en",
"username": "joe",
"created_at": "2020-06-03T19:44:15+00:00",
"updated_at": "2020-07-09T16:16:50+00:00",
"public_name": "Joe Blow",
"super_admin": false,
"email_address": "joeblow@sonar.software",
"mobile_number": null,
"is_sonar_staff": false,
"completed_setup": true,
"sonar_unique_id": "VXNlcl8xMA=="
},
"object_id": 10,
"triggered_at": "2020-07-09 16:19:16.913858"
}
The web server receiving the webhook MUST support both the http HEAD and POST methods. You can verify this using:
curl --head https://server.example.com/webhook.php

Once you have received a webhook, you may want to respond to it with API queries to get more details. If you are not familiar with Sonar’s powerful GraphQL API, please see the series of articles written about it, starting with The New Sonar API.

How did we do?

GPS Tracking Providers: Overview

How to Connect Cambium to your Sonar Instance

Contact