Twitter API V2 is a PHP package which provides an easy and fast access to Twitter REST API for Version 2 endpoints.
- Installation
- Github Actions
- Usage
- Tweets endpoints
- Users endpoints
- Contributing
To begin, you'll need to add the component to your composer.json
composer require noweh/twitter-api-v2-php
After adding the component, update your packages using composer update
or install them using composer install
.
This repository uses Github Actions for each push/pull request, employing PHPStan/PHPUnit.
Consequently, with each valid push, a new Tweet is posted from the Twitter test account.
Before anything else, you must follow this tutorial.
- Request approval for a developer account;
- Once your developer account is approved, you will need to create a Project;
- Enable read/write access for your Twitter app;
- Generate Consumer Keys and Authentication Tokens;
- Retrieve your Keys and Tokens from the Twitter Developer portal.
Expected settings are as follows:
use Noweh\TwitterApi\Client;
$settings = [
'account_id' => 'YOUR_ACCOUNT_ID',
'access_token' => 'YOUR_ACCESS_TOKEN',
'access_token_secret' => 'YOUR_TOKEN_SECRET',
'consumer_key' => 'YOUR_CONSUMER_KEY',
'consumer_secret' => 'YOUR_CONSUMER_SECRET',
'bearer_token' => 'YOUR_BEARER_TOKEN',
'free_mode' => false, // Optional
'api_base_uri' => 'https://api.twitter.com/2/', // Optional
];
$client = new Client($settings);
By changing the value of 'api_base_uri'
you can have the requests target a different server, for instance, a simulated one, thus making testing your application in isolation easier.
For a quick mock server setup you can use mockoon.
All API calls are triggered when the performRequest()
method is invoked.
Depending on the context, this method can either be empty or contain data that will be sent as PostData (refer to examples of each call below).
The performRequest()
method accepts a second parameter, $withHeaders
, which is a boolean value.
Setting this parameter to true
will include the headers information in the response.
Here are some examples of information included in headers:
x-rate-limit-limit
: the rate limit ceiling for that given endpointx-rate-limit-remaining
: the number of requests left for the 15-minute windowx-rate-limit-reset
: the remaining window before the rate limit resets, in UTC epoch seconds
Example:
$response = $this->client->tweet()->create()
->performRequest([
'text' => 'Test Tweet... '
],
withHeaders: true)
;
/*
Output:
object(stdClass)#399 (2) {
["data"]=>
object(stdClass)#398 (3) {
["edit_history_tweet_ids"]=>
array(1) {
[0]=>
string(19) "1690304934837637121"
}
["id"]=>
string(19) "1690304934837637121"
["text"]=>
string(39) "Test Tweet..."
}
["headers"]=>
...
["x-rate-limit-limit"]=>
array(1) {
[0]=>
string(5) "40000"
}
["x-rate-limit-reset"]=>
array(1) {
[0]=>
string(10) "1691835953"
}
["x-rate-limit-remaining"]=>
array(1) {
[0]=>
string(5) "39998"
}
...
}
}
*/
This API can be used in free mode, which allows for a limited usage of the API.
In this mode, the Find me method is the only one that can be used.
You have to set the free_mode
parameter to true
when creating the client.
Example:
...
$settings['free_mode'] = true;
$client = new Client($settings);
Example:
$return = $client->timeline()->getRecentMentions($accountId)->performRequest();
Example:
$return = $client->timeline()->getRecentTweets($accountId)->performRequest();
Example:
$return = $client->timeline()->getReverseChronological()->performRequest();
Example:
$return = $client->tweetLikes()->addMaxResults($pageSize)->getLikedTweets($accountId)->performRequest();
Example:
$return = $client->tweetLikes()->addMaxResults($pageSize)->getUsersWhoLiked($tweetId)->performRequest();
Example:
$return = $client->tweetLookup()
->showMetrics()
->onlyWithMedias()
->addFilterOnUsernamesFrom([
'twitterdev',
'Noweh95'
], \Noweh\TwitterApi\TweetLookup::OPERATORS['OR'])
->addFilterOnKeywordOrPhrase([
'Dune',
'DenisVilleneuve'
], \Noweh\TwitterApi\TweetLookup::OPERATORS['AND'])
->addFilterOnLocales(['fr', 'en'])
->showUserDetails()
->performRequest()
;
$client->tweetLookup()
->addMaxResults($pageSize)
->addFilterOnKeywordOrPhrase($keywordFilter)
->addFilterOnLocales($localeFilter)
->showUserDetails()
->showMetrics()
->performRequest()
;
->addFilterOnConversationId($tweetId);
Example:
$return = $client->tweet()->->fetch(1622477565565739010)->performRequest();
Example:
$return = $client->tweet()->create()->performRequest(['text' => 'Test Tweet... ']);
Example:
$file_data = base64_encode(file_get_contents($file));
$media_info = $client->uploadMedia()->upload($file_data);
$return = $client->tweet()->create()
->performRequest([
'text' => 'Test Tweet... ',
"media" => [
"media_ids" => [
(string)$media_info["media_id"]
]
]
])
;
Example:
$return = $client->tweetQuotes()->getQuoteTweets($tweetId)->performRequest();
Example:
$return = $client->retweet()->performRequest(['tweet_id' => $tweet_id]);
Example:
$return = $client->->tweetReplies()->hideReply($tweetId)->performRequest(['hidden' => true]);
Example:
$return = $client->->tweetReplies()->hideReply($tweetId)->performRequest(['hidden' => false]);
Example:
$return = $client->tweetBookmarks()->lookup()->performRequest();
Example:
$return = $client->userBlocks()->lookup()->performRequest();
Example:
$return = $client->userFollows()->getFollowers()->performRequest();
Example:
$return = $client->userFollows()->getFollowing()->performRequest();
Example:
$return = $client->userFollows()->follow()->performRequest(['target_user_id' => $userId]);
Example:
$return = $client->userFollows()->unfollow($userId)->performRequest(['target_user_id' => self::$userId]);
Example:
$return = $client->userMeLookup()->performRequest();
findByIdOrUsername()
expects either an array, or a string.
You can specify the search mode as a second parameter (Client::MODES['USERNAME']
OR Client::MODES['ID']
)
Example:
$return = $client->userLookup()
->findByIdOrUsername('twitterdev', \Noweh\TwitterApi\UserLookup::MODES['USERNAME'])
->performRequest()
;
Example:
$return = $client->userMutes()->lookup()->performRequest();
Example:
$return = $client->userMutes()->mute()->performRequest(['target_user_id' => $userId]);
Example:
$return = $client->userMutes()->unmute()->performRequest(['target_user_id' => $userId]);
Fork/download the code and run
composer install
copy test/config/.env.example
to test/config/.env
and add your credentials for testing.
./vendor/bin/phpunit
./vendor/bin/phpstan analyse .