Show a User's Mission Progress - Code Sample
The following code samples show how you can use the /users/{userId}/challenges/{challengeId}/progress API.
PHP
Copy
<?php
require_once('./NitroOAuth.php');
//Connection Info
$userId = $_ENV["USER_ID"];
$clientId = $_ENV["CLIENT_ID"];
$secretId = $_ENV["CLIENT_SECRET"];
$api = $_ENV["API"];
$nitro = new NitroOAuth($clientId, $secretId, $api);
$token = $nitro->setAccessToken($userId);
echo "\n" . $token;>
//API calls
$eligibleChallenges = $nitro->OAuthCall('/users/'.$userId.'/challenges?type=eligible', '', ['reqType' => 'get']); //Get challenges the user is eligible to complete
echo "eligible challenges\n";
print_r($eligibleChallenges);
$completedChallenges = $nitro->OAuthCall('/users/'.$userId.'/challenges?type=completed', '', ['reqType' => 'get']); //Get challenges that the user has completed
echo "completed chalelnges\n";
print_r($completedChallenges);
if(count($eligibleChallenges->response) > 0) {
$progress = $nitro->OAuthCall('/users/'.$userId.'/challenges/'.$eligibleChallenges->response[0]->id.'/progress', '', ['reqType' => 'get']); //Get the user's challenge progress of a specific challenge
}
//Display responses
echo "challenges progress\n";
print_r($progress);
Copy
<?php
class NitroOAuth {
protected $accessToken;
protected $clientId;
protected $clientSecret;
protected $environment;
/**
* Generate an access token
*
* @param $clientId : OAuth client ID (string | required)
* @param $clientSecret : OAuth client secret (string | required)
* @param $environment : Environment of the endpoint (string | optional)
*/
public function __construct($clientId, $clientSecret, $environment = 'api') {
$this->clientId = $clientId;
$this->clientSecret = $clientSecret;
$this->environment = $environment;
}
/**
* Generate an access token
*
* @param $threeLegToken : Generate 3 leg token when true (bool | optional)
*/
public function setAccessToken($userId = null) {
$endpoint = "https://" . $this->environment . ".bunchball.com/oauth/token/";
$headers = ['Content-Type: application/x-www-form-urlencoded'];
$data = [
"grant_type" => "client_credentials",
"client_id" => $this->clientId,
"client_secret" => $this->clientSecret
];
if (isset($userId)) {
$data["xoauth_end_user_id"] = $userId;
}
$options = ['headers' => $headers];
$response = json_decode($this->execute($endpoint, http_build_query($data), $options), true);
$this->accessToken = $response['access_token'];
return $response;
}
/**
* Builds & executes an APIGateway API call (POST)
*
* @param $path : path of the URL call to add to the endpoint (String | Required)
* @param $data : Post data payload (String | Required)
* @param array $options : Options to be passed in
*$options['reqType'] : Request type (string | Optional | default: post)
*$options['headers']: Headers to send with request (array | Optional | default: empty)
*/
public function OauthCall($path, $data = '', $options = []) {
$endpoint = "https://" . $this->environment . ".bunchball.com" . $path;
$headers = [
'Authorization: Bearer ' . $this->accessToken,
'Content-Type: application/x-www-form-urlencoded'
];
$options['headers'] = $headers;
$response = $this->execute($endpoint, $data, $options);
return json_decode($response);
}
/**
* Execute URL (POST)
*
* @param $url : URL to be passed in (Required)
* @param $data : Post data to send (Required)
* @param array $options : Options to be passed in
*$options['reqType'] : Request type (string | Optional | default: post)
*$options['headers']: Headers to send with request (array | Optional | default: empty)
*/
public function execute($url, $data, $options = []) {
//Set defaults
$options = array_merge(array(
'reqType' => 'post',
'headers' => []
), $options);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $options['reqType'],
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => $options['headers']
));
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $this->response = $response;
}
}
Node.js
For this snippet, the following node modules are expected to be installed:
Copy
const NitroOauth = require('./NitroOauth');
var userID = process.env.USER_ID;
var nitro = new NitroOauth(process.env.CLIENT_ID, process.env.CLIENT_SECRET, process.env.API);
async function example() {
try {
// First lets generate an OAuth token for the user
let token = await nitro.makeToken(userID);
console.log('token', token);
// Now let's see what eligible challenges there are for this user ID
let eligibleChallenges = await nitro.OAuthCall(token.access_token, {'path' : `/users/${userID}/challenges?type=eligible`})
console.log('eligibleChallenges', eligibleChallenges)
// Now let's see what challenges this user ID has completed
let completedChallenges = await nitro.OAuthCall(token.access_token, {'path' : `/users/${userID}/challenges?type=completed`})
console.log('completedChallenges', completedChallenges)
// Get this user's challenge progress of the first eligible challenge
if(eligibleChallenges.response.length > 0) {
let challengeProgress = await nitro.OAuthCall(token.access_token, {'path' : `/users/${userID}/challenges/${eligibleChallenges.response[0].id}/progress`})
console.log('challengeProgress', challengeProgress)
}
} catch (e) {
console.error(e);
}
};
example();
Copy
const request = require('request'); //Using request module for post request
"use strict";
module.exports = class NitroOauth {
constructor(client, secret, environment = 'api') {
this.client = client;
this.secret = secret;
this.env = environment;
this.url = '';
}
/**
* Request an access token
*
* @param userId : pass in a userId to generate a 3 legged token
*/
makeToken(userId = '') {
let data = {
grant_type: "client_credentials",
client_id: this.client,
client_secret: this.secret,
};
if (userId) { //If userID is passed in generate a three legged token
data.xoauth_end_user_id = userId;
}
let options = {
url: `https://${this.env}.bunchball.com/oauth/token/`,
form: data,
json: true,
method: 'POST'
}
console.log("options", options)
return this.execute(options);
}
OAuthCall(token, opts) {
if (opts.form === undefined) {
opts.form = {};
}
if (opts.path === undefined) {
console.error('Path not defined');
opts.path = '';
}
if (opts.method === undefined) {
opts.method = 'get';
}
let options = {
url: `https://${this.env}.bunchball.com${opts.path}`,
form: opts.form,
json: true,
method: opts.method,
headers: {
Authorization: `Bearer ${token}`
}
}
return this.execute(options);
}
/**
* Execute API call
*
* @param {*} opt : options to send with request (object | optional)
*/
execute(opt) {
return new Promise((resolve, reject) => {
request(opt, function (err, res, body) {
if(err) reject(err)
resolve(body);
});
});
}
}
See also