Yii 1.1: facebook-opengraph

Provides easy access to Facebook's PHP SDK and JS SDK, Social Plugin widgets and Open Graph meta tags

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


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:

    '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

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) {
  //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;


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
   '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()) ?>
  try {

    $response = Yii::app()->facebook->makeRequest('/me/feed', 'POST', array(
      'link' => 'www.example.com',
      'message' => 'User provided message'

    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 ?>


  • New version 2.x breaks everything from previous version and requires PHP 5.4


  • 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

Total 20 comments

#19613 report it
benomatis at 2015/10/02 06:47pm
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 output og:og:title which is obviously incorrect.

#17974 report it
sirius at 2014/08/20 12:59am
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:

accessToken = response.authResponse.accessToken;
fbUserID = response.authResponse.userID;
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:

$accessToken = 'you access token';
$fbID = 'you fb user id';
$facebook = Yii::app()->facebook; //the facebook extension
$user = $facebook->getUser();

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.

#17439 report it
Sukunj Mendpara at 2014/06/12 03:12am
User data issue


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.

#16700 report it
inProcess at 2014/03/20 11:46pm
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

#15623 report it
Carlos Adrián at 2013/11/30 10:40am
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


I answer myself. In config/main.php in facebook extension I had to set:


Thank you

#15589 report it
thaddeusmt at 2013/11/26 06:43pm
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!")');
#15588 report it
Carlos Adrián at 2013/11/26 05:43pm
Clic on Like Button

I would like to detect when a user clics on like button, something like this:

  FB.Event.subscribe('edge.create', function(href, widget) {
    alert('You liked ' + href, widget);

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

#15559 report it
Deele at 2013/11/21 05:57am
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?

#14839 report it
thaddeusmt at 2013/09/13 06:29pm
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 {
} 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();
#14687 report it
Carlos Adrián at 2013/09/03 12:45pm
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

#14087 report it
fernandrez at 2013/07/18 12:07am
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
        $permissions='manage_pages, publish_stream';
        //Get token and user if available
            //If a user is available  then
            //publish the post in iseeci.com and facebook.com/iSeeCI
            if(isset($_POST['Post']) && $_POST['Post']['message']!=''){
                    $postedFB=$fb->api($url, 'POST', $msg);
                catch(FacebookApiException $error){
                    echo $error->getMessage();
                $query='select page_id, name from page where page_id = '.Yii::app()->params['fbPageId'];
            catch(FacebookApiException $error){
                echo $error->getMessage();

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.

#13624 report it
lindomar at 2013/06/12 05:39am
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!

#13509 report it
hemc at 2013/06/03 01:02am
Re :-can't get the email address of user



Instead of

#13502 report it
drmaxmad at 2013/06/02 03:08am
can't get the email address of user


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){
$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.

#13451 report it
Sebastian at 2013/05/29 10:29am
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!)

#13445 report it
drmaxmad at 2013/05/29 08:24am
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.

#13433 report it
hemc at 2013/05/29 05:08am

or you can use

$facebook -> destroySession();
#13432 report it
Sebastian at 2013/05/29 05:01am
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';
    $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)));

But I would recommend not to use it.

#13429 report it
drmaxmad at 2013/05/29 04:45am
How would i logout


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.

#13238 report it
Dũng Ninh Bình at 2013/05/17 12:35am
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


'status'=>false, // JS SDK - check login status

Leave a comment

Please to leave your comment.

Create extension