atymic/twitter

repository·main·Indexed 21 days ago

https://github.com/atymic/twitter

A PHP library for interacting with the X (formerly Twitter) API, optimized for Laravel 10.x and 11.x and supporting other frameworks via PHP-DI. It provides comprehensive support for both API v1.1 and v2, including account management, tweet lookup, search, streaming, and direct messaging. The library includes a Laravel service provider and a Twitter facade with helper functions like linkify.

Tokens
6.7K
Snippets
20
Records
34
Agent score
75%

What's inside atymic/twitter

  1. Switch between Twitter API v1.1 and v2

    main

    By default, the package uses API v1.1.

    To set API v2 as the global default, set TWITTER_API_VERSION=2 in your .env file.

    To switch versions fluently in your code:

    • Use Twitter::forApiV2() to get an instance of the v2 client.
    • Use Twitter::forApiV1() to get an instance of the v1 client.

    Note: It is safe to call Twitter::forApiV1() on either a v1 or v2 client instance.

    // If default is v1.1, get v2 client
    $v2Client = Twitter::forApiV2();
    
    // If default is v2, get v1 client
    $v1Client = Twitter::forApiV1();
  2. Publish the Twitter configuration file in Laravel

    main

    For advanced configuration, publish the package's configuration file to your config/ directory using the Artisan command:

    php artisan vendor:publish --provider="Atymic\Twitter\ServiceProvider\LaravelServiceProvider"
  3. Implement Twitter Sign-in (OAuth)

    main

    To implement a full Twitter login flow in Laravel, follow these steps:

    1. Login Route: Use getRequestToken to get an OAuth token, then getAuthenticateUrl to redirect the user to Twitter.
    2. Callback Route: Use usingCredentials($request_token, $request_token_secret) to initialize a client, then getAccessToken($oauth_verifier) to exchange the verifier for access tokens.
    3. Session Management: Store the resulting access tokens in the session to authenticate future requests on behalf of the user.
    4. Logout: Clear the access token from the session.
    // 1. Login Flow
    $token = Twitter::getRequestToken(route('twitter.callback'));
    $url = Twitter::getAuthenticateUrl($token['oauth_token']);
    // Store $token['oauth_token'] and $token['oauth_token_secret'] in session...
    
    // 2. Callback Flow
    $twitter = Twitter::usingCredentials(session('oauth_request_token'), session('oauth_request_token_secret'));
    $token = $twitter->getAccessToken(request('oauth_verifier'));
    
    // 3. Use new tokens for subsequent calls
    $twitter = Twitter::usingCredentials($token['oauth_token'], $token['oauth_token_secret']);
    $credentials = $twitter->getCredentials();
  4. Upgrade from 2.x to 3.x: Namespace Change

    main
    When upgrading to version 3.x, the package namespace has changed from Thujohn\Twitter to Atymic\Twitter. You must update all code references, imports, and class names to use the new Atymic\Twitter namespace.
  5. Configure a Twitter Webhook and CRC validation

    main

    To successfully set up a Twitter webhook, your endpoint must respond to a challenge request by returning a hash of the provided crc_token using the Twitter::crcHash() method.

    Route::post('twitter/webhook', ['as' => 'twitter.webhook', function(){
    	if (request()->has('crc_token'))
    		return response()->json(['response_token' => Twitter::crcHash(request()->crc_token)], 200);
    	
    	// Your webhook logic goes here
    }]);
  6. Upgrade from 2.x to 3.x: Update Laravel Config Files

    main

    The configuration keys in the ttwitter config file have changed in version 3.x.

    If you have not published or modified the config file, you can skip this step as the environment variable names remain unchanged.

    If you have custom configurations, follow these steps:

    1. Publish the new configuration file using the Artisan command below.
    2. Compare your existing ttwitter config file with the newly published one.
    3. Manually migrate your custom settings to the new format.
    4. Delete the old configuration file.
    php artisan vendor:publish --provider="Atymic\Twitter\ServiceProvider\LaravelServiceProvider"
  7. Configure X (formerly Twitter) for Laravel

    main

    To set up the package in a Laravel application, add the following environment variables to your .env file:

    • TWITTER_CONSUMER_KEY
    • TWITTER_CONSUMER_SECRET
    • TWITTER_ACCESS_TOKEN
    • TWITTER_ACCESS_TOKEN_SECRET
    • TWITTER_API_VERSION
    TWITTER_CONSUMER_KEY=
    TWITTER_CONSUMER_SECRET=
    TWITTER_ACCESS_TOKEN=
    TWITTER_ACCESS_TOKEN_SECRET=
    TWITTER_API_VERSION=
  8. Debug Twitter API requests

    main

    To debug API calls, first enable debug mode in your configuration file. You can then catch exceptions and use Twitter::logs() to inspect the request/response history.

    try {
        $response = Twitter::getUserTimeline(['count' => 20, 'response_format' => 'array']);
    } catch (Exception $e) {
        dd(Twitter::logs());
    }
  9. X (formerly Twitter) API v1.1 Account functions

    main

    The v1.1 API provides several methods for managing the authenticating user's account settings, profile, and credentials.

    Account Management

    • getSettings(): Returns settings including current trend, geo, and sleep time information.
    • getCredentials(): Retrieves account credentials.
    • postSettings(): Updates the authenticating user's settings.
    • postSettingsDevice(): Sets the device for Twitter updates. Sending none as the device parameter disables SMS updates.
    • postProfile(): Updates specific values under the 'Account' tab of settings.
    • postBackground(): Updates or enables/disables the profile background image.
    • postProfileImage(): Updates the profile image. Note: This method expects raw multipart data, not an image URL.
    • destroyUserBanner(): Removes the profile banner. Returns HTTP 200 on success.
    • postUserBanner(): Uploads a profile banner.
  10. X (formerly Twitter) API v1.1 Favorite functions

    main

    Manage liked (favorited) Tweets.

    • getFavorites(): Returns the 20 most recent Tweets favorited by the user (or a specified user).
    • destroyFavorite($id): Un-favorites a status by ID.
    • postFavorite($id): Favorites a status by ID.
  11. X (formerly Twitter) API v2 Streaming and Counts

    main

    Real-time data and metrics using API v2.

    Streaming

    • getStreamRules(): Returns active rules on the streaming endpoint.
    • postStreamRules(...): Adds or deletes rules for the stream.
    • getStream(...): Streams Tweets in real-time based on filter rules.
    • getSampledStream(): Streams approximately 1% of all Tweets in real-time.

    Tweet Counts

    • countRecent(...): Count of Tweets matching a query in the last 7 days.
    • countAll(...): Count of all Tweets matching a query. Note: Requires Academic Research product track.

    Other

    • hideTweet($id): Hides or unhides a reply to a Tweet.