Access Kidozen API Tools with Titanium

Hector Suárez | May 12, 2015 | Mobile App Development

This blog post will teach you how to access Kidozen API Tools with Titanium and connect to Kidozen mBaaS via oAuth in order to utilize all the tools Kidozen has to offer. If you’re new to mBaaS/Kidozen, we also suggest you check out Kidozen—Mobile Backend as a Service (mBaaS).

We pride ourselves on our Appcelerator expertise. Be aware, this is the first-ever solution built for integrating Kidozen with Titanium. If after reading this you’re still having trouble getting Kidozen to work with Titanium, please give Propelics a call.

Why use Kidozen mBaaS ?

Naturally, many mobile strategy issues involve backend technologies. Generally speaking, clients who already possess a well-developed (Web Services) backend would prefer to leverage their existing structure, and here’s where an Enterprise mBaaS like Kidozen comes in handy. With just a couple mouse-clicks, existing API’s may be integrated and functions like security via Active Directory, SMS, and email (plus many more) can be easily added to the mix.

Connecting Kidozen to Titanium

For this “How-to” we will use the sample Tasks app featured on the Kidozen dashboard. To connect to Kidozen Apps you must use either the Kidozen SDK or access via oAuth Login. Since Titanium lacks an SDK, we will access via oAuth. To achieve this we need the oAuth URL from Kidozen to display the Login screen. When the user Logs-In we will then retrieve the session and refresh tokens. Lets code!

1. Initial Setup

In order to utilize Kidozen APIs, we begin by retrieving authorization credentials. First, you’ll need to create a new Titanium Alloy project from scratch, so open CLI, create a project, and name it “kidozenTasks”.

  • Create Project

ti create --name=kidozenTasks --id=com.propelics.kidozenTasks

  • Select “app” as project-type


What type of project would you like to create?
1) app
2) module
Select a type by number or name [app]: 1

  • Select your target platform

Target platform (all|iphone|ipad|mobileweb|android|blackberry) [all]: iphone

  • Add Alloy framework components


cd kidozenTasks
allow new

2. GET App Config from Kidozen

To retrieve the login URL we first need a configuration object Kidozen sends to you when you query a GET to your public API app URL, like so: “https://[companyname].kidocloud.com/publicapi/apps?name=[AppName]”.

  • In your project, remove all code from the index.js file and type the following to retrieve the Config from Kidozen


var kidozenConfig = {};

function init() {

var xhr = Ti.Network.createHTTPClient();
var url = "https://[companyname].kidocloud.com/publicapi/apps?name=tasks";
xhr.open("GET", url);

xhr.onload = function(){
var data = JSON.parse(this.responseText);
kidozenConfig = data[0];
}

xhr.send();
}

init();
$.index.open();


* You will also need to remove this element from index.xml
<Label id="label" onClick="doClick">Hello, World</Label>

3. Setting the Login URL to a Web View

The kidozenConfig variable contains the Tasks App configuration in JSON; the login URL is stored in: kidozenConfig.authConfig.signInURL.

  • Add WebView control to index controller

index.xml

<Alloy>
<Window class="container">
<WebView id="logInWebView" />
</Window>
</Alloy>

index.tss

".container": {
backgroundColor:"white"
},

"#logInWebView" : {
height : Ti.UI.FILL,
width : Ti.UI.FILL
}

index.js

xhr.onload = function(){
var data = JSON.parse(this.responseText);
kidozenConfig = data[0];
$.logInWebView.url = kidozenConfig.authConfig.signInUrl;
}

Now we have a running App that displays the Login. If you haven’t already configured security settings on the Kidozen App management screen, it should look something like this:

screenshot

4. Retrieving the access token from the document title

When you (or a user) logs into the app, the Login screen will indicate a successful login. Kidozen then places a payload in the document title. We will use this payload value and decode this string to achieve access and refresh tokens.

index.js

var kidozenUser = {};

$.logInWebView.addEventListener(‘load’, function(){
var payload = $.logInWebView.evalJS(‘document.title’);

if(payload.indexOf(‘payload’) > 0){
payload = JSON.parse(Ti.Utils.base64decode(payload.substring(16)));
kidozenUser.access_token = payload.access_token;
kidozenUser.refresh_token = payload.refresh_token;

}
});

Now you have the access_token and refresh_token needed to call the Kidozen REST API (complete documentation can be found here: Kidozen-Rest API). For this example we will first tackle some common tasks, like storing and retrieving data from the cloud, followed by a lesson on sending SMS messages from Kidozen.

Storing data on Kidozen

Let’s store a simple object with a task-description and status along with device date & time to indicate when the task was completed. According to Kidozen’s documentation we will use the POST method and the name “task” as our object-set. There’s no need to go to Kidozen to add this object. It will receive the data object from our App. If the object doesn’t exist it will create a “table” with the object-set name we assigned it.

function addTask(text){
var d = new Date();
var month = d.getMonth() + 1;
var kidozenTask = {
description : text,
dateTime : month + '-' + d.getDate() + '-' + d.getFullYear() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
}

var xhr = Ti.Network.createHTTPClient();
var url = kidozenConfig.url + 'storage/local/task';
xhr.open("POST", url);
xhr.setRequestHeader('Content-Type', "application/json");
xhr.setRequestHeader('Authorization', kidozenUser.access_token);
xhr.onload = function(){
var response = JSON.parse(this.responseText);
alert(" Task Added !!!");
}
xhr.onerror = function(e){
console.log(JSON.stringify(e));
alert(e.error);
}

xhr.send(JSON.stringify(kidozenTask));

}

Retrieving data from Kidozen

Now that we have stored tasks in our data object in Kidozen, it’s time to retrieve the data so we can have a list of all tasks we submit. We will use the GET method to retrieve the tasks and display them in a TableView.

function getTasks(){
var xhr = Ti.Network.createHTTPClient();
var url = kidozenConfig.url + 'storage/local/task';
xhr.open("GET", url);
xhr.setRequestHeader('Content-Type', "application/json");
xhr.setRequestHeader('Authorization', kidozenUser.access_token);

xhr.onload = function(){
var data = JSON.parse(this.responseText);
console.log(data);

var tableRows = [];

_.each(data, function(task){
var row = Alloy.createController('taskRow', task).getView();
tableRows.push(row);
});

$.taskListTable.data = tableRows;
}

xhr.onerror = function(e){
console.error(JSON.stringify(e));
alert(e.error);
}

xhr.send();
}

Sending SMS from Kidozen
Many additional functions are available within the Rest API, such as Logging, sending eMails, notifications and more. Now let’s discuss how to use the Kidozen platform to send SMS. In the App we are building there is an option to send tasks to a phone number whenever they are submitted from the server, like so:


function sendSMS(text, phoneNumber){
var xhr = Ti.Network.createHTTPClient();
var url = kidozenConfig.url + 'sms?to=' + phoneNumber + '&message=' + Ti.Network.encodeURIComponent(text);
xhr.open("POST", url);
xhr.setRequestHeader('Content-Type', "application/json");
xhr.setRequestHeader('Authorization', kidozenUser.access_token);

xhr.onload = function(){
resumeSubmit();
var response = JSON.parse(this.responseText);
alert(" Task Added & SMS Sent !!!");
$.taskText.value = '';
}

xhr.onerror = function(e){
resumeSubmit();
console.log(JSON.stringify(e));
alert(" Task Added\n Error sending SMS\n" + e.error);
}

xhr.send();
}

We hope you enjoyed—and can benefit from—this first-ever solution for getting Kidozen to work with Titanium by way of oAuth. While this sample app example will work for some applications, if you’re looking for a more complex solution that involves connecting Kidozen with Appcelerator, please check out our Kickstarter offerings and give us a call. Propelics drives real business results with Mobile Strategies and premier Apps for Enterprise clients worldwide.

Hector Suárez

Hector Suárez is a Developer with Propelics where he helps many Fortune 500 companies determine the direction of their mobile apps. He is Titanium-certified with a focus on B2B solutions. Hector has cofounded two technology startups, TreStudios and Monch, acting as CEO, client-ambassador and lead-developer. He developed POS admin software for Industrial Zapatera JR, built Cobol-based money transfer-modules for Banco de Mexico (Banamex), developed a Windows home-sales app for PLASGO, created 2000 Gas, Mexico’s first natural gas-ordering app, and developed C# Windows and Mobile apps for Eva Green SA de CV.

More Posts

Follow Me:
LinkedIn