Libring Usage API

 

Libring Usage API allows you to track and monitor realtime usage or events generated by users in your application (session start/end, in-app purchases, button clicks…).

Request

https://api.libring.com/v1/events/new

Method

POST

Required Authorization

NameExample
token‘Authorization’=>”Token TOKEN_CODE”

Required Parameters

ParameterTypeDescriptionExample
Unique IdentifierStringAny unique id from your database to identify individual contacts: Unique numbers (PK), Contact Id’s, emails, etc.“VqQGAfdeTNAKYgwOFiaoqGk”
App NameStringName of the app“My Game 1”
PlatformStringPredefined platforms: iOS, Android, Facebook, Windows Phone, Windows, Linux, Mac OSX, Black Berry, Others“Mac OSX”
Event TimestampDateTimeTime the event occurred.“2014-04-21 09:57:40 -0400”
Event TypeStringPredefined types: level start, level end, init session, end session, inapp purchase, ad impression, ad click, ad completion, ad request or custom“ad click”

Optional Parameters

ParameterTypeDescriptionExample
AmountDecimalIf the event generated some earning, enter the amount.100.45
Ad TypeStringif this event was generated from advertising, enter the type of the ad.“Banner”
Ad FormatStringIf this event was generated from advertising, enter the format of the ad.“900x70”
Ad NetworkStringIf this event was generated from advertising, enter the network.“AdMob”
User IPStringInformation about contact’s IP address.“127.0.0.1”
User DeviceStringInformation about contact’s device.“iPhone 6”
User NameStringInformation about contact’s name.“John Maclane”
User EmailStringInformation about contact’s email.“my@email.com”
User CountryStringInformation about contact’s country.“USA”
Metadata**
(Event’s or contact’s additional information)
HashAdditional information about the event. Ex: item purchased, operacional system used, etc. Use JSON: { “name”: “value”, “name”: “value”, … }{ “items”: “Coin 100, Coin 200”, “card”: “VISA” }

**Metadata is a field to add extra information associated to the events. Your metadata can have any information specific to your business – ‘Photo filetype’ makes sense for Instagram, but it likely doesn’t apply to your events. You might have metadata like ‘visits_per_month’ or ‘phase’… A variety of metadata means more description for you events, which allows for deeper analysis with Libring.

 

Strategies

Thinking about strategies, there are two ways to use Libring Usage API:

1. Make one call per action

You can call our API every time your user executes an action. For example:

  • one call when the user starts a session;
  • one call when the user views an ads;
  • one call when the user starts a new level in your game;
  • one call when the user finishes this level;
  • one call when the user ends a session.

5 calls to our API, no problem. Just be sure that it will not decrease the performance of your app.

Or…

2. Make just one call per session

You can store all your user’s actions inside your app (local variables) and when the user ends a session (close the app, put it in background or logout), you can send all actions with just one call.

That means there are 5 actions in just one call with 5.

JSON Structure Example

{
  "libring": {
    "VqQGAfdeTNAKYgwOFiaoqGkgCrrI": {
      "app_name": "My Game 1",
      "contact" : {
        "name": "John Maclane",
        "email": "john@email.com",
        "country": "France",
        "metadata": {
          "ip": "204.194.200.10",
          "device": "iPhone 6s"
        }
      },

      "events": {

        "2014-04-21 09:57:40 -0400": [ {
          "type": "init session",
          "platform": "iOS"
          },
          {
            "type": "ad impression",
            "ad_type": "banner",
            "ad_format": "100x100",
            "ad_network": "AdMob",
            "platform": "iOS",
            "metadata": {
              "place": "game view 1",
              "times_tried": "2"
            }
        } ],

        "2014-04-21 10:00:20 -0400": [ {
          "type": "level start",
          "platform": "iOS"
        } ],

        "2014-04-21 10:03:20 -0400": [ {
          "type": "inapp purchase",
          "amount": 0.05,
          "platform": "iOS"
        } ],

        "2014-04-23": [ {
          "type": "end session",
          "platform": "iOS"
        } ]
      }
    }
  }
}

Response

HTTP Status
200 OKPositive response, all fine
400 Bad RequestIf required parameter (did) is not passed
401 UnauthorizedWhen an api_token fails to pass or the wrong api_token does pass

Examples

require “net/https”
require “uri”

uri = URI.parse(“https://api.libring.com/v1/events/new”)

https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true

req = Net::HTTP::Post.new(uri.request_uri, initheader = {‘Content-Type’ =>’application/json’, ‘Authorization’ => ‘Token 1043tL2eZvKYlo2CSU3Tbnci’, ‘HTTP_ORIGIN’ => request.headers[“SERVER_NAME”]})

req.set_form_data({ libring: { “contact_1” => { “app_name” => “My Game 1”, “contact” => { “name” => “John”, “age” => “31”, “country” => “Brazil” }, “events” => { “2015-05-18 09:57:40 -0400” => [{ “type” => “ad impression”, “ad_type” => “banner”, “platform” => “iOS”, “ad_format” => “100×100”, “ad_network” => “AdMob”, “metadata” => {“device” => “iPhone 6”, “level” => “1”} }] } } }.to_json })

resp = https.request(req)

$access_token = “VqQGAfdeTNAKYgwOFiaoqGkgCrrI”;

$json_data = ‘{ “contact_1”: { “app_name”: “My Game 1”, “contact”: { “name”:”John”, “age”: “31”, “country”: “Brazil” }, “events”: { “2015-05-18 09:57:40 -0400”: [{ “type”: “ad impression”, “ad_type”: “banner”, “platform”: “iOS”, “ad_format”: “100×100″,”ad_network”: “AdMob”, “metadata”:{“device”:”iPhone 6″, “level”:”1″} }] } } }’;

$headers = array(‘Authorization: Token ‘ . $access_token);

$ch_subs = curl_init();
curl_setopt($ch_subs, CURLOPT_URL, ‘https://api.libring.com/v1/events/new’);
curl_setopt($ch_subs, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_subs, CURLOPT_SSL_VERIFYPEER, true);

curl_setopt($ch_subs, CURLOPT_POST, 1);
curl_setopt($ch_subs, CURLOPT_POSTFIELDS, ‘libring= ‘ . $json_data);

curl_setopt($ch_subs, CURLOPT_HTTPHEADER, $headers);

echo curl_exec($ch_subs);

curl_close($ch_subs);

string token = “eFvAQALQpFeaedstLnuh3xZBL”;
string json = “{ \”libring\”: { \”contact_1\”:{\”app_name\”:\”My Game 1\”,\”contact\”:{\”name\”:\”John\”,\”age\”:\”31\”,\”country\”:\”USA\”},\”events\”:{\”2015-05-18 09:57:40 -0400\”:[{\”type\”:\”ad impression\”,\”ad_type\”:\”banner\”,\”platform\”:\”iOS\”,\”ad_format\”:\”100×100\”,\”ad_network\”:\”AdMob\”,\”metadata\”:{\”device\”:\”iPhone 6\”,\”level\”:\”1\”}}]}}} }”;

byte[] data = Encoding.ASCII.GetBytes(json.ToCharArray());

var form = new WWWForm();
var headers = form.headers;

headers[“Authorization”] = “Token ” + token;
headers[“Content-Type”] = “application/json”;

WWW www = new WWW(“https://api.libring.com/v1/events/new”, data, headers);

yield return www;

if(www.error != null) {
Debug.Log(“Error: ” + www.error + ” : ” + www.text);
}
else {
Debug.Log(“Success!”);
}

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Globalization;

public class Libring : MonoBehaviour {

//set API token in runtime
public static void Init(string tokenAPI, string appName, string appVersion) {

m_tokenAPI = tokenAPI;
m_appName = appName;
m_appVersion = appVersion;
}

//log in-app purchase events, with optional custom parameters
public static bool LogIAP(string productId, string amount = null, string currency = null) {

return LogEvent(“inapp purchase”, new Dictionary<string, string=””> {
{ “product”, productId },
{ “amount”, amount != null ? amount : “” },
{ “currency”, currency != null ? currency : “” },
});
}

//log in-app purchase events, with optional custom parameters
public static bool LogLevelStart(string gameMode = null, string levelNumber = null, string playerData = null) {

return LogEvent(“custom”, new Dictionary<string, string=””> {
{ “action”, “level start” },
{ “game_mode”, gameMode != null ? gameMode : “” },
{ “level_num”, levelNumber != null ? levelNumber : “” },
{ “player_data”, playerData != null ? playerData : “” },
});
}

//log in-app purchase events, with optional custom parameters
public static bool LogLevelEnd(string gameMode = null, string levelNumber = null, string playerData = null) {

return LogEvent(“custom”, new Dictionary<string, string=””> {
{ “action”, “level end” },
{ “game_mode”, gameMode != null ? gameMode : “” },
{ “level_num”, levelNumber != null ? levelNumber : “” },
{ “player_data”, playerData != null ? playerData : “” },
});
}

#region INTERNAL METHODS AND DATA

const string m_libringURL = “https://api.libring.com/v1/events/new”;

const int m_maxBufferedEvents = 10;

static string m_tokenAPI = null;
static string m_appName = null;
static string m_appVersion = null;

static Libring m_instance = null;

static bool m_getConf = true;
static bool m_logInit = true;
static bool m_logEnd = true;

static string m_deviceUID;
static string m_deviceModel;
static string m_platform;

static List m_eventsData = new List();

//log generic events, with optional custom parameters
static bool LogEvent(string eventId, Dictionary<string, string=””> metadata = null) {

if ((!string.IsNullOrEmpty(m_tokenAPI)) &&
(!string.IsNullOrEmpty(m_appName)) &&
(!string.IsNullOrEmpty(m_appVersion))) {

if (m_getConf) {

m_getConf = false;

m_deviceUID = g_Misc.MyGetDeviceUniqueIdentifier();

m_deviceModel = SystemInfo.deviceModel;

#if UNITY_ANDROID
m_platform = “Android”;
#elif UNITY_IPHONE
m_platform = “iOS”;
#else
m_platform = “Other”;
#endif
}

System.DateTime d = System.DateTime.Now;

System.TimeSpan ts = System.TimeZone.CurrentTimeZone.GetUtcOffset(d);

string dateTime = d.Year.ToString(“D4”) + “-” + d.Month.ToString(“D2”) + “-” + d.Day.ToString(“D2″) + ” ” +
d.Hour.ToString(“D2”) + “:” + d.Minute.ToString(“D2”) + “:” + d.Second.ToString(“D2″) + ” ” +
ts.Hours.ToString(“D2”) + ts.Minutes.ToString(“D2”);

string custom = “”;

if (metadata != null) {

foreach(KeyValuePair<string, string=””> m in metadata)
custom += “,\””+cleanForJSON(m.Key)+”\”:\””+cleanForJSON(m.Value)+”\””;
}

string data =
“{\”libring\”:{\”” + cleanForJSON(m_deviceUID) +
“\”:{\”app_name\”:\”” + cleanForJSON(m_appName) +
“\”,\”app_version\”:\”” + cleanForJSON(m_appVersion) +
“\”,\”device_uid\”:\”” + cleanForJSON(m_deviceUID) +
“\”,\”events\”:{\”” + dateTime +
“\”:[{\”type\”:\”” + cleanForJSON(eventId) +
“\”,\”platform\”:\”” + m_platform +
#if UNITY_EDITOR
“\”,\”dev_mode\”:\”1″ +
#endif
“\”,\”metadata\”:{\”device\”:\”” + cleanForJSON(m_deviceModel) +
“\””+custom+”}}]}}}}”;

lock(m_eventsData) {

while(m_eventsData.Count > m_maxBufferedEvents)
m_eventsData.RemoveAt(0);

m_eventsData.Add(data);
}

return true;
}
else {

Debug.LogError(“Libring not initialized!”);
return false;
}
}

void Start() {

if (m_logInit)
m_logInit = !LogEvent(“init session”);
}

void OnApplicationQuit() {

if (m_logEnd)
m_logEnd = !LogEvent(“end session”);
}

bool m_sendingRequest = false;

void Update() {

if (!m_sendingRequest) {

lock(m_eventsData) {

if (m_eventsData.Count > 0) {

#if UNITY_EDITOR
Debug.Log(m_eventsData[0]);
#endif

StartCoroutine( DoRequest(m_eventsData[0]) );

m_eventsData.RemoveAt(0);
}
}
}
}

IEnumerator DoRequest(string data) {

m_sendingRequest = true;

byte[] outData = Encoding.ASCII.GetBytes(data.ToCharArray());

var form = new WWWForm();
var headers = form.headers;

headers[“Authorization”] = “Token ” + m_tokenAPI;
headers[“Content-Type” ] = “application/json”;

WWW request = new WWW(m_libringURL, outData, headers);

yield return request;

if (!string.IsNullOrEmpty(request.error))
Debug.LogError(“Libring Error: ” + request.error);

m_sendingRequest = false;
}

static string cleanForJSON(string s) {

if (s == null || s.Length == 0)
return “”;

int len = s.Length;

StringBuilder sb = new StringBuilder(len + 4);

for (int i = 0; i < len; i += 1) {

char c = s[i];

switch(c) {

case ‘\\’:
case ‘”‘:
sb.Append(‘\\’);
sb.Append(c);
break;

case ‘/’:
sb.Append(‘\\’);
sb.Append(c);
break;

case ‘\b’:
sb.Append(“\\b”);
break;

case ‘\t’:
sb.Append(“\\t”);
break;

case ‘\n’:
sb.Append(“\\n”);
break;

case ‘\f’:
sb.Append(“\\f”);
break;

case ‘\r’:
sb.Append(“\\r”);
break;

default:
if (c < ‘ ‘) {

string t = “000” + string.Format(“X”, c);
sb.Append(“\\u” + t.Substring(t.Length – 4));
}
else {

sb.Append(c);
}
break;
}
}

return sb.ToString();
}

#endregion
}

Using Alamofire:
https://github.com/Alamofire/Alamofire

let parameters = [
    "libring": [
        "PLAYER11111": [
            "app_name": "My game 1",
            "contact": [
                "name": "Player John",
                "email": "john@email.com"
            ],
            "events":[
                "2015-04-27": [
                    [
                      "type": "ad impression",
                      "platform": "Android"
                    ]
                ]
            ]
        ]
    ]
]

Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": "Token eFvAQALQpFeaedstLnuh3xZBL"]

var request = Alamofire.request(.POST, "https://api.libring.com/v1/events/new", parameters: parameters, encoding: .JSON)

request.responseJSON{
    (request,response,JSON,error) in
    println("The Result: ")
    println(JSON)
    println("response status code :\(response?.statusCode)")
    println("error:\(error)")
}

Using Android Studio and Ion (Android Asynchronous Networking and Image Loading):
https://github.com/koush/ion

Imports:

import com.koushikdutta.ion.Ion;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.Future;
import com.koushikdutta.async.future.FutureCallback;

Call Code:

JsonObject json = new JsonObject();
json.addProperty("libring", "{ 'contact_1': { 'app_name': 'My Game 1', 'contact': { 'name':'John', 'age': '31', 'country': 'Brazil' }, 'events': { '2015-05-18 09:57:40 -0400': [{ 'type': 'ad impression', 'ad_type': 'banner', 'platform': 'iOS', 'ad_format': '100x100','ad_network': 'AdMob', 'metadata':{'device':'iPhone 6', 'level':'1'} }] } } }");

Ion.with(this)
        .load("https://api.libring.com/v1/events/new")
        .setHeader("Authorization", "Token eFvAQALQpFeaedstLnuh3xZBL")
        .setJsonObjectBody(json)
        .asJsonObject()
        .setCallback(new FutureCallback< JsonObject >() {
            @Override
            public void onCompleted(Exception e, JsonObject result) {
                System.out.println("Success!");
            }
        });

Insert Your Information:

×
mautic is open source marketing automation