This is my code
// Replace these with your actual keys and tokens
$consumer_key = 'consumer_key';
$consumer_secret = 'consumer_secret';
$access_token = 'access_token';
$access_token_secret = 'access_token_secret';
// Your tweet content
$tweet = "Hello, this is my tweet from localhost! #PHP #TwitterAPI";
// Create the OAuth 1.0a header
$oauth_nonce = md5(uniqid(rand(), true));
$oauth_timestamp = time();
$oauth_signature_key = rawurlencode($consumer_secret) . '&' . rawurlencode($access_token_secret);
$oauth_params = [
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => $oauth_nonce,
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => $oauth_timestamp,
'oauth_token' => $access_token,
'oauth_version' => '1.0'
];
$base_string = 'POST&' . rawurlencode('https://api.twitter.com/1.1/statuses/update.json') . '&' . rawurlencode(http_build_query($oauth_params) . '&' . rawurlencode('status=' . rawurlencode($tweet)));
$oauth_signature = base64_encode(hash_hmac('sha1', $base_string, $oauth_signature_key, true));
$oauth_params['oauth_signature'] = $oauth_signature;
$oauth_header = 'OAuth ' . urldecode(http_build_query($oauth_params, '', ', '));
// Prepare the cURL request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.twitter.com/1.1/statuses/update.json');
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/x-www-form-urlencoded", "Authorization: $oauth_header"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['status' => $tweet]);
// Send the tweet
$result = curl_exec($ch);
// Check for cURL errors
if (curl_errno($ch)) {
// echo "cURL Error: " . curl_error($ch);
$log_message = "cURL Error: " . curl_error($ch) . PHP_EOL;
file_put_contents(plugin_dir_path(__FILE__) . 'publish-log.txt', $log_message, FILE_APPEND);
// Additional error handling if needed
} else {
// Check for HTTP status code
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 200) {
echo "Tweet sent successfully!";
} else {
// echo "Error sending tweet: " . $result;
$log_message = "Error sending tweet: " . $result;
file_put_contents(plugin_dir_path(__FILE__) . 'publish-log.txt', $log_message, FILE_APPEND);
}
}
// Close cURL resource
curl_close($ch);
But getting this in error log,
Error sending tweet: {"errors":[{"code":32,"message":"Could not authenticate you."}]}
I get tokens and secrets for twitter developer account