I am trying to get a list of all my Twilio numbers using cURL inside of a php function. I am getting the information I need back from Twilio however it is just a string of all the information with no whitespace or anything.
This is what I am getting back. I have removed my account number and sid:
string(1621) " {{ SID }}ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX(936) 585-6544+19365856544https://demo.twilio.com/welcome/sms/reply/POSTPOSTfalseWed, 11 May 2016 14:39:22 +0000Wed, 18 May 2016 15:41:25 +0000https://demo.twilio.com/welcome/sms/reply/POSTPOSTnonefalsetruetruetruePOST2010-04-01/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers/PN5e0ef24464a1fbbcf4e2bd127c471892"
Here is the function I am using to cURL Twilio.
function post_incoming($POST) {
// resource url & authentication
$uri = 'https://api.twilio.com/2010-04-01/Accounts/' . $this->sid . '/IncomingPhoneNumbers';
$auth = $this->sid . ':' . $this->authtoken;
$res = curl_init();
// set cURL options
curl_setopt( $res, CURLOPT_URL, $uri );
curl_setopt( $res, CURLOPT_USERPWD, $auth ); // authenticate
curl_setopt( $res, CURLOPT_RETURNTRANSFER, true ); // don't echo
// send cURL
$result = curl_exec( $res );
var_dump($result);
return $result;
}
I need to get the information back as a json array or some kind of array that way I can parse out the Twilio phone number for later.
It is a lot easier if you use the PHP helper library. It woudl look something like this:
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token = "{{ auth_token }}";
$client = new Services_Twilio($sid, $token);
$numbers_arr = array();
// Loop over the list of numbers and echo a property for each one
foreach ($client->account->incoming_phone_numbers as $number) {
$numbers_arr[] = $number->phone_number;
}
return json_encode($numbers_arr);
}
This function uses the Twilio PHP SDK to get a list of all numbers in the account then puts them into an array variable $numbers_arr and returns that variable as JSON.
I am using YQL to pull some data for my yahoo fantasy football league. I have created the app and it gave me a consumer/secret key but how do I pass this information to the yahoo api to log me in? I know I have to use OAuth but I am not sure how to use the key in tandem with CURL and YQL
Here is my PHP Code:
<pre>
<?php
$BASE_URL = "https://query.yahooapis.com/v1/public/yql";
// Form YQL query and build URI to YQL Web service
$yql_query = "select * from fantasysports.leagues.standings where league_key='331.l.777400'";
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
// Make call with cURL
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
var_dump($phpObj);
?>
</pre>
and the error I get is
"Authentication Error. The table fantasysports.leagues.standings
requires a higher security level than is provided, you provided ANY
but at least USER is expected"
I need to import quotes into vtiger.
I find out it can be be done using vtiger web services API
I find out the reference manual:
https://wiki.vtiger.com/archives/index.php/vtiger510:Webservice_reference_manual
But i can't find any example PHP script, neither what data fields I need to pass to webservice.php.
Please help, I need some guidance.
I have done something like this, I have a quick and (rather) dirty but working solution:
<?php
function createOffer($account_id,$subject,$offerlanguage, $totalamount,$date_submission,$date_decision,$date_start,$assigned_user_id,$quotestage,$winningchance,$description,$productarray){
global $adb;
$endpointUrl = "[your URL]/webservice.php";
$userName="admin";
$userAccessKey = '[your accesskey]';
$httpc = new HTTP_CLIENT();
//getchallenge request must be a GET request.
$httpc->GET($endpointUrl."?operation=getchallenge&username=".$userName);
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);
//check for whether the requested operation was successful or not.
if($jsonResponse['success']==false)
//handle the failure case.
die('getchallenge failed:'.$jsonResponse['error']['errorMsg']);
//operation was successful get the token from the reponse.
$challengeToken = $jsonResponse['result']['token'];
//create md5 string concatenating user accesskey from my preference page
//and the challenge token obtained from get challenge result.
$generatedKey = md5($challengeToken.$userAccessKey);
//getchallenge request must be a GET request.
$httpc->post("$endpointUrl",
array('operation'=>'login', 'username'=>$userName, 'accessKey'=>$generatedKey), true);
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);
//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
//handle the failure case.
die('login failed:'.$jsonResponse['error']['errorMsg']);
//login successful extract sessionId and userId from LoginResult to it can used for further calls.
$sessionId = $jsonResponse['result']['sessionName'];
$userId = $jsonResponse['result']['userId'];
$currency_id=1;
$params = array('description'=>$description,'subject'=>$subject,'quotestage'=>$quotestage,'assigned_user_id'=>'2x'.$assigned_user_id,'account_id'=>'3x'.$account_id,'cf_682'=>$offerlanguage,'currency_id'=>'21x'.$currency_id,'taxtype'=>'group','cf_683'=>$date_submission,'cf_684'=>$date_decision,'cf_685'=>$date_start,'cf_766'=>$winningchance);
$urlArgs = "?&total=".$totalamount;
//encode the object in JSON format to communicate with the server.
$objectJson = Zend_JSON::encode($params);
//name of the module for which the entry has to be created.
$moduleName = 'Quotes';
//sessionId is obtained from loginResult.
$params = array("sessionName"=>$sessionId, "operation"=>'create', "element"=>$objectJson, "elementType"=>$moduleName);
//Create must be POST Request.
$httpc->post($endpointUrl.$urlArgs, $params, true);
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);
$savedObject = $jsonResponse['result'];
$id = $savedObject['id'];
$id=str_replace("13x", "", $id);
echo $id." offer: ".$subject." created for amount ".$totalamount." for customer: ".$account_id." assigned to: ".$assigned_user_id;
return $id;
}
As you see there are a few custom fields too so you can see how I've handled those.
You can call this function like this:
createOffer($account_id, $subject, $offerlanguage, $totalamount, $date_submission, $date_decision, $date_start, $assigned_user_id, $quotestage, $winningchance, $description, $productarray)
Then you need to add the products too, which I've found the easiest via a separate function as there can be more products per quote...
<?php
function createProducts($productarray,$id) {
$counter = 1;
foreach ($productarray as $prod) {
$query ="insert into vtiger_inventoryproductrel(id, productid, sequence_no, quantity, listprice) values(?,?,?,?,?)";
$qparams = array($id,$prod['prod'],$counter,$prod['pcs'],$prod['price']);
$productadded=$adb->pquery($query,$qparams);
$counter=$counter+1;
}
}
use it like this:
$prodlist = array();
array_push($prodlist,array('prod'=>"prod1",'pcs'=>2,'price'=>1000));
array_push($prodlist,array('prod'=>"prod2",'pcs'=>2,'price'=>100));
createProducts($prodlist,10);
so my logic is like this:
you create the quote with the createOffer function. It returns with the newly created quote's ID
then you build the array of products (I have just the very basic data here) and add that by referencing the quote's ID
Maybe not the most beautiful solution but works.
Maybe you can start like this (according to your reference link).
Manual: https://wiki.vtiger.com/archives/index.php/vtiger510:Webservice_reference_manual
Login: https://wiki.vtiger.com/archives/index.php/vtiger510:Webservice_reference_manual#Login
Pseudo;
<?php
class VTiger_Login
{
private $serviceURL = 'http://vtiger_url/webservice.php?operation=login&username=%s&accessKey=%s';
// A Vtiger username.
private $userName = 'my_username';
// An md5 of the concatenation of the challenge token and the user's webservice access key.
private accessKey = 'my_accesskey';
public function login() {
// Open CURL
$ch = curl_init();
// Set URL as same as on manual
curl_setopt($ch, CURLOPT_URL, sprintf($this->serviceURL, $this->userName, $this->accessKey));
// Need POST according to manual
curl_setopt($ch, CURLOPT_POST, 1);
// Receive server response = TRUE
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Exec CURL
$result = curl_exec($ch);
// Close CURL
curl_close($ch);
/*
$result should be like this according to manual;
LoginResult {
sessionId: String // Unique Identifier for the session
userId: String // The vtiger id for the logged in user
version: String // The version of the webservices api
vtigerVersion: String // The version of the vtiger crm.
}
*/
// From manual: All structural data including response from the api is represented as JSON strings.
$result =# json_decode($result);
// See "Response" on manual
if (null === $result) {
throw new Exception('No response returned from Vtiger server!');
}
// See "ErrorObject" on manual
if (null !== $result->success && false === $result->success) {
throw new Exception('Something went wrong with login operation! errorCode: '.
$result->errorCode .', errorMessage: '. $result->errorMessage);
}
// I think, there is no problem anymore, go with $result after this line...
}
}
I have integrated Facebook Like into my website.Now i need to get/list the count of the Facebook like in the Admin panel of my website. Is there any way to get this done?Need suggestions.Thanks in advance.
$url = 'http://graph.facebook.com/PAGE_OR_APP_ID';
echo '['.$url.']: '.json_decode(file_get_contents($url))->{'likes'};
In order to get the number of likes of any object using Facebook API, use a Facebook API of your choice and commands like this:
https://graph.facebook.com/< your object id>/
You will receive a JSON object and you can extract the number of likes from it:
{
"id": "567454",
"link": "http://www.facebook.com/pages/PHP-Developer/103146756409401",
"likes": 250,
"type": "page"
}
More info on https://developers.facebook.com/docs/reference/api/
The more direct / updated link for this topic on facebook is
https://developers.facebook.com/docs/reference/api/page/
function fbLikeCount($appid,$appsecret){
//Construct a Facebook URL
$json_url ='https://graph.facebook.com/'.$appid.'?access_token='.$appsecret;
$json = file_get_contents($json_url);
$json_output = json_decode($json);
//Extract the likes count from the JSON object
if($json_output->likes){
return $likes = $json_output->likes;
}else{
return 0;
}
}
Facebook - <?php echo fbLikeCount('app/page id here','token here'); ?>
You can achieve that using the Graph API (v3)
function checkFacebookReactions($url){
$access_token = 'YOUR-FACEBOOK-TOKEN'; // Generate a Facebook Token first
$api_url = 'https://graph.facebook.com/v3.0/?id=' . urlencode( $url ) . '&fields=engagement&access_token=' . $access_token;
$fb_connect = curl_init(); // initializing
curl_setopt( $fb_connect, CURLOPT_URL, $api_url );
curl_setopt( $fb_connect, CURLOPT_RETURNTRANSFER, 1 ); // return the result, do not print
curl_setopt( $fb_connect, CURLOPT_TIMEOUT, 20 );
$json_return = curl_exec( $fb_connect ); // connect and get json data
curl_close( $fb_connect ); // close connection
$body = json_decode( $json_return );
// Print each key values, if needed
foreach($body->engagement as $k=>$v){
echo $k .": " .$v ."<br>";
}
$count = $body->engagement->reaction_count; // Return only reactions (likes + other reactions)
return $count;
}
$url = "REPLACE-WITH-YOUR-URL"; // The url you want to fetch details from
checkFacebookReactions($url);
First, you will need to generate a Facebook token. You can fin plenty of resources that explain how to get a token. This one will do the trick: https://elfsight.com/blog/2017/10/how-to-get-facebook-access-token
I wrote a function that uses YQL to pull stock info as follows:
function quote_func() {
$BASE_URL = "https://query.yahooapis.com/v1/public/yql";
// Form YQL query and build URI to YQL Web service
$yql_query = "select * from yahoo.finance.quotes where symbol in ('AAPL')";
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json&env=http://datatables.org/alltables.env&callback=";
// Make call with cURL
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
// Confirm that results were returned before parsing
if(!is_null($phpObj->query->results)){
$quote = $phpObj->query->results->quote;
return $quote;
}
}
I then display the information I want using:
<?php echo quote_func()->DATA-I-WANT; ?>
I know that this is bad because each time I use the function I'm executing a GET request.
Can someone point me in the right direction at least?
I'd suggest that you cache the result. You could store the data in a database but the best place is probably a proper cache like memcached, APC or even just the filesystem.
Here's a dead simple filesystem implementation (untested and just for illustration).
$cacheFile = '/tmp/myCache.txt';
$expirePeriod = 1800; // in seconds
if (file_exists($cacheFile) && time() - filemtime() < $expirePeriod) {
$quoteData = file_get_contents($cacheFile);
} else {
$quoteData = quote_func();
file_put_contents($cacheFile, $quoteData);
}