PHP code example of revolution / socialite-mastodon

1. Go to this page and download the library: Download revolution/socialite-mastodon 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/ */

    

revolution / socialite-mastodon example snippets


    'mastodon' => [
        'domain'        => env('MASTODON_DOMAIN'),
        'client_id'     => env('MASTODON_ID'),
        'client_secret' => env('MASTODON_SECRET'),
        'redirect'      => env('MASTODON_REDIRECT'),
        'scope'         => ['read', 'write'],
    ],

Route::get('/', [MastodonController::class, 'index']);
Route::get('callback', [MastodonController::class, 'callback']);

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;

class MastodonController extends Controller
{
    public function index()
    {
        return Socialite::driver('mastodon')->redirect();
    }

    public function callback()
    {
        $user = Socialite::driver('mastodon')->user();
        dd($user);
    }
}

return Socialite::driver('mastodon')
           ->setScopes(config('services.mastodon.scope', ['read']))
           ->redirect();

use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Revolution\Mastodon\Facades\Mastodon;
use App\Models\Server;

    public function login(Request $request)
    {
        //input domain by user
        $domain = $request->input('domain');

        //get app info. domain, client_id, client_secret ...
        //Server is Eloquent Model
        $server = Server::where('domain', $domain)->first();

        if (empty($server)) {
            //create new app
            $info = Mastodon::domain($domain)->createApp(client_name: 'my-app', redirect_uris: 'https://example.com/callback', scopes: 'read write');

            //save app info
            $server = Server::create([
                'domain'        => $domain,
                'client_id'     => $info['client_id'],
                'client_secret' => $info['client_secret'],
            ]);
        }

        session(['mastodon_domain' => $domain]);

        return Socialite::driver('mastodon')->with(['domain' => $domain, 'client_id' => $server->client_id])->redirect();
    }
    
    public function callback()
    {
        $domain = session('mastodon_domain');
        $server = Server::where('domain', $domain)->first();

        $user = Socialite::driver('mastodon')->with(['domain' => $domain, 'client_id' => $server->client_id, 'client_secret' => $server->client_secret])->user();
        dd($user);
    }