TwitterOAuth Store Tokens for offline use - php

Hi sorry for my bad english, i have writed simple app for update status in twitter account.
Twitter Login:
require("twitteroauth.php");
session_start();
$twitteroauth = new TwitterOAuth('*******', '***********');
$request_token = $twitteroauth->getRequestToken('http://127.0.0.1/twitter_oauth.php');
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
if($twitteroauth->http_code==200)
{
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '. $url);
}
else
{
die('error');
}
twitter_oauth.php:
require("twitteroauth.php");
session_start();
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret']))
{
require("config.php");
$twitteroauth = new TwitterOAuth('****', '********', $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$access_token = $twitteroauth->getAccessToken();
$_SESSION['access_token'] = $access_token;
$user_info = $twitteroauth->get('account/verify_credentials');
$username= $user_info->screen_name;
$followerInit= $user_info->followers_count;
$oauth_token=$_SESSION['oauth_token'];
$oauth_token_secret=$_SESSION['oauth_token_secret'];
$update=query("SELECT 1 FROM connect WHERE id_user=(SELECT id FROM user WHERE user='$username' )");
if(mysql_num_rows($update)>0)
{
query("UPDATE connect set oauth_token='$oauth_token', oauth_token_secret='$oauth_token_secret' WHERE id_user=(SELECT id FROM user WHERE user='$username' ) ");
}
else
{
query("INSERT INTO connect(id_user,followerInit,oauth_token,oauth_token_secret) VALUES((SELECT id FROM user WHERE user='$username' ),$followerInit,'$oauth_token','$oauth_token_secret' ) ");
}
header('Location: index.php');
}
else
{
header('Location: twitter_login.php');
}
I save oauth_token,oauth_token_secret and in index.php, when user have the oauth_token,oauth_token_secret i would like update status:
session_start();
require("twitterbot/twitterbot/twitteroauth.php");
require("twitterbot/config.php");
$query=query("SELECT oauth_token,oauth_token_secret FROM connect WHERE id_user=8");
if(mysql_num_rows($query)>0)
{
$row=mysql_fetch_row($query);
}
else
{
header('Location: twitter_login.php');
}
$twitteroauth = new TwitterOAuth('bSMnfSsk3CTcSV85jKWz1w', 'HeNAG1v2sgxhkq1QyfZDd029JUDdRNGAaO85Nsg', $row[0], $row[1]);
print_r($twitteroauth);
print_r($twitteroauth->OAuthRequest('https://twitter.com/statuses/update.xml',
array('status' => "Hey! I'm posting via #OAuth!"), 'POST'));
but in index.php i have error, "Could not authenticate you. /statuses/update.xml" and i can't update status...

$access_token = $twitteroauth->getAccessToken();
$_SESSION['access_token'] = $access_token;
$user_info = $twitteroauth->get('account/verify_credentials');
$username= $user_info->screen_name;
$followerInit= $user_info->followers_count;
$oauth_token=$_SESSION['oauth_token'];
$oauth_token_secret=$_SESSION['oauth_token_secret'];
In this code you are getting an access oauth_token but saving the temporary request oauth_token in the database. You need to save the access_token instead.

Related

Twitter LogIn doesn't work. Invalid and Expired token

I follow this code and I use thid library http://hayageek.com/login-with-twitter/
Log in works but I think that the oauth token that the program generates are bad. This is my problem and I don't know how I can resolve:
$connection = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET);
$request_token = $connection->getRequestToken($OAUTH_CALLBACK); //get Request Token
if( $request_token)
{
echo print_r($request_token);
$token = $request_token['oauth_token'];
$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
switch ($connection->http_code)
{
case 200:
$url = $connection->getAuthorizeURL($token);
//redirect to Twitter .
header('Location: ' . $url);
break;
default:
echo "Coonection with twitter Failed";
break;
}
}
else //error receiving request token
{
echo "Error Receiving Request Token";
}
and after log in the page the callback page do this:
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
/
$content = $connection->get ( "account/verify_credentials" );
Now I obtain "Invalid and expiried token". Anyone can help me?

My Facebook App still logged after I logged out from Facebook

I have a website where you can login with Facebook. I login to my website, all well and good. But after going on www.facebook.com and log out, when I get back on the website and give refresh, the app works perfectly as if I logged in to Facebook. I tried all sorts of conditions, such as:
$user_profile = $facebook->api('/me');
if($user_profile !== $_SESSION['id']) {
header( 'Location: logout.php' ) ;
}
but nothing works, how can I send it to the logout page if the user is not logged on facebook?
Here is my code:
<?php
// Application Configurations
$app_id = "xxxxxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxx";
$site_url = "xxxxxxxxxxxxxxx";
try {
include_once "src/facebook.php";
}
catch(Exception $e){
error_log($e);
}
// Create our application instance
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true,
));
// Get User ID
$user = $facebook->getUser();
$user_profile = null;
// Get the current access token
// We may or may not have this data based
// on whether the user is logged in.
// If we have a $user id here, it means we know
// the user is logged into
// Facebook, but we don’t know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
// print_r($user);
if ($session) {
echo "este";
} else {
echo "nu este";
}
if(!isset($_SESSION['id']))
{
if($user){
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
// Get logout URL
$logoutUrl = $facebook->getLogoutUrl();
try{
//Connecting to the database. You would need to make the required changes in the common.php file
//In the common.php file you would need to add your Hostname, username, password and database name!
mysqlc();
$id = $user_profile['id'];
$name = $user_profile['name'];
$email = $user_profile['email'];
$gender = $user_profile['gender'];
$bio = $user_profile['bio'];
$query = sprintf("SELECT * FROM newmember WHERE id = %s", $id);
$results = mysql_query($query) or die('tubRandom - Query failed: ' . mysql_error() . "<br />\n$sql");
if(mysql_num_rows($results) == 0)
{
$query_two = sprintf("INSERT INTO newmember values(%s,%s,%s,%s,%s,'yes')", $id, $name, $email, $gender, $bio);
$insert_query_two = mysql_query($query_two) or die('tubRandom - Query failed: ' . mysql_error() . "<br />\n$sql");
$_SESSION['id'] = $user_profile['id'];
} else {
$rows = mysql_fetch_array($results);
$_SESSION['id'] = $user_profile['id'];
}
}
catch(FacebookApiException $e){
error_log($e);
$user = NULL;
}
} else {
// Get login URL
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'read_stream, publish_stream, email, user_about_me, user_website, user_work_history, user_relationships, user_religion_politics, user_relationships, user_likes, user_location, user_relationship_details, user_hometown, user_education_history',
'redirect_uri' => $site_url,
));
}
} else {
$user_profile = $facebook->api('/me');
echo $user_profile['name'] . $user_profile . $user_profile['id'] . $_SESSION['id'];
//header( 'Location: logout.php' ) ;
}
?>
Sorry if it is a dummy question, I am a girl. :D
Well, first of all I don't see why you have to make a note of your gender. Anyway, have a look at the FB.getLoginStatus function.
You can check it through $facebook->getUser(); which returns the Facebook User ID of the current user, or 0 if there is no logged-in user... ;) ;) :P

Using twitterOAuth for login scripts

I recently started working with twitteroauth login, which seems to be working in the examples (found here) but not when I amalgamate the redirect.php and callback.php
Based on the script below (which is integrated in a bit of login script I've been working on) the second portion works fine (which is based on redirect.php), returning an oauth_token and oauth_verifier, but the first part (based on callback.php) isn't even initiating it seems. Which it should when Twitter redirects the user to the homepage.
Any ideas/suggestions folks?
session_start();
require_once('socialCodes.php'); //where I keep my app ID and Secret
require_once('twitteroauth/twitteroauth.php');
if (isset($_GET['oauth_token'])) {
$connection = new TwitterOAuth($twAppID, $twAppSec, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$connection->host = "https://api.twitter.com/1.1/";
$access_token = $connection->getAccessToken($_GET['oauth_verifier']);
$_SESSION['access_token'] = $access_token;
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
if (200 == $connection->http_code) {
$userAccessToken = $access_token['oauth_token'];
$userSecretToken = $access_token['oauth_token_secret'];
$userID = $access_token['user_id'];
$userName = $access_token['screen_name'];
}
} else {
$connection = new TwitterOAuth($twAppID, $twAppSec);
$connection->host = "https://api.twitter.com/1.1/";
$request_token = $connection->getRequestToken('myhomepage');
$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
switch ($connection->http_code) {
case 200:
$url = $connection->getAuthorizeURL($token);
header('Location: ' . $url);
break;
default:
echo 'Could not connect to Twitter. Refresh the page or try again later.';
}
}
Turns out this was a caching issue, and the script now works.

Cannot login through Facebook

Here is the code of API calls and login through Facebook.
The problem is that when it redirects to Facebook, it does not sign in.
What part of my code is wrong and how can I fix it?
require 'facebook/facebook.php';
require 'config/fbconfig.php';
require 'config/functions.php';
$url = $_REQUEST['lasturl'];
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true
));
$session = $facebook->getSession();
if (!empty($session)) {
# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
try {
$uid = $facebook->getUser();
$user = $facebook->api('/me');
} catch (Exception $e) {
}
if (!empty($user)) {
# User info ok? Let's print it (Here we will be adding the login and registering routines)
// echo '<pre>';
//print_r($user);
// echo '</pre><br/>';
$username = $user['name'];
$user = new User();
$userdata = $user->checkUser($uid, 'facebook', $username);
if(!empty($userdata)){
session_start();
$_SESSION['id'] = $userdata['id'];
$_SESSION['oauth_id'] = $uid;
$_SESSION['username'] = $userdata['username'];
$_SESSION['oauth_provider'] = $userdata['oauth_provider'];
header("Location: ".$url);
}
} else {
# For testing purposes, if there was an error, let's kill the script
die("There was an error.");
}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl();
header("Location: " . $login_url);
}
Actually the code is fine and getting the login credential should work fine. But the problem is here.
if (!empty($user))
I think you should put this first before getting the user info with the API call. If the function getUser returns an ID then you don't need to get the current session just to get the user info.
Try below code : $session = $facebook->getSession(); don't work
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true
));
$uid = $facebook->getUser();
if ($uid) {
# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
try {
$user = $facebook->api('/me');
} catch (Exception $e) {
}
if ($uid) {
# User info ok? Let's print it (Here we will be adding the login and registering routines)
// echo '<pre>';
//print_r($user);
// echo '</pre><br/>';
$username = $user['name'];
$user = new User();
$userdata = $user->checkUser($uid, 'facebook', $username);
if(!empty($userdata)){
session_start();
$_SESSION['id'] = $userdata['id'];
$_SESSION['oauth_id'] = $uid;
$_SESSION['username'] = $userdata['username'];
$_SESSION['oauth_provider'] = $userdata['oauth_provider'];
header("Location: ".$url);
}
} else {
# For testing purposes, if there was an error, let's kill the script
die("There was an error.");
}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl();
header("Location: " . $login_url);
}

problem in using OAuth for Twitter

I have implemented OAuth for twitter using Abraham Williams php library. It is working fine for me on personal web server(Apache). But when I uploaded all my application files to a public web hosting domain, it stops working. When I press the button 'sign in with twitter account' that directs user to 'connect.php' which builds twitter link to authenticate my application, it doesn't build the link. Rather control halts on that 'connect.php' page. Here is connect.php
<?php
session_start();
require_once 'twitteroauth/TwitterOAuth.php';
define("CONSUMER_KEY", "***************");
define("CONSUMER_SECRET", "********************************");
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->getRequestToken('http://babar.phpnet.us/callback.php');
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] =
$request_token['oauth_token_secret'];
$url = $connection->getAuthorizeURL($request_token);
header('Location: ' . $url);
?>
Here is callback.php
<?php
session_start();
require_once 'twitteroauth/TwitterOAuth.php';
define("CONSUMER_KEY", "****************");
define("CONSUMER_SECRET", "*********************************");
if (
isset($_REQUEST['oauth_token'])
&& $_SESSION['oauth_token'] !== $_REQUEST['oauth_token'])
{
//echo 'Session expired';
header('Location: ./connect.php');
}
else {
$connection = new TwitterOAuth(CONSUMER_KEY,CONSUMER_SECRET,
$_SESSION['oauth_token'],$_SESSION['oauth_token_secret']);
$_SESSION['access_token'] =
$connection->getAccessToken($_REQUEST['oauth_verifier']);
header('Location: index1.php');
}
?>
index1.php
if (empty($_SESSION['access_token'])) {
header('Location: ./connect.php');
}
require_once 'twitteroauth/TwitterOAuth.php';
define("CONSUMER_KEY", "**************");
define("CONSUMER_SECRET", "*******************");
$connection = new TwitterOAuth(CONSUMER_KEY,CONSUMER_SECRET,
$_SESSION['access_token']['oauth_token'],
$_SESSION['access_token']['oauth_token_secret']
);
include("index.php");
$tweetmsg = $_POST['t_update'];
$result = $connection->post('statuses/update', array('status' => $tweetmsg));
if (200 === $connection->http_code) {
//echo'tweet posted';
}
else {
$resultmsg = 'Could not post Tweet. Error: '.$httpCode.'
Reason:'.$result->error;
//echo $resultmsg;
}
?>
Make sure the clock on the server is properly synced with NTP. If the time differers from the clocks on Twitter's servers by more then five minutes requests will fail.
You should also check to see if there is a firewall blocking https://api.twitter.com.

Categories