Filter results by

Your first Web app

This sample application authenticates with ARTIK Cloud, sends data messages on behalf of a sample device, and retrieves the data messages from ARTIK Cloud.

Browse source for this tutorial.

Our first tutorial uses PHP with a little JavaScript. These should interest anyone building a Web app or any service using ARTIK Cloud.

For this tutorial, we will use ARTIK Cloud's REST APIs and authenticate via OAuth2. If you are not familiar with OAuth2, you can read more about it in Authorization. But don't worry, we'll guide you through all the steps.

We assume you know or understand the basics of PHP, HTML and JavaScript.

Prerequisites

  • PHP 5.4 or higher
  • cURL support in PHP
  • Apache Web server (or equivalent HTTP server with PHP support)

Initial setup

If this is your first time using ARTIK Cloud, you will need to create an ARTIK Cloud Account. You will also use the web tools we created to handle specific tasks:

  • For developers creating apps, services and devices using ARTIK Cloud, we created the Developer Dashboard.

  • Regular users of ARTIK Cloud (and your apps) can manage permissions, connect devices and review their data at My ARTIK Cloud.

For the sake of simplicity in this tutorial, you take the role of both the application developer and the ARTIK Cloud user. You will use the sample app to access your own device.

Create an application

Follow these instructions to create an application using the Developer Dashboard. For this tutorial, select the following:

  • Set "Redirect URL" for your application to http://localhost:8000/acdemo/index.php
  • Choose "Implicit".
  • Under "PERMISSIONS", click "Add Device Type" button. Choose "Example Activity Tracker" (Device Type ID: cloud.artik.example.activitytracker) as the device type. Check both "Read" and "Write" permissions for this device type.

Make a note of your client ID. This is your application ID, which you will need later.

Connect a device

Follow these instructions to create and connect a device with My ARTIK Cloud. For this tutorial, select the following:

  • Choose "Example Activity Tracker" (device type unique name: cloud.artik.example.activitytracker).

Now as an ARTIK Cloud user, you have a device. The sample app will access your data on this device.

Get the device ID

In My ARTIK Cloud, click the settings icon of the device you just connected. A window like the following will appear.

device info screen

Make a note of the device ID on the above screen. You will use it in the sample app.

Setup your local machine

  • Install a Web server and configure it to open port 8000 on localhost.
  • Install PHP and enable cURL in PHP.
  • If you have a Windows machine, it is very likely that you need to add a CA certificate for ARTIK Cloud and point cURL to it. Below is the example of the steps performed on Windows:
  • Create a directory acdemo that is accessible via http://localhost:8000/acdemo. For example, set up http://localhost:8000/ to access C:\MyWebsites on your Windows machine. Then create acdemo under C:\MyWebsites.

Prepare the sample application files

  • Copy all files of the sample application at GitHub into the acdemo directory created above.
  • In the following line in index.php, change client_id to your application ID (accessible in the Developer Dashboard).
1
<p>Please <a href="https://accounts.artik.cloud/authorize?response_type=token&client_id=xxxxx">login</a></p>
  • Change CLIENT_ID and DEVICE_ID to your real client and device IDs in the following lines in ArtikCloudProxy.php.
1
2
3
4
<?php
const CLIENT_ID = "xxxxx";
const DEVICE_ID = "xxxxx";  
?>

Demo

Before we dig in, here's a preview of how our simple Web app will work.

  • Load http://localhost:8000/acdemo/index.php in your browser. You will see the following page:
    ARTIK Cloud first Web app
  • Click "Login" and authenticate with the account you used so far.
  • Once you complete authentication, you will be redirected to hello.php. Now you can play with ARTIK Cloud.
  • Click "Send a message" to send a message to ARTIK Cloud on behalf of your device.
  • Click "Get a message" to get the latest message from your device on ARTIK Cloud. Note that it may take up to a few seconds for your message to appear since the called API is not intended for real-time data streaming.
  • After sending and receiving messages, your window should look like this:
    ARTIK Cloud first Web app

Implementation Details

This sample application consists of four PHP files. ArtikCloudProxy.php contains a helper class, and the other PHP files communicate to ARTIK Cloud via the helper.

Warm-up

We'll start with a basic HTML page. Our index.php initially looks like the following:

1
2
3
4
5
6
7
8
9
10
11
<html lang="en">
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.1/css/bootstrap.min.css" rel="stylesheet">
    <title>ARTIK Cloud First Web App</title>
</head>
<body>
    <h1>Hello!</h1>
    <p>Please <a href="https://accounts.artik.cloud/authorize?response_type=token&client_id=YOUR_CLIENT_ID">login</a></p>
</body>
</html>

Catch authentication callback and obtain access token

Now let's enhance index.php and add hello.php to get the ARTIK Cloud authorization token. This sample application uses the OAuth2 implicit grant flow. After a successful login, ARTIK Cloud calls back the redirect URL we set in the Developer Dashboard. The URL contains the access token, as seen in the following example:

1
http://localhost:8000/acdemo/index.php#expires_in=1209600&amp;token_type=bearer&amp;access_token=e77d0e4fc3e144429e062021f70894d3

Insert the following lines of JavaScript within the document body of index.php. After ARTIK Cloud calls back, the script replaces the # with a ? and then reloads a new page hello.php.

1
2
3
4
5
6
7
8
<script>
query = window.location.hash.split("#");
if (query[1]) { 
    // ARTIK Cloud accounts sends an URL fragment in the login callback,
    // Now make Web browser to load a new url
    window.location = "hello.php?"+query[1];
}
</script>

After loading hello.php, the following PHP code in that file obtains the access token from the query string and stores it into a session variable.

1
2
3
4
5
6
<?php
session_start();
if (isset($_REQUEST['access_token'])) {
    $_SESSION['access_token'] = $_REQUEST['access_token'];
}
?>

Call the ARTIK Cloud APIs

In hello.php, create a helper instance and set the access token to it.

1
2
3
4
5
<?php
require('ArtikCloudProxy.php');
$proxy = new ArtikCloudProxy();
$proxy->setAccessToken($_SESSION['access_token']);
?>

Please see details of ArtikCloudProxy.php at the end of the document or download from GitHub.

Send a message to ARTIK Cloud

First, we'll send a message to ARTIK Cloud on behalf of the device. The application sends a POST HTTP request to ARTIK Cloud. The URL looks like this:

1
https://api.artik.cloud/v1.1/messages/

The HTTP request needs to include the authorization header and the payload. The payload contains the device ID and data. The helper class assembles the request.

Please keep in mind that you need to include the authorization header on every request you send to ARTIK Cloud. In this tutorial app, the helper class does this for you.

Now let's enhance the code to achieve this functionality. By putting the following lines of HTML in hello.php, we will add a button on the page:

1
2
<a class="btn sendMessage">Send a message</a>
<p id="sendMessageResponse">Response will be put here....</p>

Now add the following JavaScript for the button, which sends a message and updates the page with the response from ARTIK Cloud. Particularly, the script calls post-message.php to send on background.

1
2
3
4
5
6
7
8
9
<script>
// Sends a message using PHP
$('.sendMessage').click(function(ev){
    document.getElementById("sendMessageResponse").innerHTML ="waiting for response";
    $.ajax({url:'post-message.php', success:function(result){
        document.getElementById("sendMessageResponse").innerHTML = JSON.stringify(result);
        }});
});
</script>

Here is what post-message.php looks like. It uses the helper class to construct the HTTP POST request and then sends it to ARTIK Cloud.

1
2
3
4
5
6
7
8
9
10
11
<?php
session_start();
require('ArtikCloudProxy.php');
$proxy = new ArtikCloudProxy();
$proxy->setAccessToken($_SESSION["access_token"]);
$data ='{"stepCount":7994,"heartRate":100,"description":"Run","activity":2}'; // cloud.artik.example.activitytracker device type
$payload = '{"sdid":"'.ArtikCloudProxy::DEVICE_ID.'", "data":'.$data.'}';
$response = $proxy->sendMessage($payload);
header('Content-Type: application/json');
echo json_encode($response);
?>

The payload depends entirely on the device type you're using to send data to ARTIK Cloud. The provided payload is for the device with type "Example Activity Tracker".

Every time you send a message to ARTIK Cloud and it is stored successfully, you will receive a message ID. The message ID will be useful if you need to query that message later.

If something went wrong, you will receive an error message.

Get a message from ARTIK Cloud

Now get the latest message on ARTIK Cloud that was sent by the demo device. The sample app sends a GET request to ARTIK Cloud and the URL looks like this:

1
https://api.artik.cloud/v1.1/messages/last?sdids=c1717a85481b4f2aa0a1b231a1905941&count=1

In the URL, sdids is the source device ID (the demo device you created) and count is a limit for the number of messages in the result. This example queries only one device. You can add more source device IDs. For more details, please consult the API reference.

Now let's enhance the code to achieve this functionality. Put the following HTML in hello.php, which adds a button on the page:

1
2
<a class="btn getMessage">Get a message</a>
<p id="getMessageResponse">a message will be put here....</p>

Add the following JavaScript for the button, which queries ARTIK Cloud and updates the page with the response. Particularly, the script calls get-message.php to send a GET request on background.

1
2
3
4
5
6
7
8
9
10
11
12
<script>
// Get a message using PHP
$('.getMessage').click(function(ev){
  document.getElementById("getMessageResponse").innerHTML = "waiting for response";
  $.ajax({url:'get-message.php', dataType: "json", success:function(result){
     console.log(result);
     // Get the result and show it
     var message = result.data[0];
     document.getElementById("getMessageResponse").innerHTML = JSON.stringify(message);
     }});
});
</script>

Here is what get-message.php looks like. It uses the helper class to construct the HTTP GET request and then sends it to ARTIK Cloud.

1
2
3
4
5
6
7
8
9
10
<?php
session_start();
require('ArtikCloudProxy.php');
$proxy = new ArtikCloudProxy();
$proxy->setAccessToken($_SESSION["access_token"]);
$messageCount = 1;
$response = $proxy->getMessagesLast(ArtikCloudProxy::DEVICE_ID, $messageCount);
header('Content-Type: application/json');
echo json_encode($response);
?>

If everything works, the latest message shows up on the screen.

ARTIK Cloud helper class

This is the helper class used in the tutorial. You can also get all the files used in this sample application at GitHub. This helper uses cURL functions to construct HTTP requests and then communicate with ARTIK Cloud.

Below is the source code of the helper class that does not use PHP SDK.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
/**
 * ARTIK Cloud helper class that communicates to ARTIK Cloud
 * */
class ArtikCloudProxy {
    # General Configuration
    const CLIENT_ID = "xxxxx";
    const DEVICE_ID = "xxxxx";
    const API_URL = "https://api.artik.cloud/v1.1";
 
    # ARTIK Cloud API paths
    const API_USERS_SELF = "/users/self";
    const API_MESSAGES_LAST = "/messages/last?sdids=<DEVICES>&count=<COUNT>"; 
    const API_MESSAGES_POST = "/messages";
     
    # Members
    public $token = null;
    public $user = null;
     
    public function __construct(){ }
     
    /**
     * Sets the access token and looks for the user profile information
     */
    public function setAccessToken($someToken){
        $this->token = $someToken;
        $this->user = $this->getUsersSelf();
    }
     
    /**
     * API call GET
     */
    public function getCall($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPGET, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization:bearer '.$this->token));
        $json = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if($status == 200){
            $response = json_decode($json);
        }
        else{
            var_dump($json);
          $response = $json;
        }

       return $response;
    }
     
    /**
     * API call POST
     */
    public function postCall($url, $payload){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, (String) $payload);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: bearer '.$this->token));
        $json = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if($status == 200){
            $response = json_decode($json);
        }
        else{
            var_dump($json);
            $response = $json;
        }
        return $response;
    }
     
    /**
     * GET /users/self API
     */
    public function getUsersSelf(){
        return $this->getCall(ArtikCloudProxy::API_URL . ArtikCloudProxy::API_USERS_SELF);
    }
     
    /**
     * POST /message API
     */
    public function sendMessage($payload){
        return $this->postCall(ArtikCloudProxy::API_URL . ArtikCloudProxy::API_MESSAGES_POST, $payload);
    }
     
    /**
     * GET /historical/normalized/messages/last API
     */
    public function getMessagesLast($deviceCommaSeparatedList, $countByDevice){
        $apiPath = ArtikCloudProxy::API_MESSAGES_LAST;
        $apiPath = str_replace("<DEVICES>", $deviceCommaSeparatedList, $apiPath);
        $apiPath = str_replace("<COUNT>", $countByDevice, $apiPath);
        return $this->getCall(ArtikCloudProxy::API_URL.$apiPath);
    }
}
?>