PHP wrapper for the Mastodon API that includes oAuth helpers, Guzzle based.
Install it via Composer.
composer require colorfield/mastodon-api
This is a plain API wrapper, so the intention is to support further changes in the API by letting the developer pass the desired endpoint.
- Get the REST Mastodon documentation.
- Get an instance from the instance list.
An interactive demo is available.
- Clone the GitHub repository.
- cd in the cloned directory
- Run
composer install
- Run
php -S localhost:8000
- In your browser, go to http://localhost:8000/test_oauth.php
- You will get the client_id and client_secret, click on the authorization URL link, then confirm the authorization under Mastodon and copy the authorization code.
- Get the bearer: click on the "Get access token" button.
- Authenticate with your Mastodon username (email) and password: click on "Login".
- Make your own copy of test_credentials.example.php as test_credentials.php
- Define in test_credentials.php the information obtained with oAuth and your Mastodon email and password.
- In your browser, go to http://localhost:8000/test_api.php
Give it a name and an optional instance. The instance defaults to mastodon.social.
$name = 'MyMastodonApp';
$instance = 'mastodon.social';
$oAuth = new Colorfield\Mastodon\MastodonOAuth($name, $instance);
The default configuration is limited the the 'read' and 'write' scopes. You can modify it via
$oAuth->config->setScopes(['read', 'write', 'follow']);
Note that this must be done while obtaining the token so you cannot override this after. More about scopes.
- Get the authorization URL
$authorizationUrl = $oAuth->getAuthorizationUrl();
- Go to this URL, authorize and copy the authorization code.
-
Store the authorization code in the configuration value object.
$oAuth->config->setAuthorizationCode(xxx);
-
Then get the access token. As a side effect, stores it on the configuration value object.
$oAuth->getAccessToken();
The oAuth credentials should be stored from the configuration value object for later retrieval. Then you can use it in this way.
$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);
Login with Mastodon email and password.
$oAuth->authenticateUser($email, $password);
Here are a few examples of the API wrapper usage. Read the full documentation.
Get credentials
$credentials = $mastodonAPI->get('/accounts/verify_credentials');
Get followers
$followers = $mastodonAPI->get('/accounts/USER_ID/followers');
Clear notifications
$clearedNotifications = $mastodonAPI->post('/notifications/clear');
@todo complete with delete and stream.