Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Twitter application-only authentication to connect and retrieve a bearer token.
<?php
/**
* Application-only authentication
*
* Application-only authentication is a form of authentication where an
* application makes API requests on its own behalf, without the user context.
* This method is for developers that just need to access public information.
*
* developer.twitter.com/en/docs/basics/authentication/overview/application-only
*
*/
function api_twitter_connect()
{
/**
* Consumer Keys & Secret
*/
$key = 'xxxxxxxxxxxxxxxx';
$sec = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
/**
* Encode keys according to RFC 1738
*/
$enc_key = urlencode($key);
$enc_sec = urlencode($sec);
/**
* Base64 encoded bearer token credentials
*/
$credential = base64_encode($enc_key.':'.$enc_sec);
/**
* Create cURL session to Twitter oauth2/token URL & return cURL handle
*/
$ch = curl_init('https://api.twitter.com/oauth2/token');
/**
* Set cURL options & create header request
*
* The request must be a HTTP POST request.
* The request must include an Authorization header with the value of
* Basic <base64 encoded value>.
* The request must include a Content-Type header with the value of
* application/x-www-form-urlencoded;charset=UTF-8.
* The body of the request must be grant_type=client_credentials.
*/
curl_setopt_array($ch, [
//set curl timeout
CURLOPT_TIMEOUT => 20,
//set a custom user-agent
CURLOPT_USERAGENT => 'MyAwesome Twitter App 1.0',
//create the header request with credentials
CURLOPT_HTTPHEADER => [
'Authorization: Basic '.$credential,
'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
'Accept-Encoding: gzip'
],
//set body of the request
CURLOPT_POSTFIELDS => 'grant_type=client_credentials',
//return transfer as string, instead of outputting directly
CURLOPT_RETURNTRANSFER => true,
//leaving CURLOPT_ENCODING empty allows uncompressing
CURLOPT_ENCODING => '',
]);
/**
* Return false if error
*/
if (!$request = curl_exec($ch)) {
return false;
}
/**
* Decode the JSON response
*/
$token = json_decode($request);
/**
* free request data
*/
unset($request);
/**
* close cURL resource
*/
curl_close($ch);
/**
* use token to make request
*/
return $token;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.