atymic / twitter

Twitter API for Laravel 5.5+, 6.x, 7.x & 8.x
https://atymic.dev
MIT License
922 stars 290 forks source link
api-client laravel laravel-package laravel6 php tweets twitch-api twitter twitter-api twitter-bot twitter-user

Twitter for PHP

Software License StyleCI Latest Version on Packagist 3.x Downloads 2.x Downloads GitHub Release Date

Twitter API for Laravel 10.x, 11.x (and new versions as they are released). Also supports other frameworks via PHP-DI (or feel free to add support for your framework via PR)

You need to create an application and create your access token in the Application Management.

Installation

composer require atymic/twitter:^3.0 -W

Laravel Configuration

Just set the below environment variables in your .env.

TWITTER_CONSUMER_KEY=
TWITTER_CONSUMER_SECRET=
TWITTER_ACCESS_TOKEN=
TWITTER_ACCESS_TOKEN_SECRET=
TWITTER_API_VERSION=

Advanced Laravel configuration

Run php artisan vendor:publish --provider="Atymic\Twitter\ServiceProvider\LaravelServiceProvider"

/config/twitter.php

Versions

3.x

3.x is the current major version, and is not backward compatible with 2.x.

See the migration guide in UPGRADE.md.

2.x

2.x is not longer maintained. We are not accepting bug fixes, please upgrade to 3.x

Usage

Output format

You can choose between three different output formats. By default, API v1 responses will be returned as objects while API v2 responses will be returned as JSON. To change this, use the response_format option in the parameters you pass to any method.

response_format : object|json|array (v1 default:object) (v2 default:json)

Twitter API Versions

To set the default twitter API version to v2 instead of the default v1.1, set the TWITTER_API_VERSION to 2 in your .env.

If you have set the v1.1 api as the default, you can use use Twitter::forApiV2() to get an instance of the v2 client. The same goes for getting a v1 instance from a v2 client, using Twitter::forApiV1().

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

Functions

Twitter API v1.1

Account

Account Activity (Premium)

Block

DirectMessage

Favorite

Friendship

Geo

Help

List

Media

Search

Status

Trend

User

Twitter API v2

Tweet Lookup

Search Tweets

Timelines

Filtered Stream

Sampled Stream

Hide Replies

Tweet Counts

Helper Functions

Linkify : Transforms URLs, @usernames, hashtags into links. The type of $tweet can be object, array or text. By sending an object or an array the method will expand links (t.co) too.

Twitter::linkify($tweet);

Ago : Converts date into difference (2 hours ago)

Twitter::ago($timestamp);

LinkUser : Generates a link to a specific user, by their user object (such as $tweet->user), or id/string.

Twitter::linkUser($user);

LinkTweet : Generates a link to a specific tweet.

Twitter::linkTweet($tweet);

Examples

Returns a collection of the most recent Tweets posted by the user indicated by the screen_name or user_id parameters.

Route::get('/userTimeline', function()
{
    return Twitter::getUserTimeline(['screen_name' => 'thujohn', 'count' => 20, 'response_format' => 'json']);
});

Returns a collection of the most recent Tweets and retweets posted by the authenticating user and the users they follow.

Route::get('/homeTimeline', function()
{
    return Twitter::getHomeTimeline(['count' => 20, 'response_format' => 'json']);
});

Returns the X most recent mentions (tweets containing a users's @screen_name) for the authenticating user.

Route::get('/mentionsTimeline', function()
{
    return Twitter::getMentionsTimeline(['count' => 20, 'response_format' => 'json']);
});

Updates the authenticating user's current status, also known as tweeting.

Route::get('/tweet', function()
{
    return Twitter::postTweet(['status' => 'Laravel is beautiful', 'response_format' => 'json']);
});

Updates the authenticating user's current status with media.

Route::get('/tweetMedia', function()
{
    $uploaded_media = Twitter::uploadMedia(['media' => File::get(public_path('filename.jpg'))]);
    return Twitter::postTweet(['status' => 'Laravel is beautiful', 'media_ids' => $uploaded_media->media_id_string]);
});

Get User Credentials with email.

$credentials = Twitter::getCredentials([
    'include_email' => 'true',
]);

In the above, you need to pass true as a string, not as a boolean. The boolean will get converted to 1 which Twitter ignores.

This also is assuming you have your permissions setup correctly with Twitter. You have to choose 'Get user email' when you set up your Twitter app, passing the value alone will not be enough.

Sign in with twitter

use Atymic\Twitter\Facade\Twitter;

Route::get('twitter/login', ['as' => 'twitter.login', static function () {
    $token = Twitter::getRequestToken(route('twitter.callback'));

    if (isset($token['oauth_token_secret'])) {
        $url = Twitter::getAuthenticateUrl($token['oauth_token']);

        Session::put('oauth_state', 'start');
        Session::put('oauth_request_token', $token['oauth_token']);
        Session::put('oauth_request_token_secret', $token['oauth_token_secret']);

        return Redirect::to($url);
    }

    return Redirect::route('twitter.error');
}]);

Route::get('twitter/callback', ['as' => 'twitter.callback', static function () {
    // You should set this route on your Twitter Application settings as the callback
    // https://apps.twitter.com/app/YOUR-APP-ID/settings
    if (Session::has('oauth_request_token')) {
        $twitter = Twitter::usingCredentials(session('oauth_request_token'), session('oauth_request_token_secret'));
        $token = $twitter->getAccessToken(request('oauth_verifier'));

        if (!isset($token['oauth_token_secret'])) {
            return Redirect::route('twitter.error')->with('flash_error', 'We could not log you in on Twitter.');
        }

        // use new tokens
        $twitter = Twitter::usingCredentials($token['oauth_token'], $token['oauth_token_secret']);
        $credentials = $twitter->getCredentials();

        if (is_object($credentials) && !isset($credentials->error)) {
            // $credentials contains the Twitter user object with all the info about the user.
            // Add here your own user logic, store profiles, create new users on your tables...you name it!
            // Typically you'll want to store at least, user id, name and access tokens
            // if you want to be able to call the API on behalf of your users.

            // This is also the moment to log in your users if you're using Laravel's Auth class
            // Auth::login($user) should do the trick.

            Session::put('access_token', $token);

            return Redirect::to('/')->with('notice', 'Congrats! You\'ve successfully signed in!');
        }
    }

    return Redirect::route('twitter.error')
            ->with('error', 'Crab! Something went wrong while signing you up!');
}]);

Route::get('twitter/error', ['as' => 'twitter.error', function () {
    // Something went wrong, add your own error handling here
}]);

Route::get('twitter/logout', ['as' => 'twitter.logout', function () {
    Session::forget('access_token');

    return Redirect::to('/')->with('notice', 'You\'ve successfully logged out!');
}]);

Webhook

In order to setup webhook successfully, you'll need to return a hash using the CRC token in response from your webhook URL (more info).


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

}]);


### Twitter API v2 Examples

Get user tweets:

```php
// ...

use Atymic\Twitter\Twitter as TwitterContract;
use Illuminate\Http\JsonResponse;
use Twitter;

// ... 

public function userTweets(int $userId): JsonResponse
{
    $params = [
        'place.fields' => 'country,name',
        'tweet.fields' => 'author_id,geo',
        'expansions' => 'author_id,in_reply_to_user_id',
        TwitterContract::KEY_RESPONSE_FORMAT => TwitterContract::RESPONSE_FORMAT_JSON,
    ];

    return JsonResponse::fromJsonString(Twitter::userTweets($userId, $params));
}

Search tweets:

// ...
public function searchRecent(string $query): JsonResponse
{
    $params = [
        'place.fields' => 'country,name',
        'tweet.fields' => 'author_id,geo',
        'expansions' => 'author_id,in_reply_to_user_id',
        TwitterContract::KEY_RESPONSE_FORMAT => TwitterContract::RESPONSE_FORMAT_JSON,
    ];

    return JsonResponse::fromJsonString(Twitter::searchRecent($query, $params));
}
// ...
Call a newly added endpoint:

Since Twitter API v2 is in active development, you might need to call an endpoint we did not explicitly document in the "Functions" section above. Here is an example of how you may use this package to make calls to any newly added endpoints. Here we use the newly added "recent count" endpoint.

// ...
$querier = \Atymic\Twitter\Facade\Twitter::forApiV2()
    ->getQuerier();
$result = $querier
    ->withOAuth2Client()
    ->get('tweets/counts/recent', ['query' => 'foo']);
// ...

Debug

First activate debug mode in the config file.

Then you can access the logs() method.

try
{
    $response = Twitter::getUserTimeline(['count' => 20, 'response_format' => 'array']);
}
catch (Exception $e)
{
    // dd(Twitter::error());
    dd(Twitter::logs());
}

dd($response);