When I write code to authorize with facebook-sdk, I was confused so I write how to solve this problem.
Firstly
User move to laravel redirect controller when user click button.
use Illuminate\Support\Str; class OauthController { public function redirectToFacebook() { $state = Str::random(32); session()->put('state', $state); $sendData = [ "client_id" => 'client_id-xxxxx-xxxx', "redirect_url" => 'https://hogehoge.com/facebook/callback', "state" => $state, "response_type" => 'code', ]; $url = 'https://www.facebook.com/v8.0/dialog/oauth?'.http_build_query($sendData); return redirect($url); } }
You need to set session ‘state’ for XSRF.
Then, you redirect to facebook authorize page.
Yser come back to callback url you set in sendData After user authorize.
Secondly
You set function for callback from facebook.
use Facebook\Facebook; use Facebook\PersistentData\PersistentDataInterface; class OauthController { ... public function callbackFromFacebook(string $accessToken = null) { $facebook = new Facebook([ 'app_id' => FACEBOOK_APPLICATION_ID, 'app_secret' => FACEBOOK_SECRET_ID, 'default_graph_version' => 'v2.9', 'persistent_data_handler' => new MyLaravelPersistentDataHandler(), ]); $helper = $facebook->getRedirectLoginHelper(); if ($accessToken) { $accessToken = $helper->getAccessToken(); } $response = $facebook->get('/me?fields=id', $accessToken); $user = $response->getGraphUser(); $userId =$user->getId(); ... } } class MyLaravelPersistentDataHandler implements PersistentDataInterface { public function get($key) { return session()->get($key); } public function set($key, $value) { session()->put($key, $value); } }
First, you make instance of Facebook.
If you want to use FacebookDataHandler, you make FacebookDataHandler class and set persistent_data_handler key and value.
getRedirectLoginHelper method is used to generate a “Login with Facebook” link and obtain an access token from a redirect.
This method check session of state for csrf measures.
Second, try to get user data with accessToken.
There you can set field like id,email,first_name,family_name which you want to get at field.
After this. you make user-data object by using getGraphUser.
This object can get user data by method.
FInally, you write function you want.
I refer to this page.
https://developers.facebook.com/docs/php/Facebook/5.0.0
https://developers.facebook.com/docs/php/PersistentDataInterface/5.0.0
0件のコメント