Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 46 additions & 38 deletions Oauth.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// fill in your consumer key and consumer secret below
define('CONSUMER_KEY', 'enter_your_consumer_key_here');
define('CONSUMER_SECRET', 'enter_your_consumer_secret_here');
define('APPLICATION', 'enter_your_twitter_app_name_here');
/**
* Get the Bearer Token, this is an implementation of steps 1&2
* from https://dev.twitter.com/docs/auth/application-only-auth
Expand All @@ -23,18 +24,17 @@ function get_bearer_token(){
$encoded_consumer_key = urlencode(CONSUMER_KEY);
$encoded_consumer_secret = urlencode(CONSUMER_SECRET);
// step 1.2 - concatinate encoded consumer, a colon character and the encoded consumer secret
$bearer_token = $encoded_consumer_key.':'.$encoded_consumer_secret;
$consumer_token = $encoded_consumer_key.':'.$encoded_consumer_secret;
// step 1.3 - base64-encode bearer token
$base64_encoded_bearer_token = base64_encode($bearer_token);
$base64_encoded_consumer_token = base64_encode($consumer_token);
// step 2
$url = "https://api.twitter.com/oauth2/token"; // url to send data to for authentication
$headers = array(
"POST /oauth2/token HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: jonhurlock Twitter Application-only OAuth App v.1",
"Authorization: Basic ".$base64_encoded_bearer_token."",
"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
"Content-Length: 29"
"User-Agent: ".APPLICATION,
"Authorization: Basic ".$base64_encoded_consumer_token,
"Content-Type: application/x-www-form-urlencoded;charset=UTF-8"
);

$ch = curl_init(); // setup a curl
Expand All @@ -43,23 +43,27 @@ function get_bearer_token(){
curl_setopt($ch, CURLOPT_POST, 1); // send as post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return output
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials"); // post body/fields to be sent
$header = curl_setopt($ch, CURLOPT_HEADER, 1); // send custom headers
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_setopt($ch, CURLOPT_HEADER, 1); // send custom headers

$retrievedhtml = curl_exec ($ch); // execute the curl
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch); // close the curl
$output = explode("\n", $retrievedhtml);
$bearer_token = '';
foreach($output as $line)
{
if($line === false)
{
// there was no bearer token
}else{
$bearer_token = $line;
}

// parse response into associative array, remove header
$results = explode("\r\n\r\n", $retrievedhtml);
$data = json_decode($results[1], true);
// if response was 'OK'
if ($httpcode == 200) {
// if the token is a bearer token
if ($data['token_type'] == 'bearer') {
// return token
return $data['access_token'];
}
}
// else, return data with returned error message
else {
return $data;
}
$bearer_token = json_decode($bearer_token);
return $bearer_token->{'access_token'};
}

/**
Expand All @@ -77,11 +81,10 @@ function invalidate_bearer_token($bearer_token){
$headers = array(
"POST /oauth2/invalidate_token HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: jonhurlock Twitter Application-only OAuth App v.1",
"Authorization: Basic ".$base64_encoded_consumer_token."",
"User-Agent: ".APPLICATION,
"Authorization: Basic ".$base64_encoded_consumer_token,
"Accept: */*",
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: ".(strlen($bearer_token)+13).""
"Content-Type: application/x-www-form-urlencoded"
);

$ch = curl_init(); // setup a curl
Expand All @@ -90,11 +93,16 @@ function invalidate_bearer_token($bearer_token){
curl_setopt($ch, CURLOPT_POST, 1); // send as post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return output
curl_setopt($ch, CURLOPT_POSTFIELDS, "access_token=".$bearer_token.""); // post body/fields to be sent
$header = curl_setopt($ch, CURLOPT_HEADER, 1); // send custom headers
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_setopt($ch, CURLOPT_HEADER, 1); // send custom headers

$retrievedhtml = curl_exec ($ch); // execute the curl
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch); // close the curl
return $retrievedhtml;

// parse response into associative array, remove header
$results = explode("\r\n\r\n", $retrievedhtml);
$data = json_decode($results[1], true);
return($data);
}

/**
Expand All @@ -112,20 +120,20 @@ function search_for_a_term($bearer_token, $query, $result_type='mixed', $count='
$headers = array(
"GET /1.1/search/tweets.json".$formed_url." HTTP/1.1",
"Host: api.twitter.com",
"User-Agent: jonhurlock Twitter Application-only OAuth App v.1",
"Authorization: Bearer ".$bearer_token."",
"User-Agent: ".APPLICATION,
"Authorization: Bearer ".$bearer_token,
);
$ch = curl_init(); // setup a curl
curl_setopt($ch, CURLOPT_URL,$url.$formed_url); // set url to send to
curl_setopt($ch, CURLOPT_URL,$url.$formed_url); // set url to send to
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // set custom headers
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return output

$retrievedhtml = curl_exec ($ch); // execute the curl
curl_close($ch); // close the curl
return $retrievedhtml;
}

// lets run a search.
$bearer_token = get_bearer_token(); // get the bearer token
print search_for_a_term($bearer_token, "test"); // search for the work 'test'
invalidate_bearer_token($bearer_token); // invalidate the token
?>

// parse response into associative array, remove header
$results = explode("\r\n\r\n", $retrievedhtml);
$data = json_decode($results[1], true);
return($data);
}
82 changes: 82 additions & 0 deletions testPage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

// lib
require_once('Oauth.php');

// Obtain bearer token
if (isset($_POST['getBearerToken'])) {

$tokenResult = get_bearer_token();
}

// invalidate/revoke bearer token
if (isset($_POST['invalidateBearerToken'])) {

$token = get_bearer_token();
$invalidate_result = invalidate_bearer_token($token);
}

// test bearer token with a search
if (isset($_POST['testBearerToken'])) {

$query = $_POST['search'];
$token = get_bearer_token();
// search request
$results = search_for_a_term($token, $query, 'mixed', 5);
// Put response into separate array, display below.
// This site is helpful for examining JSON: http://jsonviewer.stack.hu
// (Use twitter api example json, since function returns php associative array)
$tweets = $results['statuses'] ;
}

?>

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>App-only Oauth</title>
</head>

<body>
<h1>App-only Oauth</h1>
<p>Get, revoke or test an application bearer token for application-only requests to Twitter API.</p>
<hr>
<h3>Get token</h3>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<input type="submit" name="getBearerToken" value="Get Bearer Token">
</form>
<?php if ($tokenResult) {

if (is_array($tokenResult)) {
echo "Error: <br>\n";
print_r($tokenResult);
} else {
echo "Token: ".$tokenResult;
}
} ?>
<hr>
<h3>Revoke token</h3>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<input type="submit" name="invalidateBearerToken" value="Invalidate Bearer Token">
</form>
<?php if ($invalidate_result) print_r($invalidate_result); ?>
<hr>
<h3>Test token</h3>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label>Search:</label><br>
<input type="text" name="search" value="jonhurlock"><br>
<input type="submit" name="testBearerToken" value="Test Bearer Token">
</form>
<?php if ($tweets) {
echo "<ul>\n";
foreach ($tweets as $tweet) {
echo "<li>\n";
echo "\t<h4>".$tweet['user']['screen_name'].":</h4>\n";
echo "\t<p>".$tweet['text']."</p>\n";
echo "</li>\n";
}
echo "</ul>\n";
} ?>
</body>
</html>