27.05.2013

Thema

How To use Facebook PHP-SDK with Yii Framework

First Time You have to clone the Facebook SDK Repository


git clone git@github.com:facebook/facebook-php-sdk.git

Load the SDK in Your Controller

Add a Test Controller in your /protected/controllers and add some vars.

public $appId = 'Your Facebook App ID';
public $appSecret = 'Your Facebook Secret App id';
public $facebook;

Add in your TestController init method this call

public function init()
{
    //init facebook
    $this->promiseFacebook();
}

Now load the sdk

 /**
  * use facebook sdk implememt it and check config
  */
    private function promiseFacebook(){
        require(realpath("Path to your Facebook SDK" . DIRECTORY_SEPARATOR .'facebook.php'));
        $this->facebook = new Facebook(array(
            'appId' => $this->appId,
            'secret' => $this->appSecret,
            'cookie' => true
        ));
    }

Get the Signedrequest

/**
* return facebook signedRequest
*/
public $signedRequest;
public function getSignedRequest(){
    $this->signedRequest = $this->facebook->getSignedRequest();
}

User hast App liked or not

/**
 * return is the paged like or not
 */
private $_liked;
public function isLiked(){
    if($this->signedRequest['page']['liked'])
    {
        $this->_liked = true;
    }
}

Get Permission from User

/**
* return the facebook script to access the app
* https://developers.facebook.com/docs/reference/login/#permissions
*/
public function setLoginUrl()
{
    $this->_facebookUserLoginUrl = $this->facebook->getLoginUrl(
        array(
            'canvas'    => 1,
            'fbconnect' => 0,
            'scope' => 'email,publish_stream,user_birthday',
            'redirect_uri' => $this->createAbsoluteUrl('permission')
        )
    );
    Yii::app()->clientScript->registerScript('loginUrl','var loginUrl ="'.$this->_facebookUserLoginUrl.'"',CClientScript::POS_HEAD);
}

The redirect_uri is important after the User Accept the App.

Post on the User Wall

/**
* @return Exception|FacebookApiException
*/
public function postToWall ()
{
    try {
        $paramters = array(
            'message'=>'noch nix da',
            'link' => 'your Server App Url',
            'name' => 'App Name',
            'description' => 'max 255',
            'picture' => your Image Path       
        );
        $response = $this->facebook->api('/me/feed','post',$paramters);
            return array($response,$paramters); 
    } catch (FacebookApiException $e) {
        error_log($e);
        return $e;
    }
}
 

Leave a Comment