2013年7月25日 星期四

Facebook API with PHP SDK


1. Get the AppID and Secret from Facebook Developerment




2. Login User Part :



 
   /*
     *    do the facebook init work
     *    check if user login or will pop user for login and authorization 
     */
    require_once('fb-php-sdk/facebook.php');
    require_once('include/config.php');
    // Production
    $app_id = 'ur-AppID';
    $app_secret = 'ur-Secret';
    $app_namespace = 'ur-App-NameSpace';

    $app_url = 'http://apps.facebook.com/' . $app_namespace . '/';

    $scope = 'email,publish_actions';

    // Init the Facebook SDK
    $facebook = new Facebook(array(
        'appId'  => $app_id,
        'secret' => $app_secret,
    ));

    $user = $facebook->getUser();

    // If the user has not installed the app, redirect them to the Login Dialog
    if (!$user) {
        $loginUrl = $facebook->getLoginUrl(array(
            'scope' => $scope,
            'redirect_uri' => $app_url,
        ));

       print('');

    } else {
        try {
        // Proceed knowing you have a logged in user who's authenticated.
       
            //$user_profile = $facebook->api('/me');
            $user_profile = $facebook->api( array(
                'method' => 'fql.query',
                'query' => 'select email from user where uid=me()',
            ));

            //get user email
            if( isset($user_profile) && isset($user_profile[0]) ) {
                $usermail = $user_profile[0]['email'];
                if(DEBUG) print_r($usermail);
            }

        } catch (FacebookApiException $e) {
           
            error_log($e);
            $user = null;
           
        }
    }
?>



3. post to the wall



 
    $user = $facebook->getUser();
    $feed_dir = '/'. $user . '/feed';
    $accessToken = $facebook->getAccessToken();


    $data['access_token'] = $accessToken;
    $data['message'] = strip_tags($result);
    $data['link'] = 'the-link-which-icon-and-name-will-link-to';
    $data['picture'] = 'the-pictures-url';
    $data['name'] =  'the-name-u-want-to-show';
    $data['description'] = 'the-description-will-show-in-the-msg';
   
    $result = false;


    try {
       
        $result = $facebook->api($feed_dir, 'post', $data);
       
        if(DEBUG) {
            print_r($result);
        }
       
    } catch (FacebookApiException $e) {
       
        error_log(sprintf("Error to Post to Wall, user = %s", $user));
        error_log($e);
       
        if(DEBUG) {
            echo "HAS ERROR!!!";
            print_r($e);
        }
    };

?>

沒有留言:

張貼留言