You should use Laravel Socialite since it will simplify the whole process.
Follow the installation instructions here https://laravel.com/docs/8.x/socialite
Don't forget to put the fb credentials in your config/service.php like so:
'facebook' => [
'client_id' => env('FACEBOOK_CLIENT_ID'),
'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
'redirect' => env('FACEBOOK_REDIRECT_URL'),
],
Now that we have set up Socialite to work with Facebook, we should redirect the user to the facebook login page where it will enter his credentials.
Define the login route:
Route::get('facebook', 'FacebookLoginController@redirectToProvider');
Define the controller and the method:
class FacebookLoginController extends Controller
{
/**
* Redirect the user to the FB authentication page.
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function redirectToProvider(RedirectToProviderRequest $request)
{
return Socialite::driver('facebook')->scopes(['instagram_basic'])->asPopup()->usingGraphVersion('v7.0')->redirect();
}
}
Once the user has enter his credentials and allowed your app to have access to his data, we need to grab the access token to make calls to the fb api on his behalf.
Define the callback route in the same controller:
Route::get('facebook/callback','FacebookLoginController@handleProviderCallback');
Define the callback method in the controller:
public function handleProviderCallback(Request $request)
{
if ($request->input('error') == "access_denied")
{
return 'user has decline the authorization';
}
$user = Socialite::driver('facebook')->usingGraphVersion('v7.0')->user();
$token = $user->token;
$refreshToken = $user->refreshToken;
$id = $user->getId();
}
From here, your have your access token ($token) to call the fb api.
Please note that the user can cancel the authorization, so will probably want to catch the error in the callback. I didn't put all the error handling stuff since it can complicate the code