Twitter API and obtaining user information PHP - php

I'm having issues with Twitter API and understanding OAuth in general. I'm able to make request to pull information from my account with ease. The problem I'm having is with other users who would be using "Sign In with Twitter". Even though I am able to get other user information after they sign in, I'm unable to make separate future request with their information on other .php pages (I am not trying to pull info from MySQL). I can only get their information one time on the original .php page after they sign in and the page has loaded.
I will post some code but my main concerns/questions are -- is it possible to save user access token information (and re-use) or will I be needing to have the user sign in every time and authenticate just to pull information from their account? I am having trouble understanding this. What information can I save to make a request in the future on behalf of a user with out having to have them log in every time?
Code example:
require "autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
define('CONSUMER_KEY', 'my consumer key');
define('CONSUMER_SECRET', 'secret');
define('OAUTH_CALLBACK', 'API/Twitter/Twitter.php');
$access_token = 'beep boop boop beep';
$access_token_secret = 'super secret';
session_start();
if (isset($_SESSION['oauth_token'])) {
$oauth_token = $_SESSION['oauth_token'];
echo "<div style='background-color:white; width:100%;'>";
echo $oauth_token; echo "</div>";
unset($_SESSION['oauth_token']);
$connection = new Abraham\TwitterOAuth\TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$params = array("oauth_verifier" => $_GET['oauth_verifier'], 'oauth_token' => $_GET['oauth_token']);
$access_token = $connection->oauth('oauth/access_token', $params);
$connection = new Abraham\TwitterOAuth\TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$content = $connection->get('account/verify_credentials');
//Printing the profile data
//print_r($content);
$TimeLine = $connection->get("statuses/user_timeline", ["screen_name"=>$content->screen_name, "count"=>10]);
echo "<br><br><br>";
echo "<div style='width:100%; background-color:red; height:auto;'>";
print_r($connection);
echo "</div>";
//print_r($TimeLine);
} else {
$connection = new Abraham\TwitterOAuth\TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$temporary_credentials = $connection->oauth('oauth/request_token', array("oauth_callback" => $callback));
$_SESSION['oauth_token'] = $temporary_credentials['oauth_token'];
$_SESSION['oauth_token_secret'] = $temporary_credentials['oauth_token_secret'];
$url = $connection->url('oauth/authenticate', array('oauth_token' => $temporary_credentials['oauth_token']));
}

What you need in order to maintain access to user information on behalf of them is the generated oAuth Token and oAuth Token Secret. In my particular case listed above, the steps should be
$connection = new Abraham\TwitterOAuth\TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, USER_oAuth_TOKEN, USER_oAuth_TOKEN_SECRET);
$content = $connection->get('account/verify_credentials');
You will need your own application CONSUMER_KEY and CONSUMER_SECRET. When someone signs in with Twitter, you have to save their oAuth Token and oAuth Token Secret. When you have this information (stored in a database), you can now make calls on behalf of the user for future request.
More into the specific problem I had listed above, I was not saving this information. I kept making new oAuth Tokens and Secrets.

Related

Hello guys how can i scrap cookies after login gmail using oauth gmail doc?

i want to grab cookies after gmail oauth check login is true and i can login without password!
i use this script php to check (gmail) but now i want grab cookies after this
save cookie in file cookie.txt
`
<?php
require_once 'vendor/autoload.php';
//google-api-php-client--PHP5.6/
// init configuration
$clientID = 'clientID';
$clientSecret = 'clientSecret ';
$redirectUri = 'redirectUri ';
// create Client Re quest to access Google API
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
// authenticate code from Google OAuth Flow
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($token['access_token']);
// get profile info
$google_oauth = new Google_Service_Oauth2($client);
$google_account_info = $google_oauth->userinfo->get();
$email = $google_account_info->email;
$name = $google_account_info->name;
// now you can use this profile info to create account in your website and make user logged in.
} else {
echo "<a href='".$client->createAuthUrl()."'>Google Login</a>";
}
?>
`
Any idea?
i want scrape the cookies after request checker

How to get twitter user's profile picture (not pixeled) by having user's screen_name or user's id?

I know that there are tons of similar questions, but NONE worked for me. I have an Oauth twitter system integrated into my website. I can get user's id, screen_name, etc. However, I don't know how to get user's profile photo in original size or full size. Please, if you're going to answer this question, don't copy and paste a bunch of document library from twitter, because that's Mandarin Chinese to me and I've already tried to do it with no success. I just need an url where I can replacethe user's id into one part of the url and then put that url as img's src to show it in html (obviously, I'd do so by executing an "echo" in the oAuth php file. Thanks beforehand.
My code:
<?php
if(!isset($_SESSION)){
session_start();
}
require 'autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
define('CONSUMER_KEY', 'xxxxxxxxxxxxxxxxxxxxxxxxx'); // add your app consumer key between single quotes
define('CONSUMER_SECRET', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); // add your app consumer secret key between single quotes
define('OAUTH_CALLBACK', 'http://www.chapatelo.com.ar/chm/peticiones/callback.php'); // your app callback URL
if (!isset($_SESSION['access_token'])) {
$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);
} else {
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$user = $connection->get("account/verify_credentials");
$_SESSION["id"] = $user->id;
$_SESSION["usuario"] = $user->screen_name;
$_SESSION["start"] = time();
$_SESSION["expire"] = $_SESSION["start"] + (3600 * 60);
echo '<img src="https://api.twitter.com/1/users/show.json?screen_name=' . $user->screen_name . '"/>'; //Of course, this echo doesn't show any image...
}
?>

Post tweet option using php only working for me, how to make it general?

Hi all i developed an application for posting tweet using PHp with twitter api 1.1. But that option is only working for me only. If any one authenticated and try to send tweet using that. It's posting tweet on my wall.
How to make this generalized for anyone.
YOUR_CONSUMER_KEY = 'xxxxxxxxxxxxxx';
YOUR_CONSUMER_SECRET = 'xxxx';
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET);
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken('http://xxxx/xxxx/getTwitterData.php');
//print_r($request_token);
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET, $request_token['oauth_token'], $request_token['oauth_token_secret']);
$tmessage = $_POST['message'];
$content = $twitteroauth->post('statuses/update', array('status' => $tmessage));
it's posting tweets on your wall because you're using access token and secret of the app, or you're the authenticated user. You need to log in the user you want to post for, get their access token and secret, then use consumer key, secret, user access token and user access secret to post on their behalf.
It's a bit unclear what you're trying to do, but here's a sample post action with Abraham William's library, which you're using:
require_once('twitteroauth.php');
$key = "***";
$secret = "***";
$token = "***";
$token_secret = "***";
$connection = new TwitterOAuth($key, $secret, $token, $token_secret);
$message = "whatever";
$status = $connection->post($message);
$response= $connection->http_code;
if($response !=200){
echo "ERROR";
}else{
echo "life is good";
}

Login with twitter; Getting http_code of 0

I have this code to enable login with twitter in my site
<?php
require("twitter/twitteroauth.php");
require 'config/twconfig.php'; //CONTAINS CONSUMER SECRET AND CONSUMER KEY
session_start();
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET);
$twitteroauth->host = "https://api.twitter.com/1.1/";
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken('http://MY WEBSITE URL');
// Saving them into the session
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
// If everything goes well..
if ($twitteroauth->http_code == 200) {
// Let's generate the URL and redirect
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: ' . $url);
} else {
// It's a bad idea to kill the script, but we've got to know when there's an error.
die('Something wrong happened.'.$twitteroauth->http_code);
}
?>
I am using Abraham Williams twitter oauth. This worked well for a couple of weeks, but now
am getting a http_code of 0, which is not even listed in twitters list of error codes.
What could be the problem
Here is snippted i am using which works fine.
First make sure of the follownig
In dev twitter, you app can read / write
Refresh consumer key, Recreate access token.
If the folling is not working, the problem lies elsewhere t is something else!
see https://dev.twitter.com/search/apachesolr_search/HTTP%20CODE%200
Please read instructions, FOLLOW THEM and YOUR CODE will WORK
<?php
require_once('twitteroauth.php');
session_start();
/*
* INSTRUCTIONS!!!
* https://dev.twitter.com/
* create app
* https://dev.twitter.com/ TAB settings
* website: THE_URL_TO_YOUR_SCRIPT_WITH_THIS_CODE
* callback_url http://www.YOURDOMAIN.COM/
* Read, Write and Access direct messages !
* Allow this application to be used to Sign in with Twitter
* GO BACK TO DETAILS RECREATE / REFRESH - ACCESS TOKEN!
*/
$consumerKey = '******************';
$consumerSecret = '******************';
$oAuthToken = '*********************';
$oAuthSecret = '**************************';
// The TwitterOAuth instance
$twitteroauth = new TwitterOAuth($consumerKey, $consumerSecret);
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken('http://DOMAIN.com/YOURLOGINSCRIPT.php');
// Saving them into the session
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
// If everything goes well..
if($twitteroauth->http_code==200){
// Let's generate the URL and redirect
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '. $url);
} else {
// It's a bad idea to kill the script, but we've got to know when there's an error.
die('Something wrong happened.');
}
?>

Authenticate with Twitter OAuth API

I am currently trying to integreate twitter into a php web app that I am working on with OAuth.
I have an HTML page which provides a link to the twitter app authentication url which appears to be working fine and is showing the authentication screen.
Below is the code that calls the function.
if (!isset($_GET['oauth_token']))
{
//include("phpHandler/twitterLib/secret.php");
getTwitterURL($consumer_key, $consumer_secret);
}
The consumer_key and consumer_secret are included within a php file.
Below is the code that gets the twitter authorisation url.
function getTwitterUrl($consumer_key, $consumer_secret)
{
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$url = $twitterObj->getAuthorizationUrl();
echo '<a class="linkButtons" href="'.$url.'">Add Twitter</a>';
}
This redirect back to the page fine and then I call the authentication method to retrieve info like twitter username. Below is the function that does the authentication
function authenticate($consumer_key, $consumer_secret)
{
require ("twitterLib/EpiCurl.php");
require ("twitterLib/EpiOAuth.php");
require ("twitterLib/EpiTwitter.php");
require ("twitterLib/secret.php");*/
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$twitterObj->setToken($_GET['oauth_token']);
$token = $twitterObj->getAccessToken();
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
$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();
echo '<pre>';
print_r($twitterInfo->response);
}
The echo and print_r is to show the response return from twitter.
I am getting the following error printed out in the array
Array (
[error] => Invalid / expired Token
[request] => /account/verify_credentials.json )
How can I fix this error. I don't know why its invalid or expired, I have closed the browser and started again but get the same error appear.
Thanks for any help you can provide.
Your access token will be invalid if a user explicitly rejects your application from their settings or if a Twitter admin suspends your application. If your application is suspended there will be a note on your application page saying that it has been suspended.
Many users trust an application to read their information but not necessarily change their name or post new statuses. Updating information via the Twitter API - be it name, location or adding a new status - requires and HTTP POST. We stuck with the same restriction when implementing this. Any API method that requires an HTTP POST is considered a write method and requires read & write access.
Whatever your storage system may be, you'll need to begin storing an oauth_token and oauth_token_secret (collectively, an "access token") for each user of your application. The oauth_token_secret should be stored securely. Remember, you'll be accessing these values for every authenticated request your application makes to the Twitter API, so store them in a way that will scale to your user base. When you're using OAuth, you should no longer be storing passwords for any of your users.
require '../tmhOAuth.php';
require '../tmhUtilities.php';
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'YOUR_CONSUMER_KEY',
'consumer_secret' => 'YOUR_CONSUMER_SECRET',
'user_token' => 'AN_ACCESS_TOKEN',
'user_secret' => 'AN_ACCESS_TOKEN_SECRET',
));
// we're using a hardcoded image path here. You can easily replace this with an uploaded image-see images.php example)
// 'image = "#{$_FILES['image']['tmp_name']};type={$_FILES['image']['type']};filename={$_FILES['image']['name']}",
$image = "./dickvandyke.jpg';
$code = $tmhOAuth->request('POST', 'https://upload.twitter.com/1/statuses/update_with_media.json',
array(
'media[]' => "#{$image}",
'status' => "Don't slip up" // Don't give up..
),
true, // use auth
true // multipart
);
if ($code == 200) {
tmhUtilities::pr(json_decode($tmhOAuth->response['response']));
} else {
tmhUtilities::pr($tmhOAuth->response['response']);
}
I've managed to find the problem. I always creating two new EpiTwitter objects in the authenticate function.
I worked on new Twitter API. It is working fine for me with following code I did.
<?php
require "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
$consumer_key = "XXXXXXX";
$consumer_secret = "XXXXXXX";
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
$request_token= $connection->oauth('oauth/request_token', array('oauth_callback' => "http://callbackurlhere.com/callback.php"));
$url = $connection->url("oauth/authorize", array("oauth_token" => $request_token['oauth_token']));
header('Location: '. $url);
?>
callback.php code below to obtain the permanent oauthToken and save it in database for further use:
<?php
require "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
// session_start();
if(isset($_REQUEST['oauth_verifier'])){
$oauth_access_token = $_REQUEST['oauth_token'];
$oauth_access_token_secret = $_REQUEST['oauth_verifier'];
$consumer_key = "XXXXXXXXXXXXXXXX";
$consumer_secret = "XXXXXXXXXXXXXXX";
$connection = new TwitterOAuth($consumer_key, $consumer_secret,$oauth_access_token , $oauth_access_token_secret );
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $oauth_access_token_secret));
var_dump($access_token); die("--success here--");// Obtain tokens and save it in database for further use.
}
?>

Categories