Twitter API for Laravel 5.5+, 6.x, 7.x & 8.x

Overview

Twitter for PHP

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

Twitter API for Laravel 6.x, 7.x, 8.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

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 responses will be returned as objects. To change this, use the format option in the parameters you pass to any method.

format : object|json|array (default:object)

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

  • getSettings() - Returns settings (including current trend, geo and sleep time information) for the authenticating user.
  • getCredentials()
  • postSettings() - Updates the authenticating user’s settings.
  • postSettingsDevice() - Sets which device Twitter delivers updates to for the authenticating user. Sending none as the device parameter will disable SMS updates.
  • postProfile() - Sets some values that users are able to set under the “Account” tab of their settings page. Only the parameters specified will be updated.
  • postBackground() - Updates the authenticating user’s profile background image. This method can also be used to enable or disable the profile background image.
  • postProfileImage() - Updates the authenticating user’s profile image. Note that this method expects raw multipart data, not a URL to an image.
  • destroyUserBanner() - Removes the uploaded profile banner for the authenticating user. Returns HTTP 200 upon success.
  • postUserBanner() - Uploads a profile banner on behalf of the authenticating user. For best results, upload an profile_banner_url node in their Users objects.

Account Activity (Premium)

  • setWebhook($env, $url) - Registers a webhook url for all event types in the given environment.
  • crcHash($crcToken) - Returns HMAC SHA-256 hash from the given CRC token and consumer secret. You'll need to return this on your webhook (more info).
  • getWebhooks($env) - Returns webhook URLs for the given environment (or all environments if none provided), and their statuses for the authenticating app.
  • updateWebhooks($env, $webhookId) - Triggers the challenge response check (CRC) for the given enviroments webhook for all activites. If the check is successful, returns true and reenables the webhook by setting its status to valid.
  • destroyWebhook($env, $webhookId) - Removes the webhook from the provided application's all activities configuration. Returns true on success.
  • setSubscriptions($env) - Subscribes the provided application to all events for the provided environment for all message types. Returns true on success.
  • getSubscriptions($env) - Returns true if the provided user context has an active subscription with provided application.
  • getSubscriptionsCount() - Returns the count of subscriptions that are currently active on your account for all activities.
  • getSubscriptionsList($env) - Returns a list of the current All Activity type subscriptions.
  • destroyUserSubscriptions($env, $userId) - Deactivates subscription for the specified user id from the environment. Returns true on success.

Block

  • getBlocks() - Returns a collection of user objects that the authenticating user is blocking.
  • getBlocksIds() - Returns an array of numeric user ids the authenticating user is blocking.
  • postBlock() - Blocks the specified user from following the authenticating user. In addition the blocked user will not show in the authenticating users mentions or timeline (unless retweeted by another user). If a follow or friend relationship exists it is destroyed.
  • destroyBlock() - Un-blocks the user specified in the ID parameter for the authenticating user. Returns the un-blocked user in the requested format when successful. If relationships existed before the block was instated, they will not be restored.

DirectMessage

  • getDm() - Returns a single direct message event, specified by an id parameter.
  • getDms() - Returns all Direct Message events (both sent and received) within the last 30 days. Sorted in reverse-chronological order.
  • destroyDm() - Destroys the direct message specified in the required ID parameter. The authenticating user must be the recipient of the specified direct message.
  • postDm() - Publishes a new message_create event resulting in a Direct Message sent to a specified user from the authenticating user. Returns an event if successful. Supports publishing Direct Messages with optional Quick Reply and media attachment.

Favorite

  • getFavorites() - Returns the 20 most recent Tweets favorited by the authenticating or specified user.
  • destroyFavorite() - Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful.
  • postFavorite() - Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful.

Friendship

  • getNoRters() - Returns a collection of user_ids that the currently authenticated user does not want to receive retweets from.
  • getFriendsIds() - Returns a cursored collection of user IDs for every user following the specified user.
  • getFollowersIds() - Returns a cursored collection of user IDs for every user following the specified user.
  • getFriendshipsIn() - Returns a collection of numeric IDs for every user who has a pending request to follow the authenticating user.
  • getFriendshipsOut() - Returns a collection of numeric IDs for every protected user for whom the authenticating user has a pending follow request.
  • postFollow() - Allows the authenticating users to follow the user specified in the ID parameter.
  • postUnfollow() - Allows the authenticating user to unfollow the user specified in the ID parameter.
  • postFollowUpdate() - Allows one to enable or disable retweets and device notifications from the specified user.
  • getFriendships() - Returns detailed information about the relationship between two arbitrary users.
  • getFriends() - Returns a cursored collection of user objects for every user the specified user is following ( otherwise known as their “friends”).
  • getFollowers() - Returns a cursored collection of user objects for users following the specified user.
  • getFriendshipsLookup() - Returns the relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided. Values for connections can be: following, following_requested, followed_by, none, blocking, muting.

Geo

  • getGeo() - Returns all the information about a known place.
  • getGeoReverse() - Given a latitude and a longitude, searches for up to 20 places that can be used as a place_id when updating a status.
  • getGeoSearch() - Search for places that can be attached to a statuses/update. Given a latitude and a longitude pair, an IP address, or a name, this request will return a list of all the valid places that can be used as the place_id when updating a status.
  • getGeoSimilar() - Locates places near the given coordinates which are similar in name. Conceptually you would use this method to get a list of known places to choose from first. Then, if the desired place doesn't exist, make a request to POST geo/place to create a new one. The token contained in the response is the token needed to be able to create a new place.

Help

  • postSpam() - Report the specified user as a spam account to Twitter. Additionally performs the equivalent of POST blocks / create on behalf of the authenticated user.
  • getHelpConfiguration() - Returns the current configuration used by Twitter including twitter.com slugs which are not usernames, maximum photo resolutions, and t.co URL lengths.
  • getHelpLanguages() - Returns the list of languages supported by Twitter along with the language code supported by Twitter.
  • getHelpPrivacy() - Returns Twitter’s Privacy Policy.
  • getHelpTos() - Returns the Twitter Terms of Service. Note: these are not the same as the Developer Policy.
  • getAppRateLimit() - Returns the current rate limits for methods belonging to the specified resource families.

List

  • getLists() - Returns all lists the authenticating or specified user subscribes to, including their own. The user is specified using the user_id or screen_name parameters. If no user is given, the authenticating user is used.
  • getListStatuses() - Returns a timeline of tweets authored by members of the specified list. Retweets are included by default. Use the include_rts=false parameter to omit retweets.
  • destroyListMember() - Removes the specified member from the list. The authenticated user must be the list’s owner to remove members from the list.
  • getListsMemberships() - Returns the lists the specified user has been added to. If user_id or screen_name are not provided the memberships for the authenticating user are returned.
  • getListsSubscribers() - Returns the subscribers of the specified list. Private list subscribers will only be shown if the authenticated user owns the specified list.
  • postListSubscriber() - Subscribes the authenticated user to the specified list.
  • getListSubscriber() - Returns the subscribers of the specified list. Private list subscribers will only be shown if the authenticated user owns the specified list.
  • destroyListSubscriber() - Unsubscribes the authenticated user from the specified list.
  • postListCreateAll() - Adds multiple members to a list, by specifying a comma-separated list of member ids or screen names. The authenticated user must own the list to be able to add members to it. Note that lists can’t have more than 5,000 members, and you are limited to adding up to 100 members to a list at a time with this method.
  • getListMember() - Check if the specified user is a member of the specified list.
  • getListMembers() - Returns the members of the specified list. Private list members will only be shown if the authenticated user owns the specified list.
  • postListMember() - Add a member to a list. The authenticated user must own the list to be able to add members to it. Note that lists cannot have more than 5,000 members.
  • destroyList() - Deletes the specified list. The authenticated user must own the list to be able to destroy it.
  • postListUpdate() - Updates the specified list. The authenticated user must own the list to be able to update it.
  • postList() - Creates a new list for the authenticated user. Note that you can’t create more than 20 lists per account.
  • getList() - Returns the specified list. Private lists will only be shown if the authenticated user owns the specified list.
  • getListSubscriptions() - Obtain a collection of the lists the specified user is subscribed to, 20 lists per page by default. Does not include the user’s own lists.
  • destroyListMembers() - Removes multiple members from a list, by specifying a comma-separated list of member ids or screen names. The authenticated user must own the list to be able to remove members from it. Note that lists can’t have more than 500 members, and you are limited to removing up to 100 members to a list at a time with this method.
  • getListOwnerships() - Returns the lists owned by the specified Twitter user. Private lists will only be shown if the authenticated user is also the owner of the lists.

Media

  • uploadMedia() - Upload media (images) to Twitter, to use in a Tweet or Twitter-hosted Card.

Search

  • getSearch() - Returns a collection of relevant Tweets matching a specified query.
  • getSavedSearches() - Returns the authenticated user’s saved search queries.
  • getSavedSearch() - Retrieve the information for the saved search represented by the given id. The authenticating user must be the owner of saved search ID being requested.
  • postSavedSearch() - Create a new saved search for the authenticated user. A user may only have 25 saved searches.
  • destroySavedSearch() - Destroys a saved search for the authenticating user. The authenticating user must be the owner of saved search id being destroyed.

Status

  • getMentionsTimeline() - Returns the 20 most recent mentions (tweets containing a users’s @screen_name) for the authenticating user.
  • getUserTimeline() - Returns a collection of the most recent Tweets posted by the user indicated by the screen_name or user_id parameters.
  • getHomeTimeline() - Returns a collection of the most recent Tweets and retweets posted by the authenticating user and the users they follow. The home timeline is central to how most users interact with the Twitter service. *
  • getRtsTimeline() - Returns the most recent tweets authored by the authenticating user that have been retweeted by others.
  • getRts() - Returns a collection of the 100 most recent retweets of the tweet specified by the id parameter.
  • getTweet() - Returns a single Tweet, specified by the id parameter. The Tweet’s author will also be embedded within the tweet.
  • destroyTweet() - Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status. Returns the destroyed status if successful.
  • postTweet() - Updates the authenticating user’s current status, also known as tweeting.
  • postRt() - Retweets a tweet. Returns the original tweet with retweet details embedded.
  • getOembed() - Returns a single Tweet, specified by either a Tweet web URL or the Tweet ID, in an oEmbed-compatible format. The returned HTML snippet will be automatically recognized as an Embedded Tweet when Twitter’s widget JavaScript is included on the page.
  • getRters() - Returns a collection of up to 100 user IDs belonging to users who have retweeted the tweet specified by the id parameter.
  • getStatusesLookup() - Returns fully-hydrated tweet objects for up to 100 tweets per request, as specified by comma-separated values passed to the id parameter.

Trend

  • getTrendsPlace() - Returns the top 10 trending topics for a specific WOEID, if trending information is available for it.
  • getTrendsAvailable() - Returns the locations that Twitter has trending topic information for.
  • getTrendsClosest() - Returns the locations that Twitter has trending topic information for, closest to a specified location.

User

  • getUsersLookup() - Returns fully-hydrated user objects for up to 100 users per request, as specified by comma-separated values passed to the user_id and/or screen_name parameters.
  • getUsers() - Returns a variety of information about the user specified by the required user_id or screen_name parameter. The author’s most recent Tweet will be returned inline when possible.
  • getUsersSearch() - Provides a simple, relevance-based search interface to public user accounts on Twitter. Try querying by topical interest, full name, company name, location, or other criteria. Exact match searches are not supported.
  • getUserBanner() - Returns a map of the available size variations of the specified user’s profile banner. If the user has not uploaded a profile banner, a HTTP 404 will be served instead. This method can be used instead of string manipulation on the profile_banner_url returned in user objects as described in Profile Images and Banners.
  • muteUser() - Mutes the user specified in the ID parameter for the authenticating user.
  • unmuteUser() - Un-mutes the user specified in the ID parameter for the authenticating user.
  • mutedUserIds() - Returns an array of numeric user ids the authenticating user has muted.
  • mutedUsers() - Returns an array of user objects the authenticating user has muted.
  • getSuggesteds() - Access the users in a given category of the Twitter suggested user list.
  • getSuggestions() - Access to Twitter’s suggested user list. This returns the list of suggested user categories. The category can be used in GET users / suggestions / :slug to get the users in that category.
  • getSuggestedsMembers() - Access the users in a given category of the Twitter suggested user list and return their most recent status if they are not a protected user.

Twitter API v2

Tweet Lookup

  • getTweet() - Returns a variety of information about a single Tweet specified by the requested ID.
  • getTweets() - Returns a variety of information about the Tweet specified by the requested ID or list of IDs.

Search Tweets

  • searchRecent() - The recent search endpoint returns Tweets from the last seven days that match a search query.

  • searchAll() - The full-archive search endpoint returns the complete history of public Tweets matching a search query; since the first Tweet was created March 26, 2006.

    Note: This endpoint is only available to those approved for the Academic Research product track.

Timelines

  • userTweets() - Returns Tweets composed by a single user, specified by the requested user ID. By default, the most recent ten Tweets are returned per request. Using pagination, the most recent 3,200 Tweets can be retrieved.
  • userMentions() - Returns Tweets mentioning a single user specified by the requested user ID. By default, the most recent ten Tweets are returned per request. Using pagination, up to the most recent 800 Tweets can be retrieved.

Filtered Stream

  • getStreamRules() - Return a list of rules currently active on the streaming endpoint, either as a list or individually.
  • postStreamRules() - Add or delete rules to your stream.
  • getStream() - Streams Tweets in real-time based on a specific set of filter rules.

Sampled Stream

  • getSampledStream() - Streams about 1% of all Tweets in real-time.

Hide Replies

  • hideTweet() - Hides or unhides a reply to a Tweet.

Tweet Counts

  • countRecent() - Receive a count of Tweets that match a query in the last 7 days

  • countAll() - Receive a count of Tweets that match a query

    Note: Only available via the Academic Research product track.

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:

// ...

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);
Comments
  • Class 'Twitter' not found

    Class 'Twitter' not found

    Hello, while implementing this plugin, I am getting an error as:

    Class 'Twitter' not found

    What I have done:

    update composer.json

    "thujohn/twitter": "~2.0" Run composer update

    In config/app.php and added the service provider

    'providers' => [ Thujohn\Twitter\TwitterServiceProvider::class, ]

    added aliases:

    'aliases' => [ 'Twitter' => Thujohn\Twitter\Facades\Twitter::class, ]

    In top of my controller, I import the twitter as
    use Twitter;

    but still getting the error

    Class 'Twitter' not found

    Please help

    opened by vijayrana99 26
  • Not able to set param for direct message

    Not able to set param for direct message

    Hello There,

    I have integrated this in my web app and now wants to use direct message but I am able to send because getting error.

    Array to string conversion

    so it means either I am using and sending parameters wrong in postDm method or something need to change in tmhOAuth.php which we are using for sending request.

    Please let me know how I can create params and can use direct message apis.

    Here is the code sample which I am following ->

    
    $twitterConfigs=[
    'consumer_key' => 'my_consumer_key',
    'consumer_secret' => 'my_consumer_secret',
    'token'     => 'my_oauth_token',
    'secret'     => 'my_oauth_token_secret',
    ];
    Twitter::reconfig($twitterConfigs);
    
    $recipient_id = 1234567890; 
    $pm_mesaage = urlencode('Hello World');
    
    
    $params = ['type'=>'message_create', 
    			 'message_create' => [ 
    			 	'target' => ['recipient_id' => $recipient_id],
    			 	'message_data' => ["text" => $pm_mesaage]
    			 ]
    			];
    try
    {
    	$response = Twitter::postDm($params);
    	print_r($response);
    }
    catch (\Exception $e)
    {
    	$errors = Twitter::error();
    	print_r($errors);
    }
    
    bug 
    opened by pspatel 22
  • postTweet posting endlessly in command?

    postTweet posting endlessly in command?

    Hello,

    I've been using this package for over a year now, this is the only time I've had an issue so first and foremost - thank you.

    I've been using 2.0.*@dev for about a month now as suggested for Laravel 5. I was due to launch a Laravel 5 version of one of my sites this evening, when I hit a bit of a wall when running composer update on my production server. Of course, this package had updated since I last did a composer update on my local therefore my production was ahead.

    So, the previous code I had was:

    $twitter = \Twitter::postTweetMedia([
        'status' => twitter_status($photo->female),
        'media[]'=> file_get_contents($photo->path),
        'format' => 'json'
    ]);
    $twitter = json_decode($twitter);
    

    This was working perfectly up until about an hour ago when I updated the package locally to fix it here to ensure I can sleep happy.

    Following the documentation provided, I've updated my config file (of which contains the new UPLOAD_URL, etc.) and have updated my code to be the following:

    $media = \Twitter::uploadMedia([
        'media' => file_get_contents($photo->path)
    ]);
    
    $twitter = \Twitter::postTweet([
        'status'    => twitter_status($photo->female),
        'media_ids' => $media->media_id_string
    ]);
    
    $twitter = json_decode($twitter);
    

    Now, this is working fine - but it has some odd behaviour. At least what I have experienced, the best way I can show you this is suggested you check out this screen recording - I quickly explain what's happening: https://www.youtube.com/watch?v=BhuzrzJL13I

    Note, at the time of posting this - the video is still processing on the above link, but shouldn't take too long.

    So to shorten down what I have done;

    • Pulled in latest updates for this package
    • Configured as per documentation
    • Adjust code to implement new Twitter uploading method
    • Code previously was fine (fired once), now continuously fires - doesn't stop until I manually stop the queue worker.

    I hope you can help! Thanks, Joe.

    opened by joedawson 20
  • Override config settings for user tokens

    Override config settings for user tokens

    Hey there, I'm trying to use your library for allowing any registered user of my app to programatically post tweets. If I'm not mistaken, the current setup will just pull whatever token pair I choose to hardcode into the config. I'm wondering if there's a way to dynamically push the token creds of a currently logged in user to the twitter library?

    opened by dambridge 17
  • 'Unknown Error'

    'Unknown Error'

    Hey, been using this lib for a few months now, and its started giving a random error that just says 'unknown error' here's the stack trace. Please let me know what you think

    Next ErrorException: [0] Unknown error (View: /var/www/oblivion-networks.com/resources/views/layouts/main.blade.php) (View: /var/www/oblivion-networks.com/resources/views/layouts/main.blade.php) in /var/www/oblivion-networks.com/vendor/thujohn/twitter/src/Thujohn/Twitter/Twitter.php:297
    Stack trace:
    #0 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/View/Engines/PhpEngine.php(44): Illuminate\View\Engines\CompilerEngine->handleViewException(Object(ErrorException), 0)
    #1 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php(59): Illuminate\View\Engines\PhpEngine->evaluatePath('/var/www/oblivi...', Array)
    #2 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/View/View.php(149): Illuminate\View\Engines\CompilerEngine->get('/var/www/oblivi...', Array)
    #3 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/View/View.php(120): Illuminate\View\View->getContents()
    #4 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/View/View.php(85): Illuminate\View\View->renderContents()
    #5 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Http/Response.php(45): Illuminate\View\View->render()
    #6 /var/www/oblivion-networks.com/vendor/symfony/http-foundation/Response.php(201): Illuminate\Http\Response->setContent(Object(Illuminate\View\View))
    #7 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Routing/Router.php(1028): Symfony\Component\HttpFoundation\Response->__construct(Object(Illuminate\View\View))
    #8 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Routing/Router.php(653): Illuminate\Routing\Router->prepareResponse(Object(Illuminate\Http\Request), Object(Illuminate\View\View))
    #9 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Routing\Router->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
    #10 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(41): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
    #11 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(137): Illuminate\Routing\Middleware\SubstituteBindings->handle(Object(Illuminate\Http\Request), Object(Closure))
    #12 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(33): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #13 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(65): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
    #14 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(137): Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure))
    #15 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(33): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #16 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
    #17 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(137): Illuminate\View\Middleware\ShareErrorsFromSession->handle(Object(Illuminate\Http\Request), Object(Closure))
    #18 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(33): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #19 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(64): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
    #20 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(137): Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), Object(Closure))
    #21 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(33): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #22 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
    #23 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(137): Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), Object(Closure))
    #24 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(33): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #25 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(59): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
    #26 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(137): Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), Object(Closure))
    #27 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(33): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #28 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(104): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
    #29 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Routing/Router.php(655): Illuminate\Pipeline\Pipeline->then(Object(Closure))
    #30 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Routing/Router.php(629): Illuminate\Routing\Router->runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
    #31 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Routing/Router.php(607): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
    #32 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(268): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
    #33 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
    #34 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(46): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
    #35 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(137): Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure))
    #36 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(33): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #37 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(104): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
    #38 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(150): Illuminate\Pipeline\Pipeline->then(Object(Closure))
    #39 /var/www/oblivion-networks.com/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(117): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
    #40 /var/www/oblivion-networks.com/public/index.php(53): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
    #41 {main}
    
    opened by z1haze 16
  • Call to undefined function GuzzleHttp\Psr7\parse_query()

    Call to undefined function GuzzleHttp\Psr7\parse_query()

    I tried to use

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

    And got the following error

    Call to undefined function GuzzleHttp\Psr7\parse_query()

    Laravel 8.4 version

    Using the 3.1 version of the package

    Twitter API 1.1 version

    bug 
    opened by stephen1204paul 14
  • Support twitter API v2

    Support twitter API v2

    This adds support for Twitter API v2.

    Highlights:

    • Easily switch between v2 endpoints and v1 endpoints by way of config.
    • Automatic use of oAuth1 or oAuth2 based on endpoint.

    Todo:

    • [x] oAuth2 support
    • [x] tests
    • [x] readme update

    Supported v2 endpoints:

    • [x] Tweet lookup
    • [x] Timelines
    • [x] Search Tweets
    • [x] Hide replies
    • [x] User lookup
    • [x] Follows
    • [x] Filtered Stream
    • [x] Sampled stream

    Try it out

    composer require atymic/twitter:dev-twitter-api-v2

    References

    • Twitter v2 API doc: https://developer.twitter.com/en/docs/twitter-api/early-access
    • Related issue(s): https://github.com/atymic/twitter/issues/330
    • Twitter + Laravel playground repo: https://github.com/reliq/laravel-twitter-playground
    • Twitter + PHP DI playground repo: https://github.com/reliq/php-di-twitter-playground
    opened by reliq 13
  • Video upload

    Video upload

    Marking it here to keep it on track - Twitter is going to add video upload support soon, so I would love this library to be updated as well (for Laravel 4).

    https://twittercommunity.com/t/twitter-video-support-in-rest-and-streaming-api/31258/15

    enhancement help wanted 
    opened by YOzaz 13
  • [64] The Twitter REST API v1 is no longer active. Please migrate to API v1.1

    [64] The Twitter REST API v1 is no longer active. Please migrate to API v1.1

    Hi,

    I'm using the library with Laravel version 5.2.45 and i receive this error when i try to post. I dont know if im doing something wrong, but in the config file the version for the API is 1.1

    opened by crmolinaz 12
  • Undefined ttwiter index

    Undefined ttwiter index

    Hi, Mr. John. I got error when trying to initiate your package. It showed error like this:

    ThanksForYourHelp :+1:

    ErrorException (E_UNKNOWN)

    Undefined index: ttwitter::config Open: /var/www/html/integration/vendor/thujohn/twitter/src/Thujohn/Twitter/Twitter.php

    * Only for debugging
    */
    private $debug;
    private $log = [];
    public function __construct($config = [], SessionStore $session)
    {
    if (is_array($config['ttwitter::config']))
    {
    $this->tconfig = $config['ttwitter::config'];
    
    opened by kriskornel 12
  • Twitter Premium API Support

    Twitter Premium API Support

    Is there any way to use Twitter's premium API? I saw your query method (Twitter.php:230) that you are concating the URL provided in the config file with the service name (in my case "/tweets/search/"). Since I would like to use Twitter's premium services I need to add "30day" or "fullarchive" after "/search/" and before the .json file as you can see here. Can you help me to get it done?

    enhancement help wanted 
    opened by lucasctd 11
  • Not installable with Laravel 9.38.0

    Not installable with Laravel 9.38.0

    Tried to install it under Laravel 9.38.0 but got the following error message:

    ➜  DotSexyV4 git:(dev) ✗ composer require atymic/twitter
    Using version ^3.1 for atymic/twitter
    ./composer.json has been updated
    Running composer update atymic/twitter
    Gathering patches for root package.
    Loading composer repositories with package information
    Updating dependencies
    Your requirements could not be resolved to an installable set of packages.
    
      Problem 1
        - atymic/twitter 3.1.15 requires php-di/php-di ^6.2 -> satisfiable by php-di/php-di[6.2.0, ..., 6.4.0].
        - atymic/twitter[3.1.0, ..., 3.1.14] require illuminate/support 6 - 8 -> found illuminate/support[v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev] but these were not loaded, likely because it conflicts with another require.
        - php-di/php-di[6.2.0, ..., 6.4.0] require psr/container ^1.0 -> found psr/container[1.0.0, ..., 1.x-dev] but the package is fixed to 2.0.2 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
        - Root composer.json requires atymic/twitter ^3.1 -> satisfiable by atymic/twitter[3.1.0, ..., 3.1.15].
    
    Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
    You can also try re-running composer require with an explicit version constraint, e.g. "composer require atymic/twitter:*" to figure out if any version is installable, or "composer require atymic/twitter:^2.1" if you know which you need.
    
    Installation failed, reverting ./composer.json and ./composer.lock to their original content.
    

    Enviroment Information:

    • Laravel Version 9.38.0
    • PHP Version 8.1.11
    • Composer Version 2.3.10
    opened by syntafin 1
  • Media not uploaded

    Media not uploaded

    Hi, i have a code like this :

    if(!empty($request->images)){
        		foreach ($request->images as $key => $value) {
        			$uploaded_media = Twitter::uploadMedia(['media' => File::get($value->getRealPath())]);
        			if(!empty($uploaded_media)){
                        $newTwitte['media_ids'][$uploaded_media->media_id_string] = $uploaded_media->media_id_string;
                    }
        		}
        	}
    

    But after i test it upload 1 image , there is no image on status twitter.

    I've to try dump and die and get like this

    {#1356 ▼
      +"media_id": 1573632180668231680
      +"media_id_string": "1573632180668231680"
      +"size": 150424
      +"expires_after_secs": 86400
      +"image": {#1354 ▼
        +"image_type": "image/jpeg"
        +"w": 2000
        +"h": 2000
      }
    }
    

    It's something wrong or ??? Please help, thank you!

    opened by unsa1nted 0
  • Why empty array is required for: Twitter::getTweet(12345678911, []) ?

    Why empty array is required for: Twitter::getTweet(12345678911, []) ?

    I'm using the package with laravel, Why the second argument is required for parameter ?

    v3:

    Twitter::getTweet(12345678911, [])
    

    Why not just using Twitter::getTweet(12345678911)?

    If this is a laravel package why not just return a collection ?

    opened by foremtehan 0
  • [324] Tweet must not have more than 4 mediaIds

    [324] Tweet must not have more than 4 mediaIds

    exception: "RuntimeException" file: "/home/ashlar/..../vendor/thujohn/twitter/src/Thujohn/Twitter/Twitter.php" line: 316 message: "[324] Tweet must not have more than 4 mediaIds."

    opened by codewithali 1
  • Tweet with polls parameter

    Tweet with polls parameter

    I find polls not listed as one of postTweet() parameters. Does the package have a different helper for polls that I failed to find, or is POST-ing polls not supported yet?

    opened by fidlines 1
Releases(3.1.15)
Owner
I'm a full stack developer from Australia. I maintain @laravel-notification-channels, @SocialiteProviders and @geocoder-php.
null
Twitter REST API for PHP 5.3+

README The Wid'op Twitter REST library is a modern PHP 5.3+ API allowing you to easily interact with Twitter 1.1. In order to sign your request with t

Wid'op 24 Aug 10, 2020
A PHP class for querying the Twitter API and rendering tweets as an HTML list

TweetPHP A PHP class for querying the Twitter API and rendering tweets as an HTML list. Features Works with Twitter API v1.1 Tweets are cached to avoi

Jonathan Nicol 151 Nov 25, 2022
PHP package providing easy and fast access to Twitter API V2.

Twitter API V2 is a PHP package that provides an easy and fast access to Twitter REST API for Version 2 endpoints.

Julien SCHMITT 34 Nov 26, 2022
Get the twitter user authentication keys

TwitterLogin Get the twitter user authentication keys Step 1: Go to Twitter Developer Portal and Apply to create app. Step 2: Go to app setting and en

Mohammad Zarchi 1 Nov 21, 2021
This package is a simple API laravel wrapper for Pokemontcg with a sleek Model design for API routes and authentication.

This package is a simple API laravel wrapper for Pokemontcg with a sleek Model design for API routes and authentication.

Daniel Henze 3 Aug 29, 2022
DigitalOcean API v2 client for Symfony and API Platform

DigitalOcean Bundle for Symfony and API Platform DunglasDigitalOceanBundle allows using the DigitalOcean API from your Symfony and API Platform projec

Kévin Dunglas 25 Jul 27, 2022
API SDK for OpenTrade Commerce API: Taobao, Alibaba, JD, 1688, Aliexpress, Ebay.

OtapiPhpClient Create Client $client = new OtClient($key, $secret, $lang); key (Access Key) secret (Secret for access key) language (2 symbol lang id

OpenTrade Commerce 5 Sep 20, 2022
Nexmo REST API client for PHP. API support for SMS, Voice, Text-to-Speech, Numbers, Verify (2FA) and more.

Client Library for PHP Support Notice This library and it's associated packages, nexmo/client and nexmo/client-core have transitioned into a "Maintena

Nexmo 75 Sep 23, 2022
API client for ThePay - payment gate API

This is the official highly compatible public package of The Pay SDK which interacts with The Pay's REST API. To get started see examples below.

ThePay.cz s.r.o. 3 Oct 27, 2022
Code Quiz MonoRepo (API, API Client, App)

Code Quiz Welcome to the Code Quiz Open Source project from How To Code Well. This is an Open Source project that includes an API and an App for the d

How To Code Well 2 Nov 20, 2022
A DigitalOcean API bridge for Laravel

Laravel DigitalOcean Laravel DigitalOcean was created by, and is maintained by Graham Campbell, and is a DigitalOcean PHP API Client bridge for Larave

Graham Campbell 418 Nov 1, 2022
A GitHub API bridge for Laravel

Laravel GitHub Laravel GitHub was created by, and is maintained by Graham Campbell, and is a PHP GitHub API bridge for Laravel. It utilises my Laravel

Graham Campbell 536 Nov 18, 2022
A simple API documentation package for Laravel using OpenAPI and Redoc

Laravel Redoc Easily publish your API documentation using your OpenAPI document in your Laravel Application. Installation You can install this package

Steve McDougall 14 Sep 6, 2022
Integrate RajaOngkir API with laravel

Baca ini dalam bahasa: Indonesia This is my package laravel-rajaongkir Installation You can install the package via composer: composer require kodepin

Kode Pintar 6 Aug 11, 2022
🤖 Telegram Bot API PHP SDK. Lets you build Telegram Bots easily! Supports Laravel out of the box.

Telegram Bot API - PHP SDK Telegram Bot PHP SDK lets you develop Telegram Bots in PHP easily! Supports Laravel out of the box. Telegram Bot API is an

Irfaq Syed 2.5k Nov 27, 2022
Twitch Helix API PHP Wrapper for Laravel

Laravel Twitch PHP Twitch Helix API Wrapper for Laravel 5+ ⚠️ Changes on May 01, 2020 Since May 01, 2020, Twitch requires all requests to contain a va

Roman Zipp 86 Nov 22, 2022
Spikkl API client for Laravel

Spikkl for Laravel Spikkl-php-laravel-client incorporates the Spikkl API into your Laravel or Lumen project. Requirements Get yourself a free Spikkl a

Spikkl 0 Jul 17, 2022
MobilePay API for Laravel 9.x

MobilePay for PHP MobilePay API for Laravel 9.x Installation You can install the package via composer: composer require robert-hansen/mobilepay-php Yo

Robert 4 Nov 15, 2022
Laravel 8.x package wrapper library for Metatrader 5 Web API

Laravel 8.x package wrapper library for Metatrader 5 Web API

Ali A. Dhillon 10 Nov 13, 2022