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.
Related
I have create a website using php which is having google and facebook login. This website having 6 pages. For all the 6 pages header and footer are common(included). Assume I am login into the site using google from page 5. After successful/failure login, the page navigate to index.php (page 1) instead of page5. How can i navigate to the same page after successful/failure login of google and facebook. Is this possible without adding all the pages in google/facebook developer console?
Also i have tried to change the header location after successful login. It throws cannot reach, out of time error. Can any one help to solve this problem. Thanks in advance.
Note: I am using google and facebook Oauth service for login.
Here is my code:
google login.
<?php
session_start();
require_once 'dbconnection.php';
//Google API PHP Library includes
require_once 'gvendor/vendor/autoload.php';
require_once 'gvendor/vendor/google/apiclient/src/Google/Client.php';
require_once 'gvendor/vendor/google/apiclient/src/Google/Service/Oauth2.php';
// Fill CLIENT ID, CLIENT SECRET ID, REDIRECT URI from Google Developer Console
$client_id = 'xxxxxxx';
$client_secret = 'xxxxxxx';
$redirect_uri = 'http://localhost:80/tthtml/index.php';
$simple_api_key = 'xxxxxxx';
global $googleauthUrl;
//Create Client Request to access Google API
$client = new Google_Client();
$client->setApplicationName("PHP Google OAuth Login Example");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($simple_api_key);
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
$client->setAccessType('offline');
//Send Client Request
$objOAuthService = new Google_Service_Oauth2($client);
try{
//Logout
if (isset($_REQUEST['logout'])) {
$client->revokeToken($_SESSION['access_token']);
unset($_SESSION['access_token']);
unset($_SESSION['google_user_name']);
session_unset();
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); //redirect user back to page
}
//Authenticate code from Google OAuth Flow
//Add Access Token to Session
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
//Set Access Token to make Request
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
}
//Get User Data from Google Plus
//If New, Insert to Database
if ($client->getAccessToken()) {
$userData = $objOAuthService->userinfo->get();
$_SESSION['google_user_name']=$userData['given_name'];
$_SESSION['user_id']=$userData->id;
if(!empty($userData)) {
$dbObj=new database();
$dbObj->openconnection();
$sql='select * from tttbl_user where google_fb_id='.$userData->id;
$existing_member = $dbObj->existingMember($sql);
if(empty($existing_member)) {
$sql="insert into tttbl_user (google_fb_id, user_name, gender, email_id, gplus_link, profile_photo, created_date) values('".$userData->id."','".$userData->name."','".$userData->gender."','".$userData->email."','".$userData->link."','".$userData->picture."',now())";
$dbObj->newUser($sql);
}
$dbObj->closeconnection();
}
}
else{
$googleauthUrl = $client->createAuthUrl();
}
}
catch(Exception $ee)
{ }
?>
facebook login
<?php //
//ob_start();
session_start();
require_once 'dbconnection.php';
require_once 'fvendor/vendor/autoload.php';
require_once 'fvendor/vendor/facebook/php-sdk/src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
global $facebook_loginUrl;
$appId='xxxxxx';
$secretkey='xxxxxx';
$facebook = new Facebook(array(
'appId' => 'xxxxxxx',
'secret' => 'xxxxxxxx',
));
// Get User ID
$fb_user = $facebook->getUser();
if(isset($_REQUEST['fb_logout'])){
//$accessToken=null;
//$logoutUrl = $helper->getLogoutUrl($_SESSION['facebook_access_token'], 'http://localhost/fblogin/fblogin.php');
//unset($_SESSION['facebook_access_token']);
unset($_SESSION['facebook_user_name']);
session_unset();
session_destroy();
$fb_user = null;
header('Location: http://localhost:80/tthtml/index.php');
}
if ($fb_user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$uid = $facebook->getUser();
$user_profile = $facebook->api('/me?fields=id,name,picture,email,gender');
}
catch (FacebookApiException $e) {
error_log($e);
$fb_user = null;
}
}
else
{
$facebook_loginUrl = $facebook->getLoginUrl(array('scope' => 'email,user_birthday,user_photos','req_perms' => 'user_mobile_phone',));
$facebookurlstring=$facebook_loginUrl;
$x=strpos($facebookurlstring,'redirect_uri=');
$y=strpos($facebookurlstring, 'state');
$facebookurllength= strlen($facebookurlstring);
//substr($str,0,$y+13).'http://localhost/tthtml/index.php'.substr($str, $y+13+$x,$length)
$facebook_loginUrl=substr($facebookurlstring,0,$x+13).'http://localhost/tthtml/index.php'.substr($facebookurlstring, $y-1,$facebookurllength);
}
if($fb_user)
{
$userid=$user_profile['id'];
$username = $user_profile['name'];
$useremail = $user_profile['email'];
$userpicture=$user_profile['picture']['data']['url'];
$usergender=$user_profile['gender'];
$mobilenumber=$user_profile['user_mobile_phone'];
$_SESSION['facebook_user_name']=$username;
$_SESSION['user_id']=$userid;
if(isset($_SESSION['facebook_user_name'])&& $_SESSION['facebook_user_name']) {
$dbObj=new database();
$dbObj->openconnection();
$sql='select * from tttbl_user where google_fb_id='.$userid.';';
$existing_member = $dbObj->existingMember($sql);
if(empty($existing_member)) {
$sql="insert into tttbl_user (google_fb_id, user_name, gender, email_id, profile_photo, created_date)"
. " values('".$userid."','".$username."','".$usergender."','".$useremail."','".$userpicture."',now())";
$dbObj->newUser($sql);
}
$dbObj->closeconnection();
}
}
?>
If I change the redirect URI, it will search in the URL list in developer console. If it is not available in the list of developer console, then it throws ulr is not available in whitelist(for facebook) and page not found (for google) error is thrown.
Try to redirect with jQuery code
echo "<script>window.location.href ='yourpage.php';</script>";
I need to incorporate twitter feature in a project of mine. Among all the libraries and wrappers, codebird seemed convenient. I tried to do the basic authentication using codes from their example, but upon uploading the files on the server, i cant get to access them at all. It shows error 500 in server and i cant test them on localhost.
the index.php file
<?php
require_once ('codebird.php');
\Codebird\Codebird::setConsumerKey('123456', '1234567'); // static, see 'Using multiple Codebird instances'
$cb = \Codebird\Codebird::getInstance();
session_start();
if (! isset($_SESSION['oauth_token'])) {
// get the request token
$reply = $cb->oauth_requestToken([
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
]);
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
header('Location: ' . $auth_url);
die();
} elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);
// get the access token
$reply = $cb->oauth_accessToken([
'oauth_verifier' => $_GET['oauth_verifier']
]);
// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}
// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
the callback.php
<?php
require_once ('codebird.php');
\Codebird\Codebird::setConsumerKey('123456', '1234567'); // static, see 'Using multiple Codebird instances'
$cb = \Codebird\Codebird::getInstance();
if(isset($_SESSION['oauth_token'] && isset($_SESSION['oauth_token_secret']))){
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']); // see above
$reply = (array) $cb->statuses_homeTimeline();
print_r($reply);
}
else {
echo 'necessary session variables couldnt be found!';
}
?>
This might be a really noob question as i have only basic knowledge in PHP, but any help would be much appriciated, please.
I'm using Abraham's TwitterOAuth library to implement Twitter OAuth in my application. However, on clicking the Login button, users are sometimes redirected to the following page:
I said 'sometimes', because sometimes the Twitter OAuth provider does generate the request token, and the users are taken to the 'Grant Permission' page.
Is this a library issue? Or is this an issue with the Twitter OAuth provider? If there was an issue with my code, then this page should appear every time a user tries to login using his/her Twitter account, and not at random tries.
Here's the code of the template that the users are redirected to after clicking the Login button:
<?php
/*
*Template Name: OAuth
*/
?>
<pre>
<?php
session_start();
require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
define('CONSUMER_KEY', "XXXXXXXXXXXXXXX");
define('CONSUMER_SECRET', "XXXXXXXXXXXXXXXXXXXX");
define('OAUTH_CALLBACK', "http://localhost/wordpress/index.php/callback/");
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => OAUTH_CALLBACK));
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
$url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));
header('Location: '.$url);
?>
</pre>
PS: I also tried regenerating the Consumer Key and Consumer Secret, but that doesn't seem to have solved the problem.
The two scenarios that seem most likely to me are:
1) There is an error while getting the request token. Try adding some error handling.
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => OAUTH_CALLBACK));
if ($connection->getLastHttpCode() == 200) {
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
$url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));
header('Location: '.$url);
} else {
var_dump($request_token);
exit('Error getting request_token');
}
2) Twitter has a bug where it's not recognizing the the request_token for some reason.
The next step in debugging is to find out the status of $request_token that results in the error.
I'm building a Twitter app with PHP using the TwitterOAuth library for user authentication.
I am able to redirect the user to Twitter for authentication and to receive the oauth token, oauth secret and oauth verifier, however I am not able to complete the last step of authentication where I get the access token.
I'm developing on localhost and I have set up the callback path with
http://127.0.0.1:80/TwitterApp/update.php
My app has read and write permissions.
Here's my code:
index.php
<?php
session_start();
include "twitteroauth/autoload.php";
include "oauthConsts.php";
use Abraham\TwitterOAuth\TwitterOAuth;
// request authentication tokens
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $oauth->getRequestToken(
'http://127.0.0.1/TwitterApp/update.php');
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_secret'] = $request_token['oauth_token_secret'];
if($oauth->getLastHttpCode()==200){
// Let's generate the URL and redirect
$url = $oauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '. $url);
} else {
echo "something went wrong";
}
?>
update.php
<?php
session_start();
include "twitteroauth/autoload.php";
include "oauthConsts.php";
use Abraham\TwitterOAuth\TwitterOAuth;
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token'])
&& !empty($_SESSION['oauth_secret'])) {
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,
$_SESSION['oauth_token'], $_SESSION['oauth_secret']);
$access_token = $oauth->oauth("oauth/access_token",
array("oauth_verifier" => $_GET['oauth_verifier']));
$_SESSION['access_token'] = $access_token;
}
else {
header('Location: index.php');
}
?>
On execution, $access_token in update.php becomes
'{"error":"Invalid / expired
Token","request":"/oauth/access_token"}' with HTTP response status
401 instead of returning the authentication values.
As it turns out my particular issue was caused by sessions and the callback url.
I was accessing the index page through localhost/path/to/file , but twitter was redirecting to 127.0.0.1/path/to/file after user authentication, meaning the session data stored on localhost was not accessible on 127.0.0.1.
Using 127.0.0.1 rather than localhost to access the index page solved the problem.
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.