Skip to content

Instantly share code, notes, and snippets.

@lgladdy
Created March 12, 2013 09:46
Show Gist options
  • Save lgladdy/5141615 to your computer and use it in GitHub Desktop.
Save lgladdy/5141615 to your computer and use it in GitHub Desktop.
A working example of Twitter's new application-only auth, written in PHP.
<?php
//This is all you need to configure.
$app_key = '';
$app_token = '';
//These are our constants.
$api_base = 'https://api.twitter.com/';
$bearer_token_creds = base64_encode($app_key.':'.$app_token);
//Get a bearer token.
$opts = array(
'http'=>array(
'method' => 'POST',
'header' => 'Authorization: Basic '.$bearer_token_creds."\r\n".
'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
'content' => 'grant_type=client_credentials'
)
);
$context = stream_context_create($opts);
$json = file_get_contents($api_base.'oauth2/token',false,$context);
$result = json_decode($json,true);
if (!is_array($result) || !isset($result['token_type']) || !isset($result['access_token'])) {
die("Something went wrong. This isn't a valid array: ".$json);
}
if ($result['token_type'] !== "bearer") {
die("Invalid token type. Twitter says we need to make sure this is a bearer.");
}
//Set our bearer token. Now issued, this won't ever* change unless it's invalidated by a call to /oauth2/invalidate_token.
//*probably - it's not documentated that it'll ever change.
$bearer_token = $result['access_token'];
//Try a twitter API request now.
$opts = array(
'http'=>array(
'method' => 'GET',
'header' => 'Authorization: Bearer '.$bearer_token
)
);
$context = stream_context_create($opts);
$json = file_get_contents($api_base.'1.1/statuses/user_timeline.json?count=1&screen_name=lgladdy',false,$context);
$tweets = json_decode($json,true);
echo "@lgladdy's last tweet was: ".$tweets[0]['text']."\r\n";
?>
@davidandorf
Copy link

It worked for me you have to put api_key and api_secret (app_token) , also this approach only works if you want to get application level data or data of application account

@nwalton3
Copy link

Thank you! This is just what I needed.

@zikiivan
Copy link

zikiivan commented Nov 5, 2015

This code is way much organised and easier to learn than all those libraries put out there...(GOD BLESS YOU)...this is what, we need Steps to getting things done not libraries of code you cannot understand.

@fabiotnt
Copy link

Awesome Solution, man. Thanks a lot.

@tusharv
Copy link

tusharv commented Dec 1, 2016

I have gone through lot of Documentation but understand nothing, Come across this page now I understand most of things. You are the BEST!! 👍

@debojyotighosh
Copy link

This is awesome! Thanks a ton.

@cedricARN
Copy link

how to respond to a twitt from a friend from this code .?

@ArifAli999
Copy link

I'm getting a 401 HTTP error? Any idea

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment