Determine if a user has liked my page using Facebook PHP SDK? - php

My search has come up empty because when you search for "Facebook" and "like" I get all kinds of other results.
I have an app that is only on my company's Facebook page. In that app I need to find out if the user has liked the company's page. I'll show one thing if not and another thing if so. How can I do this using the Facebook PHP SDK v.3.1.1?

It can be done this way:
<?php
require('facebook.php');
$config = array(
'appId' => 'your facebook app id',
'secret' => 'your facebook app secret code',
'allowSignedRequest' => false
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if (isset($user_id)) {
try {
$likes = $facebook->api('/me/likes/your_facebook_page_id_here', 'GET');
if (!empty($likes['data'])) // if user has liked the page then $likes['data'] wont be empty otherwise it will be empty
{
echo 'Thank you for liking our fan page!';
}
else {
//show something else
}
} catch (FacebookApiException $e) {
$login_url = $facebook->getLoginUrl();
echo 'Please click here to login into your Facebook account.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
$login_url = $facebook->getLoginUrl();
echo 'Please lick here to login into your Facebook account';
}
?>
The user will click on the "Please click here to login into your Facebook account." text which will redirect it to Facebook app permissions page, once user allows the permission to your app the code will fetch user's data and will display what ever you want if user hasn't liked your fan page.

You can do this using FQL. You'll also need to make sure that you have the user_likes permission set.
I pulled this example from an older app that is now offline, it may need to be changed depending on what Facebook has changed in their last round of updates. Lately I've been using javascript and I subscribe to the edge.create event.... just replace the page_id with your page's id and give it a try
$checkIfUserLikePage = $facebook->api(array(
"method" => "fql.query",
"query" => "select uid from page_fan where uid=me() and page_id=1234567"
));
$checkIfUserLikePage = sizeof($checkIfUserLikePage) == 1 ? true : false;

This should work for you! I had to do a lot of these types of pages so I created a really simple way of creating like gated pages. https://github.com/DrewDahlman/FBVersion
Enjoy!

$signed_request = $_REQUEST['signed_request'];
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
$this->assign('verify', $signed_request->page->liked);
}
else {
echo "Please click on the Like button to view our Coupons!";
jexit();
}
}
I hope this will help you :)

Old topic, but wanted to weigh in as I have recently learned a lot about how to do this and have had to put it into practice.
Have a look at this link: http://nickring.com/blog/2012/11/facebook-fan-gate-using-php/. It uses the signed_request variable as some of the other responses show, but it shows how it does not require requesting the signed_request variable via $_REQUEST.
The one main thing to remember is that signed_request is only available when the PHP script accessing signed_request is run within Facebook. If you run this script outside of Facebook in a script attempting to use the Facebook API, it will return an empty array.
Here's an example - the following script will run when you go to this address: https://www.facebook.com/yourFacebookPage/app_xxxxxxxxxxxxxxx with 'xxxxxxxxxxxxxxx' being the app ID.
// Check if the user has liked us on Facebook, require the Facebook SDK
require_once('linked/facebook/facebook.php');
// Setup the Config
$config = array(
'appId' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy',
'cookie' => true
);
// Create a Facebook SDK instance
$facebook = new Facebook($config);
// Get the signed_request variable that we so desparately need
$signed_request = $facebook->getSignedRequest();
$like_status = $signed_request["page"]["liked"];
// Make sure that it worked
if (!empty($signed_request))
{
// Get the signed_request information
if ($like_status == 1)
{
// Wo0t! Show the FB fan only page stuff here
}
else
{
// Show the 'Please like us page'
$page = file_get_contents('pages/facebookLikeUs.html');
// Finish the page
echo $page;
exit();
} // End if ($like_status == 1) ELSE Clause and IF
} // End if (!empty($signed_request)) IF Clause
else
{
// Damn, it didn't work. Show an error
}
The above script is the script that is called from the URL set in the Canvas URL in the "App on Facebook" section of the App's settings. The facebookLikeUs.html page is simply a page asking them to click "Like" to continue. If I'm in a situation that I want them to be redirected back into a website that requires the Facebook like I simply replace the // Wo0t! section with something like this:
// Wo0t! They're all set, establish some cookies, get a cookie, and redirect back to the PHD program site
setcookie('fbls', $signed_request['page']['id'] . '-' . $signed_request['user_id'], time() + 300);
$redirectURL = "http://www.myurl.com/theScriptIWantToReceiveTheUserFromFB.php";
// Since Facebook really wants to keep us in the page, we need to create a page that will automatically break out of FB
$page = file_get_contents('pages/facebookRedirectBack.html');
// Replace some stuff
$page = str_replace('$redirectURL', $redirectURL, $page);
// Output the page
echo $page;
exit();
With the facebookRedirectBack.html page being this:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
window.top.location.href = '$redirectURL';
</script>
</body>
</html>
If you're looking to have a bit more security on this, you can have the redirecting PHP script write some cookies and attach them to the URL such that the receiving script must compare the cookies and the URL params then delete the cookies after they've been read.
Hope this helps as I personally haven't found any consistent information on this subject.

Related

Facebook PHP web app doesn't work when accessed from account other than app administrator

I have a very simple PHP app that retrieves a users & friends RSVPd events using FQL. It is using the latest PHP SKD. The code works perfectly when I am logged in and authenticated as the account that created the app, but it fails with 'unknown error' if I am logged in and authenticated as anyone else.
Here is the login portion of my code
$config = array();
$config['appId'] = $validId;
$config['secret'] = $validSecret;
$facebook = new Facebook($config);
$uid = $facebook->getUser();
// get the url where to redirect the user
$location = "". $facebook->getLoginUrl(array('scope' => 'user_events, friends_events'));
// check if we have valid user
if ($uid) {
try {
$fb_user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$fb_user_id = NULL;
// seems we don't have enough permissions
print '<script language="javascript" type="text/javascript"> top.location.href="'. $location .'"; </script>';
// kill the code so nothing else will happen before user gives us permissions
die();
}
} else {
// seems our user hasn't logged in
print '<script language="javascript" type="text/javascript"> top.location.href="'. $location .'"; </script>';
// kill the code so nothing else will happen before user gives us permissions
die();
}
print "Authenticated ". $fb_user_profile['name']." <a href='logout.php'>Logout</a><br>";
Here is the FQL portion of my code
$param = array(
'method' => 'fql.query',
'query' => $validFqlQuery,
'callback' => '',
'access_token' => $facebook->getAccessToken()
);
echo "<br>Working...";
$fqlResult = $facebook->api($param);
print_r($fqlResult);
Your App needs to be reviewed by Facebook before it goes Live for
other users to Login.
You do not need to go through Login Review if your app requests these three basic permissions:
public_profile
user_friends
email
To ask your app's users for any other permissions, you will need to submit for review.
However, in order to help you craft your Facebook Login experience, your app's developers will be able to see, and grant, any permission without requiring review by Facebook.
Note: People who are listed in your app's Roles tab will have access
to extended permissions without going through review (e.g.
publish_actions or manage_pages). For example, if you use the Facebook
Plugin for Wordpress to publish your blog posts to your Facebook Page
or Profile, you do not need to submit for review so long as all your
publishers are listed in your app's Roles tab.

Load page in facebook app via ajax

I have created a facebook app which I'm using as a Page Tab. I'm using the PHP SDK and Javascript SDK, and have authenticated and set it up perfectly to display the dialogs and then my page within the tab iframe.
I would now like to load other pages of my site asynchronously, however I can not access the users data (name, etc.) on the asynchronously loaded pages. How do I pass the authentication and variables to the ajax loaded pages?
(EDIT) Solution:
The PHP SDK creates a session automatically to use amongst pages loaded with ajax (or anywhere). You just have to call your authentication routine on each page loaded with ajax in order to access the data (using a php include is best).
I load pages into a div using a simple jquery load:
$('div#page').load('your-page.php');
And this is the routine I run on each php page:
<?php
//facebook application configuration
$fbconfig['appid' ] = "YOUR APP ID";
$fbconfig['secret'] = "YOUR APP SECRET";
$fbconfig['baseUrl'] = "SOURCE FILES BASE URL";
$fbconfig['appBaseUrl'] = "APP BASE URL";
/*
* If user first time authenticated the application facebook
* redirects user to baseUrl, so I checked if any code passed
* then redirect him to the application url
*/
if (isset($_GET['code'])){
header("Location: " . $fbconfig['appBaseUrl']);
exit;
}
//
if (isset($_GET['request_ids'])){
//user comes from invitation
//track them if you need
}
$user = null; //facebook user uid
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
//Facebook Authentication part
$user = $facebook->getUser();
// We may or may not have this data based
// on whether the user is logged in.
// If we have a $user id here, it means we know
// the user is logged into
// Facebook, but we don’t know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown'
)
);
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
d($e); // d is a debug function defined at the end of this file
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
//get user basic description
$userInfo = $facebook->api("/$user");
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
?>
It depends of how you do your request, but you can save the data in a $_SESSION variable, like $_SESSION['userData'] = $facebook->api('/me'); and call it on every pages.

How to ask user to like facebook fan page to make download button visible?

I want to create page in which there is a download link. which is only visible to users who have liked my fan page at facebook. Otherwise it show like button.
I am using the following code but it
<?php
include_once("php/src/facebook.php");
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => '354967071210221',
'secret' => 'APP_Secret',
'cookie' => true,
));
$signed_request = $facebook->getSignedRequest();
// Return you the Page like status
$like_status = $signed_request["page"]["liked"];
if($like_status)
{
echo 'User Liked the page';
// Place some content you wanna show to user
}else{
echo 'User do not liked the page';
// Place some content that encourage user to like the page
}
?>
You can get this info using FQL queries
1) Find out your page_id
SELECT page_id, pic FROM page WHERE username="grasphub"
(It says that your page_id is 354967071210221)
2) Check if user has liked your page using this query
SELECT page_id FROM page_fan WHERE page_id=354967071210221 AND uid = me()
This query will return empty result if user did not like your page yet.
So, your code will be:
include_once("php/src/facebook.php");
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => '354967071210221',
'secret' => 'APP_Secret',
'cookie' => true,
));
$user = $facebook->getUser();
if ($user) { // Checks if there is already a logged in user
try {
$result = $facebook->api( array(
'method' => 'fql.query',
'query' => 'SELECT page_id FROM page_fan WHERE page_id=354967071210221 AND uid = me()',
));
if (!empty($result[0]['page_id'])) {
echo 'User Liked the page';
} else {
echo 'User do not liked the page';
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else { //Ask for bare minimum login
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
}
if this code works
you can set show your file inside this if
if($like_status)
{
echo 'User Liked the page';
// Place some content you wanna show to user
}
TEST it!!!
Like / Unlike your FB page and check what the page will return if it gives you different value then its working and inside this IF you know that user likes your page..
First of all try
$signed_request = $facebook->getSignedRequest();
print_r($signed_request);
If it's empty or doesn't contain correct data, you should check your application settings (canvas url, tab url etc.)
You have two options client side or server side:
Here is the a link to a great tutorial on client side scripts
http://www.saschakimmel.com/2010/05/how-to-capture-clicks-on-the-facebook-like-button/
For the server side - You need to get permission from user to access his/her likes - I do not use the FB SDK, I made my own code:
- First the user has to login using this URL:
$loginUrl = "https://www.facebook.com/dialog/oauth?client_id={$appId}&redirect_uri= {$redirectUri}&scope={$scopeEncoded}";
When the user login, FB will ask about giving permissions to this app to access Likes
After accepting & redirecting, get the code in the url using $code = $_GET['code']
The last step is to get the token, you need to make a request using curl to this URL
$url = "https://graph.facebook.com/oauth/access_token?client_id={$appId}&redirect_uri={$redirectUri}&client_secret={$secretKey}&code={$code}";
Now, you have the token you can make curl request to user likes using this URL: https://graph.facebook.com/me/likes?access_token=$accessToken
Loop through the likes and find out if the user likes your page or not or use this URL:
$url = "https://graph.facebook.com/me/likes/{$yourpageId}/?access_token={$accessToken}";
This could be done using graph API .edge.create listens to the click event of like button.
FB.Event.subscribe('edge.create',function(response)
{
download();
});
FB.api("me/likes/page_id", function(response)
{
if ( response.data.length == 1 )
{
//Has liked the page
} else
{
//Havent liked the page
}});
source and download script - http://www.webtuts.info/webdevelopment/facebook-download-script-2/225/

Facebook PHP SDK Graph API post to page not functioning properly

I'm trying to add a feature to my app that will post a status to a admin user's page timeline with the same detail as if they posted on Facebook.com. The main feature I am focusing on is the link sharing and thumbnail images, like when you paste a link into your status and it auto-detects a thumbnail image, gives you a nice link, description, etc. I have tireless read through other forums and the Graph API documents, and I keep running into problems with the post showing as the admin user, rather than the page. Here is my code:
$facebook = new Facebook(array(
'appId' => $appID,
'secret' => $appSecret,
));
$loginUrl = $facebook->getLoginUrl(array(
"scope" => 'publish_stream, read_insights, manage_pages, photo_upload, video_upload, create_note, manage_notifications'
));
$access_token = $facebook->getAccessToken();
$fbpost = array();
$fbpost['access_token'] = $access_token;
$fbpost['message'] = $message;
$fbpost['link'] = $link;
$fbpost['description'] = $description;
$fbpost['caption'] = $caption;
$fbpost['picture'] = $fbimg;
$status = $facebook->api('/'.$pageID.'/feed', 'POST', $fbpost);
var_dump($status);
When I only post the $fbpost['message'] it correctly posts the status as the page, but when I add ANYTHING else it shows the post as the authenticated admin user instead of the page. Very frustrating. Any ideas?
I keep running into problems with the post showing as the admin user, rather than the page.
Then get a page access token, not a user access token for the admin user …
Thanks to CBroe for providing a link to the Facebook docs on the page/app access token. After checking that out, I came up with this PHP (since there is no good documentation in the PHP SDK for getting a page access token):
$user_token = $facebook->getAccessToken();
$accounts = $facebook->api('/me/accounts?access_token='.$user_token);
$account_token = 0;
foreach ($accounts['data'] as $account) {
if ($account['id'] == $_SESSION['facebook']) {
$account_token = $account['access_token'];
}
}
if ($account_token) {
/// your page token code
} else {
echo 'You must be an admin on this page!';
}

Facebook PHP SDK - require login on specific account

I'm tired of digging through tons of tutorials/documentations which don't help me at all.
What I have now (everything is placed inside admin control panel):
If user is logged on correct account (administrator of page with granted rights), everything works fine, post on page is posted as impersonated site.
If he is logged on other account, nothing happens. Site redirects him to his wall.
If he isn't logged on any account, he's redirected to facebook login - if he logs onto correct account, he returns to acp (it's bad solution, because it'll clear his form)
I want to achieve:
If logged in, everything as it was
Else popup with login to specific (correct) account
At the moment I'm using only PHP, but solution with JS is permitted.
My code:
<?php
/*(...)*/
$facebook = new Facebook(array(
'appId' => $apiid,
'secret' => $secret,
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
if($me) {
//In order to post to the page later on we need to generate an Access Token for that page, to do this we get me-accounts in the following api call
$accounts = $facebook->api('/me/accounts');
//Loop through the array off accounts to find the page with a matching ID to the one we need
foreach($accounts['data'] as $account){
if($account['id'] == PAGEID){
$ACCESS_TOKEN = $account['access_token'];
}
}
}
$message=$data['facebook_text'];
$attachment = array(
'message' => $data['facebook_text'],
'name' => $data['name'],
'description' => '',
'link'=>$someurl,
'access_token' => $ACCESS_TOKEN
);
if($image_url != NULL) $attachment['picture'] = $image_url;
try {
if($facebook->api('/PAGEID/feed', 'post', $attachment))
{
//other stuff
}
} catch (FacebookApiException $e) {
error_log($e);
//other stuff
}
}
else
{
$login_url = $facebook->getLoginUrl();
header("Location: $login_url");
exit;
}
/* (...) */
?>
Solution can't redirect anywhere, because it's inside form, so all data'll be lost.
I'm not really sure I understand what you want to do here, but this is what I use in a similar situation:
$session = $this->get_admin_session_of_page ($page_id);
$session = unserialize ($session);
$facebook->setSession ($session, false);
In the facebook php SDK there is a method to manually set the session, setSession. I save the page admin user session in DB with serialize, with the offline access and manage pages permission. Then when you need some admin privileges for the application you just unserialize it, and then use setSession. The second parameter is set to FALSE, so that this session is not saved in a cookie and logout the current user.
This way it's not important who is logged in, the work is always done as an admin of the page. I think this is safe to use in an automated script, for example to upload a user photo in a page album.
Of course, you must use caution with this if it gets more involved then that, or implement your own security.

Categories