PHP code example of moova / laravel-passport-socialite

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

    

moova / laravel-passport-socialite example snippets


'providers' => [
    // Other service providers...
    Larva\Passport\Socialite\PassportSocialiteServiceProvider::class,
],

namespace App;

use Schedula\Laravel\PassportSocialite\User\UserSocialAccount;
class User extends Authenticatable implements UserSocialAccount {
    
    use HasApiTokens, Notifiable;

    /**
    * Find user using social provider's user
    * 
    * @param string $provider Provider name as requested from oauth e.g. facebook
    * @param string $socialUser User of social provider
    *
    * @return User
    */
    public static function findForPassportSocialite($provider,$socialUser) {
        $account = SocialAccount::where('provider', $provider)->where('social_id', $socialUser->getId())->first();
        if($account && $account->user) {
            return $account->user;
        }
        return;
    }
}

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Route;
class SocialLogin extends Controller {

	public function loginFacebook(Request $request) {
		try {

			$facebook = Socialite::driver('facebook')->userFromToken($request->accessToken);
			if(!$exist = SocialAccount::where('provider',  SocialAccount::SERVICE_FACEBOOK)->where('provider_user_id', $facebook->getId())->first()){
				
				// create user account
			}
			return response()->json($this->issueToken($request, 'facebook', $request->accessToken));
		}
		catch(\Exception $e) {
			return response()->json([ "error" => $e->getMessage() ]);
		}
		
	}
    
	public function issueToken($request, $provider, $accessToken) {
		
		/**
		* Here we will request our app to generate access token 
		* and refresh token for the user using its social identity by providing access token 
		* and provider name of the provider. (I hope its not confusing)
		* and then it goes through social grant and which fetches providers user id then calls 
		* findForPassportSocialite from your user model if it returns User object then it generates 
		* oauth tokens or else will throw error message normally like other oauth requests.
		*/
		$params = [
			'grant_type' => 'social',
			'client_id' => 'your-client-id', // it should be password grant client
			'client_secret' => 'client-secret',
			'accessToken' => $accessToken, // access token from provider
			'provider' => $provider, // i.e. facebook
		];
		$request->request->add($params);
		
		$requestToken = Request::create("oauth/token", "POST");
		$response = Route::dispatch($requestToken);
		
		return json_decode((string) $response->getBody(), true);
	}
}