Authentication for Slim framework not working - php

I am using Slim framework to create restful api.
I am able to create a get api, but when I add authentication to the get request, it throws an error(Advanced Rest client google chrome extension), here is the error :
<html><head><title>Slim Application Error</title><style>body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}</style></head><body><h1>Slim Application Error</h1><p>The application could not run because of the following error:</p><h2>Details</h2><div><strong>Type:</strong> ErrorException</div><div><strong>Code:</strong> 8</div><div><strong>Message:</strong> Undefined variable: apiKey</div><div><strong>File:</strong> /Library/WebServer/Documents/pascal_api/rest_api/v1/index.php</div><div><strong>Line:</strong> 34</div><h2>Trace</h2><pre>#0 /Library/WebServer/Documents/pascal_api/rest_api/v1/index.php(34): Slim\Slim::handleErrors(8, 'Undefined varia...', '/Library/WebSer...', 34, Array)
#1 [internal function]: authenticate(Object(Slim\Route))
#2 /Library/WebServer/Documents/pascal_api/rest_api/libs/Slim/Route.php(433): call_user_func_array('authenticate', Array)
#3 /Library/WebServer/Documents/pascal_api/rest_api/libs/Slim/Slim.php(1307): Slim\Route->dispatch()
#4 /Library/WebServer/Documents/pascal_api/rest_api/libs/Slim/Middleware/Flash.php(85): Slim\Slim->call()
#5 /Library/WebServer/Documents/pascal_api/rest_api/libs/Slim/Middleware/MethodOverride.php(92): Slim\Middleware\Flash->call()
#6 /Library/WebServer/Documents/pascal_api/rest_api/libs/Slim/Middleware/PrettyExceptions.php(67): Slim\Middleware\MethodOverride->call()
#7 /Library/WebServer/Documents/pascal_api/rest_api/libs/Slim/Slim.php(1254): Slim\Middleware\PrettyExceptions->call()
#8 /Library/WebServer/Documents/pascal_api/rest_api/v1/index.php(100): Slim\Slim->run()
#9 {main}</pre></body></html>
Here is my code:
<?php
require '.././libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
function isValidApiKey($api_key) {
$m = new MongoClient();
$db = $m->pascal;
$collection = $db->apiUsers;
if($collection->findOne(array('apiKey' => $api_key))){
return true;
}
else{
return false;
}
}
function authenticate(\Slim\Route $route) {
// Getting request headers
$headers = apache_request_headers();
$response = array();
$app = \Slim\Slim::getInstance();
// Verifying Authorization Header
if (isset($headers['Authorization'])) {
// get the api key
$api_key = $headers['Authorization'];
echo $apiKey;
// validating api key
//$db = new dbSupport();
if ($isValidApiKey($api_key) === false) {
// api key is not present
$response["error"] = true;
$response["message"] = "Access Denied. Invalid Api key";
echoRespnse(401, $response);
$app->halt(401);
}
else{
}
} else {
// api key is missing in header
$response["error"] = true;
$response["message"] = "Api key is misssing";
echoRespnse(400, $response);
$app->halt(401);
}
}
$app->get('/offerData','authenticate',function() use ($app) {
$m = new MongoClient();
$db = $m->pascal;
$collection = $db->offerDetails;
$offer_array = array();
$cursor = $collection->find();
$offer_array["offers"] = array();
foreach ($cursor as $document) {
$offerData = array('title' => $document['title'],
'discription' => $document['discription'],
'create_time' => $document['create_time'],
'expire_time' => $document['expire_time'],
'coordinates' => $document['loc']['coordinates'],
'address' => $document['address'],
'tags' => $document['tags'],
'phone_number' => $document['phone_number'],
'email' => $document['email'],
'website' => $document['website'],
'img_url' => $document['img_url']
);
array_push($offer_array["offers"], $offerData);
}
$offer_array["error"] = false;
echoRespnse(200, $offer_array);
});
function echoRespnse($status_code, $response) {
$app = \Slim\Slim::getInstance();
// Http response code
$app->status($status_code);
// setting response content type to json
$app->contentType('application/json');
echo json_encode($response);
}
$app->run();
?>
Any idea whats causing this error??
Thanks

Please run the print_r command on the $headers and see what are you getting in the there . I think the key is not being set or its not coming at all to your code
Okay then do this before line 28 :
$api_key=null ;
Try this once and let me know .
This is the error :
$api_key = $headers['Authorization'];
echo $apiKey;
But the echo is printing the wrong variable .It should be
echo $api_key;

Related

how to convert destinationAddresses/phone number into hash codes in PHP sms API

I want to create SMS sending application using PHP with SMS API. In my response message I can see success code and success message but my Problem is in my log file says as
Passed Exception exception 'SMSServiceException' with message 'Format
of the address is invalid'
I think problem is, starts when I hash coding phone number. And I don't know how to do that, Please help me.
I have tried to convert phone number using md5() but result is same.
my index.php
$jsonData = array( 'requestId'=> '','message' => 'thismsg hello',
'password' => '25c8db49905003e3347ad861546fce1a',
'sourceAddress' => '77000',
'deliveryStatusRequest' => '1',
'chargingAmount' => '2.00',
'destinationAddresses' => ['88b7a1e8dbf419a2c0835b4f33d06c1a'],//this convert with md5
'applicationId' => 'APP_051000',
'encoding' => '0',
'version' => '1.0',
'binaryHeader' => ''
);
my .log file result:
[01-Feb-2019 08:57:34 Asia/Colombo] Message received msg_header hello
[01-Feb-2019 08:57:35 Asia/Colombo] Passed Exception exception 'SMSServiceException' with message 'Format of the address is invalid.' in /ophielapp/lib/SMSSender.php:58
Stack trace:
#0 /ophielapp/lib/SMSSender.php(46): SMSSender->handleResponse(Object(stdClass))
#1 /ophielapp/lib/SMSSender.php(34): SMSSender->sendRequest('{"applicationId...')
#2 /ophielapp/sms.php(66): SMSSender->sendMessage('hello', '77000')
#3 {main}
I want to correctly send phone number into smsSender.php with hash code and If want to more details of other php file I can provide it.
result in my browser:this is the image of response
this is my smsSender.php
<?php
require_once 'SMSServiceException.php';
class SMSSender{
private $applicationId,
$password,
$serverURL;
public function __construct($serverURL, $applicationId, $password)
{
$this->applicationId = $applicationId;
$this->password = $password;
$this->serverURL = $serverURL;
}
public function broadcastMessage($message){
return $this->sendMessage($message, array('tel:all'));
}
public function sendMessage($message, $addresses){
if(empty($addresses))
throw new SMSServiceException('Format of the address is invalid.', 'E1325');
else {
$jsonStream = (is_string($addresses))?$this->resolveJsonStream($message, array($addresses)):(is_array($addresses)?$this->resolveJsonStream($message, $addresses):null);
return ($jsonStream!=null)?$this->sendRequest($jsonStream):false;
}
}
private function sendRequest($jsonStream){
$opts = array('http'=>array('method'=>'POST',
'header'=>'Content-type: application/json',
'content'=>$jsonStream));
$context = stream_context_create($opts);
$response = file_get_contents($this->serverURL, 0, $context);
return $this->handleResponse(json_decode($response));
}
private function handleResponse($jsonResponse){
$statusCode = $jsonResponse->statusCode;
$statusDetail = $jsonResponse->statusDetail;
if(empty($jsonResponse))
throw new SMSServiceException('Invalid server URL', '500');
else if(strcmp($statusCode, 'S1000')==0)
return true;
else
throw new SMSServiceException($statusDetail, $statusCode);
}
private function resolveJsonStream($message, $addresses){
// $addresses is a array
$messageDetails = array('message'=>$message,
'destinationAddresses'=>$addresses);
$applicationDetails = array('applicationId'=>$this->applicationId,
'password'=>$this->password);
$jsonStream = json_encode($applicationDetails+$messageDetails);
return $jsonStream;
}
public function get_location_stream( $addresse){
$reqDetails = array(
'applicationId'=>$this->applicationId,
'password'=>$this->password,
'serviceType'=>'IMMEDIATE',
'subscriberId'=>$addresse
);
return json_encode($reqDetails);
}
public function getlocation( $addresse){
//$jsonStream = get_location_stream($addresse);
$jsonStream= array(
'applicationId'=>$this->applicationId,
'password'=>$this->password,
'serviceType'=>'IMMEDIATE',
'subscriberId'=>$addresse
);
print_r($jsonStream);
json_encode($jsonStream);
$opts = array('http'=>array('method'=>'POST',
'header'=>'Content-Type: application/json',
'content'=>$jsonStream));
$context = stream_context_create($opts);
$response = file_get_contents('http://localhost:7000/lbs/locate', 0, $context);
echo $response;
//return $this->location_response(json_decode($response));
return json_decode($response);
}
public function location_response($jsonResponse){
$statusCode = $jsonResponse->statusCode;
if(empty($jsonResponse)){
throw new SMSServiceException('Invalid server URL', '500');
}else if(strcmp($statusCode, 'S1000')==0){
return array(
$jsonResponse->longitude,
$jsonResponse->latitude,
$jsonResponse->horizontalAccuracy,
$jsonResponse->freshness,
$jsonResponse->messageId
);
}else{
throw new SMSServiceException($statusDetail, $statusCode);
}
}
public function getResponse($addresse){
$jsonStream= array(
'applicationId'=>$this->applicationId,
'password'=>$this->password,
'serviceType'=>'IMMEDIATE',
'subscriberId'=>$addresse
);
$opts = array('http'=>array('method'=>'POST',
'header'=>'Content-Type: application/json',
'content'=>json_encode($jsonStream)));
$context = stream_context_create($opts);
$response = file_get_contents('http://localhost:7000/lbs/locate', 0, $context);
return json_decode($response);
}
}
?>
destinationAddresses pass as string
'destinationAddresses' =>'88b7a1e8dbf419a2c0835b4f33d06c1a',

First time fatal error lost

Hello? Is anybody in there?
I've used this before years ago now I'm back. First time gives me this:
Fatal error: Uncaught Services_Twilio_TinyHttpException in /home/www/skyphilly6.com/twill/twilio-php/Services/Twilio/TinyHttp.php:119 Stack trace: #0 /home/www/skyphilly6.com/twill/twilio-php/Services/Twilio.php(178): Services_Twilio_TinyHttp->__call('post', Array) #1 /home/www/skyphilly6.com/twill/twilio-php/Services/Twilio/ListResource.php(92): Base_Services_Twilio->createData('/2010-04-01/Acc...', Array) #2 /home/www/skyphilly6.com/twill/twilio-php/Services/Twilio/Rest/Calls.php(32): Services_Twilio_ListResource->_create(Array) #3 /home/www/skyphilly6.com/twill/index.php(9): Services_Twilio_Rest_Calls->create('8052629166', '8058130331', 'htttttp://demo.twi...') #4 {main} thrown in /home/www/skyphilly6.com/twill/twilio-php/Services/Twilio/TinyHttp.php on line 119
Here's my short code tried many additional lines same result:
<?php
require('./twilio-php/Services/Twilio.php');
$version = "2010-04-01";
$account_sid = 'ACcfc1ba0d12c58180319486144bef540e'; $auth_token = 'washere';
$client = new Services_Twilio($account_sid, $auth_token, $version);
$client->account->calls- >create('8052629166','8058133333','htttttp://demo.twilio.com/welcome/voice/');
?>
Also tried uncommenting this same result:
<?php
require('./twilio-php/Services/Twilio.php');
$version = "2010-04-01";
//$account_sid = 'SK5b9d2d022b971335e17ee50c813ae231'; $auth_token = 'was';
$account_sid = 'ACcfc1ba0d12c58180319486144bef540e'; $auth_token = 'was';
$client = new Services_Twilio($account_sid, $auth_token, $version);
//try {
//$call=
$client->account->calls->create('8052629166','8058133333','htttttp://demo.twilio.com/welcome/voice/');
//,array(
//'Method' => 'GET',
//'FallbackMethod' => 'GET',
//'StatusCallbackMethod' => 'GET',
//'Record' => 'false', ));
//echo 'Started call: ' . $call->sid;
//} catch (Exception $e) { echo 'Error: ' . $e->getMessage(); }
?>
Please point me in the right direction.
Added:
$http = new Services_Twilio_TinyHttp('https://api.twilio.com',
array('curlopts' => array(
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
))
);
//$client = new Services_Twilio($sid, $token, "2010-04-01", $http);
$client = new Services_Twilio($account_sid, $auth_token, $version,$http);
Noticed it doesn't matter what I use for my token same error
Can't find the error log:
$client->http->debug = true;
Hello?

How to get analytics data using google api without login?

I am using php and mysql. I have to get anlytics data of different sites using google sdk api and most important thing is that I need not to login in api. without login I need go get analytics data.
please have a look below code where I am able to get 'Google_AnalyticsService' object and facing error while getting data.It is saying Login Required...
require 'apigp/Google_Client.php';
require 'apigp/contrib/Google_PlusService.php';
require 'apigp/contrib/Google_AnalyticsService.php';
date_default_timezone_set('UTC');
$date_beforeonemoth = date("Y-m-d", mktime(0,0,0,date("m"),date("d")-30,date("Y")));
$date_today = date("Y-m-d", mktime(0,0,0,date("m"),date("d"),date("Y")));
$google = new Google_Client();
$google->setDeveloperKey('Google AppKey here');
$google->setClientSecret('Google ClientSecretKey here');
$google->setClientId('Google ClientID here');
$analytics = new Google_AnalyticsService($google);
$profileURL="";
$pageName="";
$brandId="";
$sql="select * from profiles where APIType='Google Plus'";
$result=mysql_query($sql);
while($rs = mysql_fetch_assoc($result))
{
$profileURL='https://plus.google.com/105932700878744xxxxxx';
$brandId=4;
$pageName=basename($profileURL);
$accounts = $analytics->management_accounts->listManagementAccounts();
if(isset($accounts['totalResults'])){
if($accounts['totalResults']>0){
$firstAccountId = $accounts['items'][0]['id'];
$webproperties = $analytics->management_webproperties->listManagementWebproperties($firstAccountId);
if(count($webproperties['items'])>0){
$firstWebpropertyId = $webproperties['items'][0]['id'];
$profiles = $analytics->management_profiles->listManagementProfiles($firstAccountId, $firstWebpropertyId);
if (count($profiles['items']) > 0) {
$profileId = $profiles['items'][0]['id'];
$profileId = $pageName;
$results = $analytics->data_ga->get(
'ga:' . $profileId,
$date_beforeonemoth,
$date_today,
'ga:visits,ga:pageviews,ga:pageviewsPerVisit,ga:avgTimeOnPage,ga:visitBounceRate,ga:percentNewVisits,ga:uniquePageviews',
array(
'dimensions' => 'ga:source,ga:keyword,ga:browser,ga:date,ga:month,ga:day,ga:year',
'sort' => '-ga:visits,ga:keyword',
// 'filters' => 'ga:medium==organic',
'max-results' => '25'));
$visits = "";
$unique_visitors = "";
$pageviews = "";
$pages_visit = "";
$avg_visit_duration = "";
$bounce_rate = "";
$new_visits = "";
echo "<br>".$visits = $results['totalsForAllResults']['ga:visits'];
echo "<br>".$unique_visitors = $results['totalsForAllResults']['ga:uniquePageviews'];
echo "<br>".$pageviews = $results['totalsForAllResults']['ga:pageviews'];
$pages_visit = $results['totalsForAllResults']['ga:pageviewsPerVisit'];
$avg_visit_duration = $results['totalsForAllResults']['ga:avgTimeOnPage'];
$bounce_rate = $results['totalsForAllResults']['ga:visitBounceRate'];
$new_visits = $results['totalsForAllResults']['ga:percentNewVisits'];
$profileName = $results['profileInfo']['profileName'];
}else{print"No profiles found for this user.";}
}else{print"No webproperties found for this user.";} //close webproperties result if condition
}else{print"No accounts found for this user.";} //close total result if condition
}
}
Error:
Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling GET https://www.googleapis.com/analytics/v3/management/accounts?key=AIzaSyBeh0Aevex7q3iRIY5bV3N9gx0WAkNBMi4: (401) Login Required' in E:\xampp\htdocs\DATAPOINTS\apigp\io\Google_REST.php:66 Stack trace: #0 E:\xampp\htdocs\DATAPOINTS\apigp\io\Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1 E:\xampp\htdocs\DATAPOINTS\apigp\service\Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest)) #2 E:\xampp\htdocs\DATAPOINTS\apigp\contrib\Google_AnalyticsService.php(139): Google_ServiceResource->__call('list', Array) #3 E:\xampp\htdocs\DATAPOINTS\anatest.php(33): Google_ManagementAccountsServiceResource->listManagementAccounts() #4 {main} thrown in E:\xampp\htdocs\DATAPOINTS\apigp\io\Google_REST.php on line 66
How to get analytics data without login in api ?
According to Google, you must send authorization credentials with each API request.
See here: https://developers.google.com/analytics/devguides/reporting/core/v3/#user_reports

DailyMotion Invalid authorization code

I'm trying to send videos by DailyMotion PHP SDK with this code:
<?php
require_once 'dailymotion-sdk-php-master/Dailymotion.php';
$api = new Dailymotion();
$api->setGrantType(Dailymotion::GRANT_TYPE_AUTHORIZATION, '081cf3f9d3f64c8d9234', '98da6430d6ebef2621f1061886ecde1a0aa57def', array('manage_videos'));
try
{
$url = $api->uploadFile('video.avi');
$result = $api->call('video.create', array('url' => $url));
}
catch (DailymotionAuthRequiredException $e)
{
// Redirect the user to the Dailymotion authorization page
header('Location: ' . $api->getAuthorizationUrl());
return;
}
catch (DailymotionAuthRefusedException $e)
{
// Handle case when user refused to authorize
// <YOUR CODE>
}
?>
I always get the following error:
Fatal error: Uncaught exception 'DailymotionAuthException' with message 'Invalid authorization code.' in /folder/public_html/dailymotion-sdk-php-master/Dailymotion.php:541 Stack trace:
#0 /folder/public_html/dailymotion-sdk-php-master/Dailymotion.php(370): Dailymotion->oauthTokenRequest(Array)
#1 /folder/public_html/dailymotion-sdk-php-master/Dailymotion.php(247): Dailymotion->getAccessToken()
#2 /folder/public_html/dailymotion-sdk-php-master/Dailymotion.php(203): Dailymotion->call('GET /file/uploa...', Array)
#3 /folder/public_html/dailymotion-sdk-php-master/Dailymotion.php(189): Dailymotion->get('/file/upload')
#4 /folder/public_html/index.php(9): Dailymotion->uploadFile('video.avi')
#5 {main} thrown in /folder/public_html/dailymotion-sdk-php-master/Dailymotion.php on line 541
I've tried the JLepage suggestion( https://stackoverflow.com/questions/12330141/dailymotion-api-invalid-authorization-code ), but without success.
Anyone can help me, please?
I suggest you try this way :
include("Dailymotion.php");
$apiKey = "xxxxxxxxxxxxxxxxxxxx";
$apiSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$username = "yourUsername";
$pwd = "yourPassword";
$filepath = "myVideo.avi";
$api = new Dailymotion();
$api->setGrantType(Dailymotion::GRANT_TYPE_PASSWORD, $apiKey, $apiSecret, array('manage_videos', 'write','delete'), array('username' => $user, 'password' => $pwd));
$url = $api->uploadFile($filePath);
$result = $api->call('video.create', array(
'url' => $url,
'title' => $title,
'description' => $description,
'private' => 'false',
'published' => 'true',
'channel' => 'lifestyle'
));
Important: Don't share your API's ID!
That works for me, hope that work for you too !

Add comment to issue using php and JIRA SOAP API

How do I add a comment to a JIRA Issue using PHP and Jura's SOAP API? I have the connection and tested it retrieving an existing issue, all runs good, but when I try the addComment method it returns this:
Fatal error: Uncaught SoapFault exception: [soapenv:Server.userException] org.xml.sax.SAXException: Bad types (class java.util.HashMap -> class com.atlassian.jira.rpc.soap.beans.RemoteComment) in /home/a7348186/public_html/jira.php:46 Stack trace:
#0 /home/a7348186/public_html/jira.php(46): SoapClient->__call('addComment', Array)
#1 /home/a7348186/public_html/jira.php(46):
SoapClient->addComment('16VGN3ohoo', 'NTP->29', Array)
#2 {main} thrown in /home/a7348186/public_html/jira.php on line 46
This is my code:
<?php
$emailplain = $_REQUEST['plain'];
$emailsubject = $_REQUEST['subject'];
$inputkey = $_REQUEST['key'];
$inputsumm = $_REQUEST['summ'];
$client = new SoapClient(NULL,
array(
"location" => "https://server.com/rpc/soap/jirasoapservice-v2?wsdl",
"uri" => "urn:xmethods-delayed-quotes",
"style" => SOAP_RPC,
"use" => SOAP_ENCODED
));
$token = $client->login("user", "pass");
$issueId = $inputkey;
$issue = $client->getIssue($token, $issueId);
echo("assignee:".$issue->assignee);
echo(" created:".$issue->created);
echo(" summary:".$issue->summary);
echo(" issueid:".$issue->key);
print $inputsumm;
$stringsummary = $issue->summary;
$string = $issue->summary;
$emailsubjectregexp = preg_replace('/[a-zA-Z]+/', '', $inputsumm);
$stringsumm = ('summary ~ "' . $emailsubjectregexp . '"');
$jqlstring = $stringsumm;
$searchjql = $client->getIssuesFromJqlSearch($token, $jqlstring, 100);
function printArray ($array, $devolver = false) {
$stringa = '<pre>' . print_r($array, true) . '</pre>';
if ($devolver) return $stringa;
else echo $stringa;
}
printArray($searchjql);
print_r ($searchjql);
$key = $searchjql[0]->key;
echo $key;
$client->addComment($token, $key, array('body' => 'your comment'));
?>
If you notice, the last line contains the code to execute what I want, but with no luck. Any ideas folks?
Change the way you create the Soap client object, change :
$client = new SoapClient(NULL,
array(
"location" => "https://server.com/rpc/soap/jirasoapservice-v2?wsdl",
"uri" => "urn:xmethods-delayed-quotes",
"style" => SOAP_RPC,
"use" => SOAP_ENCODED
));
to:
$client = new SoapClient("https://jira.watchitoo.com/rpc/soap/jirasoapservice-v2?wsdl");
This should work.
Full add comment code:
$issueKey = "key-123";
$username= "JiraUser";
$password= "JiraPassword";
$jiraAddress = "https://your.jira.com/rpc/soap/jirasoapservice-v2?wsdl";
$myComment = "your comment";
$soapClient = new SoapClient($jiraAddress);
$token = $soapClient->login($username, $password);
$soapClient->addComment($token, $issueKey, array('body' => $myComment));

Categories