colorfield / mastodon-api
Mastodon API 的 PHP 封装器
0.1.5
2023-07-28 22:15 UTC
Requires
- php: >=8.1.0
- guzzlehttp/guzzle: ^7.0.0
- vlucas/phpdotenv: ^5.5
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.22
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.2.0
- rector/rector: ^0.17.6
- spatie/ray: ^1.37
- squizlabs/php_codesniffer: ^3.7
- vimeo/psalm: ^5.13
This package is not auto-updated.
Last update: 2024-09-19 00:39:46 UTC
README
Mastodon API 的 PHP 封装器,包含 OAuth 辅助工具。基于 Guzzle。
这是一个纯 API 封装器,因此通过让开发者传递所需的端点和参数,使其更能抵御 API 变更(新参数等)。
快速入门
使用 Composer 安装。最新版本需要 PHP 8.1。对于之前的 PHP 版本,请使用 v0.1.0
。
composer require colorfield/mastodon-api
某些请求,如公开时间线,不需要任何身份验证。
获取公开数据。
初始化 API。
$name = 'MyMastodonApp'; $instance = 'mastodon.social'; $config = new Colorfield\Mastodon\ConfigurationVO($name, $instance); $this->api = new MastodonAPI($config);
请求公开端点。
$timeline = $this->api->getPublicData('/timelines/public');
这相当于
$timeline = $this->api->get('/timelines/public', [], false);
其中第 3 个参数表示我们不需要任何身份验证。
使用 OAuth 进行身份验证
对于需要令牌的端点,这是必需的。
要获取 OAuth 凭据,还有一个轻量级客户端也包含在 test_oauth 中,通过本地 PHP 服务器。它提供了客户端 ID、客户端密钥和载体。请参阅下面的 开发 部分。
注册您的应用程序
$name = 'MyMastodonApp'; $instance = 'mastodon.social'; $oAuth = new Colorfield\Mastodon\MastodonOAuth($name, $instance);
默认配置仅限于 read
和 write
权限范围。您可以通过以下方式修改它:
$oAuth->config->setScopes(['read', 'write', 'follow', 'push']);
或使用枚举
$oAuth->config->setScopes([ OAuthScope::read->name, OAuthScope::write->name, OAuthScope::follow->name, OAuthScope::push->name ]);
请注意,必须在获取令牌时执行此操作,因此之后无法覆盖它。有关权限范围更多信息。
获取授权代码
- 获取授权 URL
$authorizationUrl = $oAuth->getAuthorizationUrl();
- 转到此 URL,授权并复制授权代码。
获取载体
-
将授权代码存储在配置值对象中。
$oAuth->config->setAuthorizationCode(xxx);
-
然后获取访问令牌。作为副作用,它存储在配置值对象中。
$oAuth->getAccessToken();
使用 Mastodon API
使用配置实例化 Mastodon API
OAuth 凭据应存储在配置值对象中,以供以后检索。
$name = 'MyMastodonApp'; $instance = 'mastodon.social'; $oAuth = new Colorfield\Mastodon\MastodonOAuth($name, $instance); $oAuth->config->setClientId('...'); $oAuth->config->setClientSecret('...'); $oAuth->config->setBearer('...'); $mastodonAPI = new Colorfield\Mastodon\MastodonAPI($oAuth->config);
用户登录
使用 Mastodon 邮箱和密码登录。
$oAuth->authenticateUser($email, $password);
获取
获取凭据(默认情况下假设已提供身份验证)。
$credentials = $mastodonAPI->get('/accounts/verify_credentials');
获取关注者
$followers = $mastodonAPI->get('/accounts/USER_ID/followers');
发布
清除通知
$clearedNotifications = $mastodonAPI->post('/notifications/clear');
@todo 完成删除、PUT、补丁和流。
开发
手动测试工具
OAuth
有一个交互式演示可用。
- 克隆 GitHub 存储库。
- 在克隆的目录中运行
- 运行
composer install
- 运行
php -S localhost:8000
- 在您的浏览器中,转到 http://localhost:8000/test_oauth.php
- 您将获得客户端 ID 和客户端密钥,点击授权 URL 链接,然后在 Mastodon 下确认授权并复制授权代码。
- 获取载体:点击“获取访问令牌”按钮。
- 使用您的 Mastodon 用户名(电子邮件)和密码进行身份验证:点击“登录”。
Mastodon API
- 将
.env.local
复制为.env
- 定义使用OAuth以及您的Mastodon邮箱和密码获取的信息。
- 在您的浏览器中,访问 http://localhost:8000/test_api.php