PHP code example of atymic / twitter

1. Go to this page and download the library: Download atymic/twitter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

atymic / twitter example snippets


Twitter::linkify($tweet);

Twitter::ago($timestamp);

Twitter::linkUser($user);

Twitter::linkTweet($tweet);

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

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

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

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

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]);
});

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!');
}]);

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
}]);

// ...

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));
}

// ...
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));
}
// ...

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

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

dd($response);

/config/twitter.php