Less Annoying CRM logo Less Annoying CRM LACRM
Advanced

Webhooks code example

This page will register a hook for when any user creates a new contact, then create a contact to trigger the hook. It uses the function CallLacrmApi(), which can be found on the main tutorials page, so you'll want to copy that to the top of the page if you're trying to run this directly.

Create hook

The first page creates, then triggers a webhook for new contacts.

<?php

$ActiveWebhooks = CallLacrmApi("GetWebhooks");
if (empty($ActiveWebhooks)) {
    // Be sure to replace the EndpointUrl with a live URL that points to the 
    // example target code listed below. 
    CallLacrmApi("CreateWebhook", array(
        "EndpointUrl" => "https://www.mysite.com/webhook.php",
        "WebhookScope" => "Account",
        "Events"=> ["Contact.Create"]
    ));
}

// Trigger the webhook by adding a contact
$User = CallLacrmApi("GetUser");
CallLacrmApi("CreateContact", array(
    "Name" => "Test Contact",
    "AssignedTo" => $User["UserId"],
    "IsCompany" => false
));

?>

Receive hook

The second page, located at https://www.mysite.com/webhook.php in this example, does two things:

  1. It performs the intial handshake when CreateWebhook runs.
  2. It receives and parses the webhook body when the event is triggered in the CRM.
<?php

if (isset($_SERVER["HTTP_X_HOOK_SECRET"])) {
    $WebhookSecret = $_SERVER["HTTP_X_HOOK_SECRET"];
    // This is sent by CreateWebhook.
    // We need it to verify hook signatures, so lets save it.
    $WebhookSecretFile = fopen("/tmp/webhook_secret", "w"); 
    fwrite($WebhookSecretFile, $WebhookSecret); 
    fclose($WebhookSecretFile);

    // We also need to echo it back to LACRM in order to complete the hook registration.
    header("X-Hook-Secret: ". $WebhookSecret);
} else {
    // We got a webhook -- parse the body.
    $RequestBody = file_get_contents("php://input");

    // Check payload integrity using stored webhook secret.
    $SecretFile = fopen("/tmp/webhook_secret", "r");
    $WebhookSecret = fgets($SecretFile);
    fclose($SecretFile);
    $CalculatedSignature = hash_hmac("sha256", $RequestBody, $WebhookSecret);
    $PayloadSignature =  $_SERVER["HTTP_X_HOOK_SIGNATURE"];
    if ($CalculatedSignature !== $PayloadSignature) {
        die("Bad webhook signature.");
    }

    $Payload = json_decode($RequestBody, true);

    // The contact format matches GetContact.
    $ContactNameArray = $Payload["Contacts"][0]["Name"];
    $ContactName = "$ContactNameArray[FirstName] $ContactNameArray[LastName]";

    // You would probably want to do something more interesting, but lets 
    // just write to a logfile here.
    $WebhookLogFile = fopen("/tmp/webhook_log", "a"); 
    fwrite($WebhookLogFile, "
        Hook $Payload[TriggeringEvent] received from user $Payload[UserId].
        Contact name: $ContactName
    "); 
    fclose($WebhookLogFile);
}
exit;
?>