PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label facebook-javascript-sdk. Show all posts
Showing posts with label facebook-javascript-sdk. Show all posts

Thursday, November 3, 2022

[FIXED] How to retrieve all posts of a user via Facebook Graph API using promises and recursion?

 November 03, 2022     es6-promise, facebook-graph-api, facebook-javascript-sdk, javascript, recursion     No comments   

Issue

I am currently developing a web app which uses the Facebook Graph API.

What I would like to achieve is to get all posts of a user.

However, this is not that easy since I have to paginate the results.

At the moment I am struggeling with promises.

What I try to achieve is to fill an array with the post objects.

Therefore I use promises and recursion which does not work as expected.

My code currently looks as follows:

// Here I retrieve the user with his or her posts,
// just the first 25 due to pagination
if (accessToken) {
  return new Promise(resolve => {
    FB.api('/me?fields=id,name,posts&access_token=' + accessToken, response => {
      this.get('currentUser').set('content', response);
      resolve()
    })
  })
}

// Returns all posts of a given user
function getAllPostsOfUser(posts, postsArr) {
  // Process each post of the current pagination level
  for (var post of posts.data) {
    // Only store meaningful posts
    if (post !== undefined && post.message !== undefined) {
      postsArr.push(post)
    }
  }

  // Further posts are retrievalable via paging.next which is an url
  if (posts.data.length !== 0 && posts.paging.next !== undefined) {
    FB.api(posts.paging.next, response => {
      getAllPostsOfUser(response, postsArr)
      resolve()
    })
  }

  return postsArr
}

var posts = getAllPostsOfUser(this.get('currentUser').content.posts, [])
// I want to use all the posts here
console.log(posts)

The problem I have is that I want to use the posts where the console.log is placed but when I log the posts array a lot of posts are missing.

I am sure that I did something wrong with the promises but I do not know what.

I would be glad if anyone could guide me to a solution.

Thank you in advance.


Solution

Try this:

function getAllPosts() {
  return new Promise((resolve, reject) => {
    let postsArr = [];
    function recursiveAPICall(apiURL) {
      FB.api(apiURL, (response) => {
        if (response && response.data) {
          //add response to posts array (merge arrays), check if there is more data via paging
          postsArr = postsArr.concat(response.data);
          if (response.paging && response.paging.next) {
            recursiveAPICall(response.paging.next);
          } else {
            resolve(postsArr);
          }
        } else {
          reject();
        }
      });
    }
    recursiveAPICall("/me/posts?fields=message&limit=100");
  });
}

getAllPosts()
  .then((response) => {
    console.log(response);
  })
  .catch((e) => {
    console.log(e);
  });

Not tested, just a quick example I came up with. It returns a promise and uses a recursive function to get all entries. BTW, you don't need to add the Access Token. If you are logged in, the SDK will use it internally.



Answered By - andyrandy
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to include Group cover photo in Group Info Endpoint on Facebook Graph API

 November 03, 2022     facebook, facebook-graph-api, facebook-javascript-sdk, node.js     No comments   

Issue

I have the following endpoint to retrieve the details of a Facebook group via its id

let groupInfoUrl = `https://graph.facebook.com/${group_id}?access_token=${accessToken}`;

Below is an example of the response I got:

{
  "name": "Group Name",
  "privacy": "OPEN",
  "id": "012345678901234"
}

How can I make the response to also include the Group Cover photo or icon?

Thank you.


Solution

You just have to add fields=cover to your query:

let groupInfoUrl = `https://graph.facebook.com/${group_id}?fields=cover&access_token=${accessToken}`;


Answered By - Soufian
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, November 2, 2022

[FIXED] How to get the list of facebook groups using graph api

 November 02, 2022     facebook, facebook-graph-api, facebook-group, facebook-javascript-sdk     No comments   

Issue

I want the list of groups in which I'm member. In the Graph Api Explorer I did not find any permission like user_groups. I select all the "User Data Permissions" and "Extended Permissions" but it did not work.

In graph api explorer I am using this command GET->/v2.4/me/groups. and i get empty JSON data Like this.

{
  "data":[
  ]
}

And if I use the old graph api version 2.2 Like GET->/v2.2/me/groups then I get the groups only in which I am admin not all the groups.

If anyone have this experience and also have any solution please help me to solve my problem.


Solution

Short answer: user_groups is deprecated with v2.4, see

  • https://developers.facebook.com/docs/apps/changelog#v2_4

the user_groups permission has been deprecated. Developers may continue to use the user_managed_groups permission to access the groups a person is the administrator of. This information is still accessed via the /v2.4/{user_id}/groups edge which is still available in v2.4.



Answered By - Tobi
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 16, 2022

[FIXED] How to get mobile number from facebook login using jquery?

 July 16, 2022     facebook-graph-api, facebook-javascript-sdk, facebook-login     No comments   

Issue

I am trying to work facebook login with javascript but there are some issue faces. If facebook user register with email id then it gets email id but when user register with mobile phone then how can I get mobile_phone?

FB.api('/me', 'GET',  {fields: 'email,name,id'},function(response) {
                console.log(response);
                var id = response.id;
                var name = response.name;
                var email = response.email;

    }, {scope: 'email',return_scopes: true});

here is my code. Please help me on this. thanks


Solution

then how can I get mobile_phone?

You can’t.

Facebook does not let normal 3rd-party apps access a user’s mobile number via Graph API.

(You might have seen stuff like the login dialog from Uber, they show the phone number there. But that is because they have some sort of special deal with Facebook that enables them to do this.)



Answered By - 04FS
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to test Facebook login with localhost

 July 16, 2022     django, django-allauth, facebook, facebook-javascript-sdk, facebook-login     No comments   

Issue

I'm using Django, and want to make Facebook login with django-allauth.

I made Facebook login with few time, and tested it with localhost.

But I found out that FB login require https after 2018 march, so when I login fb in local runserver, it gives error like Insecure Login Blocked: You can't get an access token or log in to this app from an insecure page. Try re-loading the page as https://.

Is there any way to test fb login in localhost?


Solution

You can just use a real subdomain like dev.yourdomain.com and point its DNS to 127.0.0.1 (or can use lvh.me domain since it also point to 127.0.0.1 - but if you trust them all the time)

Then you need a layer to handle HTTPS in local for https://dev.yourdomain.com. I recommend https://caddyserver.com/

With a very simple config like this then Caddy can use its self-signed SSL cert (checkout Caddy docs to get the detail)

dev.yourdomain.com:443 {
    tls self_signed
    proxy / localhost:8080
}

Then you can open https://dev.yourdomain.com in some browsers like Firefox, Safari, Brave, etc. (I think Chrome blocked self-signed SSL site by default)

UPDATE I create a note here with more detail

https://gist.github.com/ralavay/5d74d35859f87d22c74984488f20186c



Answered By - neo0
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, June 29, 2022

[FIXED] How to get complete information about post using facebook sdk C#

 June 29, 2022     facebook-graph-api, facebook-javascript-sdk, facebook-sdk-4.0     No comments   

Issue

When I use postman application or Graph API explorer then i get complete information or all fields of posts as explained in https://developers.facebook.com/docs/graph-api/reference/v2.0/post

enter image description here

I have not use fields attribute in above image even then it is showing all fields so i am looking for the answer to pass field attribute in query string.

But when i use SDK i get only 3 fields created_time, id and message, please refer following image:

enter image description here

Kindly tell how to get all fields of the posts using facebook sdk c#?


Solution

You need to specify the fields parameter, it´s called "Declarative Fields" and came with v2.4 of the Graph API: /me/posts?fields=field1,field2,field3,...

The possible fields can be found in the docs, you should use the latest version though: https://developers.facebook.com/docs/graph-api/reference/v2.7/post

Make sure you are using a newer Version of the API, you are trying to use v1.0 in Postman (which does not exist anymore).



Answered By - andyrandy
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, March 13, 2022

[FIXED] One php session variable causing unsetting session on redirect

 March 13, 2022     facebook-javascript-sdk, facebook-php-sdk, mysql, php, session     No comments   

Issue

I am using a combination of Javascript and PHP Facebook sdk to integrate the log in to my website (hosted on localhost).

The code after Facebook initialization and getting the access token:

if(fbidExists($profile['id']) == true)
  {

    $query = "SELECT userid AS id, username FROM users WHERE fbid = ".   $profile['id'] ;

    $login = mysqli_fetch_assoc(mysqli_query($GLOBALS['connection'], $query));

    $_SESSION['id'] = $login['id'];
    $_SESSION['username'] = $login['username'];

    header("Location: http:\\\\localhost\website\\");
    exit();
  }

Problem: After redirect there are no session variables whenever I use $login['username'], otherwise the session variables are transferring.

If I change the SQL query and replace username by any other column there is no problem and I can see the session variables after redirect. For example : $query = "SELECT userid AS id, email FROM users WHERE fbid = ". $profile['id'] ; $_SESSION['username'] = $profile['email'] creates no problem

The $_SESSION['username'] variable can be easily set through other files and creates no problem (when i use it with my own log in)

username in MySQL is of varchar type and I am using session_start() on every page and exit() after header.


Solution

Thanks for all your help. Turns out it was a problem because in the second script one on the variables was not set which was destroying the session.



Answered By - Tamanna
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Shop section of facebook pages through api/javascript sdk

 March 13, 2022     facebook, facebook-graph-api, facebook-javascript-sdk, facebook-php-sdk     No comments   

Issue

Facebook introduced a shop section for facebook pages. I need to manage my page's shop section through javascript sdk but I am unable to find the propoer docs or reference to do that. I know how to manage or update simple fields of your pages through sdk with post method using FB.api:

FB.api(/page_id_and_post_method, function(response) {
    console.log("PAGEEEEEE DETAILS", response);
});

So, the problem is that I just could not find the proper field name for that 'shop' section so as to update it.

So how can I read/update the 'shop' section of my page through sdk/api just as the shopify do as we can see below:

https://www.facebook.com/Womansera/shop?ref=page_internal&rid=221671794535129&rt=9


Solution

This is a feature that Facebook is testing right now, with Shopify as a partner (and maybe a few others.)

It is not available for other 3rd-party apps yet.



Answered By - CBroe
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Facebook oAuth: Force email permission

 March 13, 2022     facebook, facebook-javascript-sdk, facebook-php-sdk     No comments   

Issue

How do sites like StackOverflow and Untappd "force" a user to accept their permissions?

When I've been trying with the JavaScript SDK I've been using the scope object to request email addresses, but I keep seeing "Edit the info you provide", allowing the user to not provide their email address. I've even tried following Manually Building a Login Flow, with the same results.

Image:

enter image description here

As we're giving the user the option to register on the site through Facebook, we're reliant on the email address to create an account within our database.

Yet sites like StackOverflow and Untappd offer no such option, I'm forced to accept those permissions.

So what's the secret? How do I achieve this? Is it a setting I'm overlooking somewhere? Or does it need to be "approved"?


Solution

They are using an old App created before end of April 2014, it was different back then. You can´t force it anymore, you can only check if the user authorized the permissions after login, with the return_scopes flag, for example:

https://developers.facebook.com/docs/reference/javascript/FB.login/v2.2



Answered By - andyrandy
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Facebook app that automatically writes on fans wall, when some fan have birthday?

 March 13, 2022     facebook, facebook-javascript-sdk, facebook-php-sdk, javascript, php     No comments   

Issue

Is it possible to create an facebook application for administrator of fanpage, that have functionalities for posting birthday greeting on their wall when particular fan or fans have a birthday?


Solution

Luckily, this is not possible, as it would be pure spam.

You would need to authorize every single User with the App, request the publish_actions and user_birthday permissions and store an Extended User Token (that is valid for 60 days). You will never get publish_actions approved by Facebook in their review process, because it´s not allowed to autopost. Also, the message must be 100% User generated according to the platform policy.

TL;DR:

  • Not possible
  • Not allowed


Answered By - andyrandy
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to download stickers in Facebook graph API?

 March 13, 2022     facebook, facebook-fql, facebook-graph-api, facebook-javascript-sdk, facebook-php-sdk     No comments   

Issue

I have studied Facebook API documentation and looked up other resources. It seems Facebook API does not provide a way to download stickers in a message thread. Is there any way I can retrieve stickers from Facebook threads?

If there is no way of downloading stickers available to developers, then my question is how is the Facebook messenger app able to do it?


Solution

As mentioned by WizKid (a FB employee) there is no public API available for getting stickers. The Facebook messenger app uses an internal API.



Answered By - phwd
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, March 12, 2022

[FIXED] Fatal error: Uncaught OAuthException: Error validating access token: This may be because the user logged out or may be due to a system error

 March 12, 2022     facebook-javascript-sdk, facebook-php-sdk, php     No comments   

Issue

I have received this error when logging into my app. It appears to me that only I have the problem. The others who are able to access the app have been able to access the app with the exception of me.

Fatal error: Uncaught OAuthException: Error validating access token: This may be because the user logged out or may be due to a system error. thrown in /home/dexp/public_html/mascaraza/fb-php-sdk/base_facebook.php on line 1254

This problem appeared out of the blue. Even when I reverted to my older backup of my app the problem still remains. I tried playing other games on facebook which works fine, and when I tried creating a new app and migrating my stuff over it still remains the same. I have also tried removing the app from my account and re-authenticating the app but with no avail.

What do I need to do to resolve this error?


Solution

As written in How-To: Handle expired access tokens developers blog post

Access tokens for users can become invalid due to various reasons. In most cases, they can expire if it’s past the time specified by the expires field (by default access token have a 2 hour lifetime). What many developers do not realize is that an access token can also expire if a user changes her password, logs out or if she de-authorizes the app via the App Dashboard. It is very important that your apps handle such situations. If your access token expires, you need to reacquire a valid access token.

Before we could use offline_access permission to get token that not expire (unless user is connected with application), this permission is now deprecated, see Deprecation of Offline Access Permission to see how you can get access_token with longer expiration time.

Update:
As of Aug 2012 Facebook PHP-SDK have added simple way of extending access_token (see How to extend access token validity since offline_access deprecation for more details)

Extracted from here.



Answered By - Techie
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How nametests and meaww fetch friends which is not available from graph 2.0

 March 12, 2022     facebook-graph-api, facebook-javascript-sdk, facebook-php-sdk     No comments   

Issue

I am trying to fetch friends profile pics of a logged in user.From Graph 2.0, userfriends permission will fetch only the users who are using the app. However, I am surprised to see nametests and meaww apps are fetching friends profile pics, I see they are asking just email, publicprofile, userposts and friendslist permissions.

Any help in this regard is greatly appreciated.


Solution

I assume they are using taggable_friends or invitable_friends which Facebook will only allow to be used after submitting for reviews. Link for submitting to facebook for approval Both these apps are something that increases user engagement and activity in Facebook so Facebook will approve this to developers that look promising and well designed.



Answered By - Agent Smith
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, March 6, 2022

[FIXED] get friends count from facebook graph and use it in a .php file

 March 06, 2022     facebook-fql, facebook-graph-api, facebook-javascript-sdk, facebook-php-sdk, php     No comments   

Issue

After a thorough search on facebook, api and fql keywords I found how to get facebook friends count but being a newbie and limited knowledge of php, i am struggling with the php syntax.

https://graph.facebook.com/fql?q=SELECT friend_count FROM user WHERE uid = xxxxx this gives me the count of fb friends

I have a php file that opens when I click on a link. What I want to do here is check count of friends in facebook and if the count is more than 25 then only open the page else show an alert message box "You should have atleast 25 friends to view the content"

Can someone help me with the php syntax?

Thank you in anticipation


Solution

You shouldn't use FQL as it will eventually be depreciated. You can use the taggable_friends API to get a list of friends and indirectly get a estimated friend count. The following tutorial explains the process.

PHP Code:

// get taggable friends
$taggable = (new FacebookRequest( $session, 'GET', '/me/taggable_friends' ))->execute()->getGraphObject()->asArray();

// output response
echo '<pre>' . print_r( $taggable, 1 ) . '</pre>';

// output total friends
echo count( $taggable['data'] );


Answered By - Niraj Shah
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] JQuery script doesn't fire in FB app for other participants

 March 06, 2022     facebook, facebook-javascript-sdk, facebook-php-sdk, jquery     No comments   

Issue

I'm learning to create a FB iframe tab app. For now I just want to check if the user that watches the page is an admin or not. So I have this code in my index.php:

<?php
require 'inc/facebook.php';

$facebook = new Facebook(array(
  'appId'  => 'xxxxxxxxxxxx',
  'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxx',
));

$user = $facebook->getUser();

$access_token = $facebook->getAccessToken();

if ($user) {
   try {
      $user_friendList = $facebook->api('/me/friends?access_token='.$access_token);
       $user_profile = $facebook->api('/me','GET');

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

$signed_request = $facebook->getSignedRequest();
$page_id = "";
if( $page = $signed_request['page'] ) {
    $page_id = $page['id'];
} else { $page_id = "some id"; }
?>


<!doctype html>
<html>
<head>
<title>php-sdk</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
    var page_id = <?php echo $page_id; ?>;
    var user_id = <?php echo $user; ?>;
    var is_admin = <?php echo $page['admin']; ?>;
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="scripts/functionality.js"></script>
...rest of the code...

Then in my functionality.js file I have this code, which should fire an alert dialog when the page loads:

$(function(){
    alert("Is admin: "+is_admin);
});

I'm the creator of the page where this app is being tested and the developer of the app. When I open this tab - I see the alert dialog pop-up as it should. I gave a Developer and a Tester role to 2 of my friends, and when they open the tab - the dialog doesn't pop-up for them. Any thoughts why is it happening and how to fix it?


Solution

The signed_request returns [admin] => 1 if the user is an admin or [admin] => otherwise. There is no true or false value. You can modify your code to something like:

<script type="text/javascript">
    var page_id = "<?php echo $page_id; ?>";
    var user_id = "<?php echo $user; ?>";
    var is_admin = "<?php echo isset( $page['admin'] ) && $page['admin'] == 1 ? true : false; ?>";
</script>


Answered By - Niraj Shah
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Getting facebook current session details like user_id in different pages

 March 06, 2022     ajax, facebook, facebook-javascript-sdk, facebook-php-sdk, session-variables     No comments   

Issue

My main page is index.php. Here I perform user login and then redirected to url.php using ajax request. Now user may move to various pages.

I need current user facebook id on those pages. How can I get it?

login.php

 <script type="text/javascript">
    window.fbAsyncInit = function() {
      FB.init({
        appId: '<?php
        echo $appId;
        ?>',
        cookie: true,
        xfbml: true,
        //  channelUrl: '<?php
        echo $return_url;
        ?>channel.php',
        oauth: true}
             );
    };
    (function() {
      //alert("1");
      var e = document.createElement('script');
      e.async = true;
      e.src = document.location.protocol +'//connect.facebook.net/en_US/all.js';
      document.getElementById('fb-root').appendChild(e);
    }());
    function CallAfterLogin(data,callback){
      FB.login(function(response) {
        if (response.status === "connected")
        {
          LodingAnimate();

          FB.api('/me?fields=movies,email,name', function(mydata) {

              $.post('movies_db.php',{'myd':a, name: name, email: email, myid:myid}, function(data) 
                     {
                       $.ajax({
                         url:'url.php'
                         ,async:     true
                         ,type : 'POST'
                         ,cache:     false
                         ,data : 'myid=' + myid
                         ,dataType:  'html'
                         ,success:   function(data){
                           $('body').html(data);
                           FB.XFBML.parse();
                         }
                       }

I tried in this way: on url.php/ or whatever page at which I want to get session info

$id= $_SESSION['fb_<appID>_user_id'];
echo "X is $id";

Another try using php sdk:

require_once("facebook.php"); //given correct path

$config = array();
$config['appId'] = '1788xxxxxx2';
$config['secret'] = '390c04c60xxxxxxxxx68aca44';

$facebook = new Facebook($config);

$appId = $facebook->getAppId();  //gives correctly
$uid = $facebook->getUser();   //always 0
echo "$uid";

one more try:

<?php
session_start();
print $_SESSION['fb_<myAppID>'];  //prints correct
//print $_SESSION['fb_<userID>'];
print $_SESSION['fb_<myAppID>_user_id'] = '<user_id>';  //does not print anything
//echo "id :$x";
?>

No luck. Any other idea? Or where is the mistake here?


Solution

UPDATE

JS (jQuery)

script.js

  $('#login').click( function(e){

      e.preventdefault;

        FB.login(function(r) {
        if (r.authResponse) {
            var accessToken = r.authResponse.accessToken;
            $.ajax({ 
                type     : "GET",
                url      : "set-session.php",
                data     : { accessToken : accessToken },
                datatype : 'json',
                success  : function(user) {
                                    $('p').fadeOut( function() { 
                                         $('p').html('Hey, Good to see you <a href='+ user.link +'>'+ user.first_name +'</a>!</p>');
                                         $('p').fadeIn();
                                    });
                                    $('#login').fadeOut().remove();
                           },
                error    : function() {
                                    $('p').fadeOut( function() { 
                                         $('p').html('Something went wrong :( try again');
                                         $('p').fadeIn();
                                    });          
                           }
            });
        } else {
            $('p').fadeOut( function() { 
                 $('p').html('You didn\'t authorize the app');
                 $('p').fadeIn();
            }); 
          }
      });

    });

PHP

set-session.php

<?php
require_once 'facebook-sdk/facebook.php';
header('Content-Type: application/json');

if ( isset($_GET['accessToken']) && !empty($_GET['accessToken']) ) {

        $accessToken = $_GET['accessToken'];
        $facebook    = new Facebook(array(
                                    'appId'  => '1419692231579671',
                                    'secret' => 'd69245290e6c6fb1346faa32437652c5',
                                    'cookie' => true
        ));

        # set the access_token for $facebook for future calls
        $facebook->setAccessToken($accessToken);

        try {

             $userData = $facebook->api('v2.0/me');
             # register a new session for the user, containing their basic information, id, username, first_name, last_name, profile_picture
             # and another one for the access_token.
             $_SESSION['fb-user-token'] = $accessToken;
             $_SESSION['fb-user']       = $userData;

             echo json_encode( array('id'         => $userData['id'],
                                     'link'       => $userData['link'],
                                     'username'   => $userData['uesrname'],
                                     'first_name' => $userData['first_name'],
                                     'last_name'  => $userData['last_name'],
                                     'gender'     => $userData['gender']      ), JSON_PRETTY_PRINT);

        } catch (FacebookApiException $e) {

           error_log($e);

        }

} else {
   header('HTTP/1.1 400');
}

Index

index.php

<?php
if ( isset($_SESSION['fb-user']) ) {
    $user = $_SESSION['fb-user'];
?>
    <div>
       <p>Hey, Good to see you <a href="<?php echo $user['link'] ?>"><?php echo $user['first_name']; ?></a>!</p>
    </div> 
<?php
    } else {
?>
    <div>
       <p>Hey there, Login with your Facebook</p>
    </div>
    <a class="fsl fsl-facebook" href="#" id="login">
       <span class="fa-facebook fa-icons fa-lg"></span>
       <span class="sc-label">Login W/ Facebook</span>
    </a>    

<?php  
}
?>

DEMO

You can download & contribute to this repository on GitHub



Answered By - Adam Azad
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Creating an Edit Settings page for a FB tab app and securing it

 March 06, 2022     facebook, facebook-javascript-sdk, facebook-php-sdk, jquery, php     No comments   

Issue

I'm trying to create a FB tab app. It's supposed to have an Edit Settings page, which is obviously supposed to be accessible only to page admins. If the admin is watching the tab - he's supposed to see a link to that page. I can do something like that with jQuery:

var is_admin = "<?php echo isset( $page['admin'] ) && $page['admin'] == 1 ? true : false; ?>";
if(is_admin)
   $("<div id='div_edit_settings'>Edit Settings</div>").appendTo("some_div");

And later I can detect when this link was clicked and present the page (it's supposed to be displayed inside the tab as well, but since it's stored on the server it's also accessible through a browser).

The problem is that JS is visible to Firebug and other browser developer tools, so somebody could just insert a code line and see that link. So what can I do to make sure that only admins can see that Edit page and that only admins are editing the settings? How can I protect the link and the Edit page itself?


Solution

You should use PHP to insert the link into your page, something like:

<?php if ( isset( $page['admin'] ) && $page['admin'] == 1 ) : ?>
  <div id='div_edit_settings'>Edit Settings</div>
<?php endif; ?>

You should also save the admin status to a session (with a name that isn't obvious, possible random string you can later check for), so that you can verify on other pages if the user viewing the link is actually an admin (you lost access to $page['admin'] when accessing other pages, unless you pass the signed_request to subsequent page calls.



Answered By - Niraj Shah
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Facebook sdk. Publish on people wall

 March 06, 2022     facebook, facebook-graph-api, facebook-javascript-sdk, facebook-php-sdk     No comments   

Issue

I developed an application a while ago that published messages on people walls, but I remember I had problems with sdk upgrades that restricted publishing on wall features.

Now I'm developing a new application that's supposed to have a similar feature, but not sure if it's even possible (I'm guessing it's not though), so my questions are, with the latest Facebook sdk:

  • Is it possible to publish a message on 'someone's wall without him granting permission for it?

  • If not, is it possible to publish a message on 'someone's wall if he authorizes my application to?

  • Is it even possible to publish a message on my own wall using my user credentials?


Solution

  • Facebook has disabled posting to a friends wall completely using the SDK, whether you were granted permission or not. See the February 6, 2013 Update. You should use the JavaScript Feed dialog instead setting the to field of the user you want to message.
  • No. As above.
  • Yes, you need the publish_actions permission to do this using the SDK.


Answered By - Niraj Shah
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, March 2, 2022

[FIXED] Could CSS be used in Survey?

 March 02, 2022     css, facebook, facebook-javascript-sdk, facebook-php-sdk, survey     No comments   

Issue

Could CSS elements or attributes contribute to survey of a particular action such as a profile change?

Recently, I was surprised that facebook had this Internet.org where it went for a controller CSS entity change for for this they did the same with Gay Rights initiative as mentioned below:

enter image description here

Could it lead to activation of any survey like counting how many profiles were changed?


Solution

The answer is "it depends". According to my experience, using css class names can be used to select data from DOM using javascript or other client side scripting mechanisms. So there is a possibility that FB may be using some kind of analytics/survey type system, that actually inspects the profile/friendlist/group/commentslist or whatever to check if the profile pic element also have the "internetorg" class attached to it.

But still, it is not making any sense why FB should use some kind of client side stuff when they have one of the world's best h/w infra for these type of applications.



Answered By - Sak90
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, February 26, 2022

[FIXED] Facebook JS API errors

 February 26, 2022     facebook, facebook-javascript-sdk, facebook-php-sdk, javascript     No comments   

Issue

I am trying to create a test application the source is the following (index.php):

<?php
include_once 'facebook/facebook.php';

$facebook = new Facebook(array(
  'appId'  => 'YYYYYYYYYYYYYYYY',
  'secret' => 'XXXXXXXXXXXXXXXXXXXXXX',
));

$user = $facebook->getUser();

if($user)
{
  try
  {
    $user_profile = $facebook->api('/me');
  }
  catch(FacebookApiException $e)
  {
    error_log($e);
    $user = null;
  }
}

if( ! $user)
{
  echo "<script type=\"text/javascript\">top.location.href='" . $facebook->getLoginUrl(array(
    'scope' => 'publish_actions,publish_stream',
    'redirect_uri' => 'http://apps.facebook.com/MYAPPURL/'
  )) . "'</script>";
  exit;
}
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>TribusWar</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="http://connect.facebook.net/en_US/all.js#appId=YYYYYYYYYYYYYYYY&amp;xfbml=1"></script>
</head>
<body>
<input type="button" value="Compartilhar" id="xxxxx" />
</body>
<script type="text/javascript">
document.getElementById('xxxxx').addEventListener('click', function()
{
  FB.ui({
    method: 'feed',
    display: 'iframe',
    name: 'Dialog Name',
    caption: 'Caption for dialog',
    description: 'Lorem ipsum dolor sit amet...'
  }, function()
  {
    alert(arguments);
  });
}, false);
</script>
</html>

With this code, I wanted to show an button on the page which fires an publish dialog when clicked. When the page loads, it generates an error, when the button is clicked, another error occurs and the dialog is not shown:

Firebug Console

I don't know what is going wrong with this. I don't know if the publish_stream permission is really necessary as I am trying to use the facebook dialog. Can anyone help-me?


Solution

As Nava Salvatore (and the debugger console) says, you need to add:

<div id="fb-root"></div>

somewhere within the <body> of your code. Additionally, your final <script> block should be before the </body> tag (per convention). You don't need any additional permissions for simply displaying a dialog; publish_stream is not needed.



Answered By - Jimmy Sawczuk
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing