Implementation Example in PHP

This example is written in PHP, but you can use any language you like (NodeJS, .NET, Ruby) as long as you can run a webserver that can receive a POST request and parse it as JSON.

index.php: (server code)

<?php

/**
* Vev Examples - Webhook endpoint
*
* PHP example script for receiving PUBLISH events from Vev securely.
*
* [Read more here](https://help.vev.design/hosting/custom/webhook)
*/

const VEV_SECRET = 'fd718eb4-4498-4ed4-a73e-825fb1fedb13';

if (!isset($_SERVER['HTTP_X_VEV_SIGNATURE'])) {

http_response_code(401);

return 'Missing signature';

}

$signatureHeader = $_SERVER['HTTP_X_VEV_SIGNATURE'];

if (!$signatureHeader) {

http_response_code(401);

return 'Missing signature';

}

list($algorithm, $signature) = explode('=', $signatureHeader);

if (!$algorithm || !$signature) {

http_response_code(401);

return 'Invalid signature';

}

if (!in_array($algorithm, hash_hmac_algos())) {

http_response_code(401);

return 'Invalid algorithm';

}

$rawRequestBody = file_get_contents('php://input');

$requestBody = json_decode($rawRequestBody);

// Validating signature of request
// Done by comparing the signature with HMAC (hash-based message authentication code)) using the secret key for hasing
$generatedSignature = hash_hmac($algorithm, $rawRequestBody, VEV_SECRET);

// Comparing the request signature with the generated
// This will validate that the sender knows the secret and that the content was not tampered with
if ($generatedSignature !== $signature) {

http_response_code(401);

return 'Invalid signature';

}

$ip = $_SERVER['REMOTE_ADDR'];

if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
if (!empty($_SERVER['HTTP_CLIENT_IP'])) $ip = $_SERVER['HTTP_CLIENT_IP'];

function storeVevPage ($page) {

// Putting the files in the public dir
// if page is index page then set the path to be public/index.html
$pagePath = './public' . ($page->index ? '/index.html' : $page->path);

if (!pathinfo($pagePath)['extension']) $pagePath .= '/index.html';

$directory = substr($pagePath, 0, strrpos($pagePath, '/') - 1);

if (!file_exists($directory)) mkdir($directory, 0777, true);

// Writing the file to the page path
file_put_contents($pagePath, $page->html);

}

$payload = $requestBody->payload;
$event = $requestBody->event;

switch ($event) {

case 'PUBLISH':

foreach ($payload->pages as $page) {

storeVevPage($page);

}

echo 'I received your webhook';

break;

case 'PING':

echo "Webhook test ping received from {$ip}";

break;

}

You will still need to set the Webhook URL in your webhook settings to a URL that points to where you are running your webhook server.

Did this answer your question?