Implement Trak.io in php using cURL

Trak.io is a customer analytics for SaaS Companies. Few weeks ago I have to implement that in our SaaS project. While implementing it's API, we found that they did not provide any official php library. I can use javascript, but it won't fulfill our requirement.
Then I make a simple library using PHP-CURL. It's very easy to implement using basic curl action. So you can implement it in any framework.

We'll use Trak.io's http api to build our libray. We will use 3 endpoint, which are,

Let's create the library using these endpoints.
First create a class called Trak and insert these lines of codes. I will explain them part by part.

<?php  
/**
* @name Trak
* @author Ashraful Islam Nixon<[email protected]>
*
* This class will deal with Trak.io
*/

class Trak {

    //insert API token for your trak.Io here
    private $trakToken;


    /**
     * constructor
     */
    public function __construct ($token)
    {
    //set the API token at the beginning
    $this->trakToken = $token;
    }

    /**
     * @name identify
     * @param type $id
     * @param string $name
     * @param string $email
     * @return json
     */
    public function identify($id, $name, $email)
    {
    //prepare the json data for identify users to trak.io
    $data = array(
        'token' => $this->trakToken,
        'data' => array(
            "distinct_id" => $id,
            "properties" => array(
                        "name" => $name,
                        "email" => $email,
                          )
               )
    );

    $data_string = json_encode($data);                                                                                   

    //create a new cURL resource using trak.io identify url
    $ch = curl_init('https://api.trak.io/v1/identify');   
    //create a custome POST request
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");   
    //insert the json post data here
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);  
    //return the transfer as a string of the return value of curl_exec()
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //set the content type as json and
    //content length
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($data_string))                                                                       
    );                                                                                                                   

    //execute curl 
    $result = curl_exec($ch);

    //return the output 
    return $result;
    }

    /**
     * @name trakUser
     * @param type $event
     * @param type $page
     * @return json
     */
    public function trakUser($uniqueId, $event, $page)
    {
    //prepare the json data for identify users to trak.io
    $data = array(
        'token' => $this->trakToken,
        'data' => array(
            "distinct_id" => $uniqueId,
            "event" => $event,
            "channel" => $page,
            "properties" => array(
                    'title' => $event,
                    ),
               )
    );

    $data_string = json_encode($data);                                                                                   

    //create a new cURL resource using trak.io track url
    $ch = curl_init('https://api.trak.io/v1/track'); 
    //create a custome POST request
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
    //insert the json post data here
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
    //return the transfer as a string of the return value of curl_exec()
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    //set the content type as json and
    //content length
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($data_string))                                                                       
    );                                                                                                                   

    //execute curl 
    $result = curl_exec($ch);

    //return the output 
    return $result;
    }


    /**
     * @name createAlias
     * @param type $newId
     * @param type $existingId
     * @return json
     */
    public function createAlias($newId, $existingId)
    {
    //prepare the json data for identify users to trak.io
    $data = array(
        'token' => $this->trakToken,
        'data' => array(
                "distinct_id" => $existingId,
                "alias" => $newId

        )); 

    $data_string = json_encode($data);                                                                                   

    //create a new cURL resource using trak.io alias url
    $ch = curl_init('https://api.trak.io/v1/alias');
    //create a custome POST request
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
    //insert the json post data here
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
    //return the transfer as a string of the return value of curl_exec()
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    //set the content type as json and
    //content length
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($data_string))                                                                       
    );                                                                                                                   

    //execute curl 
    $result = curl_exec($ch);

    //return the output 
    return $result;
    }

}

Let's break the code.

At the beginning:

class Trak {

    //insert API token for your trak.Io here
    private $trakToken;


    /**
     * constructor
     */
    public function __construct ($token)
    {
    //set the API token at the beginning
    $this->trakToken = $token;
    }

At first we define we create our class Trak. Then we declare our $trakToken as private.
In our constructor method we initialized our Trak class to load the class with API token. Then we set that API token to our private trakToken.

Indentify the User:

    /**
     * @name identify
     * @param type $id
     * @param string $name
     * @param string $email
     * @return json
     */
    public function identify($id, $name, $email)
    {
    //prepare the json data for identify users to trak.io
    $data = array(
        'token' => $this->trakToken,
        'data' => array(
            "distinct_id" => $id,
            "properties" => array(
                        "name" => $name,
                        "email" => $email,
                          )
               )
    );

    $data_string = json_encode($data);                                                                                   

    //create a new cURL resource using trak.io identify url
    $ch = curl_init('https://api.trak.io/v1/identify');   
    //create a custome POST request
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");   
    //insert the json post data here
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);  
    //return the transfer as a string of the return value of curl_exec()
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //set the content type as json and
    //content length
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($data_string))                                                                       
    );                                                                                                                   

    //execute curl 
    $result = curl_exec($ch);

    //return the output 
    return $result;
    }

Before start tracking data for a user we have to identify the user to trak.io first. To fullfill this we use the class identify.
To identify a user we need an unique id, name(optional), email(optional) for that user. That's why we set $id,$name and $email as the parameter for this method.
Trak.io receives json format data over http request. That's why we prepare our data in json formate. Then we create a new cURL resource using the identify url. After that we set the data, request type, content type, length for the cURL method.
Afther execution we return the return value.

Track a user:

    /**
     * @name trakUser
     * @param type $uniqueId
     * @param string $event
     * @param string $page
     * @return json
     */
    public function trakUser($uniqueId, $event, $page)
    {
    //prepare the json data for identify users to trak.io
    $data = array(
        'token' => $this->trakToken,
        'data' => array(
            "distinct_id" => $uniqueId,
            "event" => $event,
            "channel" => $page,
            "properties" => array(
                    'title' => $event,
                    ),
               )
    );

    $data_string = json_encode($data);                                                                                   

    //create a new cURL resource using trak.io track url
    $ch = curl_init('https://api.trak.io/v1/track'); 
    //create a custome POST request
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
    //insert the json post data here
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
    //return the transfer as a string of the return value of curl_exec()
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    //set the content type as json and
    //content length
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($data_string))                                                                       
    );                                                                                                                   

    //execute curl 
    $result = curl_exec($ch);

    //return the output 
    return $result;
    }

Using this portion we will track a user activity. Most of the part is same as before. The changed parts is how to track a user.
In last method identify we used an unique id for each user. So to track down an user we will use that id. We have set three parameter for trakUser method, $uniqueId, $event and $page(optional). $event will be the event we want to track for the user. $page will be used as channel for the event we can send the url for which the event is occuring. In properties section we can add as many data as we need. It's totally optional.

Merge two users into one

    /**
     * @name createAlias
     * @param type $newId
     * @param type $existingId
     * @return json
     */
    public function createAlias($newId, $existingId)
    {
    //prepare the json data for identify users to trak.io
    $data = array(
        'token' => $this->trakToken,
        'data' => array(
                "distinct_id" => $existingId,
                "alias" => $newId

        )); 

    $data_string = json_encode($data);                                                                                   

    //create a new cURL resource using trak.io alias url
    $ch = curl_init('https://api.trak.io/v1/alias');
    //create a custome POST request
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
    //insert the json post data here
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
    //return the transfer as a string of the return value of curl_exec()
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    //set the content type as json and
    //content length
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($data_string))                                                                       
    );                                                                                                                   

    //execute curl 
    $result = curl_exec($ch);

    //return the output 
    return $result;
    }

If you want to merge two user into one then you have to use this method. To merge two users we need unique id of two users. That's why we have set two parameter as $newId, $existingId. Now rest of the code is almost same as before. In $data we set one id for primary using distinct_id as array index and another id for alias using alias as array index.

How to Use:

To use this class we need to include this class in our php script and simply use the class.

<?php  
//load the class
require_once('class.trak.html');

---
---
//set the api token
$apiToken = 'YOUR API TOKEN';

//load the class
$trakData = new Trak($apiToken);

########## identify the user - starts from here ##########
$uniqueId = 'your unique id for the user';
$name = 'name of the user';
$email = 'email of the user';

//identify the user to trakIo
//note: you have to use this once per user
$result = $trakData->identify($uniqueId, $name, $email);
########## identify the user - ends here ##########


########## track a user - starts from here ##########
$uniqueId = 'unique id for current user';
$event = 'logged in';
$page = 'https://www.test.com/login';

//trak current user's activity
$result = $trakData->trakUser($uniqueId, $event, $page);
########## track a user - ends here ##########

########## merge two user - starts from here ##########
$newId = 'the id of the user, we want to merge';
$existingId = 'the id of the main user';

//trak current user's activity
$result = $trakData->createAlias($newId, $existingId);
########## merge two user - ends here ##########

By using these codes we can easily implement trak.io in php. If you want the source code of the trak.io cURL class, you can check here.

comments powered by Disqus