noweh/twitter-api-v2-php
Composer 安装命令:
composer require noweh/twitter-api-v2-php
包简介
This library provides methods for sending messages to Twitter and receiving statuses.
README 文档
README
Twitter API V2 is a PHP package which provides an easy and fast access to Twitter REST API for Version 2 endpoints.
Documentation
- Installation
- Github Actions
- Usage
- Tweets endpoints
- Users endpoints
- Contributing
Installation
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.
Github Actions
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.
Usage
Active your developer 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.
Configuration setup
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.
API Functionality
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).
Include the HTTP headers provided by Twitter in the response
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" } ... } } */
Free mode
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);
Tweets endpoints
Timeline endpoints
Find Recent Mentioning for a User
Example:
$return = $client->timeline()->getRecentMentions($accountId)->performRequest();
Find Recent Tweets for a User
Example:
$return = $client->timeline()->getRecentTweets($accountId)->performRequest();
Reverse Chronological Timeline by user ID
Example:
$return = $client->timeline()->getReverseChronological()->performRequest();
Tweet/Likes endpoints
Tweets liked by a user
Example:
$return = $client->tweetLikes()->addMaxResults($pageSize)->getLikedTweets($accountId)->performRequest();
Users who liked a tweet
Example:
$return = $client->tweetLikes()->addMaxResults($pageSize)->getUsersWhoLiked($tweetId)->performRequest();
Tweet/Lookup endpoints
Search specific tweets
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() ;
Find all replies from a Tweet
->addFilterOnConversationId($tweetId);
Tweet endpoints
Fetch a tweet by Id
Example:
$return = $client->tweet()->->fetch(1622477565565739010)->performRequest();
Create a new Tweet
Example:
$return = $client->tweet()->create()->performRequest(['text' => 'Test Tweet... ']);
Upload image to Twitter (and use in Tweets)
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"] ] ] ]) ;
Tweet/Quotes endpoints
Returns Quote Tweets for a Tweet specified by the requested Tweet ID
Example:
$return = $client->tweetQuotes()->getQuoteTweets($tweetId)->performRequest();
Retweet endpoints
Retweet a Tweet
Example:
$return = $client->retweet()->performRequest(['tweet_id' => $tweet_id]);
Tweet/Replies endpoints
Hide a reply to a Tweet
Example:
$return = $client->->tweetReplies()->hideReply($tweetId)->performRequest(['hidden' => true]);
Unhide a reply to a Tweet
Example:
$return = $client->->tweetReplies()->hideReply($tweetId)->performRequest(['hidden' => false]);
Tweet/Bookmarks endpoints
Lookup a user's Bookmarks
Example:
$return = $client->tweetBookmarks()->lookup()->performRequest();
Users endpoints
User/Blocks endpoints
Retrieve the users which you've blocked
Example:
$return = $client->userBlocks()->lookup()->performRequest();
User/Follows endpoints
Retrieve the users which are following you
Example:
$return = $client->userFollows()->getFollowers()->performRequest();
Retrieve the users which you are following
Example:
$return = $client->userFollows()->getFollowing()->performRequest();
Follow a user
Example:
$return = $client->userFollows()->follow()->performRequest(['target_user_id' => $userId]);
Unfollow a user
Example:
$return = $client->userFollows()->unfollow($userId)->performRequest(['target_user_id' => self::$userId]);
User/Lookup endpoints
Find Me
Example:
$return = $client->userMeLookup()->performRequest();
Find Twitter Users
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() ;
User/Mutes endpoints
Retrieve the users which you've muted
Example:
$return = $client->userMutes()->lookup()->performRequest();
Mute user by username or ID
Example:
$return = $client->userMutes()->mute()->performRequest(['target_user_id' => $userId]);
Unmute user by username or ID
Example:
$return = $client->userMutes()->unmute()->performRequest(['target_user_id' => $userId]);
Contributing
Fork/download the code and run
composer install
copy test/config/.env.example to test/config/.env and add your credentials for testing.
To run tests
./vendor/bin/phpunit
To run code analyzer
./vendor/bin/phpstan analyse .
noweh/twitter-api-v2-php 适用场景与选型建议
noweh/twitter-api-v2-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 259.56k 次下载、GitHub Stars 达 128, 最近一次更新时间为 2021 年 09 月 20 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「php」 「api」 「twitter」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 noweh/twitter-api-v2-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 noweh/twitter-api-v2-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 noweh/twitter-api-v2-php 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Handles basic OAuth/OAuth2 authentication along with classes for common services
Simple Twitter API wrapper
Simple Sharing generates social media share links within CP entry pages, allowing you to quickly & easily share entries.
A PSR-7 compatible library for making CRUD API endpoints
A helper module for pdf-print, print and social share functionality based on bootstrap to custom modules.
Laravel package for the simplification and integration of many of your users most wanted login providers. Installation is a breeze. Never worry about OAuth again.
统计信息
- 总下载量: 259.56k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 128
- 点击次数: 31
- 依赖项目数: 2
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-09-20