How we integrated an external service to RTW using Webhooks and PhP

11. februar 2019

How we integrated an external service to RTW using Webhooks and PhP.

In this tutorial I will show how we got data from The Things Network(ttn) in to the RTW network. This is not a hard process since ttn gives us a good toolset that makes it easy for us to integrate their service. The tool we choose to do this in our case was webhooks.

The first step to be able to do this is to set up how our payload should look like when it comes from ttn. This is done by adding a little script inside the ttn console. This is the way we did it:

get to know how the data which ttn sends looks like. This is probably available through ttns documentation but I like to use the service webhook.site to get a quick overview of how the data is structured. The way to do that is to post the link you get when you visit webhhok.site in to the http endpoint field in the ttn console like this:.

Here you see that we get all the data exposed:

We dont need all of these but we are going to use theese fields:

app_id

hardware_serial

payload_fields

payload

time

Now that we have that sorted we can start to make the php-file which the webhook Is going to post to.

The first part of the file is getting out all the information from the request as shown here:

<?php
//Getting the data that is posted to the site
$data = file_get_contents('php://input');
//Decoding the data so that it is accessible as json object.
$data = json_decode($data, true);
//Getting the app_id
$app_id = $data["app_id"];
//Getting the hardware_serial
$hardware_serial = $data["hardware_serial"];
//Getting the fields of payload_fields
$payload_fields = $data["payload_fields"];
//Getting payload from payload_fields
$payload = $payload_fields["payload"];
//Getting the fields of metadata
$metadata = $data["metadata"];
//Getting time from metadata
$time = $metadata["time"];

The next and final step is to send the data to the RTW-network this is done easily by php’s curl commands as shown below: