Use Twitteroauth to acquire twitter user info - twitter

I use the following code to set some sessions when an user logs in using his twitter account:
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);
$_SESSION['access_token'] = $access_token;
$user_info = $twitteroauth->get('account/verify_credentials');
As you see, I have all the tokens (token, secret token and access token) stored in a session, so that I can use this later on when an user wants to change his profile picture for example
But when I want to have access again to the user info... I am not able to access it. Again I build the twitteroauth connection, but now using the sessions stored during login:
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$access_token = $_SESSION['access_token'];
$user_info = $twitteroauth->get('account/verify_credentials');
if (isset($user_info->error)) {
echo "token:", $_SESSION['oauth_token'], "<br>";
echo "token_secret:", $_SESSION['oauth_token_secret'], "<br>";
echo "access-token:", $access_token, "<br>";
echo "error";
} else {
echo "oke";
}
I receive the error echo. When I echo my token strings, the all contain data and the access-token contains the value "Array".
Does someone know what I am doing wrong?

You need to use print_r to print the array values.

Related

Get Maps Engine user layers list with oAuth 2.0 from App Engine using API PHP Client Library

I am authenticating via oAuth 2.0, using Google's API PHP Client library from App Engine, in order to retrieve the current user's list of layers in Maps Engine (now called My Maps).
I'm using the following code test.php:
<?php
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/MapsEngine.php';
$client_id = 'zzzzzzzzzzzzzzzzzzzzzzzzzzz';
$client_secret = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->setAccessType('online');
$client->setApplicationName('myappname');
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey('rrrrrrrrrrrrrrrrrrrrrrrrrrrrr');
$client->setScopes("https://www.googleapis.com/auth/mapsengine");
$mymaps_service = new Google_Service_MapsEngine($client);
if (isset($_REQUEST['logout']))
{
unset($_SESSION['access_token']);
}
if (isset($_GET['code']))
{
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
echo "<html><body>";
if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
$client->setAccessToken($_SESSION['access_token']);
echo "<p>Access token set OK!</p>";
}
else
{
$authUrl = $client->createAuthUrl();
echo "<p>Could not authenticate.</p>";
echo "<p><a href='$authUrl' target=_blank>Try to authenticate by following this URL</a></p>";
}
if ($client->getAccessToken())
{
$_SESSION['access_token'] = $client->getAccessToken();
echo "<h1>Your Maps Engine Layer List:</h1>";
$layers = $mymaps_service->layers->listLayers(array());
var_dump($layers);
}
else
{
echo "<p>Could not get the Access Token.</p>";
}
echo "</body></html>";
?>
I have created my project, the client id, the secret, the developer key (simple api access key) for maps engine, the layers in maps engine (they are public), have also set up the IPs that can connect to my app in app engine, and the IP range that test.php can authenticate from.
When I deploy test.php, am logged out in the browser and load test.php I immediately get the message:
"Could not authenticate.
Try to authenticate by following this URL
Could not get the Access Token", that is, without the browser displaying Google's account select page.
Then I clic on the "Try to authenticate by following this URL" link and it opens up Google's account selection page. I provide my user and password for the account I know owns the layers in maps engine, and then I get the message:
"Access token set OK!
Your Map Engine Layer List:"
But no layer list appears... as if the $layers variable wouldn't get anything from the listLayers method.
When I try to get the list using the demo at developers.google.com I do get a list of layers OK.
What can I modify in my code in order to get the list of layers my user has access to in Maps Engine?

Google Analytics API Returning 401 On Example Code

I am attempting to retrieve the data from our content experiments from google analytics...
I am using the following code, my creds are good, and have been censored for this post...
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('Hello Analytics API Sample');
// Visit https://cloud.google.com/console to generate your
// client id, client secret, and to register your redirect uri.
$client->setDeveloperKey('xxxxx');
$service = new Google_Service_Analytics($client);
try {
$results = $service->management_experiments->listManagementExperiments('xxxx', 'xxxx', 'xxxx');
} catch (apiServiceException $e) {
print 'There was an Analytics API service error ' . $e->getCode() . ':' . $e->getMessage();
} catch (apiException $e) {
print 'There was a general API error ' . $e->getCode() . ':' . $e->getMessage();
}
echo '<pre>';
print_r($results);
echo '</pre>';
I am using the following example ....
https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtExperimentsGuide#list
Any ideas on why I am getting a 401 unauthorized? That a login is required?
The problem is that you haven't Authorized access to your data yet. Since you say its only your own data you want to access i sugest you look into a service account. By setting up a service account in Google apis console it will allow you to access your own data with out needing to login and autenticate the code all the time.
Check the following link. Read though Before you begin make sure you do all that.
https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtExperimentsGuide#service
Register your application in the Google Developers Console
Authorize access to Google Analytics data.
Create an Analytics service object
You have skiped the first two steps and gone directly to step 3 creating the service object. Once you have done step 1 you can use the following code for step 2.
Here is an example of how to use a service account in php ServiceAccount
That sample project is for the PredictionService not the google analytics service. You need to edit it slightly.
require_once '../../src/Google/Client.php';
require_once '../../src/Google/Service/Analytics.php';
// Set your client id, service account name, and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
const CLIENT_ID = 'INSERT_YOUR_CLIENT_ID';
const SERVICE_ACCOUNT_NAME = 'INSERT_YOUR_SERVICE_ACCOUNT_NAME';
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = '/super/secret/path/to/key.p12';
$client = new Google_Client();
$client->setApplicationName("Google Analytics Sample");
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME(Email),
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents(KEY_FILE))
);
$client->setClientId(CLIENT_ID);
$service = new Google_Service_Analytics($client);
Now you have $service that you can use with the rest of your calls. Note: I didnt have time to test that code let me know if it doesnt work and i will give you a hand in fixing it.

How to post statuses for users whos allow it for my application?

On my website, i want to allow for users, who is authorized with twitter, to post review on their own wall(page) in twitter, with my application.
I can do it for my page like this
$connection = new Twitter_TwitterOAuth(
$this->config->twitter->consumer_key,
$this->config->twitter->consumer_secret,
$this->config->twitter->token,
$this->config->twitter->token_secret
);
$connection->post('statuses/update', array('status' => $data['text'] . $data['name'] . "." . chr(13) . chr(10) . "More details " . $data['link'] .'?review='. $data['id']));
So what i need to do to post the same for another accounts ? i need to set account(where i want to post status with application) ID or i need to set other
$this->config->twitter->token,
$this->config->twitter->token_secret
with token and token_secret that i receive when user login with my application ?
Thanks for help.
for another account you should sleep(//someseconds); if you don't have a throttle in that library, then do the same for the other account. It looks like the account is yours, because in the code you posted I see so authorization from the user (callback). If my guess is right and you're using app authorization, you need to have authorized your own app with your other account, so ideally there should be no need to reset the tokens. If it doesn't work, try to reset them. If it still doesn't work, a trick is to have two applications (each account has an application, each account uses its own app to post). However, please bear in mind that a) Twitter counts the overall number of calls from your server and b) I'm not sure they like multiple accounts.
EDIT: if instead you need to post for users who have authorized your app and are currently online on your website, just store their tokens in a session (as Abraham Williams does in his library). In that case, you need to reset the variables to reflect the change of the tokens. Sample code, by Williams:
/* Get user access tokens out of the session. */
$access_token = $_SESSION['access_token'];
$access_token_secret = $_SESSION["access_token_secret"];
/* Create a TwitterOauth object with consumer/user tokens. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token,
$access_token_secret);
$message ="your message";
$parameters = (array('status' =>$message));
$status = $connection->post('statuses/update', $parameters);
twitteroauth_row('statuses/update', $status, $connection->http_code, $parameters);
if ($http_code = 200){
// echo "Done!";
} else {
// echo "Oops!";
}

Using Twitter OAuth to authenticate API calls for trends

I am working on a website that allows the user to search for the top ten twitter trends in a city or country. At first I was only relying on Twitter's Rest API, but I was having a lot of rate limit issues (at school my rate limit disappears faster than I have a chance to use it). I know that authenticating my API calls will help me to better deal with this issue (Authenticated API calls are charged to the authenticating user’s limit while unauthenticated API calls are deducted from the calling IP address’ allotment).
I implemented #abraham's PHP library (https://github.com/abraham/twitteroauth), unfortunately my API calls aren't being authenticated. I know I have implemented #abraham's PHP library, because it prints out my user information at the end like it should. I have my twitter trend search underneath it but the API call isn't being authenticated. I am not sure how to fix this, and any help would really be appreciated!
This is what I use to get the top ten trends by country:
function showContent(){
// we're going to point to Yahoo's APIs
$BASE_URL = "https://query.yahooapis.com/v1/public/yql";
// the following code should only run if we've submitted a form
if(isset($_REQUEST['location']))
{
// set a variable named "location" to whatever we passed from the form
$location = $_REQUEST['location'];
// Form YQL query and build URI to YQL Web service in two steps:
// first, we show the query
$yql_query = "select woeid from geo.places where text='$location'";
// then we combine the $BASE_URL and query (urlencoded) together
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
//var_dump($location);
// show what we're calling
// echo $yql_query_url;
// Make call with cURL (curl pulls webpages - it's very common)
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
// Confirm that results were returned before parsing
if(!is_null($phpObj->query->results)){
// Parse results and extract data to display
foreach($phpObj->query->results as $result){
//var_dump($result);
$woeid = $result[0]->woeid;
if (is_numeric ($location))
{
echo "<span style='color:red; padding-left: 245px;'>Please enter a city or a country</span>";
}
else if(empty($result)){
echo "No results found";
}
else {
/* echo "The woeid of $location is $woeid <br />"; */
}
}
}
$jsontrends=file_get_contents("http://api.twitter.com/1/trends/".$woeid.".json");
$phpObj2 = json_decode($jsontrends, true);
echo "<h3 style='margin-top:20px'>TRENDS: ".$phpObj2[0]['locations'][0]['name']."</h3> \r\n";
$data = $phpObj2[0]['trends'];
foreach ($data as $item) {
echo "<br />".$item['name']."\r\n";
echo "<br /> \r\n";
}
if(empty($item)){
echo "No results found";
}
}
}
I then add it to #abraham's html.inc file (along with some php to see the rate limit status) and html.inc is included in the index.php:
<h1>Top Twitter Trends</h1>
<form name='mainForm' method="get">
<input name='location' id='location' type='text'/><br/>
<button id='lookUpTrends'>Submit</button>
</form>
<?php showContent();
$ratelimit = file_get_contents("http://api.twitter.com/1/account/rate_limit_status.json");
echo $ratelimit;
?>
</div>
#abraham's index.php file has some example calls, and since my call doesn't look like this I think that is probably why it isn't being authenticated.
/* Some example calls */
//$connection->post('statuses/update', array('status' => date(DATE_RFC822)));
//$connection->post('statuses/destroy', array('id' => 5437877770));
//$connection->post('friendships/create', array('id' => 9436992));
//$connection->post('friendships/destroy', array('id' => 9436992));
Please help me find what I need to fix so that my API calls are authenticated.
update 10-21
I think in order to make an authenticated API call I need to include something like this is my code:
$connection->get('trends/place', array('id' => $woeid));
It didn't fix my problem, but maybe it is on the right track?
First off, you'll find that keeping your PHP and HTML separate will really help streamline your code and keep logical concerns separate (aggregating the data and displaying it are two different concerns)(many PHPers like MVC).
The code you have shared appears to be correct. My guess is that the issue lies in the creation of the OAuth connection, which should look something like:
<?php
/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $token,$secret);
Where CONSUMER_KEY and CONSUMER_SECRET are from your Trends Test app and $token and $secret are from the user signing in to twitter and allowing your app permission. Are all these values showing up when you create the TwitterOAuth object?
Also, be sure you update the config items in the twitteroauth.php file (specifically line 21 should be set to use the 1.1 API and line 29 should be set to 'json').

Twitter OAuth Problem

I am trying to use Twitter Oauth to login.
index.php
<?php
require ("twitteroauth/twitteroauth.php");
session_start();
// The TwitterOAuth instance
$twitteroauth = new TwitterOAuth('00000000000000000', '0000000000000000000000000000000');
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken('http://bakasura.in/twitter/twitter_oauth.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.');
}
?>
Once the page loads it takes me to the Authorization Page When i click Allow it takes me back to the http://bakasura.in/twitter/twitter_oauth.php
<?php
require ("twitteroauth/twitteroauth.php");
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret'])){
// We've got everything we need
echo "Authorized";
} else {
// Something's missing, go back to square 1
//header('Location: twitter_login.php');
echo "Not Authorized";
}
?>
And it says "Not Authorized"
you can try it here http://bakasura.in/twitter/
you did not start your session in the second page. As long as you do not call session_start(), your session variables are not available
Some PHP setups have configured their php.ini to autostart your session, but when I look at your server setup, I see you are not sending out a cookie header for your php session on your second page, so I'm pretty sure that your session is not started on your second page...

Resources