Skip to content

Instantly share code, notes, and snippets.

@t2-support-gists
Created September 14, 2012 18:08
Show Gist options
  • Save t2-support-gists/3723622 to your computer and use it in GitHub Desktop.
Save t2-support-gists/3723622 to your computer and use it in GitHub Desktop.
CMS Php RESTFul App 1
******************************************************************************************
* Licensed by AT&T under 'Software Development Kit Tools Agreement.' 2013
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION: http://developer.att.com/sdk_agreement/
* Copyright 2013 AT&T Intellectual Property. All rights reserved. http://developer.att.com
* For more information contact developer.support@att.com<mailto:developer.support@att.com>
******************************************************************************************
AT&T API Platform Samples - CMS App 1
-------------------------------------
This application demonstrates the usage of Call Management API of AT&T platform.
The application provides operations to support the creation of outgoing call session
and signals to existing sessions. Incoming call sessison will be created automatically
in the call environment.
This file describes how to set up, configure and run the PHP Application of the
AT&T API Platform sample applications. It covers all steps required to register the
application on DevConnect and, based on the generated API keys and secrets,
create and run one's own full-fledged sample applications.
1. Configuration
2. Installation
3. Parameters
4. Running the application
1. Configuration
Configuration consists of a few steps necessary to get an application registered
on DevConnect with the proper services and endpoints, depending on the type of
client-side application (autonomous/non-autonomous).
To register an application, go to https://devconnect-api.att.com/ and login with
your valid username and password. Next, choose "My Apps" from the bar at the top
of the page and click the "Setup a New Application" button.
Fill in the form, in particular all fields marked as "required".
Be careful while filling in the "OAuth Redirect URL" field. It should contain the
URL that the oAuth provider will redirect users to when he/she successfully
authenticates and authorizes your application.
NOTE: You MUST select Call Control in the list of services under field 'Services'
in order to use this sample application code.
Having your application registered, you will get back an important pair of data:
an API key and Secret key. They are necessary to get your applications working with
the AT&T Platform APIs.
Initially your newly registered application is restricted to the "Sandbox"
environment only. To move it to production, you may promote it by clicking the
"Promote to production" button. Notice that you will get a different API key and
secret, so these values in your application should be adjusted accordingly.
Depending on the kind of authentication used, an application may be based on either
the Autonomous Client or the Web-Server Client OAuth flow (see
https://devconnect-api.att.com/docs/oauth20/autonomous-client-application-oauth-flow or
https://devconnect-api.att.com/docs/oauth20/web-server-client-application-oauth-flow
respectively).
2. Installation
Requirements:
Apache web server
PHP 5.4+
PHP CURL extension
Apache and PHP configured. The package manager on most GNU/Linux systems should automatically
configure Apache/PHP upon installation.
Installation:
Install Apache, PHP, and PHP CURL extension according to their respective documentation.
Copy the sample application folder to Apache web root folder, for example /var/www/html.
3. Parameters
Each application contains a config.php file. This file holds configurable parameters described in an
easy-to-read format. Please modify the config.php file using the comments specified within the file.
Note: If your application is promoted from Sandbox environment to Production environment and you decide to use
production application settings, you must update parameters as per production application details.
4. Running the application
After the sample application folder has been copied to the Apache web root folder, you need to start Apache.
Once Apache has been started, use a web browser and open the the web page to where you copied the sample application folder.
For example, http://localhost/app1/index.php
<?php /*
fc7b147b226c9baeb0940418cebca667
0
91ddc31e7e5aaed81fabda2e8770b14bb68977ec
*/ ?>
<?php require 'index.php'; ?>
<?php
$api_key = "ddbcb85655a22b434c5eda40108a79b0";
$secret_key = "c80205296a98d6d5";
$FQDN = "https://api.att.com";
$oauth_file = "ccsoauthtoken.php";
$scope = "CMS";
$callcontrol_file = "callcontrolscript.php";
$number = "+114153401645";
$linkDownload="https://github.com/attdevsupport/ATT_APIPlatform_SampleApps/tree/master/RESTFul/CMS/PHP/app1";
$linkSource="https://gist.github.com/3723622";
$linkHelp="https://raw.github.com/attdevsupport/ATT_APIPlatform_SampleApps/master/RESTFul/CMS/PHP/app1/README.txt";
$scriptFunctions = array('', 'ask', 'conference', 'message', 'reject', 'transfer', 'wait');
?>
<?php
if (!isset($numberToDial)) {
$messageToPlay = "http://wdev.code-api-att.com:8181/Tropo/music.mp3";
say("Welcome to the A T and T. Call Management Services Sample Application.");
$result20 = ask("Press a digit to listen what you pressed or Press pound to skip", array(
"choices" => "[1 DIGITS]",
"terminator" => "#",
"timeout" => 5.0,
"mode" => "dtmf",
"interdigitTimeout" => 5,
"onChoice" => function($event) { say('Thank you for entering'); },
"onBadChoice" => function($event) { say('I am sorry, not able to get the digit'); }
)
);
if ($result20->value != "") {
say ($result20->value);
}
$result21 = ask("Press a digit to join 1337 conferencing or Press pound to skip", array(
"choices" => "[1 DIGITS]",
"terminator" => "#",
"timeout" => 5.0,
"mode" => "dtmf",
"interdigitTimeout" => 5,
"onChoice" => function($event) {
say ("Thank you for joining conferenceing, to quit press star at any time");
conference("1337", array(
"terminator" => "*",
"playTones" => true,
"onChoice" => function($event) {
say("Disconnecting from conference");
}
));
}
));
$result22 = ask("Press a digit to log the header value or Press pound to skip", array(
"choices" => "[1 DIGITS]",
"terminator" => "#",
"timeout" => 5.0,
"mode" => "dtmf",
"interdigitTimeout" => 5,
"onChoice" => function($event) {
if ($currentCall->getHeader("to")) {
say("Logged to header value");
log("Your header value is " .$currentCall->getHeader("to"));
} else {
say("could not find to header value");
log("Your header value was not found");
}
}
));
$result23 = ask("Enter a ten digit phone number to send sms to the requested number or press pound to skip", array(
"choices" => "[10 DIGITS]",
"terminator" => "#",
"timeout" => 120.0,
"mode" => "dtmf",
"interdigitTimeout" => 10,
"onChoice" => function($event) { say("Sending message to"); }
));
if ($result23->value != "") {
$numbertest = $result23->value;
say($numbertest);
message("Message from AT&T Call Control Service Sample Application", array(
"to" => $numbertest,
"network" => "SMS",
"callerID" => $currentCall->calledID
));
}
$result24 = ask("Press ten digit phone number for which you are calling to reject this call or Press pound to skip", array(
"choices" => "[10 DIGITS]",
"terminator" => "#",
"timeout" => 120.0,
"mode" => "dtmf",
"interdigitTimeout" =>10,
"onChoice" => function($event) {}
));
if ($result24->value != "") {
$numbertest = $result24->value;
if ($callerID = $numbertest) {
say("your calls will be rejected");
say("Thank you, for using A T and T Call management Sample Application Demo. Good Bye");
reject();
} else {
say("number not matched for reject feature");
say(" the current call id is");
say($currentCall->callerID);
say( "and you entered is ");
say($numbertest);
}
}
$result25 = ask("enter 10 digit phone number to transfer the call or Press pound to skip", array(
"choices" => "[10 DIGITS]",
"terminator" => "#",
"timeout" => 120.0,
"mode" => "dtmf",
"interdigitTimeout" =>10,
"onChoice" => function($event) { say("transfering to"); }
));
if ($result25->value != "") {
$numbertest = $result25->value;
say($numbertest);
transfer(array($numbertest, "sip:12345678912@221.122.54.86"), array(
"playvalue" => $messageToPlay,
"terminator" => "*",
"onTimeout" => function($event) { say("Sorry, but nobody answered."); }
)
);
}
$result27 = ask("Press ten digit phone number for which you are calling to wait this call or Press pound to skip", array(
"choices" => "[10 DIGITS]",
"terminator" => "#",
"timeout" => 120.0,
"mode" => "dtmf",
"interdigitTimeout" => 10,
"onChoice" => function($event) { }
));
if ($result27->value != "") {
$numbertest = $result27->value;
$callerID = $currentCall->callerID;
if ($callerID = $numbertest) {
say("entered number matched with the current call caller id");
say("your calls will be kept for three seconds wait");
wait(3000);
} else {
say("number not matched for wait feature");
say(" the current call id is");
say($currentCall->callerID);
say( "and you entered is ");
say($numbertest);
}
}
$result29 = ask("Press a digit to test the signalling or Press pound to skip", array(
"choices" => "[1 DIGITS]",
"terminator" => "#",
"timeout" => 5.0,
"mode" => "dtmf",
"interdigitTimeout" => 5,
"onChoice" => function($event) {
say("Waiting for exit signal");
say($messageToPlay, array(
"allowSignals" => "exit",
"onSignal" => function($event) {
say ("Received exit signal, hence music is paused. Enjoy the music again.");
}
));
say("Waiting for stopHold signal");
say($messageToPlay, array(
"allowSignals" => "stopHold",
"onSignal" => function($event) {
say("Received stop hold signal, hence music is paused. Enjoy the music again.");}
));
say("Waiting for dequeue signal");
say($messageToPlay, array(
"allowSignals" => "dequeue",
"onSignal" => function($event) {
say("Received dequeue signal, hence the music is stopped."); }
));
}
));
say("Thank you, for using A T and T. Call Management Service Sample Application Demo. Good Bye");
hangup();
} else {
call($numberToDial);
say("Welcome to the A T and T. Call Management Services Sample Application.");
switch($feature) {
case 'ask':
$result9 = ask("Press four or five digits and Press pound when finished", array(
"choices" => "[4-5 DIGITS]",
"terminator" => "#",
"timeout" => 90.0,
"mode" => "dtmf",
"interdigitTimeout" => 5,
"onChoice" => function($event) { say("Thank you for entering"); },
"onBadChoice" => function($event) { say("Sorry, I am not able to get four or five digits"); }
));
if ($result9->value != "") {
say($result9->value);
}
break;
case 'conference':
say ("Thank you for joining conferenceing");
say ("1337");
say("and to quit press star at any time");
conference("1337", array(
"terminator" => "*",
"playTones" => true,
"onChoice" => function($event) { say("Disconnecting from conference"); }
));
break;
case 'reject':
$callerID = $currentCall->callerID;
if ($callerID = $featurenumber) {
say("your calls will be rejected");
say("Thank you for using A T and T Call management Sample Application Demo. Good Bye");
reject();
} else {
say("present id is");
say($currentCall->callerID);
say("rejectnumber is ");
say($featurenumber);
say("number not matched for reject feature");
}
break;
case 'message':
if (!isset($featurenumber)) {
say("Feature number is not provided as part of create session A P I request");
} else {
say("Sending message to");
say("<speak><say-as interpret-as = 'vxml:digits'>" . $featurenumber . "</say-as></speak>");
message("Message from AT&T Call Control Service Sample Application", array(
"to" => $featurenumber,
"network" => "SMS",
"callerID" => $smsCallerID
));
}
break;
case 'transfer':
say("transfering to ");
say($featurenumber);
transfer(array($featurenumber, "sip:12345678912@221.122.54.86"), array(
"playvalue" => $messageToPlay,
"terminator" => "*",
"onTimeout" => "timeoutFCN"
)
);
function timeoutFCN($event) {
say("Sorry, but nobody answered");
}
break;
case 'wait':
$callerID = $currentCall->callerID;
if ($callerID = $featurenumber) {
say("your calls will be kept for three seconds wait");
wait(3000);
}
else{
say("present id is");
say($currentCall->callerID);
say("requested id is");
say($featurenumber);
say("number not matched for wait feature");
}
break;
}
$result4 = ask("Press a digit to test the signalling or Press pound to skip", array(
"choices" => "[1 DIGITS]",
"terminator" => "#",
"timeout" => 5.0,
"mode" => "dtmf",
"interdigitTimeout" => 5,
"onChoice" => function($event) {
say("Waiting for exit signal");
say($messageToPlay, array(
"allowSignals" => "exit",
"onSignal" => function($event) {
say ("Received exit signal, hence music is paused. Enjoy the music again.");
}
));
say("Waiting for stopHold signal");
say($messageToPlay, array(
"allowSignals" => "stopHold",
"onSignal" => function($event) {
say("Received stop hold signal, hence music is paused. Enjoy the music again.");}
));
say("Waiting for dequeue signal");
say($messageToPlay, array(
"allowSignals" => "dequeue",
"onSignal" => function($event) {
say("Received dequeue signal, hence the music is stopped."); }
));
}
));
say("Thank you, for using A T and T. Call Management Service Sample Application Demo. Good Bye");
hangup();
}
?>
<?php
session_start();
require __DIR__ . '/config.php';
require_once __DIR__ . '/src/Controller/CMSController.php';
require_once __DIR__ . '/lib/Util/Util.php';
use Att\Api\Util\Util;
$controller = new CMSController();
$controller->handleRequest();
$results = $controller->getResults();
$errors = $controller->getErrors();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>AT&amp;T Sample Application - Call Management</title>
<meta id="viewport" name="viewport" content="width=device-width,minimum-scale=1,maximum-scale=1">
<link rel="stylesheet" type="text/css" href="style/common.css">
<script src="scripts/utils.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-33466541-1']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl'
: 'http://www')
+ '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="pageContainer">
<div id="header">
<div class="logo">
</div>
<div id="menuButton" class="hide">
<a id="jump" href="#nav">Main Navigation</a>
</div>
<ul class="links" id="nav">
<li><a href="#" target="_blank">Full Page<img src="images/max.png" /></a>
<span class="divider"> |&nbsp;</span>
</li>
<li>
<a href="<?php echo $linkSource; ?>" target="_blank">Source<img src="images/opensource.png" /></a>
<span class="divider"> |&nbsp;</span>
</li>
<li>
<a href="<?php echo $linkDownload; ?>" target="_blank">Download<img src="images/download.png"></a>
<span class="divider"> |&nbsp;</span>
</li>
<li>
<a href="<?php echo $linkHelp; ?>" target="_blank">Help</a>
</li>
<li id="back"><a href="#top">Back to top</a>
</li>
</ul> <!-- end of links -->
</div> <!-- end of header -->
<div id="content">
<div id="contentHeading">
<h1>AT&amp;T Sample Application - Call Management</h1>
<div class="border"></div>
<div id="introtext">
<div><b>Server Time: </b><?php echo Util::getServerTime(); ?></div>
<div><b>Client Time:</b> <script>document.write("" + new Date());</script></div>
<div><b>User Agent:</b> <script>document.write("" + navigator.userAgent);</script></div>
</div> <!-- end of introtext -->
</div> <!-- end of contentHeading -->
<!-- SAMPLE APP CONTENT STARTS HERE! -->
<div class="formBox" id="formBox">
<div id="formContainer" class="formContainer">
<div id="sendMessages">
<h2>Feature 1: Outbound Session from <?php echo $number; ?></h2>
<form method="post" action="index.php" id="msgContentForm" name="msgContentForm">
<div class="inputFields">
<label>
Make call to:
<?php if (isset($_SESSION['txtNumberToDial'])) { ?>
<input type="text" name="txtNumberToDial"
value="<?php echo htmlspecialchars($_SESSION['txtNumberToDial']); ?>" placeholder="Address"
title="telephone number or sip address" />
<?php } else { ?>
<input type="text" name="txtNumberToDial" value="" placeholder="Address"
title="telephone number or sip address" />
<?php } ?>
</label>
<label>
Script Function:
<select name="scriptType">
<?php foreach ($scriptFunctions as $sfunc) { ?>
<?php if (isset($_SESSION['scriptType']) && $_SESSION['scriptType'] == $sfunc) { ?>
<option value="<?php echo $sfunc; ?>" selected="selected"><?php echo $sfunc ?></option>
<?php } else { ?>
<option value="<?php echo $sfunc; ?>"><?php echo $sfunc ?></option>
<?php } ?>
<?php } ?>
</select>
</label>
<label>
Number parameter for Script Function:
<?php if (isset($_SESSION['txtNumber'])) { ?>
<input type="text" name="txtNumber"
value="<?php echo htmlspecialchars($_SESSION['txtNumber']); ?>" placeholder="Number"
title="If message or transfer or wait or reject is selected as script function, enter number for transfer-to or message-to or wait-from or reject-from"/>
<?php } else { ?>
<input type="text" name="txtNumber"
value="" placeholder="Number"
title="If message or transfer or wait or reject is selected as script function, enter number for transfer-to or message-to or wait-from or reject-from"/>
<?php } ?>
</label>
<label>
Message To Play:
<?php if (isset($_SESSION['txtNumber'])) { ?>
<input type="text" name="txtMessageToPlay"
value="<?php echo htmlspecialchars($_SESSION['txtMessageToPlay']); ?>"
placeholder="Message" title="enter long message or mp3 audio url, this is used as music on hold"/>
<?php } else { ?>
<input type="text" name="txtMessageToPlay"
value="" placeholder="Message" title="enter long message or mp3 audio url, this is used as music on hold"/>
<?php } ?>
</label>
<div id="scriptText">
<label>
Script Source Code:
</label>
<textarea name="txtCreateSession" rows="2" cols="20" disabled="disabled" id="txtCreateSession" >
<?php echo htmlspecialchars($results[CMSController::RESULT_SCRIPT_CONTENTS]); ?>
</textarea>
</div>
<div>
<button type="submit" class="submit" name="btnCreateSession" >
Create Session</button>
</div>
</div>
</form>
<?php
if (isset($results[CMSController::RESULT_CREATE_SESSION])) {
$cs = $results[CMSController::RESULT_CREATE_SESSION];
?>
<div class="successWide">
<strong>SUCCESS</strong><br>
id:&nbsp;<?php echo $cs->getId(); ?><br>
success:&nbsp;<?php echo ($cs->getSuccess() ? 'True' : 'False'); ?><br>
</div>
<?php } else if (isset($errors[CMSController::ERROR_CREATE_SESSION])) {
$err = $errors[CMSController::ERROR_CREATE_SESSION];
?>
<div class="errorWide">
<strong>ERROR:</strong>
<?php echo htmlspecialchars($err); ?>
</div>
<?php } ?>
</div> <!-- end of Create Session -->
<div class="lightBorder"></div>
<div id="sendSignal">
<h2>Feature 2: Send Signal to Session</h2>
<form method="post" name="sendSignal" action="index.php">
<div class="inputFields">
<label class="label">
Session ID: <?php echo $results[CMSController::RESULT_SESSION_ID]; ?>
</label>
<label class="label">
Signal to Send:
<select name="signal">
<?php $signals = array('exit', 'stopHold', 'dequeue');
foreach ($signals as $signal) {
if (isset($_SESSION['signal']) && $signal == $_SESSION['signal']) {
?>
<option value="<?php echo $signal; ?>" selected="selected"><?php echo $signal; ?></option>
<?php } else { ?>
<option value="<?php echo $signal; ?>"><?php echo $signal; ?></option>
<?php } ?>
<?php } /* end of foreach */ ?>
</select>
</label>
<div>
<button type="submit" class="submit" name="btnSendSignal">
Send Signal
</button>
</div>
</div>
</form>
<?php if (isset($results[CMSController::RESULT_SEND_SIGNAL])) {
$result = $results[CMSController::RESULT_SEND_SIGNAL];
$signalStatus = $result->getStatus();
?>
<div class="successWide">
<strong>SUCCESS</strong><br />
<strong>Status:&nbsp;</strong><?php echo htmlspecialchars(json_encode($signalStatus)); ?>
</div>
<?php } ?>
<?php if (isset($errors[CMSController::ERROR_SEND_SIGNAL])) {
$err = $errors[CMSController::ERROR_SEND_SIGNAL];
?>
<div class="errorWide">
<strong>ERROR:</strong>
<?php echo htmlspecialchars($err); ?>
</div>
<?php } ?>
</div> <!-- end of Send Signal -->
</div> <!-- end of formContainer -->
</div> <!-- end of formBox -->
<!-- SAMPLE APP CONTENT ENDS HERE! -->
</div> <!-- end of content -->
<div class="border"></div>
<div id="footer">
<div id="powered_by">
Powered by AT&amp;T Cloud Architecture
</div>
<p>
The Application hosted on this site are working examples
intended to be used for reference in creating products to consume
AT&amp;T Services and not meant to be used as part of your
product. The data in these pages is for test purposes only and
intended only for use as a reference in how the services perform.
<br /><br />
For download of tools and documentation, please go to
<a href="https://devconnect-api.att.com/"
target="_blank">https://devconnect-api.att.com</a>
<br> For more information contact
<a href="mailto:developer.support@att.com">developer.support@att.com</a>
<br /><br />
&#169; 2013 AT&amp;T Intellectual Property. All rights reserved.
<a href="http://developer.att.com/" target="_blank">http://developer.att.com</a>
</p>
</div> <!-- end of footer -->
</div> <!-- end of page_container -->
<script>setup();</script>
</body>
</html>
<?php
function RefreshToken($FQDN, $api_key, $secret_key, $scope, $fullToken)
{
$refreshToken = $fullToken["refreshToken"];
$accessTok_Url = $FQDN . "/oauth/token";
//http header values
$accessTok_headers = array(
'Content-Type: application/x-www-form-urlencoded'
);
//Invoke the URL
$post_data = "client_id=" . $api_key . "&client_secret=" . $secret_key . "&refresh_token=" . $refreshToken . "&grant_type=refresh_token";
$accessTok = curl_init();
curl_setopt($accessTok, CURLOPT_URL, $accessTok_Url);
curl_setopt($accessTok, CURLOPT_HTTPGET, 1);
curl_setopt($accessTok, CURLOPT_HEADER, 0);
curl_setopt($accessTok, CURLINFO_HEADER_OUT, 0);
curl_setopt($accessTok, CURLOPT_HTTPHEADER, $accessTok_headers);
curl_setopt($accessTok, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($accessTok, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($accessTok, CURLOPT_POST, 1);
curl_setopt($accessTok, CURLOPT_POSTFIELDS, $post_data);
$accessTok_response = curl_exec($accessTok);
$currentTime = time();
$responseCode = curl_getinfo($accessTok, CURLINFO_HTTP_CODE);
if ($responseCode == 200) {
$jsonObj = json_decode($accessTok_response);
$accessToken = $jsonObj->{'access_token'}; //fetch the access token from the response.
$refreshToken = $jsonObj->{'refresh_token'};
$expiresIn = $jsonObj->{'expires_in'};
if ($expiresIn == 0) {
$expiresIn = 24 * 60 * 60;
}
$refreshTime = $currentTime + (int)($expiresIn); // Time for token refresh
$updateTime = $currentTime + (24 * 60 * 60); // Time to get for a new token update, current time + 24h
$fullToken["accessToken"] = $accessToken;
$fullToken["refreshToken"] = $refreshToken;
$fullToken["refreshTime"] = $refreshTime;
$fullToken["updateTime"] = $updateTime;
} else {
$fullToken["accessToken"] = null;
$fullToken["errorMessage"] = curl_error($accessTok) . $accessTok_response;
}
curl_close($accessTok);
return $fullToken;
}
function GetAccessToken($FQDN, $api_key, $secret_key, $scope)
{
$accessTok_Url = $FQDN . "/oauth/token";
//http header values
$accessTok_headers = array(
'Content-Type: application/x-www-form-urlencoded'
);
//Invoke the URL
$post_data = "client_id=" . $api_key . "&client_secret=" . $secret_key . "&scope=" . $scope . "&grant_type=client_credentials";
$accessTok = curl_init();
curl_setopt($accessTok, CURLOPT_URL, $accessTok_Url);
curl_setopt($accessTok, CURLOPT_HTTPGET, 1);
curl_setopt($accessTok, CURLOPT_HEADER, 0);
curl_setopt($accessTok, CURLINFO_HEADER_OUT, 0);
curl_setopt($accessTok, CURLOPT_HTTPHEADER, $accessTok_headers);
curl_setopt($accessTok, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($accessTok, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($accessTok, CURLOPT_POST, 1);
curl_setopt($accessTok, CURLOPT_POSTFIELDS, $post_data);
$accessTok_response = curl_exec($accessTok);
$responseCode = curl_getinfo($accessTok, CURLINFO_HTTP_CODE);
$currentTime = time();
/*
If URL invocation is successful fetch the access token and store it in session,
else display the error.
*/
if ($responseCode == 200) {
$jsonObj = json_decode($accessTok_response);
$accessToken = $jsonObj->{'access_token'}; //fetch the access token from the response.
$refreshToken = $jsonObj->{'refresh_token'};
$expiresIn = $jsonObj->{'expires_in'};
if ($expiresIn == 0) {
$expiresIn = 24 * 60 * 60 * 365 * 100;
}
$refreshTime = $currentTime + (int)($expiresIn); // Time for token refresh
$updateTime = $currentTime + (24 * 60 * 60); // Time to get a new token update, current time + 24h
$fullToken["accessToken"] = $accessToken;
$fullToken["refreshToken"] = $refreshToken;
$fullToken["refreshTime"] = $refreshTime;
$fullToken["updateTime"] = $updateTime;
} else {
$fullToken["accessToken"] = null;
$fullToken["errorMessage"] = curl_error($accessTok) . $accessTok_response;
}
curl_close($accessTok);
return $fullToken;
}
function SaveToken($fullToken, $oauth_file)
{
$accessToken = $fullToken["accessToken"];
$refreshToken = $fullToken["refreshToken"];
$refreshTime = $fullToken["refreshTime"];
$updateTime = $fullToken["updateTime"];
$tokenfile = $oauth_file;
$fh = fopen($tokenfile, 'w');
$tokenfile = "<?php \$accessToken=\"" . $accessToken . "\"; \$refreshToken=\"" . $refreshToken . "\"; \$refreshTime=" . $refreshTime . "; \$updateTime=" . $updateTime . "; ?>";
fwrite($fh, $tokenfile);
fclose($fh);
}
function check_token($FQDN, $api_key, $secret_key, $scope, $fullToken, $oauth_file)
{
$currentTime = time();
if (($fullToken["updateTime"] == null) || ($fullToken["updateTime"] <= $currentTime)) {
$fullToken = GetAccessToken($FQDN, $api_key, $secret_key, $scope);
if ($fullToken["accessToken"] == null) {
//echo $fullToken["errorMessage"];
} else {
//echo $fullToken["accessToken"];
SaveToken($fullToken, $oauth_file);
}
} elseif ($fullToken["refreshTime"] <= $currentTime) {
$fullToken = RefreshToken($FQDN, $api_key, $secret_key, $scope, $fullToken);
if ($fullToken["accessToken"] == null) {
//echo $fullToken["errorMessage"];
} else {
//echo $fullToken["accessToken"];
SaveToken($fullToken, $oauth_file);
}
}
return $fullToken;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment