Skip to content

Instantly share code, notes, and snippets.

@webuti
Created November 24, 2023 14:06
Show Gist options
  • Save webuti/17f86408efeb73d27813d2da23ab8e90 to your computer and use it in GitHub Desktop.
Save webuti/17f86408efeb73d27813d2da23ab8e90 to your computer and use it in GitHub Desktop.
Twitter Create Tweet 2023
<?php
class TwitterAPI
{
private $apiUrl = 'https://api.twitter.com/2/tweets';
private $accessToken = '';
private $accessTokenSecret = '';
private $consumerKey = '';
private $consumerSecret = '';
public function postTweet($text)
{
$oauthTimestamp = time();
$oauthNonce = md5(uniqid(rand(), true));
$oauthParameters = array(
'oauth_consumer_key=' . $this->consumerKey,
'oauth_nonce=' . $oauthNonce,
'oauth_signature_method=HMAC-SHA1',
'oauth_timestamp=' . $oauthTimestamp,
'oauth_token=' . $this->accessToken,
'oauth_version=1.0'
);
sort($oauthParameters);
$oauthParameterString = implode('&', $oauthParameters);
$oauthBaseString = 'POST&';
$oauthBaseString .= urlencode($this->apiUrl) . '&';
$oauthBaseString .= urlencode($oauthParameterString);
$oauthSigningKey = urlencode($this->consumerSecret) . '&' . urlencode($this->accessTokenSecret);
$oauthSignature = base64_encode(hash_hmac('sha1', $oauthBaseString, $oauthSigningKey, true));
$oauthSignature = urlencode($oauthSignature);
$authorizationHeader = 'OAuth ';
$authorizationHeader .= 'oauth_consumer_key="' . $this->consumerKey . '", ';
$authorizationHeader .= 'oauth_nonce="' . $oauthNonce . '", ';
$authorizationHeader .= 'oauth_signature="' . $oauthSignature . '", ';
$authorizationHeader .= 'oauth_signature_method="HMAC-SHA1", ';
$authorizationHeader .= 'oauth_timestamp="' . $oauthTimestamp . '", ';
$authorizationHeader .= 'oauth_token="' . $this->accessToken . '", ';
$authorizationHeader .= 'oauth_version="1.0"';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.twitter.com/2/tweets',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode(['text' => $text]), // Send JSON payload
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json', // Set Content-Type header for JSON
'Authorization: ' . $authorizationHeader
),
)
);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
}
// Example usage:
$twitterAPI = new TwitterAPI();
$response = $twitterAPI->postTweet("hello world");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment