Created
April 9, 2018 19:08
-
-
Save LegaiAA/57483f8bef726f39b2168c6541321c3a to your computer and use it in GitHub Desktop.
Twitter application-only request data from a user timeline using a bearer token.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Authenticate API requests with the bearer token | |
* | |
* The bearer token may be used to issue requests to API endpoints which | |
* support application-only auth. To use the bearer token, construct a normal | |
* HTTPS request and include an Authorization header with the value of | |
* Bearer <base64 bearer token value>. Signing is not required. | |
* | |
* developer.twitter.com/en/docs/basics/authentication/overview/application-only | |
* | |
*/ | |
function api_twitter_request($token) | |
{ | |
/** | |
* Check if token_type is bearer | |
*/ | |
if ($token === false || !isset($token->token_type) | |
|| $token->token_type != 'bearer') { | |
return false; | |
} | |
/** | |
* GET statuses/user_timeline using bearer token to make request | |
* | |
* | |
* Resource Url: Twitter URL to retrieve tweets | |
* https://api.twitter.com/1.1/statuses/user_timeline.json | |
* | |
* screen_name=TTPoliceService: Screen name of user we want results from. | |
* count=25: Retrieve 25 tweets | |
* trim_user=1: Do not include user object with tweets | |
* tweet_mode=extended: Return full text tweets | |
*/ | |
$res = 'https://api.twitter.com/1.1/statuses/user_timeline.json' | |
. '?screen_name=TTPoliceService' | |
. '&count=25&trim_user=1&tweet_mode=extended'; | |
/** | |
* Create cURL session to Twitter Resource URL & return cURL handle | |
*/ | |
$ch = curl_init($res); | |
/** | |
* set appropriate options | |
*/ | |
curl_setopt_array($ch, [ | |
CURLOPT_TIMEOUT => 20, | |
CURLOPT_USERAGENT => 'MyAwesome Twitter App 1.0', | |
CURLOPT_HTTPHEADER => [ | |
'Authorization: Bearer '.$token->access_token, | |
'Accept-Encoding: gzip' | |
], | |
CURLOPT_RETURNTRANSFER => true, | |
CURLOPT_ENCODING => '', | |
]); | |
/** | |
* Return false if error | |
*/ | |
if (!$result = curl_exec($ch)) { | |
return false; | |
} | |
/** | |
* close cURL resource | |
*/ | |
curl_close($ch); | |
/** | |
* Decode results | |
*/ | |
$data = json_decode($result); | |
/** | |
* Return results | |
*/ | |
return $data; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does this work? I'm getting error using a bearer token to read user_timeline in Postman: