Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Twitteroauth Laravel Package

abraham/twitteroauth

TwitterOAuth is a widely used PHP library for Twitter’s OAuth REST API. It supports currently supported PHP versions and provides authenticated request handling for Twitter endpoints. In maintenance mode with no new features planned.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require abraham/twitteroauth
    

    Add to composer.json if not using autoloading:

    "autoload": {
        "files": ["vendor/abraham/twitteroauth/autoload.php"]
    }
    
  2. 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);
    
  3. Where to Look First


Implementation Patterns

Common Workflows

  1. OAuth 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');
    
  2. 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());
    }
    
  3. Streaming API (for real-time data)

    $stream = $connection->stream('statuses/filter', ['track' => 'laravel']);
    while ($tweet = $stream->read()) {
        // Process tweet in real-time
    }
    

Integration Tips

  • 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
    

Gotchas and Tips

Pitfalls

  1. Deprecated Endpoints

    • Twitter frequently deprecates endpoints (e.g., statuses/updatetweets API v2). Always check Twitter API v2 docs.
    • Fix: Use v2/tweets for new endpoints and handle versioning in your code.
  2. OAuth Token Expiry

    • User access tokens can expire. Implement token refresh logic or prompt users to re-authorize.
    • Fix: Store tokens in the database with expiry dates and validate before use.
  3. Rate Limits

    • Unauthorized requests or rapid calls trigger rate limits (e.g., 900 requests/15-min for unauthenticated).
    • Fix: Use sleep() or queues to space requests. Check headers:
      $headers = $connection->getLastResponseHeaders();
      $limit = $headers['x-rate-limit-remaining'];
      
  4. Callback URL Mismatch

    • Twitter requires exact callback URL matching during OAuth setup.
    • Fix: Ensure OAuthCallback in your code matches the registered URL in Twitter Dev Console.

Debugging

  • 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

Extension Points

  1. Custom Request Signing Override setToken() or setConsumer() to modify OAuth signing behavior:

    $connection->setToken('new_token', 'new_token_secret');
    
  2. 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);
    });
    
  3. Proxy Support Configure proxy settings for enterprise environments:

    $connection->setProxy('http://proxy.example.com:8080');
    
  4. Testing Use Abraham\TwitterOAuth\TwitterOAuthMock for unit tests:

    $mock = new TwitterOAuthMock('KEY', 'SECRET');
    $mock->setLastResponse('{"screen_name":"test"}');
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
bugban/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin