public function build(LaravelFacebookSdk $fb) { $user = Auth::user(); $token = Session::get('fb_user_access_token'); $fb->setDefaultAccessToken((string) $token); $response = $fb->get('/me/photos?fields=images')->getDecodedBody(); return view('build')->with(compact('response', 'user')); }
/** * View an album. * @param $id * @param \SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb * @return \Illuminate\Http\Response */ public function show($id, LaravelFacebookSdk $fb) { // Get the album details $fb->setDefaultAccessToken($fb->getApp()->getAccessToken()->getValue()); $response = $fb->get("/{$id}?fields=id,count,name"); $album = $response->getDecodedBody(); // Get the album photos $response = $fb->get("/{$id}/photos?fields=images,link,name,source&limit=500"); $photos = $response->getDecodedBody()['data']; return View::make('gallery.album')->withAlbum($album)->withPhotos($photos); }
/** * Lấy data của người dùng facebook dựa vào longlive access token * * @param $longLiveAccessToken * * @return \Illuminate\Database\Eloquent\Model */ public function getSocialUserByLongLivedAccessToken($longLiveAccessToken) { // set access token to work with API $this->laravelSocialSdk->setDefaultAccessToken($longLiveAccessToken); // Set endpoint API $response = $this->laravelSocialSdk->get('/me?fields=id,name,last_name,first_name,email'); // get data from API $facebookUserData = $response->getGraphUser(); // update social data from api to database $facebookUser = $this->socialUser->createOrUpdateGraphNode($facebookUserData); // update long-lived access token $facebookUser->setAttribute('access_token', $longLiveAccessToken)->save(); return $facebookUser; }
/** * Callback to log in users from Facebook. Be warned; it's messy. */ public function authenticateFromJavascript(Request $request, LaravelFacebookSdk\LaravelFacebookSdk $fb) { // Try to grab the Facebook API token that the SDK should give us try { $token = $fb->getJavaScriptHelper()->getAccessToken(); } catch (Facebook\Exceptions\FacebookSDKException $e) { // Failed to obtain access token; error out return Redirect::to('/login')->withErrors([$e->getMessage()]); } if (!$token) { // If the token is falsy... uhh, what the hell return Redirect::to('/login')->withErrors(["You haven't logged into Facebook correctly."]); } if (!$token->isLongLived()) { // OAuth 2.0 client handler. This is... a thing. $oauth_client = $fb->getOAuth2Client(); // Extend the access token. try { $token = $oauth_client->getLongLivedAccessToken($token); } catch (Facebook\Exceptions\FacebookSDKException $e) { return Redirect::to('/login')->withErrors([$e->getMessage()]); } } // Keep the User Access Token in Session storage, so we can use it for this request $data = $request->all(); Session::put('fb_user_access_token', (string) $token); if (isset($data["from"])) { Session::put('fb_logged_in_from', (string) $data["from"]); } // Use the user's access token by default for this request $fb->setDefaultAccessToken($token); try { // Request Facebook user data $response = $fb->get('/me?fields=id,name,email,location,bio,picture.width(800).height(800)'); } catch (Facebook\Exceptions\FacebookSDKException $e) { return Redirect::back()->withErrors([$e->getMessage()]); } // get a Graph User object $facebook_user = $response->getGraphUser(); try { $user = User::where('facebook_id', $facebook_user["id"])->firstOrFail(); } catch (ModelNotFoundException $e) { $facebook_user["username"] = $facebook_user["id"]; $user = User::createOrUpdateGraphNode($facebook_user); } // Use the Graph User to create a Laravel User with their data Auth::login($user); if (!$user->username) { $user->username = $user->facebook_id; $user->save(); return Redirect::to('/user/editProfile')->with('message', 'Almost set up! Please fill out your profile...'); } // Log the user into Laravel return Redirect::back(); }
public function fbcallback(Facebook $fb) { try { $token = $fb->getRedirectLoginHelper()->getAccessToken(); } catch (Facebook\Exceptions\FacebookSDKException $e) { // Failed to obtain access token dd($e->getMessage()); } if (!$token) { // User denied the request } try { // Returns a `Facebook\FacebookResponse` object $response = $fb->get('/me?fields=id,name,email', $token); } catch (Facebook\Exceptions\FacebookResponseException $e) { echo 'Graph returned an error: ' . $e->getMessage(); exit; } catch (Facebook\Exceptions\FacebookSDKException $e) { echo 'Facebook SDK returned an error: ' . $e->getMessage(); exit; } $user = $response->getGraphUser(); $fbid = $user['id']; $name = $user['name']; if (isset($user['email'])) { $email = $user['email']; } else { $email = ''; } $checkUser = User::where('facebook_user_id', '=', $fbid); $cntUser = $checkUser->count(); if ($cntUser > 0) { if ($checkUser->first()->registration == 0) { Session::put('fbid', $fbid); Session::put('fbname', $name); return redirect('register'); } else { Session::put('fbid', $fbid); Session::put('fbname', $name); return redirect('dashboard'); } } else { $UserDetails = new User(); $UserDetails->facebook_user_id = $fbid; $UserDetails->full_name = $name; $UserDetails->email = $email; $UserDetails->save(); Session::put('fbid', $fbid); Session::put('fbname', $name); return redirect('register'); } }
public function callback(\SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb) { // Obtain an access token. try { $token = $fb->getAccessTokenFromRedirect(); } catch (\Facebook\Exceptions\FacebookSDKException $e) { dd($e->getMessage()); } // Access token will be null if the user denied the request // or if someone just hit this URL outside of the OAuth flow. if (!$token) { // Get the redirect helper $helper = $fb->getRedirectLoginHelper(); if (!$helper->getError()) { abort(403, 'Unauthorized action.'); } // User denied the request dd($helper->getError(), $helper->getErrorCode(), $helper->getErrorReason(), $helper->getErrorDescription()); } if (!$token->isLongLived()) { // OAuth 2.0 client handler $oauth_client = $fb->getOAuth2Client(); // Extend the access token. try { $token = $oauth_client->getLongLivedAccessToken($token); } catch (\Facebook\Exceptions\FacebookSDKException $e) { dd($e->getMessage()); } } $fb->setDefaultAccessToken($token); // Save for later \Session::put('fb_user_access_token', (string) $token); // Get basic info on the user from Facebook. try { $response = $fb->get('/me?fields=id,name,email'); } catch (\Facebook\Exceptions\FacebookSDKException $e) { dd($e->getMessage()); } // Convert the response to a `Facebook/GraphNodes/GraphUser` collection $facebook_user = $response->getGraphUser(); $user = User::firstOrCreate(['facebook_user_id' => $facebook_user->getId()]); $user->name = $facebook_user->getName(); $user->email = $facebook_user->getEmail(); $user->save(); flash()->success('Successfully logged in with Facebook'); // Log the user into Laravel \Auth::login($user); return redirect('/dashboard'); }
public function index(\SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb) { $this->facebookModel = new Facebook(); //Verify if there is user on database $userExist = SocialWorkerController::userExist(); if ($userExist > 0) { //get all the users access tokens from the database $userAccessToken = SocialWorkerController::getUsersAccessToken(); // It will run the array if the access tokens, set them in the SDK, get the posts from Facebook // and send it to class which will extract the hashtags foreach ($userAccessToken as $key => $value) { // Set the user access token into the FAcebook SDK to perform searchs on Facebook Graph $fb->setDefaultAccessToken($value["AccessToken"]); //Get yesterday's date $date = new DateTime("yesterday"); //retrive yesterday's date in the format 9999-99-99 $yesterdayDate = $date->Format("Y-m-d"); // $yesterdayDate = "2015-11-28"; //Try to make a request to Facebook Graph try { //Make a request retrieving yesterday's posts message with a limit of 100 posts per page $requestUserPosts = $fb->get("me/posts?fields=message&since=" . $yesterdayDate . "&limit=100"); //$responses = $fb->sendBatchRequest($batch); } catch (\Facebook\Exceptions\FacebookResponseException $e) { // When Graph returns an error //dd('Graph returned an error: ' . $e->getMessage()); continue; } catch (Facebook\Exceptions\FacebookSDKException $e) { // When validation fails or other local issues //dd('Facebook SDK returned an error: ' . $e->getMessage()); continue; } //Try to get posts from first to last page // Get Page 1 $feedEdge = $requestUserPosts->getGraphEdge(); $this->dispatch(new \SmartCity\Jobs\FacebookPost($feedEdge)); // Get Next pages $nextFeed = $fb->next($feedEdge); //While there is more pages keep creating new jobs to process the message while ($nextFeed !== null) { $this->dispatch(new \SmartCity\Jobs\FacebookPost($nextFeed)); $nextFeed = $fb->next($feedEdge); } } } }
public function show($id, LaravelFacebookSdk\LaravelFacebookSdk $fb) { // Find the event, or fail $data['event'] = Event::findOrFail($id); // Retrieve various attributes of the location $location = $data['event']->location; $data['location_name'] = $location->name; $data['partners'] = $data['event']->partners; // If the user is authorised, get the ticket // for the event if (Auth::check()) { try { $data['ticket'] = Ticket::where('user_id', Auth::user()->id)->where('event_id', $id)->firstOrFail(); } catch (ModelNotFoundException $e) { $data['ticket'] = false; } } else { $data['ticket'] = false; } $userIds = DB::table('tickets')->where('event_id', $data['event']->id)->pluck('user_id'); $token = Session::get('fb_user_access_token'); if ($token) { $fb->setDefaultAccessToken($token); try { // Request Facebook user data $response = $fb->get('/me/friends?limit=5000&fields=id'); $friendData = $response->getDecodedBody()["data"]; $friendIds = array_flatten($friendData); } catch (Facebook\Exceptions\FacebookSDKException $e) { return Redirect::back()->withErrors([$e->getMessage()]); } $data['users'] = DB::table('users')->whereIn('id', $userIds)->whereIn('facebook_id', $friendIds)->take(10)->get(); $data["friends"] = true; } if (!$token || empty($data["users"])) { $data['users'] = DB::table('users')->whereIn('id', $userIds)->take(10)->get(); $data["friends"] = false; } $data = array_merge($data, MediaController::uploadFiles(Crypt::encrypt($data['event']->id))); // Return a view of the event return view('events.show')->with($data); }
function index(\SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb) { $fb->setDefaultAccessToken(getenv("FACEBOOK_APP_ACCESSTOKEN")); $cities = FacebookPagesController::getCities(); foreach ($cities as $key => $values) { try { //Get last saturday date $since = new DateTime("Saturday last week"); var_dump($since); // Requires the "read_stream" permission $requestPagePosts = $fb->get($values["FacebookId"] . "/posts?fields=message,created_time&limit=100&since=" . $since->Format("Y-m-d")); //2015-11-30"); } catch (\Facebook\Exceptions\FacebookResponseException $e) { // When Graph returns an error dd('Graph returned an error: ' . $e->getMessage()); continue; } catch (\Facebook\Exceptions\FacebookSDKException $e) { // When validation fails or other local issues dd('Facebook SDK returned an error: ' . $e->getMessage()); continue; } //Try to get posts from first to last page // Get Page 1 $feedEdge = $requestPagePosts->getGraphEdge(); foreach ($feedEdge as $status) { $this->dispatch(new \SmartCity\Jobs\FacebookPagePostsJob($feedEdge, $values["City"])); } // Get Next pages $nextFeed = $fb->next($feedEdge); while ($nextFeed !== null) { foreach ($nextFeed as $status) { $this->dispatch(new \SmartCity\Jobs\FacebookPagePostsJob($nextFeed, $values["City"])); } $nextFeed = $fb->next($feedEdge); } } }
public function fbCallback(\SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb) { // Obtain an access token. try { $token = $fb->getAccessTokenFromRedirect(); } catch (Facebook\Exceptions\FacebookSDKException $e) { dd($e->getMessage()); } // Access token will be null if the user denied the request // or if someone just hit this URL outside of the OAuth flow. if (!$token) { // Get the redirect helper $helper = $fb->getRedirectLoginHelper(); if (!$helper->getError()) { abort(403, 'Unauthorized action.'); } // User denied the request dd($helper->getError(), $helper->getErrorCode(), $helper->getErrorReason(), $helper->getErrorDescription()); } if (!$token->isLongLived()) { // OAuth 2.0 client handler $oauth_client = $fb->getOAuth2Client(); // Extend the access token. try { $token = $oauth_client->getLongLivedAccessToken($token); } catch (Facebook\Exceptions\FacebookSDKException $e) { dd($e->getMessage()); } } $fb->setDefaultAccessToken($token); // Save for later Session::put('fb_user_access_token', (string) $token); // Get basic info on the user from Facebook. try { $response = $fb->get('/me?fields=id,name,email,picture{url}'); } catch (Facebook\Exceptions\FacebookSDKException $e) { dd($e->getMessage()); } // Convert the response to a `Facebook/GraphNodes/GraphUser` collection $facebook_user = $response->getGraphUser(); // Create the user if it does not exist or update the existing entry. // This will only work if you've added the SyncableGraphNodeTrait to your User model. $user = User::createOrUpdateGraphNode($facebook_user); // Log the user into Laravel Auth::login($user); return redirect('/success')->with('message', $facebook_user); }
/** * Display a listing of the resource. * * @return Response */ public function login(Request $request, SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb) { //test if token for FB login is enough $token = $request->token; // return $token; // does not work since $token is string but should be token // if (! $token->isLongLived()) { // // OAuth 2.0 client handler // $oauth_client = $fb->getOAuth2Client(); // // // Extend the access token. // try { // $token = $oauth_client->getLongLivedAccessToken($token); // } catch (Facebook\Exceptions\FacebookSDKException $e) { // dd($e->getMessage()); // } // } //this is for not include $token in the get calls $fb->setDefaultAccessToken($token); // Get basic info on the user from Facebook. try { $response = $fb->get('/me?fields=id,email'); } catch (Facebook\Exceptions\FacebookSDKException $e) { dd($e->getMessage()); } try { $profileresponse = $fb->get('/me?fields=id,name,gender'); } catch (Facebook\Exceptions\FacebookSDKException $e) { dd($e->getMessage()); } // Convert the response to a `Facebook/GraphNodes/GraphUser` collection $facebook_user = $response->getGraphUser(); $mecanex_user = $profileresponse->getGraphUser(); // Create the user if it does not exist or update the existing entry. // This will only work if you've added the SyncableGraphNodeTrait to your User model. $user = User::createOrUpdateGraphNode($facebook_user); //store profile data in mecanex_users table $id = $user->id; $facebook_id = $user->facebook_user_id; $fullname = $mecanex_user->getName(); $fullname = explode(" ", $fullname); $name = $fullname[0]; $surname = $fullname[1]; $gender = $mecanex_user->getGender(); if ($gender == 'female') { $gender_id = 2; } else { $gender_id = 1; } $fbuser = MecanexUser::firstOrNew(array('facebook_user_id' => $facebook_id)); $fbuser->user_id = $id; $fbuser->facebook_user_id = $facebook_id; $fbuser->gender_id = $gender_id; $fbuser->name = $name; $fbuser->surname = $surname; $fbuser->save(); // Log the user into Laravel Auth::login($user); // create records in table users_terms-scores once a mecanex user has been created $terms = Term::all(); foreach ($terms as $term) { $fbuser->term()->sync([$term->id => ['user_score' => 0]], false); } $response = 'User was saved'; $statusCode = 201; return response($response, $statusCode)->header('Content-Type', 'application/json'); }
/** * Facebook Authentication login. * * @param FbLoginUserRequest $request * * @return Response * * @api {post} /v1/auth/fblogin User Login with Facebook token * @apiVersion 1.0.0 * @apiName AuthFBLogin * @apiGroup Authentication * * @apiParam {String} token The facebook user access token. * * @apiSuccess {String} token Authentication token. * * @apiUse ApiLimitError */ public function fbLogin(FbLoginUserRequest $request, LaravelFacebookSdk $fb) { $token = $request->input('token'); $fb->setDefaultAccessToken($token); $response = $fb->get('/me?fields=id,name,first_name,last_name,email,picture.width(120).height(120)'); // Convert the response to a `Facebook/GraphNodes/GraphUser` collection $facebookUser = $response->getGraphUser(); // If the user is already login if ($user = app('Dingo\\Api\\Auth\\Auth')->user()) { // And his fb id is not still set if ($user->facebook_user_id == 0) { // We convert his account to fb account $user->facebook_user_id = $facebookUser->getId(); $user->save(); } } $user = User::createOrUpdateGraphNode($facebookUser); try { if (!($token = JWTAuth::fromUser($user))) { return $this->response->errorUnauthorized(); } } catch (JWTException $e) { return $this->response->error('could_not_create_token', 500); } return response()->json(compact('token')); }
/** * Display a listing of the resource. * * @return Response */ public function login(Request $request, SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb) { //test if token for FB login is enough $token = $request->token; // return $token; // does not work since $token is string but should be token // if (! $token->isLongLived()) { // // OAuth 2.0 client handler // $oauth_client = $fb->getOAuth2Client(); // // // Extend the access token. // try { // $token = $oauth_client->getLongLivedAccessToken($token); // } catch (Facebook\Exceptions\FacebookSDKException $e) { // dd($e->getMessage()); // } // } //this is for not include $token in the get calls $fb->setDefaultAccessToken($token); // Get basic info on the user from Facebook. try { $response = $fb->get('/me?fields=id,email'); } catch (Facebook\Exceptions\FacebookSDKException $e) { dd($e->getMessage()); } try { $profileresponse = $fb->get('/me?fields=id,name,gender'); } catch (Facebook\Exceptions\FacebookSDKException $e) { dd($e->getMessage()); } // Convert the response to a `Facebook/GraphNodes/GraphUser` collection $facebook_user = $response->getGraphUser(); $mecanex_user = $profileresponse->getGraphUser(); $existing_mecanex_user = MecanexUser::where('email', '=', $facebook_user["email"])->get()->first(); $existing_user = User::where('email', '=', $facebook_user["email"])->get()->first(); // Create the user if it does not exist or update the existing entry. // This will only work if you've added the SyncableGraphNodeTrait to your User model. if ($existing_user == null) { $facebook_user["username"] = "******" . $facebook_user["id"]; $user = User::createOrUpdateGraphNode($facebook_user); } else { $facebook_user["username"] = $existing_user->username; $user = $existing_user; $user->facebook_user_id = $facebook_user["id"]; $user->save(); } //store profile data in mecanex_users table $id = $user->id; $facebook_id = $user->facebook_user_id; if ($existing_mecanex_user == null) { $username = "******" . $user->facebook_user_id; } else { $username = $existing_mecanex_user->username; } $email = $user->email; $fullname = $mecanex_user->getName(); $fullname = explode(" ", $fullname); $name = $fullname[0]; $surname = $fullname[1]; $gender = $mecanex_user->getGender(); if ($gender == 'female') { $gender_id = 2; } else { $gender_id = 1; } $fbuser = MecanexUser::firstOrNew(array('email' => $email)); $fbuser->username = $username; $fbuser->user_id = $id; $fbuser->facebook_user_id = $facebook_id; $fbuser->gender_id = $gender_id; $fbuser->name = $name; $fbuser->surname = $surname; $fbuser->email = $email; $fbuser->save(); // Log the user into Laravel Auth::login($user); // create records in table users_terms-scores once a mecanex user has been created if ($existing_mecanex_user == null) { $terms = Term::all(); $total_terms = count($terms); foreach ($terms as $term) { $fbuser->term()->sync([$term->id => ['user_score' => 0]], false); $fbuser->profilescore()->sync([$term->id => ['profile_score' => 0]], false); } for ($i = 1; $i <= $total_terms; $i++) { for ($j = $i + 1; $j <= $total_terms; $j++) { $mec_matrix = new MecanexUserTermHomeTermNeighbour(); $mec_matrix->mecanex_user_id = $fbuser->id; $mec_matrix->term_home_id = $i; $mec_matrix->term_neighbor_id = $j; $mec_matrix->link_score = 0.05; $mec_matrix->save(); } } } $response = ['username' => $username, 'message' => 'User was successfully logged in']; $statusCode = 201; return response($response, $statusCode)->header('Content-Type', 'application/json'); }
public function callback(SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb) { // $token = $fb->getAccessTokenFromRedirect(); // dd($token); // Obtain an access token. try { $token = $fb->getAccessTokenFromRedirect(); } catch (Facebook\Exceptions\FacebookSDKException $e) { dd($e->getMessage()); } // Access token will be null if the user denied the request // or if someone just hit this URL outside of the OAuth flow. if (!$token) { // Get the redirect helper $helper = $fb->getRedirectLoginHelper(); if (!$helper->getError()) { abort(403, 'Unauthorized action.'); } // User denied the request // echo '<p>Error: ' . $helper->getError(); // echo '<p>Code: ' . $helper->getErrorCode(); // echo '<p>Reason: ' . $helper->getErrorReason(); // echo '<p>Description: ' . $helper->getErrorDescription(); // exit ; dd($helper->getError(), $helper->getErrorCode(), $helper->getErrorReason(), $helper->getErrorDescription()); } $fb->setDefaultAccessToken($token); if (!$token->isLongLived()) { // OAuth 2.0 client handler $oauth_client = $fb->getOAuth2Client(); // Extend the access token. try { $token = $oauth_client->getLongLivedAccessToken($token); } catch (Facebook\Exceptions\FacebookSDKException $e) { dd($e->getMessage()); } } //this is for not include $token in the get calls $fb->setDefaultAccessToken($token); // Get basic info on the user from Facebook. try { $response = $fb->get('/me?fields=id,email'); } catch (Facebook\Exceptions\FacebookSDKException $e) { dd($e->getMessage()); } try { $profileresponse = $fb->get('/me?fields=id,name,gender'); } catch (Facebook\Exceptions\FacebookSDKException $e) { dd($e->getMessage()); } // Convert the response to a `Facebook/GraphNodes/GraphUser` collection $facebook_user = $response->getGraphUser(); $mecanex_user = $profileresponse->getGraphUser(); $existing_mecanex_user = MecanexUser::where('facebook_user_id', '=', $facebook_user["id"])->get()->first(); $existing_user = User::where('facebook_user_id', '=', $facebook_user["id"])->get()->first(); // Create the user if it does not exist or update the existing entry. // This will only work if you've added the SyncableGraphNodeTrait to your User model. if ($existing_user == null) { $facebook_user["username"] = "******" . $facebook_user["id"]; } else { $facebook_user["username"] = $existing_user->username; } $user = User::createOrUpdateGraphNode($facebook_user); //store profile data in mecanex_users table $id = $user->id; $facebook_id = $user->facebook_user_id; if ($existing_mecanex_user == null) { $username = "******" . $user->facebook_user_id; } else { $username = $existing_mecanex_user->username; } $email = $user->email; $fullname = $mecanex_user->getName(); $fullname = explode(" ", $fullname); $name = $fullname[0]; $surname = $fullname[1]; $gender = $mecanex_user->getGender(); if ($gender == 'female') { $gender_id = 2; } else { $gender_id = 1; } $fbuser = MecanexUser::firstOrNew(array('facebook_user_id' => $facebook_id)); $fbuser->username = $username; $fbuser->user_id = $id; $fbuser->facebook_user_id = $facebook_id; $fbuser->gender_id = $gender_id; $fbuser->name = $name; $fbuser->surname = $surname; $fbuser->email = $email; $fbuser->save(); // Log the user into Laravel Auth::login($user); if ($existing_mecanex_user == null) { // create records in table users_terms-scores once a mecanex user has been created $terms = Term::all(); $total_terms = count($terms); foreach ($terms as $term) { $fbuser->term()->sync([$term->id => ['user_score' => 0]], false); $fbuser->profilescore()->sync([$term->id => ['profile_score' => 0]], false); } for ($i = 1; $i <= $total_terms; $i++) { for ($j = $i + 1; $j <= $total_terms; $j++) { $mec_matrix = new MecanexUserTermHomeTermNeighbour(); $mec_matrix->mecanex_user_id = $fbuser->id; $mec_matrix->term_home_id = $i; $mec_matrix->term_neighbor_id = $j; $mec_matrix->link_score = 0.05; $mec_matrix->save(); } } } return redirect('/home')->with('message', 'Successfully logged in with Facebook'); }