Krajee

Social

Thankful to Krajee! BUY A COFFEEor to get more out of us.
The yii2-social module provides access to social plugins and social APIs for Yii Framework 2.0. It includes support for embedding plugins from the following networks into your website:
  • Disqus
  • Facebook
  • Google Plus
  • Google Analytics
  • Twitter
  • VKontakte
  • GitHub

Tip

Not seeing the updated content on this page! Hard refresh your browser to clean cache for this page (e.g. SHIFT-F5 on Windows Chrome)

You must setup the social module by registering it in the modules section of your Yii Configuration file. Configuring your module can help you setup application level defaults for your social widgets. These settings can be overridden at each widget level. An example of the configuration options for the social module:

'modules' => [
    'social' => [
        // the module class
        'class' => 'kartik\social\Module',

        // the global settings for the Disqus widget
        'disqus' => [
            'settings' => ['shortname' => 'DISQUS_SHORTNAME'] // default settings
        ],

        // the global settings for the Facebook plugins widget
        'facebook' => [
            'appId' => 'FACEBOOK_APP_ID',
            'secret' => 'FACEBOOK_APP_SECRET',
        ],

        // the global settings for the Google+ Plugins widget
        'google' => [
            'clientId' => 'GOOGLE_API_CLIENT_ID',
            'pageId' => 'GOOGLE_PLUS_PAGE_ID',
            'profileId' => 'GOOGLE_PLUS_PROFILE_ID',
        ],

        // the global settings for the Google Analytics plugin widget
        'googleAnalytics' => [
            'id' => 'TRACKING_ID',
            'domain' => 'TRACKING_DOMAIN',
        ],

        // the global settings for the Twitter plugin widget
        'twitter' => [
            'screenName' => 'TWITTER_SCREEN_NAME'
        ],

        // the global settings for the GitHub plugin widget
        'github' => [
            'settings' => ['user' => 'GITHUB_USER', 'repo' => 'GITHUB_REPO']
        ],
    ],
    // your other modules
]
This widget embeds the Disqus comments plugin into your website.
use kartik\social\Disqus;
echo Disqus::widget(['settings'=>['shortname'=>'DISQUS_SHORTNAME']);

This widget allows you to embed various Facebook plugins into your website. You should refer the Facebook plugin documentation for details on each plugin.

use kartik\social\FacebookPlugin;
echo FacebookPlugin::widget(['appId'=>'FACEBOOK_APP_ID']);
The social module offers an easy way to access the Facebook PHP SDK api. You must have setup the social module in your Yii configuration file with appropriate settings for Facebook. i.e. app_id or appId and app_secret or secret must be set. Once done, you can refer the SDK API as mentioned below.

Note

In case you have issues with Facebook PHP SDK and it is not being installed properly by composer, you would need to check your composer install logs or check to see if you have the right version. You may otherwise face issues of Facebook classes not found by the extension. In this situation, you may need to refresh your packages correctly (or overwrite the vendor/facebook/php-sdk-4 folder with the downloaded facebook zip or tarball from the github repo.

The following functionalities have been added to the module for working with Facebook PHP SDK. You can access these methods within kartik\social\Module.

  • New getFb method in social module to initialize and fetch a facebook object based on module settings and as per object properties in Facebook SDK v5.0. The method accepts the following parameters:

    • params: array, the app parameters which should be setup as $key => $value pairs, where $key is one of the following. If not set, the following values will be auto derived from the module settings.

      • app_id or appId: string, the Facebook Application ID.

      • app_secret or secret: string, the Facebook Application Secret.

      • default_graph_version: string, the default facebook graph version. Defaults to 'v2.8'. This typically must be set to the latest facebook graph version.

      • default_access_token: string, the default access token to initialize the facebook object.

    • Other parameters can be set as supported by the Facebook\Facebook class. Read the Facebook SDK Documentation for details.

  • New setFb method in social module to set the facebook object with custom settings or set it to null. The method is very similar to getFb method except that it does not return an object and it allows you to reset the facebook object to null. The method accepts the following parameters:

    • params: array, if this is set as null, the facebook object is set to null. If not set, it will use default module level settings to generate the facebook object. Else the following parameters can be supplied within the array as key value pairs:

      • app_id or appId: string, the Facebook Application ID.

      • app_secret or secret: string, the Facebook Application Secret.

      • default_graph_version: string, the default facebook graph version. Defaults to 'v2.8'. This typically must be set to the latest facebook graph version.

      • default_access_token: string, the default access token to initialize the facebook object.

    • Other parameters can be set as supported by the Facebook\Facebook class. Read the Facebook SDK Documentation for details.

  • New getFbLoginLink method in social module to generate a facebook login link. The method accepts the following parameters:

    • callback: string, the absolute callback url action that will be used by Facebook SDK redirect login helper. Typically this is set to an absolute url pointing to a controller action in Yii (e.g. Yii::$app->request->getAbsoluteUrl('your-action'))

    • options: array, the HTML attributes for the login link to be generated. The following special options are recognized:

      • label: string, the label to display for the link. Defaults to 'Login with Facebook'.

    • permissions: array, the permissions for the user to be authenticated by the login helper. Defaults to ['email', 'user_posts'].

    • fb: Facebook, the facebook object. If not provided, this will default to the object retrieved by getFb method.

/**
 * Facebook SDK API Example
 * VIEW FILE: view.php
 * Generate a login button
 */   
use kartik\social\Module;
use yii\helpers\Url;
$social = Yii::$app->getModule('social');
$callback = Url::toRoute(['/site/validate-fb'], true); // or any absolute url you want to redirect
echo $social->getFbLoginLink($callback, ['class'=>'btn btn-primary']);

/**
 * Facebook SDK API Example
 * CONTROLLER: SiteController.php
 * Facebook login callback validation
 */
use kartik\social\Module;

public function actionValidateFb()
{
    $social = Yii::$app->getModule('social');
    $fb = $social->getFb(); // gets facebook object based on module settings
    try {
        $helper = $fb->getRedirectLoginHelper();
        $accessToken = $helper->getAccessToken();
    } catch(\Facebook\Exceptions\FacebookSDKException $e) {
        // There was an error communicating with Graph
        return $this->render('validate-fb', [
            'out' => '<div class="alert alert-danger">' . $e->getMessage() . '</div>'
        ]);
    }
    if (isset($accessToken)) { // you got a valid facebook authorization token
        $response = $fb->get('/me?fields=id,name,email', $accessToken);
        return $this->render('validate-fb', [
            'out' => '<legend>Facebook User Details</legend>' . '<pre>' . print_r($response->getGraphUser(), true) . '</pre>'
        ]);
    } elseif ($helper->getError()) {
        // the user denied the request
        // You could log this data . . .
        return $this->render('validate-fb', [
            'out' => '<legend>Validation Log</legend><pre>' .
            '<b>Error:</b>' . print_r($helper->getError(), true) .
            '<b>Error Code:</b>' . print_r($helper->getErrorCode(), true) .
            '<b>Error Reason:</b>' . print_r($helper->getErrorReason(), true) .
            '<b>Error Description:</b>' . print_r($helper->getErrorDescription(), true) .
            '</pre>'
        ]);
    }
    return $this->render('validate-fb', [
        'out' => '<div class="alert alert-warning"><h4>Oops! Nothing much to process here.</h4></div>'
    ]);
}

/**
 * Facebook SDK API Example
 * VIEW: validate-fb.php
 * Facebook login post callback display view
 */
<?php
use yii\helpers\Html;
?>

<div class="panel panel-body">
    <div class="page-header">
        <h1>Facebook API Test Results <small><a href="https://demos.krajee.com/social">yii2-social</a></small></h1>
    </div>
    <?= $out ?>    
    <hr>
    <?= Html::a('« Return', ['/site/social', '#' => 'facebook-api-example'], ['class'=>'btn btn-success']) ?>
</div>
This widget allows you to embed various Google+ plugins into your website.
use kartik\social\GooglePlugin;
echo GooglePlugin::widget(['pageId'=>'GOOGLE_PLUS_PAGE_ID']);
This widget allows you to embed GoogleAnalytics plugin into your website.
use kartik\social\GoogleAnalytics;
echo GoogleAnalytics::widget(['id'=>'TRACKING_ID', 'domain'=>'TRACKING_DOMAIN']);
This widget allows you to embed various Twitter plugins into your website.
use kartik\social\TwitterPlugin;
echo TwitterPlugin::widget(['screenName'=>'TWITTER_SCREEN_NAME']);
This widget allows you to embed various VKontakte plugins into your website.
use kartik\social\VKPlugin;
echo VKPlugin::widget(['apiId'=>'VK_API_ID', 'type'=>VKPlugin::LIKE]);
This widget allows you to embed various GitHub plugins into your website. It is based on the unofficial github buttons plugin by @mdo.
use kartik\social\GithubPlugin;
echo GithubPlugin::widget(['type'=>GithubPlugin::WATCH, 'settings' => ['user'=>'GITHUB_USER', 'repo'=>'GITHUB_REPO']]);
This widget allows you to embed various GitHub plugins into your website. It is based on the unofficial github buttons plugin by @ntkme.
use kartik\social\GithubXPlugin;
echo GithubXPlugin::widget(['type'=>GithubXPlugin::WATCH, 'user'=>'GITHUB_USER', 'repo'=>'GITHUB_REPO']);

yii2-social is released under the BSD-3-Clause License. See the bundled LICENSE.md for details.

Note

You can now visit the Krajee Webtips Q & A forum for searching OR asking questions OR helping programmers with answers on these extensions and plugins. For asking a question click here. Select the appropriate question category (i.e. Krajee Plugins) and choose this current page plugin in the question related to field.

The comments and discussion section below are intended for generic discussions or feedback for this plugin. Developers may not be able to search or lookup here specific questions or tips on usage for this plugin.

 
visitors to Krajee Yii2 Demos since 22-May-2017