本文整理汇总了PHP中Facebook\Facebook类的典型用法代码示例。如果您正苦于以下问题:PHP Facebook类的具体用法?PHP Facebook怎么用?PHP Facebook使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Facebook类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: facebook
public function facebook()
{
$fb = new Facebook\Facebook(['app_id' => '144053429274589', 'app_secret' => '4ef6916e238aff3b6726dac08b853135', 'default_graph_version' => 'v2.4', 'default_access_token' => 'CAACDBA17B90BAKI0aOXR1vF5zDtZCOKPbWSXopnvvNpBTHZARXVhUVrZBAXn4CB1ZBgsyk13ZA38uZAWoffwchukfajiIOG7cYrNEEAm0CdlHgwDRWeBuD0OZCfT6PB6U2vsE3O45jTgx0YTc24TXEqyZC1ZBIjc9GxD3aSv6WAyIWsZCpAcbnxYPNCdL389FxaRsZD']);
try {
$response = $fb->get('/me?fields=id,name,email');
} 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;
}
$me = $response->getGraphUser();
$name = $me['name'];
$email = $me['email'];
$u_name = preg_replace('/@.*$/', '', $me['email']);
$user = new User();
$user->name = $name;
$user->type = 'general';
$user->register_type = 'facebook';
$user->username = $u_name;
$user->email = $email;
$user->password = bcrypt($u_name);
$user->save();
$lastInsertedId = $user->id;
$profile = new Profile();
$profile = $user->profile()->save($profile);
$credentials = array('email' => $email, 'password' => $u_name);
if (Auth::attempt($credentials)) {
//return Redirect::to('home');
return redirect()->intended('home');
}
//echo '<pre>'; print_r($new_name);
//echo 'Logged in as ' . $me['email'];
}
示例2: callback
public function callback()
{
$code = Input::get('code');
if (strlen($code) == 0) {
return \Redirect::to('/');
}
$facebook = new Facebook(\Config::get('facebook'));
$uid = $facebook->getUser();
if ($uid == 0) {
return \Redirect::to('/');
}
$me = $facebook->api('/me');
$profile = User::where('user_id', $uid)->first();
if (empty($profile)) {
$user = new User();
$user->username = $me['name'];
$user->photo = 'https://graph.facebook.com/' . $me['id'] . '/picture?type=large';
$user->user_id = $uid;
$user->save();
$x = new leaderboard();
$x->user_id = $uid;
$x->user_name = $me['name'];
$x->round_id = 1;
$x->save();
}
$user = User::where('user_id', $uid)->select('user_id', 'username', 'photo')->first();
session()->put(['user_id' => $uid, 'name' => $user['username']]);
return redirect('/');
}
示例3: registerWithFacebook
/**
* Create a user account for the authenticated Facebook user.
*
* @return \Models\User
* @throws \Facebook\Exceptions\FacebookSDKException
* @throws \Facebook\Exceptions\FacebookSDKException
* @throws \App\Exceptions\AccountDeactivatedException
*/
public function registerWithFacebook()
{
// Load up the facebook sdk
$fb = new Facebook(['app_id' => env('FACEBOOK_APP_ID'), 'app_secret' => env('FACEBOOK_APP_SECRET'), 'default_graph_version' => env('FACEBOOK_DEFAULT_GRAPH_VERSION')]);
// Retrieve the access token
$jsHelper = $fb->getJavaScriptHelper();
$accessToken = $jsHelper->getAccessToken();
if (!$accessToken) {
throw new FacebookSDKException('The access token is invalid.');
}
// Get the profile info
$profileResponse = $fb->get('/me', $accessToken);
if ($profileResponse->getHttpStatusCode() != 200) {
throw new FacebookSDKException('We could not retrieve your profile info.');
}
$profileInfo = $profileResponse->getGraphUser();
// Check if the user is already registered
$user = User::findBySocialAccountIdAndTypeId($profileInfo['id'], SocialAccountType::FACEBOOK);
if ($user && !$user->active) {
throw new AccountDeactivatedException();
}
// Create a new user account or update the existing one
$user = $user ?: new User();
$user->social_account_type_id = SocialAccountType::FACEBOOK;
$user->social_account_id = $profileInfo['id'];
$user->name = $profileInfo['name'];
$user->email = isset($profileInfo['email']) ? $profileInfo['email'] : '';
$user->location_name = isset($profileInfo['location']) ? $profileInfo['location']->getName() : '';
$user->loggedin_at = date('Y-m-d H:i:s');
$user->active = true;
$user->save();
return $user;
}
示例4: set_fb_request_session
/**
* Create an instance of Facebook session
*/
private function set_fb_request_session()
{
$settings = array('app_id' => self::$appId, 'app_secret' => self::$appSecret, 'default_graph_version' => 'v2.5');
$fb = new Facebook\Facebook($settings);
$fb->setDefaultAccessToken(self::$fbToken);
self::$fbSession = $fb;
}
示例5: newsFeed
/**
* @return array|mixed
*/
public function newsFeed()
{
$request = new Facebook($this->fbConfig);
$response = $request->get($this->pageId . '/posts?limit=5');
$postFeeds = json_decode($response->getGraphEdge()->asJson());
return $postFeeds;
}
示例6: facebookLogin
public function facebookLogin(Request $request, $offline = null)
{
if ($offline) {
$facebook_id = '129795977365516';
$name = 'Offline User';
$gender = 'male';
} else {
$fb = new Facebook\Facebook(['app_id' => config('services.facebook.client_id'), 'app_secret' => config('services.facebook.client_secret'), 'default_graph_version' => 'v2.5', 'default_access_token' => $request->input('access_token')]);
try {
$response = $fb->get('/me?fields=id,name,gender,email');
} catch (Facebook\Exceptions\FacebookResponseException $e) {
return response('Graph returned an error: ' . $e->getMessage(), 500);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
return response('Facebook SDK returned an error: ' . $e->getMessage(), 500);
}
$user = $response->getGraphUser();
$facebook_id = $user->getId();
$name = $user->getName();
$gender = $user->getProperty('gender');
}
$participant = Participant::where('facebook_id', $facebook_id)->first();
if ($participant) {
session(['participantId' => $participant->id]);
return response()->json(['alreadyExists' => true]);
}
$participant = new Participant();
$participant->name = $name;
$participant->facebook_id = $facebook_id;
$participant->gender = $gender;
session(['participant' => $participant]);
return response()->json(['alreadyExists' => false]);
}
示例7: checkGrantExtension
/**
* @see OAuth2\IOAuth2GrantExtension::checkGrantExtension
*/
public function checkGrantExtension(IOAuth2Client $client, array $inputData, array $authHeaders)
{
if (!isset($inputData['facebook_access_token'])) {
return false;
}
$this->facebookSdk->setDefaultAccessToken($inputData['facebook_access_token']);
try {
// Try to get the user with the facebook token from Open Graph
$fbData = $this->facebookSdk->get('/me?fields=email,id,first_name,last_name,name,name_format');
if (!$fbData instanceof \Facebook\FacebookResponse) {
return false;
}
// Check if a user match in database with the facebook id
$user = $this->userManager->findUserBy(['facebookId' => $fbData->getDecodedBody()['id']]);
// If none found, try to match email
if (null === $user && isset($fbData->getDecodedBody()['email'])) {
$user = $this->userManager->findUserBy(['email' => $fbData->getDecodedBody()['email']]);
}
// If no user found, register a new user and grant token
if (null === $user) {
// TODO: Create new user
return false;
} else {
// Else, return the access_token for the user
// Associate user with facebookId
$user->setFacebookId($fbData->getDecodedBody()['id']);
$this->userManager->updateUser($user);
return array('data' => $user);
}
} catch (\FacebookApiExceptionion $e) {
return false;
}
}
示例8: handle
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$fb = new Facebook(['app_id' => env('FACEBOOK_APP_ID'), 'app_secret' => env('FACEBOOK_APP_SECRET'), 'default_graph_version' => 'v2.5']);
$helper = $fb->getRedirectLoginHelper();
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$accessToken = $helper->getAccessToken();
}
} catch (Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
$_SESSION['facebook_access_token'] = (string) $accessToken;
return $next($request);
}
$permissions = ['public_profile', 'publish_actions'];
$loginUrl = $helper->getLoginUrl(env('CALLBACK'), $permissions);
return redirect($loginUrl);
}
示例9: fbUserInfoAction
public function fbUserInfoAction()
{
$fb = new Facebook(['app_id' => '1475718472749501', 'app_secret' => 'a67fee083c27186f52030ff3a72f24f9', 'default_graph_version' => 'v2.4']);
try {
$helper = $fb->getJavaScriptHelper();
$accessToken = $helper->getAccessToken();
$fb->setDefaultAccessToken((string) $accessToken);
$response = $fb->get('/me?locale=en_US&fields=name,email');
$userNode = $response->getGraphUser();
$email = $userNode->getField('email');
$name = $userNode->getField('name');
$arr = explode("@", $email);
$login = $arr[0];
$arr2 = explode(" ", $name);
$firstname = $arr2[0];
$lastname = $arr2[1];
return new JsonResponse(['firstname' => $firstname, 'lastname' => $lastname, 'login' => $login, 'email' => $email]);
} catch (FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
exit;
}
示例10: getTokenInfo
/**
* @param string $token
*
* @return UserProfileInterface|null
*/
protected function getTokenInfo($token)
{
try {
// Get the Facebook\GraphNodes\GraphUser object for the current user.
$response = $this->facebook->get('/me?fields=id,name,email,first_name,last_name', $token);
$user = $response->getGraphUser();
// check if we can get user identifier
if (empty($user->getId())) {
return null;
}
// do not accept tokens generated not for our application even if they are valid,
// to protect against "man in the middle" attack
$tokenMetadata = $this->facebook->getOAuth2Client()->debugToken($token);
// this is not required, but lets be sure because facebook API changes very often
$tokenMetadata->validateAppId($this->facebook->getApp()->getId());
$userProfile = new UserProfile();
$userProfile->setIdentifier($user->getId());
$userProfile->setDisplayName($user->getName());
$userProfile->setFirstName($user->getFirstName());
$userProfile->setLastName($user->getLastName());
$userProfile->setEmail($user->getEmail());
// facebook doesn't allow login with not verified email
if (!empty($user->getEmail())) {
$userProfile->setEmailVerified(true);
}
return $userProfile;
} catch (FacebookSDKException $e) {
return null;
}
}
示例11: callback
public function callback()
{
$fb = new Facebook(['app_id' => Config::get('facebook.app_id'), 'app_secret' => Config::get('facebook.app_secret'), 'default_graph_version' => Config::get('facebook.default_graph_version'), 'persistent_data_handler' => Config::get('facebook.persistent_data_handler')]);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch (Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
return Redirect::to('/')->with('mensaje', 'Graph returned an error: ' . $e->getMessage());
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
return Redirect::to('/')->with('mensaje', 'Facebook SDK returned an error: ' . $e->getMessage());
exit;
}
if (!isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
//echo '<h3>Access Token</h3>';
//var_dump($accessToken->getValue());
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
//echo '<h3>Metadata</h3>';
//var_dump($tokenMetadata);
// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId(Config::get('facebook.app_id'));
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();
if (!$accessToken->isLongLived()) {
// Exchanges a short-lived access token for a long-lived one
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
return Redirect::to('/')->with('mensaje', "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n");
exit;
}
//echo '<h3>Long-lived</h3>';
//var_dump($accessToken->getValue());
}
Session::put('fb_access_token', (string) $accessToken);
// User is logged in with a long-lived access token.
// You can redirect them to a members-only page.
return Redirect::to('/')->with('mensaje', 'Ya puede publicar');
}
示例12: index
public function index()
{
$fb = new Facebook(['app_id' => '178541382481710', 'app_secret' => '00ad5032a61d3ca526c6693f006db028', 'default_graph_version' => 'v2.4']);
$fb->setDefaultAccessToken('178541382481710|4K7VTpySNyFIp2gIKlAY3T5pXAc');
$response = $fb->get('/LesGetsOfficiel/feed?fields=id,message,full_picture,link,type&limit=100');
$response = $response->getDecodedBody();
debug($response);
die;
}
示例13: getProfile
public function getProfile($token)
{
if (empty($this->profile) === true) {
$fb = new Facebook(['app_id' => Config::get('facebook.app.id'), 'app_secret' => Config::get('facebook.app.secret'), 'default_access_token' => $token]);
$profile = $fb->get('/me')->getGraphUser();
$this->profile = array('provider' => self::PROVIDER_NAME, 'id' => $profile->getField('id'), 'email' => $profile->getField('email'), 'firstName' => $profile->getFirstName(), 'lastName' => $profile->getLastName());
}
return $this->profile;
}
示例14: indexAction
/**
* @Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
$this->get('session')->start();
$config = ['app_id' => '1690300947880602', 'app_secret' => '0b6107ea187ee9cd79adc66a2dd84254', 'default_graph_version' => 'v2.5', 'persistent_data_handler' => 'session'];
$fb = new Facebook\Facebook($config);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch (Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (!isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '<h3>Metadata</h3>';
var_dump($tokenMetadata);
// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId($config['app_id']);
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();
if (!$accessToken->isLongLived()) {
// Exchanges a short-lived access token for a long-lived one
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
exit;
}
echo '<h3>Long-lived</h3>';
var_dump($accessToken->getValue());
}
return new Response();
}
示例15: verifyCredentials
/**
*
*/
public function verifyCredentials(Request $request)
{
$config = app()->make('config');
$fb = new Facebook\Facebook(['app_id' => $config->get('services.facebook.client_id'), 'app_secret' => $config->get('services.facebook.client_secret'), 'default_graph_version' => 'v2.5']);
$helper = $fb->getJavaScriptHelper();
try {
// $accessToken = $helper->getAccessToken();
$accessToken = new AccessToken($request->input('accessToken'), $request->input('expiresIn'));
} catch (Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (!isset($accessToken)) {
echo 'No cookie set or no OAuth data could be obtained from cookie.';
exit;
}
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=id,name,email,picture,friends', $accessToken->getValue());
/*$friendsResponse = $fb->get('/me/friends', $accessToken->getValue());
//$result['data'];
foreach($friendsResponse->getGraphEdge() as $node) {
var_dump($node);
}
exit;*/
} 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;
}
// Logged in
$user = $response->getGraphUser();
// var_dump($user);exit;
// echo 'Name: ' . $user['name'];
// $_SESSION['fb_access_token'] = (string) $accessToken;
$authUser = $this->findOrCreateUser($user);
app()['auth']->login($authUser, true);
$hasher = app()->make('hash');
/*var_dump( $hasher->make(
"app()->make('config')->get('app.key')" . $authUser->facebook_id
));exit;*/
return ['username' => $authUser->email, 'password' => app()->make('config')->get('app.pass_prefix') . $authUser->facebook_id];
//return redirect()->route('home');
// get posted credentials.
// verify credentials against FB.
// fetch user data.
// check user existance: true => return user.
// check user existance: false => register and return user.
}