Twitter API - Fetching tweets fails to get tweets on occasion - php

I've got a script that I use in PHP to write tweets to a text file and use them on my website. I've also set up a cron job that will hourly run the script and fetch the latest tweets. This works and is set up correctly.
However, I'm noticing that sometimes it fails to get any tweets and writes to the file leaving it as 0KB and thus I get my clients ringing me saying it's broken.
Has anyone else experience this problem with the twitter API?
Here's the script:
<?php
session_start();
require_once("twitteroauth-master/twitteroauth/twitteroauth.php");
//Path to twitteroauth library
$twitteruser = "Username";
$notweets = 10;
$consumerkey = "****";
$consumersecret = "****";
$accesstoken = "*****";
$accesstokensecret = "*****";
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
//Check twitter response for errors.
if ( isset( $tweets->errors[0]->code )) {
// If errors exist, print the first error for a simple notification.
echo "Error encountered: ".$tweets->errors[0]->message." Response code:" .$tweets->errors[0]->code;
} else {
// No errors exist. Write tweets to json/txt file.
$url = "/var/www/html/etc etc etc";
$file = $url.$twitteruser."-tweets.txt";
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, json_encode($tweets));
fclose($fh);
if (file_exists($file)) {
echo $file . " successfully written (" .round(filesize($file)/1024)."KB)";
} else {
echo "Error encountered. File could not be written.";
}
}
?>

Your script is written to print the error message. You should investigate what that message was.
If you're running it from cron, you can configure cron to to catch all output and send it in an email.
You can also change the script to log the output, using error_log function or a logging library.

Related

Quickbooks Online Error PHP

When I attempt to connect to QBO via the Consolibyte package I downloaded I get an error.
Error Code: internal_error
Message: Error getting application from request token
You can contact us for further assistance. Error
Id:ixnkryec2iu513ef45f3f5xv-12940655
I have set up the config.php file as directed in the instructions and even got to the point of authorizing the application with Quickbooks but now when I navigate to the page it indicates that I am not logged in and when I click the "Connect to QuickBooks" button on the index.php page I get the error above. I'm not familiar enough with the process to know where to start troubleshooting this problem and any help would be greatly appreciated.
Link: http://production.technology-architects.com/unleashed_new/quickbook/docs/partner_platform/example_app_ipp_v3/
example_app_ipp_v3/config.php code
require_once dirname(__FILE__) . '/../../../QuickBooks.php';
$token = 'f5ddd229b1d19b4153b8218b08b97897050f';
$oauth_consumer_key = 'qyprdYvvyNLq1om6FSw0xLebctZEAz';
$oauth_consumer_secret = 'KCLYZRgZ4LnHUB35AzvylxnH6c8CDCyjhva8I9Gp';
$sandbox = true; // When you're using development tokens
$quickbooks_oauth_url = 'http://production.technology-architects.com/unleashed_new/quickbook/docs/partner_platform/example_app_ipp_v3/oauth.php';
$quickbooks_success_url = 'http://production.technology-architects.com/unleashed_new/quickbook/docs/partner_platform/example_app_ipp_v3/success.php';
$quickbooks_menu_url = 'http://production.technology-architects.com/unleashed_new/quickbook/docs/partner_platform/example_app_ipp_v3/menu.php';
$dsn = 'mysqli://myusername:mypassword#localhost/databasename';
$encryption_key = 'bcde1234';
$the_username = 'DO_NOT_CHANGE_MEddd';
$the_tenant = 'sdfaswrqwerqwr';
if (!QuickBooks_Utilities::initialized($dsn)){
QuickBooks_Utilities::initialize($dsn);
}
$IntuitAnywhere = new QuickBooks_IPP_IntuitAnywhere($dsn, $encryption_key, $oauth_consumer_key, $oauth_consumer_secret, $quickbooks_oauth_url, $quickbooks_success_url);
if ($IntuitAnywhere->check($the_username, $the_tenant) and $IntuitAnywhere->test($the_username, $the_tenant)){
$quickbooks_is_connected = true;
$IPP = new QuickBooks_IPP($dsn);
$creds = $IntuitAnywhere->load($the_username, $the_tenant);
$IPP->authMode(
QuickBooks_IPP::AUTHMODE_OAUTH,
$the_username,
$creds);
if ($sandbox){
$IPP->sandbox(true);
}
$realm = $creds['qb_realm'];
$Context = $IPP->context();
$CompanyInfoService = new QuickBooks_IPP_Service_CompanyInfo();
$quickbooks_CompanyInfo = $CompanyInfoService->get($Context, $realm);
} else {
$quickbooks_is_connected = false;
}
None of the tokens or OAuth credentials you have in your code match what you have in the screenshot.
Fix your tokens and OAuth values.
$token = 'f5ddd229b1d19b4153b8218b08b97897050f';
$oauth_consumer_key = 'qyprdYvvyNLq1om6FSw0xLebctZEAz';
$oauth_consumer_secret = 'KCLYZRgZ4LnHUB35AzvylxnH6c8CDCyjhva8I9Gp';

Getting could not connect to host error when using soap

I am using SOAP to call a web servicefrom a Linux Centos 6 server and a php client. In this week I have been getting could not connect to host error from soapCall method. My code is as below and I have not changed it at all for some months but recently it gets this error most of the time. I have read most answers to related questions here but my problem have not been solved.
$wsdl="http://x.x.x.x:x/gw/services/Service?wsdl";
//Set key as HTTP Header
$aHTTP['http']['header'] = "key:" .$key ."\r\n";
$context = stream_context_create($aHTTP);
try
{
$client = new SoapClient($wsdl,array("soap_version" => SOAP_1_2,'trace' => 1,"stream_context" => $context));
}
catch(Exception $e)
{
return "something";
}
//I make $parametrs
try
{
$res = $client->__soapCall("send",array($parametrs));
}
catch(Exception $e)
{
print_r($e->getMessage()); //Most of the time it prints could not connect to host
}
I changed SOAP from _1_1 to _1_2 but nothing changed.
This is how I call SOAP webservice, please note Service?wsdl should be Service.wsdl
Example
//Initialize values
$wsdl = "Service.wsdl";
$url = "http://x.x.x.x:x/gw/services/";
$username = "********"; //add username
$password = "********"; //add password
$client = new SoapClient("$url".$wsdl);
$params = array(
"username"=>$username,
"password"=>$password
);
$response = $client->UserLogIn($params); //UserLogIn is the function name
var_dump($response); // to see webservice response

Twitter API only gets twitter JSON on local server

I've been using this script to get tweets using twitter OAUTH on a local version of my website. When I upload it to my live web server it doesn't work.
It returns a JSON prettified list of twitter data based on a string that I provide.
Could anyone tell me why it isn't returning the JSON response on the live server?
<?php
session_start();
require_once("twitteroauth-master/twitteroauth/twitteroauth.php"); //Path to twitteroauth library
$notweets = 6;
$consumerkey = "**************************";
$consumersecret = "**************************";
$accesstoken = "**************************";
$accesstokensecret = "**************************";
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$search_term = urlencode("pizza");
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
$tweets = $connection->get("https://api.twitter.com/1.1/search/tweets.json?q=$search_term&count=$notweets&result_type=recent&include_rts=false");
header('Content-Type: application/json');
echo json_encode($tweets, JSON_PRETTY_PRINT);
?>
SOLVED
I updated my php.ini file to display errors and was given the following message.
Use of undefined constant JSON_PRETTY_PRINT
I was then able to solve my problem. Thanks to all who commented and I learnt how to track down errors appropriately in a live PHP / server environment.

Twitter APIs not working on hosting [Works fine on localhost]

I am working on an app to show the tweets done in 1 mile radius of given geolocation (Latitude and Longitude). This is my PHP code,
<?php
// $lat = $_GET['lat'];
$lat = 26.511740;
// $long = $_GET['long'];
$long = 80.234973;
require_once("twitteroauth/twitteroauth.php"); //Path to twitteroauth library
$notweets = 100;
$consumerkey = "XXXX";
$consumersecret = "XXXX";
$accesstoken = "XXXX-XXXX";
$accesstokensecret = "XXXX";
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey,$consumersecret, $accesstoken, $accesstokensecret);
$tweets = $connection->get("https://api.twitter.com/1.1/search/tweets.json?geocode=".$lat.",".$long.",5mi&result_type=recent&count=".$notweets);
// echo $tweets;
echo json_encode($tweets);
?>
I am using Wamp server (PHP V5.5.12) and my code is working fine on it. But when I host my application on some free hosting sites (I have tried hostinger.in and 000webhost.com), this script fails and just prints 'null'.
Please help me to solve this problem.
Thanks in advance.
I've tried in both, hostinger and 000webhost and several others. The reason they dont work is the library to connect to twitter uses php curl, and many free hosting have disabled curl, or outgoing connections or twitter refuses the curl connection when it comes from the ips from free hosting servers. For what I've read in internet it's probably because many hackers have been messing with twitter and hosting from free hosting accounts. So finding a free hosting with cpanel that works with Twitter API it's a challenge, i've tried over 20 and they dont work, some of them automatically deleted the account or the file or block the ftp access if you try to curl to twitter
Likely to be related to the libraries available to you.
Add error_reporting(E_ALL) to the top of the script.
Check that cURL is installed on the cheap hosting as I believe that's the only php library that twitteroauth requires.
What is your TwitterOAuth version? Your code seems to be so legacy and not compatible with latest version.
https://twitteroauth.com/
<?php
require "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
$lat = 26.511740;
$long = 80.234973;
$notweets = 100;
$ck = "XXXX";
$cs = "XXXX";
$ot = "XXXX-XXXX";
$os = "XXXX";
$to = new TwitterOAuth($ck, $cs, $ot, $os);
$tweets = $to->get('search/tweets', [
'geocode' => "$lat,$long",
'result_type' => 'recent',
'count' => $notweets,
]);
if (isset($tweets->errors[0]->message)) {
echo 'Error: ' . $tweets->errors[0]->message;
} elseif (!is_array($tweets)) {
echo 'Unknown Error';
} else {
echo '<pre>';
var_dump($tweets);
echo '</pre>';
}
Alternatively, you can use TwistOAuth instead of TwitterOAuth. I'm the author of this library. This library is almost compabible with TwitterOAuth, but support strict exception handling. Error reasons are always to be clear.
https://github.com/mpyw/TwistOAuth
<?php
require 'TwistOAuth.phar'; // Or 'vendor/autoload.php' for composer
$lat = 26.511740;
$long = 80.234973;
$notweets = 100;
$ck = "XXXX";
$cs = "XXXX";
$ot = "XXXX-XXXX";
$os = "XXXX";
try {
$to = new TwistOAuth($ck, $cs, $ot, $os);
$tweets = $to->get('search/tweets', [
'geocode' => "$lat,$long",
'result_type' => 'recent',
'count' => $notweets,
]);
echo '<pre>';
var_dump($tweets);
echo '</pre>';
} catch (TwistException $e) {
echo 'Error: ' . $e->getMessage();
}
Which code do you like?

Abraham Twitter API 1.1 Oauth library only returning "null"

I've been trying to get the latest status back from a user's twitter feed using Abraham Williams' Twitter Oauth Library (https://github.com/abraham/twitteroauth) I followed the tutorial found at http://www.webdevdoor.com/php/authenticating-twitter-feed-timeline-oauth/ and created the get_tweet.php file as my index. When I run this on my website an all white page, with "null" in the top left corner is displayed.
As far as I am to understand my Oauth keys I have are valid, I am using 000webhost.com to host my website, my webserver is using PHP 5.2.17 and cURL is enabled, From the tutorial and sample files I have been using my index file should be correct, my website can be found at http://authortryndaadair.site90.net where the results of this call is being dispayed.
I have been able to troubleshoot a small amount, but I am unsure of what else could try to get this Api call working. Any help in solving this problem would be much appreciated.
Below is the contents of the index file substituting for get_tweet1.1.php:
session_start();
// Path to twitteroauth library
require_once("twitteroauth/twitteroauth/twitteroauth.php");
$twitteruser = "JaneSmith";
$notweets = 10;
$consumerkey = "123456";
$consumersecret = "789123";
$accesstoken = "456789";
$accesstokensecret = "1023456";
function getConnectionWithAccessToken($cons_key, $cons_secret,
$oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth($cons_key, $cons_secret,
$oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret,
$accesstoken, $accesstokensecret);
$tweets = $connection->get(
"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name="
. $twitteruser . "&count=" . $notweets
);
echo json_encode($tweets);
Assuming you are running the latest TwitterOAuth code the get line should look like this.
$tweets = $connection->get(
"statuses/user_timeline",
array("screen_name" => $twitteruser, "count" => $notweets)
);

Categories