Installation
composer require abraham/twitteroauth
Add to composer.json if not using autoloading:
"autoload": {
"files": ["vendor/abraham/twitteroauth/autoload.php"]
}
First Use Case: OAuth Authentication
require 'vendor/autoload.php';
$connection = new Abraham\TwitterOAuth\TwitterOAuth(
'CONSUMER_KEY',
'CONSUMER_SECRET',
'OAUTH_TOKEN',
'OAUTH_TOKEN_SECRET'
);
$content = $connection->get('account/verify_credentials');
print_r($content);
Where to Look First
examples/ folder in the package for quick use casesOAuth Flow (User Authentication)
// Step 1: Request OAuth token
$request_token = $connection->oauth('oauth/request_token', [], 'GET', 'oauth_callback=OAuthCallback');
// Step 2: Redirect user to Twitter for authorization
header('Location: ' . $connection->url('oauth/authorize', ['oauth_token' => $request_token['oauth_token']]));
// Step 3: Handle callback (after user authorizes)
$verifier = $_GET['oauth_verifier'];
$access_token = $connection->oauth('oauth/access_token', [
'oauth_verifier' => $verifier
], 'GET');
// Step 4: Use access token for authenticated requests
$user = $connection->get('account/verify_credentials');
API Requests with Error Handling
try {
$response = $connection->post('statuses/update', ['status' => 'Hello, Twitter!']);
if ($response->status_code == 200) {
// Success
}
} catch (Abraham\TwitterOAuth\TwitterOAuthException $e) {
// Handle errors (e.g., rate limits, invalid credentials)
Log::error($e->getMessage());
}
Streaming API (for real-time data)
$stream = $connection->stream('statuses/filter', ['track' => 'laravel']);
while ($tweet = $stream->read()) {
// Process tweet in real-time
}
Laravel Service Provider Bind the client to the container for dependency injection:
$this->app->singleton('twitter', function ($app) {
return new Abraham\TwitterOAuth\TwitterOAuth(
config('services.twitter.consumer_key'),
config('services.twitter.consumer_secret'),
config('services.twitter.token'),
config('services.twitter.token_secret')
);
});
Rate Limiting
Use getLastResponseHeaders() to check x-rate-limit-* headers and implement retries with exponential backoff.
Environment Configuration
Store credentials in .env:
TWITTER_CONSUMER_KEY=your_key
TWITTER_CONSUMER_SECRET=your_secret
TWITTER_TOKEN=your_token
TWITTER_TOKEN_SECRET=your_token_secret
Deprecated Endpoints
statuses/update → tweets API v2). Always check Twitter API v2 docs.v2/tweets for new endpoints and handle versioning in your code.OAuth Token Expiry
Rate Limits
sleep() or queues to space requests. Check headers:
$headers = $connection->getLastResponseHeaders();
$limit = $headers['x-rate-limit-remaining'];
Callback URL Mismatch
OAuthCallback in your code matches the registered URL in Twitter Dev Console.Enable Debugging
Set debug to true in the constructor:
$connection = new Abraham\TwitterOAuth\TwitterOAuth(
'KEY', 'SECRET', 'TOKEN', 'TOKEN_SECRET', true
);
Logs HTTP requests/responses to stderr.
Common Errors
| Error Message | Likely Cause | Solution |
|---|---|---|
Could not authenticate you |
Invalid credentials | Verify keys/tokens in Twitter Dev Console |
Invalid or expired token |
Token revoked/expired | Re-authorize user |
Not authorized |
Missing permissions | Update app permissions in Twitter Dev |
Rate limit exceeded |
Too many requests | Implement retries/rate limiting |
Custom Request Signing
Override setToken() or setConsumer() to modify OAuth signing behavior:
$connection->setToken('new_token', 'new_token_secret');
Middleware for Requests
Add logic before/after requests via setRequestMethod() or hooks:
$connection->setRequestMethod('POST');
$connection->setLastResponseCallback(function ($response) {
// Modify response (e.g., decode JSON)
return json_decode($response, true);
});
Proxy Support Configure proxy settings for enterprise environments:
$connection->setProxy('http://proxy.example.com:8080');
Testing
Use Abraham\TwitterOAuth\TwitterOAuthMock for unit tests:
$mock = new TwitterOAuthMock('KEY', 'SECRET');
$mock->setLastResponse('{"screen_name":"test"}');
How can I help you explore Laravel packages today?