Send leads to a webhook

You can send your Riddle leads and responses automatically to your marketing software or data warehouse for each person who completes your lead generation form. Here's some more information about webhooks and APIs.

Add a webhook

  1. Create a Riddle that includes at least one lead block.
    create riddle
  2. Set up a URL for a webhook on your web server. For testing purposes we recommend creating a free webhook on https://webhook.site as this will allow you to inspect the data Riddle sends to the webhook.
    set up test webhook
  3. In Riddle, go to PUBLISH and click on Save and connect data.
    save and connect data
  4. Under Add integrations, find Webhook, and click on ADD.
    add webhook integration
  5. Enter the URL of your webhook endpoint into the Webhook URL field and click on CONTINUE.
    enter webhook url
  6. A test lead will be sent automatically but you can retest by clicking on SEND.
    test lead for webhook
  7. Click on CONTINUE. The test lead will appear on your webhook site.
    test lead on webhook site
  8. Play your published Riddle. You will see all the Riddle events on your test webhook and, when then in use, on your server. Here is the payload using our example Riddle:
    {
      "uniqueId": "613361996f3862696d2b60506e756144689e6ebf6a5c666f6127bf8b4f5e9d0ae4",
      "riddleId": "4kTPnvQ3",
      "confirmed": true,
      "identifier": "charlotte@riddle.com",
      "version": 3,
      "createdAt": "2024-04-25 08:54:43",
      "data": {
        "riddle": [
          {
            "title": "What do you enjoy most?",
            "blockId": 3,
            "value": [
              "Type the sport you enjoy most."
            ]
          },
          {
            "title": "What was the last event you went to as a spectator?",
            "blockId": 7,
            "value": [
              "A running event"
            ]
          },
          {
            "title": "What was the last event you participated in?",
            "blockId": 5,
            "value": [
              "A running event"
            ]
          }
        ],
        "form": [
          {
            "title": "Name",
            "blockId": 6,
            "fieldId": 0,
            "value": "Charlotte"
          },
          {
            "title": "Email",
            "blockId": 6,
            "fieldId": 1,
            "value": "charlotte@riddle.com"
          },
          {
            "title": "Checkbox",
            "blockId": 6,
            "fieldId": 2,
            "value": true
          }
        ],
        "time": 36696,
        "result": {
          "score": 0,
          "maxScore": 0,
          "blockId": 1,
          "title": "Thanks for sharing."
        }
      }
    }
    
  9. When you add a webhook, you automatically get a signature key. This key is then used when a webhook comes in. In Riddle.com's backend, a hash with the response content and the signature key are created. The point of this is that the same happens in the webhook code, i.e. you hash the received content with your own signature key. If the hashes match then it comes from Riddle.com.

Process the webhook

Please note that the code below is very specific to a Riddle with one question and one form field. You need to adjust your code to capture the data from your Riddle. By using https://webhook.site you will get a good overview of all the data your Riddle sends to the webhook.

::riddle-code-example

#php
```php
<?php

// read the raw payload from the request
$rawPayload = file_get_contents('php://input');

if (!$rawPayload) {
    http_response_code(400);
    die('No payload received');
}

file_put_contents(__DIR__.'/payload.json', $rawPayload); // optional: save the payload to a file for debugging

// now, let's decode the payload
$payload = json_decode($rawPayload, true);

// ======
// == Extract data points from the payload

// basic information about the lead itself
$uniqueId = $payload['uniqueId'];
$riddleId = $payload['riddleId'];
$identifier = $payload['identifier'];
$version = $payload['version'];
$createdAt = $payload['createdAt'];

// information about the Riddle
$riddleTitle = $payload['data']['riddle'][0]['title'];
$riddleBlockId = $payload['data']['riddle'][0]['blockId'];
$riddleValue = $payload['data']['riddle'][0]['value'][0];

// information about the form; in our case we only have *ONE* form field.
$formTitle = $payload['data']['form'][0]['title'];
$formBlockId = $payload['data']['form'][0]['blockId'];
$formFieldId = $payload['data']['form'][0]['fieldId'];
$formValue = $payload['data']['form'][0]['value'];

// information about the result
$resultBlockId = $payload['data']['result']['blockId'];
$resultTitle = $payload['data']['result']['title'];
$resultScore = $payload['data']['result']['score'];
$resultMaxScore = $payload['data']['result']['maxScore'];

// NOW: do whatever you want with the data, for example save it to a MySQL database
$sql = "INSERT INTO [...]";
```
#js
```js
const http = require("http");

const requestListener = function (req, res) {
  const methodType = req.method.toUpperCase();

  if (methodType == "POST") {
    getRequestBodyAndGenerateResponse(req, res, postMethodHandler);
  }

  res.writeHead(200);
  res.end();
};

const getRequestBodyAndGenerateResponse = (req, res, callback) => {
  let body = "";
  req.on("data", (chunk) => {
    body += chunk.toString();
  });
  req.on("end", () => {
    callback(res, JSON.parse(body));
  });
};

const postMethodHandler = (res, body) => {
  try {
    const reqBody = body;
    console.log("reqBody: ", reqBody);
    parseRiddleWebhookData(reqBody);
    res.writeHead(200);
    res.end();
  } catch (err) {
    console.error(err);
    res.writeHead(400);
    res.end();
  }
};

const parseRiddleWebhookData = (riddleResponse) => {
  const uniqueId = riddleResponse.uniqueId;
  const riddleId = riddleResponse.riddleId;
  const confirmed = riddleResponse.confirmed;
  const identifier = riddleResponse.identifier; // can be null
  const version = riddleResponse.version;
  const createdAt = riddleResponse.createdAt;

  console.log("uniqueId: ", uniqueId);
  console.log("riddleId: ", riddleId);
  console.log("confirmed: ", confirmed);
  console.log("identifier: ", identifier);
  console.log("version: ", version);
  console.log("createdAt: ", createdAt);

  const data = riddleResponse.data; // array with question & answer data
  processRiddleBlockData(data.riddle);

  const form = data.form; // array with form data. can be undefined
  processFormData(form);

  const result = data.result; // object with result data
  processResultData(result);
};

function processResultData(result) {
  console.log("processResultData");

  const title = result.title; // string with title
  const blockId = result.blockId; // number with block id

  console.log("title: ", title);
  console.log("blockId: ", blockId);
}

function processFormData(form) {
  console.log("processFormData");

  if (form) {
    form.forEach((formEntry) => {
      const title = formEntry.title; // string with title
      const blockId = formEntry.blockId; // number with block id
      const answer = formEntry.value;

      console.log("title: ", title);
      console.log("blockId: ", blockId);

      if (isNaN(answer)) {
        // answer is a string
        const answerText = answer;

        // do something with answerText
        console.log("answerText: ", answerText);
      } else {
        // answer is a number
        const answerNumber = answer;

        // do something with answerNumber
        console.log("answerNumber: ", answerNumber);
      }
    });
  }
}

function processRiddleBlockData(riddle) {
  console.log("processRiddleBlockData: ", riddle);

  riddle.forEach((block) => {
    const title = block.title; // string with title
    const blockId = block.blockId; // number with block id
    const value = block.value; // array with answer data

    console.log("title: ", title);
    console.log("blockId: ", blockId);

    value.forEach((answer) => {
      if (isNaN(answer)) {
        // answer is a string
        const answerText = answer;

        // do something with answerText
        console.log("answerText: ", answerText);
      } else {
        // answer is a number
        const answerNumber = answer;

        // do something with answerNumber
        console.log("answerNumber: ", answerNumber);
      }
    });
  });
}

const host = "localhost";
const port = 8000;

const server = http.createServer(requestListener);
server.listen(port, host, () => {
  console.log(`Server is running on http://${host}:${port}`);
});

```
::