I’ve been testing the Twitter API v2 (Basic) since yesterday and would like to implement this with my PHP script. For testing, I created a simple script and its task is to post a tweet on twitter. However, the script returns:
Error posting a test tweet. HTTP Code: 404 API Response: NULL
This is my code:
<?php
require_once 'vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
// OAuth settings
$consumerKey = 'xxx';
$consumerSecret = 'xxx';
$accessToken = 'xxx';
$accessTokenSecret = 'xxx';
// Create TwitterOAuth object
$twitter = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
// Create a Tweet
$tweetParams = [
'text' => 'This is a test tweet.',
];
$status = $twitter->post('tweets', $tweetParams, true);
if ($twitter->getLastHttpCode() == 201) {
echo "Successfully posted a test tweet.\n";
echo "Tweet ID: " . $status->data->id . "\n";
echo "Tweet Text: " . $status->data->text . "\n";
} else {
echo "Error posting a test tweet.\n";
echo "HTTP Code: " . $twitter->getLastHttpCode() . "\n";
echo "API Response:\n";
var_dump($status);
}
?>
According to the twitter documentation, the Abraham\TwitterOAuth library is compatible with v2.
If AbrahamTwitterOAuth is not v2 compatible, could someone point me in the right direction?
Thanks,
Oblakany
Abraham\TwitterOAuth primarily uses v1.1.
You have to set the version.
// Use Twitter API v2
$twitter->setApiVersion('2');
$status = $twitter->post('tweets', $tweetParams, true);
Anybody got this still working for Twitter v2.0 API & free tier?
<?php
require_once 'vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
// OAuth settings
$consumerKey = '';
$consumerSecret = '';
$accessToken = '';
$accessTokenSecret = '';
// Create TwitterOAuth object
$twitter = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
// Create a Tweet
$tweetParams = [
'text' => 'This is a test tweet.',
];
$twitter->setApiVersion('2');
$status = $twitter->post('tweets', $tweetParams, true);
if ($twitter->getLastHttpCode() == 201) {
echo "Successfully posted a test tweet.\n";
echo "Tweet ID: " . $status->data->id . "\n";
echo "Tweet Text: " . $status->data->text . "\n";
} else {
echo "Error posting a test tweet.\n";
echo "HTTP Code: " . $twitter->getLastHttpCode() . "\n";
echo "API Response:\n";
var_dump($status);
}
?>
$ php init.php
PHP Fatal error: Uncaught Error: Call to undefined method Abraham\TwitterOAuth\TwitterOAuth::setApiVersion() in D:\xampp\htdocs\twitterPHP\init.php:18
Stack trace:
#0 {main}
thrown in D:\xampp\htdocs\twitterPHP\init.php on line 18
Fatal error: Uncaught Error: Call to undefined method Abraham\TwitterOAuth\TwitterOAuth::setApiVersion() in D:\xampp\htdocs\twitterPHP\init.php:18
Stack trace:
#0 {main}
thrown in D:\xampp\htdocs\twitterPHP\init.php on line 18
How to solve this