Hello guys I'm following this tutorial 'QuickBooks OAuth – PHP Example' to set up the api and get the data from the quickbooks. I have successfully setup the api but the problem that I'm facing now is that I'm unable to get the data from the quick books. It always returns me null even though their is alot of data present over there
Here is the code to what I'm doing.
config.php
<?php
// setting up session
/* note: This is not a secure way to store oAuth tokens. You should use a secure
* data sore. We use this for simplicity in this example.
*/
// session_save_path('./abc/temp');
session_save_path('./abc/temp');
session_start();
echo "<h4>If you see a Session warning above you need to run the command: 'chmod 777 temp' in the terminal on the code page. </h4>";
define('OAUTH_CONSUMER_KEY', 'some key');
define('OAUTH_CONSUMER_SECRET', 'some key');
if(strlen(OAUTH_CONSUMER_KEY) < 5 OR strlen(OAUTH_CONSUMER_SECRET) < 5 ){
echo "<h3>Set the consumer key and secret in the config.php file before you run this example</h3>";
}
?>
index.php
<?php
require_once("./config.php");
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Connect Page</title>
<script type="text/javascript" src="https://appcenter.intuit.com/Content/IA/intuit.ipp.anywhere.js"></script>
<script>
// Runnable uses dynamic URLs so we need to detect our current //
// URL to set the grantUrl value ########################### //
/*######*/ var parser = document.createElement('a');/*#########*/
/*######*/parser.href = document.url;/*########################*/
// end runnable specific code snipit ##########################//
intuit.ipp.anywhere.setup({
menuProxy: '',
grantUrl: 'http://'+parser.hostname+'/QuickbooksTest/oauth.php?start=t'
// outside runnable you can point directly to the oauth.php page
});
</script>
</head>
</head>
<body>
<?php
require_once('./v3-php-sdk-2.3.0/config.php'); // Default V3 PHP SDK (v2.0.1) from IPP
require_once(PATH_SDK_ROOT . 'Core/ServiceContext.php');
require_once(PATH_SDK_ROOT . 'DataService/DataService.php');
require_once(PATH_SDK_ROOT . 'PlatformService/PlatformService.php');
require_once(PATH_SDK_ROOT . 'Utility/Configuration/ConfigurationManager.php');
error_reporting(E_ERROR | E_PARSE);
// print connect to QuickBooks button to the page
echo "<ipp:connectToIntuit></ipp:connectToIntuit><br />";
// After the oauth process the oauth token and secret
// are storred in session variables.
if(!isset($_SESSION['token'])){
echo "<h3>You are not currently authenticated</h3>";
} else {
$token = unserialize($_SESSION['token']);
$requestValidator = new OAuthRequestValidator(
$token['oauth_token'], $token['oauth_token_secret'], OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET);
$realmId = $_SESSION['realmId'];
// uncomment any of these to see more information
//echo "realmId: $realmId <br />";
//echo "oauth token: ". $token['oauth_token'] . "<br />";
//echo "oauth secret: ". $token['oauth_token'] . "<br />";
/*echo "<pre><h2>Session Variables</h2>";
var_dump($_SESSION);
echo "</pre>"; */
$serviceType = $_SESSION['dataSource'];
$serviceContext = new ServiceContext($realmId, $serviceType, $requestValidator);
$dataService = new DataService($serviceContext);
// $startPosition = 1;
// $maxResults = 10;
// $allCustomers = $dataService->FindAll('Customer', $startPosition, $maxResults);
$allCustomers = $dataService->Query("SELECT * FROM Customer");
echo "<pre><h2>Customers List</h2>";
var_dump($allCustomers);
echo "</pre>";
}
?>
</body>
</html>
UPDATED INDEx
<?php
require_once("./config.php");
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Connect Page</title>
<script type="text/javascript" src="https://appcenter.intuit.com/Content/IA/intuit.ipp.anywhere.js"></script>
<script>
// Runnable uses dynamic URLs so we need to detect our current //
// URL to set the grantUrl value ########################### //
/*######*/ var parser = document.createElement('a');/*#########*/
/*######*/parser.href = document.url;/*########################*/
// end runnable specific code snipit ##########################//
intuit.ipp.anywhere.setup({
menuProxy: '',
grantUrl: 'http://'+parser.hostname+'/testProject/oauth.php?start=t'
// outside runnable you can point directly to the oauth.php page
});
</script>
</head>
</head>
<body>
<intuit>
<ipp>
<logger>
<!-- To enable/disable Request and Response log-->
<requestLog enableRequestResponseLogging="true" requestResponseLoggingDirectory="C:\IdsLogs" />
</logger>
</ipp>
</intuit>
<?php
require_once('./v3-php-sdk-2.3.0/config.php'); // Default V3 PHP SDK (v2.0.1) from IPP
require_once(PATH_SDK_ROOT . 'Core/ServiceContext.php');
require_once(PATH_SDK_ROOT . 'DataService/DataService.php');
require_once(PATH_SDK_ROOT . 'PlatformService/PlatformService.php');
require_once(PATH_SDK_ROOT . 'Utility/Configuration/ConfigurationManager.php');
require_once(PATH_SDK_ROOT . 'QueryFilter/QueryMessage.php');
error_reporting(E_ERROR | E_PARSE);
// print connect to QuickBooks button to the page
echo "<ipp:connectToIntuit></ipp:connectToIntuit><br />";
// After the oauth process the oauth token and secret
// are storred in session variables.
if(!isset($_SESSION['token'])){
echo "<h3>You are not currently authenticated</h3>";
} else {
$token = unserialize($_SESSION['token']);
$requestValidator = new OAuthRequestValidator(
$token['oauth_token'], $token['oauth_token_secret'], OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET);
$realmId = $_SESSION['realmId'];
error_log($realmId);
// uncomment any of these to see more information
//echo "realmId: $realmId <br />";
//echo "oauth token: ". $token['oauth_token'] . "<br />";
//echo "oauth secret: ". $token['oauth_token'] . "<br />";
/*echo "<pre><h2>Session Variables</h2>";
var_dump($_SESSION);
echo "</pre>"; */
// error_log("Value in dataSource session is: " . $_SESSION['dataSource']);
// $serviceType = $_SESSION['dataSource']; //5:15 PM
$serviceType = IntuitServicesType::QBO; //5:16 PM
$serviceContext = new ServiceContext($realmId, $serviceType, $requestValidator);
$dataService = new DataService($serviceContext);
// $startPosition = 1;
// $maxResults = 10;
// $allCustomers = $dataService->FindAll('Customer', $startPosition, $maxResults);
// $allCustomers = $dataService->Query("SELECT * FROM Customer");
$allCustomers = $dataService->FindAll('Customer');
// $oneQuery = new QueryMessage();
// $oneQuery->sql = "SELECT";
// $oneQuery->entity = "Customer";
// $oneQuery->orderByClause = "FamilyName";
// Run a query
// $queryString = $oneQuery->getString();
// $allCustomers = $dataService->Query($queryString);
// $ch = curl_init("http://www.example.com/");
// $fp = fopen("example_homepage.txt", "w");
// curl_setopt($ch, CURLOPT_FILE, $fp);
// curl_setopt($ch, CURLOPT_HEADER, 0);
// curl_exec($ch);
// curl_close($ch);
// fclose($fp);
echo "<pre><h2>Customers List</h2>";
var_dump($allCustomers);
echo "</pre>";
}
?>
</body>
</html>
***APP.CONFIG*
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<intuit>
<ipp>
<!--Json serialization not supported in PHP SDK v2.0.0 -->
<message>
<request serializationFormat="Xml" compressionFormat="None"/>
<response serializationFormat="Xml" compressionFormat="None"/>
</message>
<service>
<baseUrl qbd="https://quickbooks.api.intuit.com/" qbo="https://quickbooks.api.intuit.com/" ipp="https://appcenter.intuit.com/api/" />
</service>
<logger>
<!-- To enable/disable Request and Response log-->
<requestLog enableRequestResponseLogging="true" requestResponseLoggingDirectory="./IdsLogs" />
</logger>
</ipp>
</intuit>
</configuration>
Related
I'd like to change my tags of a YouTube video using the YouTube Data API. But I'm already stuck on login:
My page shows the message: You need to authorize access before proceeding. I click on authorize access and select my Google account and then my YouTube channel, I select allow and get redirected to the login message.
The code is directly from the sample files on Github:
<?php
/**
* This sample adds new tags to a YouTube video by:
*
* 1. Retrieving the video resource by calling the "youtube.videos.list" method
* and setting the "id" parameter
* 2. Appending new tags to the video resource's snippet.tags[] list
* 3. Updating the video resource by calling the youtube.videos.update method.
*
* #author Ibrahim Ulukaya
*/
/**
* Library Requirements
*
* 1. Install composer (https://getcomposer.org)
* 2. On the command line, change to this directory (api-samples/php)
* 3. Require the google/apiclient library
* $ composer require google/apiclient:~2.0
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
session_start();
/*
* You can acquire an OAuth 2.0 client ID and client secret from the
* {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
* For more information about using OAuth 2.0 to access Google APIs, please see:
* <https://developers.google.com/youtube/v3/guides/authentication>
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$OAUTH2_CLIENT_ID = 'myID';
$OAUTH2_CLIENT_SECRET = 'mySec';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
$htmlBody = '';
try{
// REPLACE this value with the video ID of the video being updated.
$videoId = "Zqt-NvuMKYU";
// Call the API's videos.list method to retrieve the video resource.
$listResponse = $youtube->videos->listVideos("snippet",
array('id' => $videoId));
// If $listResponse is empty, the specified video was not found.
if (empty($listResponse)) {
$htmlBody .= sprintf('<h3>Can\'t find a video with video id: %s</h3>', $videoId);
} else {
// Since the request specified a video ID, the response only
// contains one video resource.
$video = $listResponse[0];
$videoSnippet = $video['snippet'];
$tags = $videoSnippet['tags'];
// Preserve any tags already associated with the video. If the video does
// not have any tags, create a new list. Replace the values "tag1" and
// "tag2" with the new tags you want to associate with the video.
if (is_null($tags)) {
$tags = array("tag1", "tag2");
} else {
array_push($tags, "tag1", "tag2");
}
// Set the tags array for the video snippet
$videoSnippet['tags'] = $tags;
// Update the video resource by calling the videos.update() method.
$updateResponse = $youtube->videos->update("snippet", $video);
$responseTags = $updateResponse['snippet']['tags'];
$htmlBody .= "<h3>Video Updated</h3><ul>";
$htmlBody .= sprintf('<li>Tags "%s" and "%s" added for video %s (%s) </li>',
array_pop($responseTags), array_pop($responseTags),
$videoId, $video['snippet']['title']);
$htmlBody .= '</ul>';
}
} catch (Google_Service_Exception $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'REPLACE_ME') {
$htmlBody = <<<END
<h3>Client Credentials Required</h3>
<p>
You need to set <code>\$OAUTH2_CLIENT_ID</code> and
<code>\$OAUTH2_CLIENT_ID</code> before proceeding.
<p>
END;
} else {
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>Video Updated</title>
</head>
<body>
<?=$htmlBody?>
</body>
</html>
Would be great if someone has a tip for me.
Fixed... was a space key inside secret
Although, we'd prepared YouTube channel art upload mechanism as described on the it's official documentation page, (https://developers.google.com/youtube/v3/docs/channelBanners/insert), from few days, we are facing following error,
A service error occurred: { "error": { "errors": [ { "domain": "global", "reason": "backendError", "message": "Backend Error" } ], "code": 500, "message": "Backend Error" } }
Which was perfectly working before.
/**
* This sample sets a custom banner for a user's channel by:
*
* 1. Uploading a banner image with "youtube.channelBanners.insert" method via resumable upload
* 2. Getting user's channel object with "youtube.channels.list" method and "mine" parameter
* 3. Updating channel's banner external URL with "youtube.channels.update" method
*
* #author Ibrahim Ulukaya
*/
/**
* Library Requirements
*
* 1. Install composer (https://getcomposer.org)
* 2. On the command line, change to this directory (api-samples/php)
* 3. Require the google/apiclient library
* $ composer require google/apiclient:~2.0
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
session_start();
//session_destroy();
/*
* You can acquire an OAuth 2.0 client ID and client secret from the
* {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
* For more information about using OAuth 2.0 to access Google APIs, please see:
* <https://developers.google.com/youtube/v3/guides/authentication>
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$OAUTH2_CLIENT_ID = 'OUR_CLIENT_ID';
$OAUTH2_CLIENT_SECRET = 'OUR_CLIENT_SECRET';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
$htmlBody = '';
try{
// REPLACE with the path to your file that you want to upload for thumbnail
$imagePath = "2560x1440-pixels-image.jpg";
$imageSize = get_headers($imagePath, 1);
// Specify the size of each chunk of data, in bytes. Set a higher value for
// reliable connection as fewer chunks lead to faster uploads. Set a lower
// value for better recovery on less reliable connections.
$chunkSizeBytes = 1 * 1024 * 1024;
// Setting the defer flag to true tells the client to return a request which can be called
// with ->execute(); instead of making the API call immediately.
$client->setDefer(true);
$chan = new Google_Service_YouTube_ChannelBannerResource();
// Create a request for the API's channelBanners.insert method to upload the banner.
$insertRequest = $youtube->channelBanners->insert($chan);
// Create a MediaFileUpload object for resumable uploads.
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'image/jpeg',
null,
true,
$chunkSizeBytes
);
//$media->setFileSize(filesize($imagePath));
$media->setFileSize($imageSize["Content-Length"]);
// Read the media file and upload it chunk by chunk.
$status = false;
$handle = fopen($imagePath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($handle);
// If you want to make other calls after the file upload, set setDefer back to false
$client->setDefer(false);
$thumbnailUrl = $status['url'];
// Call the API's channels.list method with mine parameter to fetch authorized user's channel.
$listResponse = $youtube->channels->listChannels('brandingSettings', array(
'mine' => 'true',
));
/*echo '<pre>';
print_r($listResponse);
echo '</pre>';*/
$responseChannel = $listResponse[0];
$responseChannel['brandingSettings']['image']['bannerExternalUrl']=$thumbnailUrl;
// Call the API's channels.update method to update branding settings of the channel.
$updateResponse = $youtube->channels->update('brandingSettings', $responseChannel);
$bannerMobileUrl = $updateResponse["brandingSettings"]["image"]["bannerMobileImageUrl"];
$htmlBody .= "<h3>Thumbnail Uploaded</h3><ul>";
$htmlBody .= sprintf('<li>%s</li>',
$thumbnailUrl);
$htmlBody .= sprintf('<img src="%s">', $bannerMobileUrl);
$htmlBody .= '</ul>';
} catch (Google_Service_Exception $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'OUR_CLIENT_ID') {
$htmlBody = <<<END
<h3>Client Credentials Required</h3>
<p>
You need to set <code>\$OAUTH2_CLIENT_ID</code> and
<code>\$OAUTH2_CLIENT_ID</code> before proceeding.
<p>
END;
} else {
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>Banner Uploaded and Set</title>
</head>
<body>
<?=$htmlBody?>
</body>
</html>
Any suggestions?
I am following the tutorial on https://www.twilio.com/docs/api/rest/change-call-state#post I am coding in php the portion that allows you to forward a current inbound call to a new Twiml URL. I am finding that in order for this to work, I have to specify a To and From parameter in the update array. I need the call forwarded to the URL specified not the number specified in the To parameter. However, the Twilio API throws an error that says the To parameter is required but the docs indicate that it is not. Is there something I am doing wrong here?
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once('TwilioAPI/twilio-php-master/Services/Twilio.php'); // Loads the library
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = 'XXXXXXX';
$token = 'XXXXXXX';
$callSid = $_POST['CallSid'];
$client = new Services_Twilio($sid, $token);
// Get an object from its sid. If you do not have a sid,
// check out the list resource examples on this page
$call = $client->account->calls->get($callSid);
$call->update(array(
"Url" => "http://ftstoo.com/Phone/TheFinalTouchSecurity/forwardToBob.xml",
"Method" => "POST"
));?>
forwardToBob.xml contains a Response with a Say Verb.
This php code (not the twiml) throws the error
Uncaught exception 'Services_Twilio_RestException' with message 'No 'To' number is specified' in /home/wcmtechnologies/public_html/Phone/TheFinalTouchSecurity/TwilioAPI/twilio-php-master/Services/Twilio.php:297
If I add
"To" => "Some Ten Digit Phone Number",
"From" => "Some Ten Digit Phone Number",
to the array, the error is not thrown. The call is then directed to the "To" phone number. If the phone number specified in the "To" parameter answers, then the call is connected AND the twiml at forwardToBob.xml executes all at the same time.
EDIT # 3----------------------------------------------------------------------
Here is my entire code....
This is the Twiml that is executed everytime the Twilio verified number is called. I got this code from the Twilio quickstart site.
<?php
header('Content-type: text/xml');
$callerId = "+19012311158";
// put your default Twilio Client name here, for when a phone number isn't given
$number = "Bob";
// get the phone number from the page request parameters, if given
if (isset($_REQUEST['PhoneNumber'])) {
$number = htmlspecialchars($_REQUEST['PhoneNumber']);
}
// wrap the phone number or client name in the appropriate TwiML verb
// by checking if the number given has only digits and format symbols
if (preg_match("/^[\d\+\-\(\) ]+$/", $number)) {
$numberOrClient = "<Number>" . $number . "</Number>";
} else {
$numberOrClient = "<Client>" . $number . "</Client>";
}
?>
<Response>
<Dial callerId="<?php echo $callerId ?>">
<?php echo $numberOrClient ?>
</Dial>
</Response>
This is the client browser which I mostly copied from the Twilio quickstart site.
<?php
include 'TwilioAPI/twilio-php-master/Services/Twilio/Capability.php';
// put your Twilio API credentials here
$accountSid = 'XXXXXXXX';
$authToken = 'XXXXXXXX';
// put your Twilio Application Sid here
$appSid = 'XXXXXXXXXXXXX';
// put your default Twilio Client name here
$clientName = 'Bob';
// get the Twilio Client name from the page request parameters, if given
if (isset($_REQUEST['client'])) {
$clientName = $_REQUEST['client'];
}
$capability = new Services_Twilio_Capability($accountSid, $authToken);
$capability->allowClientOutgoing($appSid);
$capability->allowClientIncoming($clientName);
$token = $capability->generateToken();
?>
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script type="text/javascript"
src="//static.twilio.com/libs/twiliojs/1.2/twilio.min.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<link href="http://static0.twilio.com/bundles/quickstart/client.css"
type="text/css" rel="stylesheet" />
<script type="text/javascript">
var callSid = "";
Twilio.Device.setup("<?php echo $token; ?>");
Twilio.Device.ready(function (device) {
$("#log").text("Client '<?php echo $clientName ?>' is ready");
});
Twilio.Device.error(function (error) {
$("#log").text("Error: " + error.message);
});
Twilio.Device.connect(function (conn) {
callSid = conn.parameters.CallSid;
$("#log").text("Successfully established call");
});
Twilio.Device.disconnect(function (conn) {
$("#log").text("Call ended");
});
Twilio.Device.incoming(function (conn) {
$("#log").text("Incoming connection from " + conn.parameters.From);
// accept the incoming connection and start two-way audio
conn.accept();
});
Twilio.Device.presence(function (pres) {
if (pres.available) {
// create an item for the client that became available
$("<li>", {id: pres.from, text: pres.from}).click(function () {
$("#number").val(pres.from);
call();
}).prependTo("#people");
}
else {
$("#" + pres.from).remove();
}
});
function call() {
// get the phone number or client to connect the call to
params = {"PhoneNumber": $("#number").val()};
Twilio.Device.connect(params);
}
function forward() {
var xmlhttp = new XMLHttpRequest();
params = "?CallSid=" + callSid + "&ForwardTo=" + document.getElementById("number").value;
xmlhttp.open("POST","forward.php" + params,false);
xmlhttp.send();
document.getElementById("log").innerHTML=xmlhttp.responseText;
}
function hangup() {
Twilio.Device.disconnectAll();
}
</script>
</head>
<body>
<button class="call" onclick="call();">
Call
</button>
<button class="hangup" onclick="hangup();">
Hangup
</button>
<input type="text" id="number" name="number"
placeholder="Enter a phone number or client to call"/>
<button class="call" onclick="forward();">
Forward
</button>
<div id="log">Loading pigeons...</div>
<ul id="people"/>
</body>
</html>
This is the forwarding code that is called via an HTTP POST request from my forward() function.
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once('TwilioAPI/twilio-php-master/Services/Twilio.php'); // Loads the library
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = 'XXXXXX';
$token = 'XXXXXX';
$callSid = $_POST['CallSid'];
$client = new Services_Twilio($sid, $token);
// Get an object from its sid. If you do not have a sid,
// check out the list resource examples on this page
$call = $client->account->calls->get($callSid);
$call->update(array(
"Url" => "http://ftstoo.com/Phone/TheFinalTouchSecurity/forwardToBob.xml",
"Method" => "POST"
));
The first code snippet shows the Twiml that is executed when 901-231-1158 is called. It is then directed to the Client "Bob". Once the connection is successful, I press the forward button which I added in. This forward button calls the forward function which then makes an HTTP POST request to the PHP script which is the last snippet. Upon executing, if I do not have the "To" and "From" parameters specified in the array for the update function, I receive an error. Any suggestions on what I should try to fix this would help very much!
PLEASE NOTE: The button that I created in HTML is called Forward and it calls the function forward() which I created. I am getting the call Sid and saving it in an instance variable. I retrieve this value in the Twilio.Device.Connect function.
The full stack trace.
Stack trace:
#0 /home/wcmtechnologies/public_html/Phone/TheFinalTouchSecurity/TwilioAPI/twilio-php-master/Services/Twilio.php(180): Base_Services_Twilio->_processResponse(Array)
#1 /home/wcmtechnologies/public_html/Phone/TheFinalTouchSecurity/TwilioAPI/twilio-php-master/Services/Twilio/InstanceResource.php(31): Base_Services_Twilio->createData('/2010-04-01/Acc...', Array)
#2 /home/wcmtechnologies/public_html/Phone/TheFinalTouchSecurity/forward.php(22): Services_Twilio_InstanceResource->update(Array)
#3 {main}
thrown in /home/wcmtechnologies/public_html/Phone/TheFinalTouchSecurity/TwilioAPI/twilio-php-master/Services/Twilio.php on line 297
[12-Jun-2015 00:19:39 UTC] PHP Fatal error: Uncaught exception 'Services_Twilio_RestException' with message 'No 'To' number is specified' in /home/wcmtechnologies/public_html/Phone/TheFinalTouchSecurity/TwilioAPI/twilio-php-master/Services/Twilio.php:297
Twilio developer evangelist here.
Thanks for all the details, I managed to put together most of what you were trying to do in order to find the errors. I never received the error message you had though, so bare that in mind.
I found I had to change the following parts of your code to get this to work.
In your XHR request, stop trying to make the request synchronously (I was using Firefox and it was deprecated), just use:
xmlhttp.open("POST","forward.php" + params);
I was also not getting the call sid from the XHR request in my PHP, so I changed $_POST to $_REQUEST and that started to work.
Finally, the call sid on the client side is not the same as the originating call sid. That is the parent call and you can get hold of it like this using the twilio-php helper library:
$callSid = $_REQUEST['CallSid'];
$client = new Services_Twilio($sid, $token);
// Get an object from its sid. If you do not have a sid,
// check out the list resource examples on this page
$call = $client->account->calls->get($callSid);
$parentCall = $client->account->calls->get($call->parent_call_sid);
$parentCall->update(array(
"Url" => "http://ftstoo.com/Phone/TheFinalTouchSecurity/forwardToBob.xml",
"Method" => "POST"
));
You then need to update the parent call to forward it on to your original URL and hang up on the client side.
I hope this helps!
I'm using an old version of symfony 1.0.11
slot('breadcrumbs');
include_component('page','breadcrumbs',array('past_pages'=>array(
'/module/action/parameter/value'=>'Home ')));
end_slot();
The problem with this code is that parameter and value do not get passed, so If i click on home i get /module/action but the parameters are not being passed. Any suggestions?
Thanks.
There is also a way automatically set the breadcrumbs this is in the breadcrumbs actions:
// Get the full path without get parameters
$fullPath = $request->getPathInfo();
// get the get parameters
$urlParams = $request->getGetParameters();
// set get parameters as string for url
$this->extend = "";
foreach ($urlParams as $key => $urlParam) {
if (empty($this->extend)) {
$this->extend = "?";
}
this->extend .= $key."=".$urlParam;
}
// Get the URL path and Explode by /
$paths = explode('/', $fullPath);;
$this->paths = $paths;
then in the component itself, you can foreach through the paths and if empty just continue. And always give the GET variables with the link if the browser has some.
Home
<?php foreach($paths as $path):
if(empty($path))
continue;
if(empty($fullPath))
$fullPath = "";
$fullPath .= "/".$path.$extend;
$path = str_replace("-", " ", $path);
?>
<?php if(key($paths->getRawValue()) != (count($paths)-1)): ?>
<?php echo ucwords($path); ?>
<?php else: ?>
<span><?php echo ucwords($path); ?></span>
<?php endif; ?>
This way you never have to set your breadcrumbs if you have a correct url structure.
the way i fixed it is
include_component('page','breadcrumbs',array('past_pages'=>array(
'/module/action?parameter=value'=>'Home ')));
I was using basic auth to send tweets from a server every time a song changed. Now they have blocked basic auth and I am not sure how to incorporate it. I have a server at home that updates an html file on the webserver and then calls the following script to tweet out from that file. Any ideas on how to accomplish this simply?
<?php
//====================================================
// CONFIGURATION
//====================================================
// YOUR TWITTER USERNAME AND PASSWORD
$username = '#####';
$password = '#####';
DEFINE(htmlfile, '/homec/public_html/site.com/twitter.html');
$stationURL = "http://www.site.com";
$maxLimit = "139";
$da="";
$f=#fopen(htmlfile, "r");
if ($f!=0)
{
$da=#fread($f, 4096);
fclose($f);
}
else
{
exit;
}
$da=str_replace("\r", "\n", $da);
$da=str_replace("\n\n", "\n", $da);
$d=explode("\n", $da);
$d[0]=trim($d[0], "|"); // title
$d[1]=trim($d[1], "|"); // artist
//====================================================
if ($d[0]=="" || $d[1]=="")
{
// IF WE COULD NOT GRAB THE ARTIST AND
// SONG TITLE FROM THE SAM-GENERATED HTML FILE,
// WE'LL BAIL OUT NOW WITHOUT SUBMITTING ANY TEXT
// TO TWITTER.
exit;
}
else
{
// SUCCESS IN GETTING ARTIST AND TITLE!
// WE'LL PROCEED WITH BUILDING A TEXT STRING TO SUBMIT TO TWITTER.
$message = urlencode('' . $d[1] . ' - ' . $d[0] . ' #bandradio #nowplaying ');
$stationURL = urlencode(' ' . $stationURL);
if ((strlen($message) + strlen($stationURL)) > $maxLimit)
{
// We have to truncate the artist-title string to make room for the station URL string.
$message = substr($message, 0, (($maxLimit - 2) - strlen($stationURL)));
$message .= ".." . $stationURL;
}
else
{
// No need to truncate, it all fits.
$message = $message . $stationURL;
}
} // if ($d[0]=="" || $d[1]=="")
//====================================================
// The twitter API address
$url = 'http://twitter.com/statuses/update.json';
// Set up and execute the curl process
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, "$url");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
//curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$message");
//curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");
$buffer = curl_exec($curl_handle);
$resultArray = curl_getinfo($curl_handle);
curl_close($curl_handle);
Download the latest version of TwitterOAuth from http://github.com/abraham/twitteroauth/downloads Unpack the download and place the twitteroauth.php and OAuth.php files in the same directory as a file with the following code. Register an application at http://dev.twitter.com/apps and from your new apps details page click on "my access token" to get your access token. Fill the four required variables into the script below and you can then run it to post new tweets.
<?php
require_once('twitteroauth.php');
$connection = new TwitterOAuth('app consumer key', 'app consumer secret', 'my access token', 'my access token secret');
$connection->post('statuses/update', array('status' => 'text to be tweeted'));