has('code') && request()->query('state') == Session::get('facebook_auth_state')) { $this->authenticate(); $this->storePages(); } } public function authenticate(): void { $client = $this->client(); $response = $client->get('/v11.0/oauth/access_token', ['query' => [ 'client_id' => Setting::get('facebook_client_id'), 'redirect_uri' => $this->redirectUri(), 'client_secret' => Setting::get('facebook_client_secret'), 'code' => request()->query('code') ]]); $accessToken = json_decode((string) $response->getBody())->access_token; $response = $client->get('/v11.0/oauth/access_token', ['query' => [ 'grant_type' => 'fb_exchange_token', 'client_id' => Setting::get('facebook_client_id'), 'client_secret' => Setting::get('facebook_client_secret'), 'fb_exchange_token' => $accessToken, ]]); $accessToken = json_decode((string) $response->getBody())->access_token; Setting::set('facebook_access_token', $accessToken); } public function storePages(): void { $client = $this->client($auth = true); $response = $client->get('/me'); $userId = json_decode((string) $response->getBody())->id; $response = $client->get('/v11.0/'.$userId.'/accounts'); $response = json_decode((string) $response->getBody()); foreach ($response->data as $page) { Page::updateOrCreate( ['remote_id' => $page->id], ['type' => 'facebook', 'remote_id' => $page->id, 'access_token' => $page->access_token, 'name' => $page->name], ); } } public function render() { $this->prepareVars(); return $this->makePartial('facebooklogin'); } public function redirectUri(): string { return env('FACEBOOK_REDIRECT_URI', url()->current()); } /** * Prepares the form widget view data */ public function prepareVars() { $state = str_random('20'); Session::put('facebook_auth_state', $state); $this->vars['name'] = $this->formField->getName(); $this->vars['value'] = $this->getLoadValue(); $this->vars['model'] = $this->model; $this->vars['client_id'] = Setting::get('facebook_client_id'); $this->vars['redirect_url'] = $this->redirectUri();; $this->vars['state'] = $state; } public function loadAssets() { $this->addCss('css/facebooklogin.css', 'zoomyboy.social'); $this->addJs('js/facebooklogin.js', 'zoomyboy.social'); } public function getSaveValue($value) { return $value; } private function client(bool $auth = false): Client { $query = $auth ? ['access_token' => Setting::get('facebook_access_token')] : []; return new Client([ 'base_uri' => 'https://graph.facebook.com', 'query' => $query, ]); } }