PHP code example of coderello / laravel-passport-social-grant

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

    

coderello / laravel-passport-social-grant example snippets




namespace App\Resolvers;

use Coderello\SocialGrant\Resolvers\SocialUserResolverInterface;
use Illuminate\Contracts\Auth\Authenticatable;
use Laravel\Socialite\Facades\Socialite;
use Laravel\Socialite\Two\User as ProviderUser;

class SocialUserResolver implements SocialUserResolverInterface
{
    /**
     * Resolve user by provider credentials.
     */
    public function resolveUserByProviderCredentials(string $provider, string $accessToken): ?Authenticatable
    {
        // Return the user that corresponds to provided credentials.
        // If the credentials are invalid, then return NULL.
         $providerUser = Socialite::driver($provider)->userFromToken($accessToken);
         
         return $this->findOrCreateUser($provider, $providerUser);;
    }
    
    protected function findOrCreateUser(string $provider, ProviderUser $providerUser): ?Authenticatable
    {
        // todo your logic here      
        // $email = $providerUser->getEmail();
    }
}



namespace App\Providers;

use App\Resolvers\SocialUserResolver;
use Coderello\SocialGrant\Resolvers\SocialUserResolverInterface;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * All the container bindings that should be registered.
     */
    public $bindings = [
        SocialUserResolverInterface::class => SocialUserResolver::class,
    ];
}



use GuzzleHttp\Client;
use Illuminate\Support\Arr;

$http = new Client;

$response = $http->post($domain . '/oauth/token', [
    RequestOptions::FORM_PARAMS => [
        'grant_type' => 'social', // static 'social' value
        'client_id' => $clientId, // client id
        'client_secret' => $clientSecret, // client secret
        'provider' => $providerName, // name of provider (e.g., 'facebook', 'google' etc.)
        'access_token' => $providerAccessToken, // access token issued by specified provider
    ],
    RequestOptions::HTTP_ERRORS => false,
]);
$data = json_decode($response->getBody()->getContents(), true);

if ($response->getStatusCode() === Response::HTTP_OK) {
    $accessToken = Arr::get($data, 'access_token');
    $expiresIn = Arr::get($data, 'expires_in');
    $refreshToken = Arr::get($data, 'refresh_token');

    // success logic
} else {
    $message = Arr::get($data, 'message');
    $hint = Arr::get($data, 'hint');

    // error logic
}