Retain Access Token in Epi Twitter Oauth - twitter

I'm setting up a website using the EPI Twitter Oauth method. I'm able to get a user to login and retrieve their information. However when I refresh the page that has their info, the info is lost. I'm guessing this is to do with the Access Token, and am hoping someone can suggest the easiest way to fix this.
<?php
include 'lib/EpiCurl.php';
include 'lib/EpiOAuth.php';
include 'lib/EpiTwitter.php';
include 'lib/secret.php';
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$oauth_token = $_GET['oauth_token'];
if($oauth_token == '')
{
$url = $twitterObj->getAuthorizationUrl();
echo "<div id=\"container\">";
echo "<div id=\"content\">";
echo "<div id=\"holder\">";
echo "</div>";
echo "<div id=\"nav\">";
echo "<a href='$url'><img src=\"signup.jpg\" class=\"linkimage\" /></a>";
echo "</div>";
echo "</div>";
echo "</div>";
}
else
{
$twitterObj->setToken($_GET['oauth_token']);
$token = $twitterObj->getAccessToken();
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
$_SESSION['ot'] = $token->oauth_token;
$_SESSION['ots'] = $token->oauth_token_secret;
$twitterInfo= $twitterObj->get_accountVerify_credentials();
$twitterInfo->response;
$username = $twitterInfo->screen_name;
$profilepic = $twitterInfo->profile_image_url;
include 'home.php';
}
if(isset($_POST['submit']))
{
$msg = $_REQUEST['tweet'];
$twitterObj->setToken($_SESSION['ot'], $_SESSION['ots']);
$update_status = $twitterObj->post_statusesUpdate(array('status' => $msg));
$temp = $update_status->response;
echo "<br /><div align='center'>Updated your Timeline Successfully .</div>";
}
?>

It looks to me that you are only checking $_GET for the oauth token. I believe that this may be causing this "lost info" issue because by the time you refresh the page the oauth token has been stored in a session variable and may no longer be stored in the URL. I think you may want to replace the following:
$oauth_token = $_GET['oauth_token'];
with
$oauth_token = empty($_SESSION['ot']) ? $_SESSION['ot'] : $_GET['oauth_token'];

Related

Google API login failed always: back to needing to authorize

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

How to get the page Info.totalResults from the youtube api Search: list

Below is the code i have created so far, my goal is to use the youtube Search: list api to find streams for specific games and then publish how many streams there are for that game, I have a database for the game titles and this is my function below, my api link does work im just not able to get the Info.totalResults from it, any help would be great, Thank you for any help you can provide
function totalgamelist() {
global $wpdb;
$gamelistname = $wpdb->prefix . 'Games';
global $wpdb;
$getgames = $wpdb->get_results( 'SELECT * FROM '.$gamelistname , OBJECT );
if (empty($getgames)) {
//empty array
echo 'This is empty sorry!';
} else {
echo 'We Got Something!';
foreach ( $getgames as $getgame )
{
echo '<div class="gamename">'.$getgame->GameTitle;
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/search?part=snippet&eventType=live&type=video&videoCategoryId=20&regionCode=US&maxResults=50&q='.$getgame->GameTitle.'&key=[API KEY]");
$json_data = json_decode($JSON, true);
echo $json_data['totalResults'];
echo '</div>';
}
}
}
EDIT:
So with the help from johnh10, i was able to find out that it wasn't my ability to display the results although the echo johnh10 gave is correct :) it was also that my server was blocking access to the url i was asking to view. Below is the curl code i used to access the url, hope it helps others.
$urlgame = 'https://www.googleapis.com/youtube/v3/search?part=snippet&eventType=live&type=video&videoCategoryId=20&regionCode=US&maxResults=1&q='.$getgame->GameTitle.'&key=[API Key]';
$ch = curl_init($urlgame);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$json_data = json_decode($data, true);
if (!empty($json_data)) {
$streamnumber = $json_data['pageInfo']['totalResults'];
echo ' Streams:'.$streamnumber;
} else {
echo ' Streams: No Streams Found';
}
echo $json_data['pageInfo']['totalResults'];

ZF2 read mail content

I need to read the content of a mail in a ZF2 project. I'm able to read the header and the contentType, but not the 'body'. The contentType = multipart/alternative. Until now I use thos following code:
$params = array('host' => 'myHost', 'user' => 'myUser', 'password' => 'myPwd');
$mail = new \Zend\Mail\Storage\Imap($params);
$cntMail = $mail->countMessages();
for ($i = $cntMail; $i > 0; $i--) { // reverse order
$message = $mail->getMessage($i);
if (stristr($message->subject, '[Ticket#: I' . 411401 . ']')) {
echo $message->subject . "\n";
echo $message->contentType;
if ($message->isMultipart())
echo 'is multipart';
// here the body
echo $mail->getRawContent($i); //throws an error
exit;
}
Any help will be appreciated, Andrea
I connected to smartermail and apparently it is not possible with ZF2 to get the content of mails in smartermail...

Auto Post on Twitter after authentication : getting Invalid access token error

Here I need to automatically post on Twitter after authentication.
My code
<?php
session_start();
include("twitteroauth.php");
define('CONSUMER_KEY','zubLdCze6Erz9SVNIgG3w');
define('CONSUMER_SECRET','ZnZQ77bNnpBER2aSxTQGEXToAQODz9qEBSAXIdeYw');
define('OAUTH_CALLBACK','http://dev.pubs.positive-dedicated.net/Licensee/addPubEventWeekly.php');
/* Build TwitterOAuth object with client credentials. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
/* Get temporary credentials. */
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);
/* Save temporary credentials to session. */
$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
switch ($connection->http_code) {
case 200:
/* Build authorize URL and redirect user to Twitter. */
$url = $connection->getAuthorizeURL($token);
header('Location: ' . $url);
break;
default:
/* Show notification if something went wrong. */
echo 'Could not connect to Twitter. Refresh the page or try again later.';
}
?>
and
ksort($_SESSION);
$tweet = new TwitterOAuth('zubLdCze6Erz9SVNIgG3w','ZnZQ77bNnpBER2aSxTQGEXToAQODz9qEBSAXIdeYw',$_SESSION['oauth_token'],$_SESSION['oauth_token_secret']);
print_r($tweet);
$account = $tweet->get('account/verify_credentials');
$message = "This is an example twitter post using PHP";
$postVal = $tweet->post('statuses/update', array('status' => $message));
But here I am getting "Invalid/Expired access token" Error.
I have changed twittreauth.php library file also from 1.0 to 1.1 from here
public $host = "https://api.twitter.com/1.1/";
Please suggest how to fix this

Using basic oauth to send a tweet

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'));

Resources