The master branch is not stable, please use tagged release branches. The previous stable branch with support for the old API is now under the opengraph-v1.0 branch.
This is a Yii application component wrapper for the official Facebook PHP SDK 4.0
Also included are some helper functions that:
- Include the Facebook JS SDK on your pages
- Allow setting Open Graph meta tags
- Easy rendering of Facebook Social Plugins.
Facebook PHP SDK: https://developers.facebook.com/docs/reference/php/4.0.0 https://github.com/facebook/facebook-php-sdk-v4
Facebook JS SDK: https://developers.facebook.com/docs/javascript
Facebook Social Plugins: https://developers.facebook.com/docs/plugins/
Open Graph Protocol: https://developers.facebook.com/docs/graph-api
INSTALLATION: ¶
It is recommended that you install this via composer.
"require": {
"splashlab/yii-facebook-opengraph": "dev-master"
}
Run composer update
to get the extension. This will pull down the official Facebook SDK as a dependency.
Configure Yii application component SFacebook in your yii config file:
'components'=>array(
'facebook'=>array(
'class' => '\YiiFacebook\SFacebook',
'appId'=>'YOUR_FACEBOOK_APP_ID', // needed for JS SDK, Social Plugins and PHP SDK
'secret'=>'YOUR_FACEBOOK_APP_SECRET', // needed for the PHP SDK
//'version'=>'v2.2', // Facebook APi version to default to
//'locale'=>'en_US', // override locale setting (defaults to en_US)
//'jsSdk'=>true, // don't include JS SDK
//'async'=>true, // load JS SDK asynchronously
//'jsCallback'=>false, // declare if you are going to be inserting any JS callbacks to the async JS SDK loader
//'callbackScripts'=>'', // default JS SDK init callback JavaScript
//'status'=>true, // JS SDK - check login status
//'cookie'=>true, // JS SDK - enable cookies to allow the server to access the session
//'xfbml'=>true, // JS SDK - parse XFBML / html5 Social Plugins
//'frictionlessRequests'=>true, // JS SDK - enable frictionless requests for request dialogs
//'hideFlashCallback'=>null, // JS SDK - A function that is called whenever it is necessary to hide Adobe Flash objects on a page.
//'html5'=>true, // use html5 Social Plugins instead ofolder XFBML
//'defaultScope'=>array(), // default Facebook Login permissions to request
//'redirectUrl'=>null, // default Facebook post-Login redirect URL
//'expiredSessionCallback'=>null, // PHP callable method to run if expired Facebook session is detected
//'userFbidAttribute'=>null, // if using SFacebookAuthBehavior, declare Facebook ID attribute on user model here
//'accountLinkUrl'=>null, // if using SFacebookAuthBehavior, declare link to user account page here
//'ogTags'=>array( // set default OG tags
//'og:title'=>'MY_WEBSITE_NAME',
//'og:description'=>'MY_WEBSITE_DESCRIPTION',
//'og:image'=>'URL_TO_WEBSITE_LOGO',
//),
),
),
Then, to enable the JS SDK and Open Graph meta tag functionality in your base Controller,
add this function to override the afterRender()
callback:
protected function afterRender($view, &$output) {
parent::afterRender($view,$output);
//Yii::app()->facebook->addJsCallback($js); // use this if you are registering any additional $js code you want to run on init()
Yii::app()->facebook->initJs($output); // this initializes the Facebook JS SDK on all pages
Yii::app()->facebook->renderOGMetaTags(); // this renders the OG tags
return true;
}
USAGE: ¶
Setting OG tags on a page (in view or action):
<?php Yii::app()->facebook->ogTags['og:title'] = "My Page Title"; ?>
Render Facebook Social Plugins using helper Yii widgets:
<?php $this->widget('\YiiFacebook\Plugins\LikeButton', array(
//'href' => 'YOUR_URL', // if omitted Facebook will use the OG meta tag
'show_faces'=>true,
'share' => true
)); ?>
You can, of course, just use the code for this as well if loading the JS SDK on all pages using the initJs() call in afterRender():
<div class="fb-like" data-share="true" data-show-faces="true"></div>
To use the PHP SDK anywhere in your application, just call it like so (there pass-through the Facebook class):
<?php $userid = Yii::app()->facebook->getUserId() ?>
<?php $accessToken = Yii::app()->facebook->getToken() ?>
<?php $longLivedSession = Yii::app()->facebook->getLongLivedSession() ?>
<?php $exchangeToken = Yii::app()->facebook->getExchangeToken() ?>
<?php $loginUrl = Yii::app()->facebook->getLoginUrl() ?>
<?php $reRequestUrl = Yii::app()->facebook->getReRequestUrl() ?>
<?php $accessToken = Yii::app()->facebook->accessToken() ?>
<?php $sessionInfo = Yii::app()->facebook->getSessionInfo() ?>
<?php $signedRequest = Yii::app()->facebook->getSignedRequest() ?>
<?php $signedRequestData = Yii::app()->facebook->getSignedRequestData() ?>
<?php $property = Yii::app()->facebook->getSignedRequestProperty('property_name) ?>
<?php $logoutUrl = Yii::app()->facebook->getLogoutUrl('http://example.com/after-logout') ?>
<?php $graphPageObject = Yii::app()->facebook->makeRequest('/SOME_PAGE_ID')->getGraphObject(\Facebook\GraphPage::className()) ?>
<?php
try {
$response = Yii::app()->facebook->makeRequest('/me/feed', 'POST', array(
'link' => 'www.example.com',
'message' => 'User provided message'
))->getGraphObject()
echo "Posted with id: " . $response->getProperty('id');
} catch (\Facebook\FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
?>
<?php Yii::app()->facebook->destroySession() ?>
I also created a couple of little helper functions:
<?php $graphUserObject = Yii::app()->facebook->getMe() // gets the Graph info of the current user ?>
<?php $graphUserObject = Yii::app()->facebook->getGraphUser($user_id) // gets the Graph info of the current user ?>
<?php $imageUrl = Yii::app()->facebook->getProfilePicture('large') // gets the Facebook picture URL of the current user ?>
<?php $imageUrl = Yii::app()->facebook->getProfilePicture(array('height'=>300,'width'=>300)) // $size can also be specific ?>
<?php $userinfo = Yii::app()->facebook->getInfoById($openGraphId) // gets the Graph info of a given OG entity ?>
<?php $imageUrl = Yii::app()->facebook->getProfilePictureById($openGraphId, $size) // gets the Facebook picture URL of a given OG entity ?>
BREAKING CHANGES: ¶
New version 2.x breaks everything from previous version and requires PHP 5.4
- *
CHANGE LOG: ¶
beta-1.0.1 Updating or PHP SDK 4.0
- *
I plan on continuing to update and bugfix this extension as needed.
Please log bugs to the GitHub tracker.
Extension is posted on Yii website also: http://www.yiiframework.com/extension/facebook-opengraph/
The original version with support for SDK 3.x and API 1x was forked from ianare's faceplugs Yii extension: http://www.yiiframework.com/extension/faceplugs https://github.com/digitick/yii-faceplugs
Updated Jan 14th 2015 by Evan Johnson http://splashlabsocial.com
Two things
Hi thaddeusmt,
thanks for sharing a such valuable extension but I got to notify you two issues:
1) there's a small error on your setup guide, to include this extension in the config file is needed to add one more nested level in components array
'components'=>array( 'facebook' => array ( 'class' => 'ext.yii-facebook-opengraph.SFacebook', 'appId'=>'YOUR_FACEBOOK_APP_ID', // needed for JS SDK 'secret'=>'YOUR_FACEBOOK_APP_SECRET', // needed for the PHP SDK //rest of the settings... ), ),
2) Adding afterRender override makes the app crash saying that the function is missing one argument "Missing argument 2 for CController::afterRender(), called in" . Maybe it's cause I'm running it over Yii 1.1.9?
Best Regards
Giuliano
Two things
Change the render line to:
protected function afterRender($view, &$output)
that should fix it.
Bug fixed
Thanks guys! For some reason I never got that error, maybe it was a "notice" and I have PHP notice reporting turned off. Anyway you are right, you should have that second $output parameter on the afterRender() overload, I updated the documentation to reflect this. Thanks again.
fb-root bug fixed
There was a large bug where the fb-root div was not being inserted into the DOM, causing the Social Plugins and some other JS SDK stuff not to work. It's fixed now. :)
fb-root fix
Yep,, I just encountered it and I was about to tell you but then I've found out that you laready fixed it :)
Id like to ask you one thing about the registration and login process. The best practice should be the following one:
the User makes the registration through the dedicated plugin and then is redirected in the Callback URL that you have to provide to Facebook when creating an app.
Then on the landing page where the user is redirected the site is supposed to collect User Data with the Api call:
<?php $results = Yii::app()->facebook->api('/me') ?>
Now on this landing page I let the user complete his registration through a form in which he can insert his password.
So now we have our user registered with all FB Data we want. Next time he want to login how can the website recognized that he already made the registration and is connected to the website? I guess the website should check user status with:
<?php $result = Yii::app()->facebook->status ?>
Then if he results logged am I supposed to recognize him against my database on his email? userId? or I have to handle some kind of fb token?
Thank you in advance. Best regards.
Giuliano
Logging in user registered via Facebook
A common practice is to store the user's Facebook ID in your database (along with other user information, usually in your User table). Then, when a user logs in via Facebook, I request the user's UID like so, then query my database to do the login:
$uid = Yii::app()->facebook->user; // get the current authenticated Facebook user $user = User::model()->findByUid($uid); // find the local user in your app $user->doLogin(); // your login function, whatever that is
I guess I would be curious to know if there is a better (more secure?) way to do this, but that's what I do (and what I've seen in other code). You could also hash the UID and authenticate it like a password? The email won't work, in case they change their email on Facebook.
Yii::app()->facebook->status
In this case I guess I've found another bug cause I cant explain why the "status" property has always 1 as value.
It is setted to 1 if I'm connected both to facebook and to the app.
It is setted to 1 if I'm just connected to facebook.
And the weirdest thing is that it returns 1 even if I'm logged out from Facebook.
So there's something wrong or it's me that Im misunderstanding the
Yii::app()->facebook->status property?
Moreover another strange behaviour is related to the getLoginStatusUrl() function. It passes me back always all the three possible links (ok_user, ok_session, no_session), shouldnt I get back only the valid one for the user?
Regards
PHP SDK 'status'
The
Yii::app()->facebook->status
is a boolean value that YOU set, which is used by the JS SDK. It's set to 'true' by default, so unless you change it, it will always return '1'. It is not a function that pings the Facebook session or anything like that. I guess the name is confusing though...With the
getLoginStatusUrl()
method, I don't actually use it, but it's my understanding that it's returns a URL you can redirect to, which will redirect you BACK conditionally based on your Facebook login status information to one of the three URLs you pass in. Here's the documentation.Also... there is a bug I'm tracking right now where the
logout()
is not destroying the session, meaning the app always thinks you are logged in. This could be causing you confusing too if you are experiencing it:fb.logout still returning active session even with destroySession();
Small fix
Ok about status property, I was wondering about it cause in the previous comment you said to check:
$uid = Yii::app()->facebook->status; // get the current authenticated Facebook user
to get the authenticated user, while it should be getUser() method :)
Moreover I guess I've found a small bug. In the SFacebook.api() function you left commented the whole catch (Exception $e) statement so that if a user makes an api call without a valid user access token the app crash. Catching the error everything runs fine and the error get logged.
public function api(/* polymorphic */) { $args = func_get_args(); $result = false; try { $result = call_user_func_array(array($this->_getFacebook(), 'api'), $args); } catch (CurlException $e) { //timeout so try to resend $result = call_user_func_array(array($this->_getFacebook(), 'api'), $args); } catch (Exception $e) { Yii::log('Failed to make Facebook API call. Exception: '.$e->getMessage()); } return $result; }
Oops, I meant ->user not ->status!
You are right, I put
Yii::app()->facebook->status;
but SHOULD have putYii::app()->facebook->user;
Sorry for the confusion, I fixed my comment below.The reason I left the
catch (Exception $e)
inapi()
commented out is that, while at first I thought it was a good idea to catch those Exceptions, when I started to actually use this extension in my own projects I realized that sometimes it would throw aFacebookApiException
which I wanted to catch elsewhere so I could look at the error codes and do some other error handling logic. But if it works better for you to catch Exceptions there, go for it. :)Posting an item and catching the succesfull
Hi thaddeusmt,
I was wondering about how to make the user post something on his wall with a dialog box and how to catch if the posting action was succefully completed by the user, any hint?
Best regards,
Giuliano
facebook connect
I would have blamed the lack of documentation for this but I must admit I'm a bit of a NOOB myself. I'm lost as to how do I use access token in an api call? Gives me an exception "An active access token must be used to query information about the current user."
Facebook Support ;)
@sfsultan
Once the user has authenticated you Facebook Application by clicking on a Facebook login button, the JS SDK and the PHP SDK will handle the access_token transparently, storing it in the session (I think...). Just use the PHP or JS SDKs to log the user in to your app, then you can make API calls without worrying about the access token (unless you are making API calls on someone's behalf, like a Page, but you'll need to Google that).
@giulianoiacobelli
Sorry, that's a pretty open ended question and a little outside the scope of supporting my Yii extension. It sounds like you need to write some client side JavaScript. Just call ths initJs() method like I have documented and the Facebook JS SDK will be included for you to use. Then call the Facebook FB.ui() dialog method. This is documented on the Facebook support site.
Extended Permissions and post content
Hi,
How can we post a image or create an algum using this?
Thanks
A small mistake in example
In the code -
<?php $this->widget('ext.yii-facebook-opengraph.plugins.LikeButton', array(
//'href' => 'YOUR_URL', // if omitted Facebook will use the OG meta tag
'show-faces'=>true,
'send' => true
)); ?>
'show-faces' should be 'show_faces'
Thanks a ton for the extension btw!
Facebook Comments - Additional Fields
Hi,
Thanks for the hard work on creating this extension! In using the Comments feature, I noticed 2 attributes were missing in the 'Comments.php' plugin file.
Firstly I wasn't able to assign the light or dark color scheme - and even after I'd added it, it was being ignored by Facebook.
The Comments widget kept insisting that a HREF parameter be added (as it was missing). After adding the HREF parameter, the color scheme parameter was then listened to as well. So, here's what to add to 'Comments.php' to fix this:
/** * @var string URL of current page */ public $href; /** * @var string Define the theme for the comments */ public $colorscheme; // "light", "dark"
Then usage of the widget is:
$this->widget('extensions.facebook-opengraph.plugins.Comments', array( 'href' => $this->createAbsoluteUrl(Yii::app()->request->getRequestUri()), 'colorscheme' => 'dark', 'publish_feed' => true, 'width' => '590px', ));
This means the Facebook widget stops complaining about a missing HREF & also listens to the colourscheme parameter.
Thanks again!
Redirecting to a specific URL after Facebook login
After having read this extension, I was a bit puzzled on how to go about redirecting the user to a specific URL to either update or save the user details after login.
I ended up going with the solution shown at
http://blog.mixu.net/2011/01/09/implementing-facebook-login-part-3/ which included amending the initJs method to use a parameter called postLoginRedir when subscribed to auth.login, as illustrated below:
if ($this->async) { $init = "window.fbAsyncInit = function(){{$init}; // whenever the user logs in, we tell our login service FB.Event.subscribe('auth.login', function() { window.location = ' " . Yii::app()->baseUrl.$this->postLoginRedir . "'; }); }; (function(d){ var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = '{$script}'; d.getElementsByTagName('head')[0].appendChild(js); }(document));"; }
It works fine, but I understand this might not be the best way. If not, let me know of other ways to achieve that.
Cheers
Cass
New extension update 0.4
I have updated the extension to fix some bugs. Mainly: some of the Social Plugin helpers had out of date attributes, or were missing entirely. Also, I removed the OG tag "whitelist" checking, since now you can define new OG objects and properties it would be impossible to have a whitelist.
Login with facebook?
Has anyone used this extension for Facebook login? (combined yii-user???)
Would you guys give some hints about how to do that?
Or some tutorials...?
I am relatively new to fb api...
Thanks so much for sharing.
facebook login
jzhong5:
I did use this extention for this:
http://www.yiiframework.com/forum/index.php/topic/31548-bootstrapped-yii-blog-demo-with-facebook-and-persona-login/
Usage in console
Will be nice if extension will work with console application well. Because persistent data stored in session and is not accessible in console by default.
Bug in SendButton
Hi, when making use of the SendButton Plugin its complaining about profile_id.
It make sense since its not defined anywhere.. but i do wonder what was the idea behind it?
Licensing
It's nice to see that someone updated and improved my extension!
A few points however:
You changed the license from LGPLv3 to GPLv2, you're not allowed to do that, you have to license either under LGPLv3 or GPLv3.
I would prefer you kept the orignal license, as right now I can't back-merge any of the improvements you made. Not cool.
You removed the original copyright notice, it must be kept.
Licensing gaff resolved (and profile_id bug)
@ianare Sorry about that, I am a n00b and idiot when it comes to licensing, I hope I have resolved it correctly. Everything is LGPL now and I restored the original copyright notice as well.
@zwobbel Yes you found a copypasta bug, I removed the profile_id code to fix it. It appears that profile_id is no longer a parameter for any of the Facebook Open Graph Plugins (and it never was for the Send button anyway). Thanks for pointing the bug out!
Facebook session persistence and console applications
@pauldee I ran in to this as well, while unit testing. Right now this extension stores persistent Facebook data by overriding the SDK's BaseFacebook class to use the
Yii::app()->session
component. Yii defaults to regular $_SESSION storage, but Yii also has aCDbHttpSession
component, and you can use other extensions for other storage types. So I resolved the console issue by creating a newConsoleSession
component which just writes to the disk. I set thesession
component as that in my unit test and console config.php script. I hope that helps, and I'd like to hear other solutions people have used?Licensing
Thanks for taking the time to fix the licensing, it is appreciated :-)
Error when logging out of Facebook
I have an error that I can reproduce when I am logged into my application through Facebook, and then I log out of my system, and go to Facebook and log out of Facebook. This only happens in the scenario where I am not logged into Facebook (if I am, everything works fine). I am using the Facebook redirect method to login which passes a "code" back in the GET (however, I'm not doing anything with that code). Then, when I try to relogin to my system through Facebook, I get the following error:
An active access token must be used to query information about the current user.
Here is the call-stack:
#0 + /Users/spmorgan/projects/ClubCardio-beta/protected/extensions/yii-facebook-opengraph/php-sdk-3.1.1/base_facebook.php(743): BaseFacebook->throwAPIException(array("error" => array("message" => "An active access token must be used to query information about t...", "type" => "OAuthException", "code" => 2500))) #1 unknown(0): BaseFacebook->_graph("/me") #2 + /Users/spmorgan/projects/ClubCardio-beta/protected/extensions/yii-facebook-opengraph/php-sdk-3.1.1/base_facebook.php(552): call_user_func_array(array(SBaseFacebook, "_graph"), array("/me")) #3 unknown(0): BaseFacebook->api("/me") #4 + /Users/spmorgan/projects/ClubCardio-beta/protected/extensions/yii-facebook-opengraph/SFacebook.php(553): call_user_func_array(array(SBaseFacebook, "api"), array("/me")) #5 + /Users/spmorgan/projects/ClubCardio-beta/protected/modules/user/components/FBUserIdentity.php(20): SFacebook->api("/me")
And my code called in my identity class:
public function authenticate() { $facebook_id = Yii::app()->facebook->getUser(); $user_info = Yii::app()->facebook->api('/me'); if ($user_info) { $user = User::model()->find('facebook_id=?', array($facebook_id)); if ($user === null) return $this->errorCode == self::ERROR_UNKNOWN_IDENTITY; else { $this->_id = $user->id; $this->_username = $user->username; $this->_name = $user->username; $this->errorCode = self::ERROR_NONE; $this->setState('fullName', $user_info['first_name']." ".$user_info['last_name']); $this->setState('avatar', Yii::app()->facebook->getProfilePicture('large')); $this->setState('avatarThumb', Yii::app()->facebook->getProfilePicture('square')); } } else return $this->errorCode == self::ERROR_UNKNOWN_IDENTITY; return $this->errorCode == self::ERROR_NONE; }
Any ideas here?
You should check Facebook session before querying Open Graph
@spmorgan - It might work if you check
Yii::app()->facebook->getUser()
before callingYii::app()->facebook->api('/me');
. If the Facebook session cookie is not set API calls will throw an exception, so check for the session first. I'm not positive that's the issue though, the Facebook session stuff can get a little confusing. Good luckNope, that isn't it...
@thaddeusmt That isn't the problem here, if you look at the code I listed, I am calling getUser() first.
You need to check the result, not just call it
Like this:
$facebook_id = Yii::app()->facebook->getUser(); if ($facebook_id) { // check that you get a Facebook ID before calling api() // now we know we have a Facebook Session, $user_info = Yii::app()->facebook->api('/me'); // so it's safe to call api() if ($user_info) { // ... your code here ... } }
Cheers
Same problem
I don't think it's the right place to discuss about this, but, i have the same problem.
I get the uid but after that...
Do i need to open a bug on github?
EDIT:
Works with:
$access = Yii::app()->facebook->getAccessToken(); $info = Yii::app()->facebook->api('/me?access_token='.$access);
Scope
How do I manage the scope for the user permissions, for example to see the email of the user in facebook?
How do I tell the extensions what is the scope?
thank you
Great Extension
Great extension colleague. How con I add a custom meta tag with custom verbs i created and save them to the Open Graph? Thanks in advance for your attention.
Annoying CURL Error 60 (breaks page)
For a while I was getting "Invalid or no certificate authority found, using bundled information" and was unable to fix it. I resorted to adding the following line to base_facebook.php on line 863.
$opts[CURLOPT_CAINFO] = getcwd().'/protected/extensions/yii-facebook-opengraph/php-sdk-3.1.1/fb_ca_chain_bundle.crt';
It forces the Fb sdk to use the Cert first and not output the error. I know that is works, but was there a better way to resolve this issue?
Permissions / scope
@vihuarar This extension does not actually handle login/authentication and permission scope, it just provides access to those functions for you to integrate in to your application. If you want a global set of permissions (scope) just declare that as global Yii param, and use that when calling the PHP getLoginUrl() method or the JS FB.login() method, which both take in 'scope' as a parameter.
Custom OG meta tags
@fernandrez I just uploaded a new version which supports custom OG meta tags. It does break backward compatibility: anyone upgrading and using the OG meta tags part will need to now declare the full tag name ("og:title") instead of just the short name ("title").
Errors
@Molinski Not sure what is going on there - file system permissions issue maybe? I have not seen that issue before.
@Polux and Shawn - I'm not sure what the root of your error is, but yes please open bug reports on GitHub. It looks like an issue with the Access Token being cached incorrectly in a cookie? The new PHP SDK 3.2 I included in the new 0.6 version of the extension has some improved cookie/session code, maybe that will fix it? Also, I call destroySession() in the Yii logout action which helps clean things out, worth a try.
SBaseFacebook path
I put in the extensions/yii-facebook-opengraph folder
but in the SFacebook.php there is a Yii::import("ext.facebook.SBaseFacebook");
it does not works for me (can't find the extensions/facebook/SBaseFacebook.php)
I replaced it to require_once('SBaseFacebook.php'); and it works now
Fixed import path bug in SFacebook
@uvegpohar thanks for finding that bug, my mistake.
Yii::import("ext.facebook.SBaseFacebook");
should have beenYii::import("ext.yii-facebook-opengraph.SBaseFacebook");
. Although doing what you did fixes it just as well. I updated the download file with the fix.when user logout facebbok in other broswer tab.
when user logout from facebook in other tab in that case code
$facebook_id = Yii::app()->facebook->getUser(); if ($facebook_id) { // check that you get a Facebook ID before calling api() // now we know we have a Facebook Session, $user_info = Yii::app()->facebook->api('/me'); // so it's safe to call api() if ($user_info) { // ... your code here ... } }
in this case $facebook_id is set but error occurs as valid session required.
why this vaariable set?
getUser() returning uid even with invalid session?
@hemc The getUser() method in the PHP SDK calls getUserFromAvailableData() to get the user ID. This method checks the signed request first, then the session (getUserFromAvailableData()), then looks for an access token. So it's possible that if the user has logged out Facebook in another window, getUser() might still return the user_id from the Session? I'm not sure though. This StackOverflow answer says he has to put a try/catch around the API call to destroy the session, give this a try: http://stackoverflow.com/a/8829619/164439
offline_access deprecated
Hi My code was working fine till yesderday. Today I started getting error too many redirects. I googled for the solution and I think it is due to deprecation of offline_access. How can I handle the situation here. to get 60 days accesss. Thanks
Use setExtendedAccessToken() to extend access token in place of offline_access perm
@rigel I have not used the offline_access tokens, but if that is in fact your issue, this extensions wraps the official PHP SDK which has the setExtendedAccessToken() method you can use to request an extended access token, as detailed in the migration info.
An active access token must be used to query information about the current user.
An active access token must be used to query information about the current user. Help My
help me
can you please help me.. i try to follow all of the step, but i end up facing some problem. when i paste the afterRender function in the controller, the page view gone blank. can you please notified where i go wrong..
Valid access token problem
all those are facing this problem, please update php sdk to 3.2.2 . currently no wrapper for Yii is available for this version.Facebook have solved the active token issue on 6th December 2012 including migrations of DEC 5, 2012 changes. I am enhancing the old extension soon it will be available to download.
----->
Wrapper is available to use https://github.com/hemendra619/yii-facebook-opengrpah
Updated to include Facebook PHP SDK 3.2.2
I hope this fixes any issues folks have encountered. Updated in GitHub and in the download ZIP, version 0.7.
An active access token must be used to query information about current user SOLVED
Hi.
Extension works great!
But I suppose access token expire to quickly. Couple minutes and my application requires re-login again. Could someone help me with it?
Here is what I have in log
An active access token must be used to query information about about the current user.
(I uncommented
catch (Exception $e) {
Yii::log('Failed to make Facebook API call. Exception: ' . $e->getMessage()); }
) to see it
======================
Problem was in my sessions. Ensure that php do not lost sessions on disk and cookie that stores session id has correct lifetime
EXAMPLE:
ini_set('session.gc_maxlifetime', 8 60 60);
session_set_cookie_params(8 60 60);
session_save_path(realpath(dirname(FILE) . '/../protected/runtime/'));
Two additions
To use the LoginButton, I had to work out how to use it:
$this->widget('ext.yii-facebook-opengraph.plugins.LoginButton', array( 'show_faces'=>false, 'skin'=>'light',));
Setting the skin was crucial, as facebook denies to use the "default" skin. I do miss some documentation.
I also needed to have the profile picture resized. Facebook can do this for us, but we have to change this function in SFacebook.php:
public function getProfilePictureById($id, $size = null) { if (is_array($size) && isset($size['height']) && isset($size['width'])) { return $this->getProtocol().'://graph.facebook.com/'.$id.'/picture?width='.$size['width'].'&height='.$size['height']; } else if ($size && !is_array($size)) return $this->getProtocol().'://graph.facebook.com/'.$id.'/picture?type='.$size; else return $this->getProtocol().'://graph.facebook.com/'.$id.'/picture'; }
It was quite less hassle than I thought before. However, I am missing a "afterLogin"-action somehow. Have to figure out, how to create accounts for the newly logged in users.
Reference Error : FB is not defined
Hi ,
I am little confused. I am trying to use this custom multi-friend select plugin from here
https://github.com/mbrevoort/jquery-facebook-multi-friend-selector.
When I call any function related to FB example FB.api on some event like click even on button the script facebook sdk works fine. But when tryin to call FB related function on event like onLoad I get error
> Reference Error : FB is not defined
Is it realted to loading of this script
I dont know how to resolve this issue. I want the plugin to showup as page loads
Login Button fix, profile picture custom sizes and async JS callback
@Sebastien Thanks or the heads up on the 'skin' bug, the extension was accidentally passing the skin="default" parameter into the Login Button plugin, which was causing it not to show up. It is fixed now. And thanks for the profile picture dimensions suggestion, I will add that to the extension soon.
Anyone else finding bugs or suggesting code enhancements, please file them in GitHub, thanks.
@rigel If you are loading the Facebook JS SDK using this extension's default settings, it is loading asynchronously. This means FB will not be available in $.ready() or onLoad events. You need to put code dependent on FB in the async callback. You can do this with this extension using the
Yii::app()->facebook->addJsCallback()
method.Composer Package
This extension is now available for composer from the Phundament package repository
Using both PHP and Jssdk
@thaddeusmt Thanks Yii::app()->facebook->addJsCallback() method worked
But i am facing similar issue like @Tpoxa.
I have use PHP sdk for login and authentication. Rest of the facebook features I wish to use JSsdk. Though the Js does not work in many pages (sometimes on refresh it does).
In most of the cases I get the following Error
/**/ FB._callbacks.__gcb2({"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}});
*update.
I guess I found the issue
http://freeporoxy.appspot.com/facebook.stackoverflow.com/questions/7338763/facebook-js-sdk-and-php-sdk-access-token-conflict .
Will try and implement it
issue logged out from facebook.com too while logging out from the site using facebook-opengraph
You get issue logged out from facebook.com too while logging out from the site using facebook-opengraph
It was resolved for me by. In config of extension in file main i edit this line:
//'status'=>true, // JS SDK - check login status
to
'status'=>false, // JS SDK - check login status
How would i logout
HI,
great extension by the way and it works like a charm, can please any one tell me how can logout using this extension and show user that he is logged out.
How to log out
@drmaxmad I advise you to not think of a Facebook logout. It is not as convenient as you would think.
By logging out the user, you will log him out from all Facebook instances. This means, if the user visits facebook.com after logging out at your site, he will have to log in again. Most people do not like this extra effort.
However, if you want to cherish this idea, I once did it like this:
public function actionLogout() { Yii::app()->homeUrl = 'http://www.yourdomain.abc'; Yii::app()->user->logout(); $facebookLoggedIn = true; try { $userinfo = Yii::app()->facebook->getInfo(); // will throw Exception when not logged in } catch (Exception $e) { $facebookLoggedIn = false; } if (!$userinfo) $facebookLoggedIn = false; if ($facebookLoggedIn) $this->redirect(Yii::app()->facebook->getLogoutUrl(array('next' => Yii::app()->homeUrl))); $this->redirect(Yii::app()->homeUrl); }
But I would recommend not to use it.
@drmaxmad
or you can use
logged in status get status.
Thanks for your help on my previous post, i am very new on Yii platform (actually php) so please allow me ask this dumb question, how can i get the status of user after he logs in. What i mean is that if i place a login button (facebook) on my page using this extension and some one logs in, i want to make a call to my database and check if the logged in user exist or not.
Also i have tried to you use addjscallback
Yii::app()->facebook->addJsCallback($js);
but i have no idea where to put the js code, would it be complete script wrapped in single quoted text or i can make javascript function inside the layout/main.php and it would be called. i will study the javascript api for facebook for this issue but any help would be much appreciated.
How to do JS callback on login
@drmaxmad I did the following in my protected/components/Controller.php:
protected function afterRender($view, &$output) { Yii::app()->facebook->addJsCallback('FB.Event.subscribe(\'auth.login\', function () { window.location = "http://www.yourdomain.abc/user/facebook"; });'); Yii::app()->facebook->initJs($output); // this initializes the Facebook JS SDK on all pages return parent::afterRender($view, $output); }
Whereas /user/facebook is a function actionFacebook() in the UserController.php, which checks the Facebook-user's uid, name and so on in the database and creates an account when there is none yet.
Good luck. (And don't forget to enable jsSdk in the extension's settings!)
can't get the email address of user
Hi,
Highly appreciate your help on the issues i was facing last time, it worked out quite well. There is one more thing that i am stuck with. I can't get the user email, I have set up the permissions for the application on facebook as given below.
Default Activity Privacy:
Only Me
User & Friend Permissions:
email; user_about_me;
Extended Permissions:
Auth Token Parameter:
Query String (?code=...)
Now i am using the following code to get the profile of facebook user but email is not returned (i can see the email if use my own facebook account but not with the test account that i made).
$user = Yii::app()->facebook->getUser(); if ($user){ Yii::app()->facebook->setAccessToken($accessToken); $facebookUserInfo = Yii::app()->facebook->api('/me?scope=email'); $facebookUser = Yii::app()->facebook->getUser(); $data = $facebookUserInfo; } else { $data = null; } echo "<pre>"; print_r($data); echo "</pre>"; exit();
please tell me what am i missing here.
Re :-can't get the email address of user
use
Yii::app()->facebook->api('/me');
Instead of
Yii::app()->facebook->api('/me?scope=email');
Cerate Event
with this exetension a can create an event on facebook page using the opengraph API?
If yes, how can i do it?
Thanks for your extension. it helps a lot!
Post to Facebook Page
Hey guys, I'm trying to post a message to a Facebook Page feed with this action:
public function actionIndex() { //Create a Post model $post=new Post; //Currently just for iSeeCI FB App $post->page_id = Yii::app()->params['fbPageId']; //Variables to call an eventual login $returnUrl='http://localhost/iseeci'; $permissions='manage_pages, publish_stream'; //Get token and user if available $fb=Yii::app()->facebook; $token=$fb->getAccessToken(); $fb->setAccessToken($token); $fbUser=Yii::app()->facebook->getUser(); if($fbUser){ //If a user is available then //publish the post in iseeci.com and facebook.com/iSeeCI $postedFB; if(isset($_POST['Post']) && $_POST['Post']['message']!=''){ try{ $post->attributes=$_POST['Post']; $msg=array('message'=>$post->message, //'name'=>$post->name, //'caption'=>$post->caption, //'description'=>$post->description, //'link'=>$post->link, //'object_attachment'=>$post->object_attachment, ); $url='/'.$post->page_id.'/feed'; $postedFB=$fb->api($url, 'POST', $msg); $saved=$post->save(); } catch(FacebookApiException $error){ echo $error->getMessage(); } } try{ $query='select page_id, name from page where page_id = '.Yii::app()->params['fbPageId']; $page=$fb->api(array('method'=>'fql.query','query'=>$query)); $this->breadcrumbs=array(Yii::t('app','blog')); } catch(FacebookApiException $error){ echo $error->getMessage(); } } else{ $loginUrl=Yii::app()->facebook->getLoginUrl(array('scope'=>$permissions,'redirect-uri'=>$returnUrl)); } $pars=array('post'=>$post,'page'=>$page); if(isset($postedFB)) $pars['postedFB']=$postedFB; if(isset($loginUrl)) $pars['loginUrl']=$loginUrl; if(isset($saved)) $pars['saved']=$saved; $this->render('blog',$pars); }
When I try to use all of the parameters besides 'message', like 'name', 'caption', 'description', 'link'... the post doesnt get to the Facebook Page. Am I missing something? Am I doing something wrong? Thanks for any help guys.
Access Token problem
I am getting the error: Error validating access token: Session has expired at unix time 1378162800. The current unix time is 1378224732
I see it is solved in https://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/ but I am not sure if this code is implemented in the Yii Facebook Opengrah Extension, is it? what should I do to avoid that error?
Thank you
Expired Access Token error handling
@Carlos Detecting expired authorize tokens and directing the user to re-authenticate will be different in every application, so just like Facebook PHP SDK that is not handled automatically by this extension.
I assume this error you got is being returned as an FacebookApiException PHP exception object, from the Facebook PHP SDK? The way you'll want to handle all Facebook API exceptions is by catching them with a try/catch construct, and handling it however you want from there. Something like this:
try { Yii::app()->facebook->api('/me'); } catch (FacebookApiException $e) { // in here you can look at the Exception $e, and determine if it's an expired // access token error, and if it is, you can redirect your user somewhere to // re-authenticate if you want - either by redirecting them to the login page, // or by showing a Flash message with the JavaScript Login button, etc echo $e->getMessage(); }
New Like and Share buttons
You should upgrade your plugins, to work with new Like and Share buttons, because currently, at least share plugin, does not work, when used the one, generated in Share button.
Edit: Sorry. It works, I noticed that there was problem loading JS SDK, now it works ok. But still, I don't see "Share" plugin, or it is named in different way?
Clic on Like Button
I would like to detect when a user clics on like button, something like this:
<script> FB.Event.subscribe('edge.create', function(href, widget) { alert('You liked ' + href, widget); }); </script>
The problem is that I do not want to use Yii::app()->facebook->addJsCallback() because I only want that code in one specific view, not in all my views.
What is the right approach for this?
Thank you
Adding additional JS to async callback
@Carlos - You can add more JS code to the Facebook Async callback any place you would like. You can put it in the default Controller code, or put it in a single Action, or directly in the View:
Yii::app()->facebook->addJsCallback('console.log("view-specific JS code")'); Yii::app()->facebook->addJsCallback('console.log("more JS code!")');
RE: Adding additional JS to async callback
@thaddeusmt, I have tried your code, but it does nothing. The console log is empty:
Yii::app()->facebook->addJsCallback('console.log("view-specific JS code")'); Yii::app()->facebook->addJsCallback('console.log("more JS code!")');
What can be the problem? It seems that addJsCallback does not work for me...
Thank you
Edit:
I answer myself. In config/main.php in facebook extension I had to set:
'jsCallback'=>true,
Thank you
Example of Updating a Facebook User's Status
Have any one been successful at posting to a facebook user's wall with this extension? If so, can anyone provide an example? I dont' see a plug-in specifically for this. I have everything set up, but I need a start of what to do next to accomplish this task.
Thanks very much
User data issue
Hello,
I can not get the user data like and share buttons are working good but i want the data of the user who has done like or share.i have use all the functions to fetch the data of the user.
This is how I made it work
Hi All,
I checked this extension and it is good. Since it uses Facebook PHP SDK 3.2.3, it goes well with Yii 1.*. To make this component work, you first need to store access token which you will get after a user logs in into facebook. You can do that by using FB JS SDK or using the login button. But you will need to capture the login event and store fb user id and access token. The code is something like:
You can store the above tokens in db using an ajax call. After that is done, then you can make api calls with this extension. This is how I did it:
try{
$response = $facebook->api('/'.$user);
var_dump($response);
}catch(FacebookException $e)
{
}
The above code will display information about the user even if the user is not logged in. I think $facebook->getUser() statement is not necessary but the api request didn't work without that request.
I hope this helps to all the people who are checking this extension.
Usage example is incorrect
<?php Yii::app()->facebook->ogTags['og:title'] = "My Page Title"; ?>
...should be...
<?php Yii::app()->facebook->ogTags['title'] = "My Page Title"; ?>
ie. remove the
og:
in the key name, otherwise it will outputog:og:title
which is obviously incorrect.If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.