I'm using the facebook API to get my wall feed using the graph API.
<?php
require_once('facebook.php');
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '188687744521977',
'secret' => 'c2c3692845602812f473436d1da95014',
'cookie' => true
));
// Get User ID
$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.
if($user)
{
try
{
// Proceed knowing you have a logged in user who's authenticated.
$access_token = $_SESSION['fb_188687744521977_access_token'];
$user_profile = $facebook->api('/me');
$likes = $facebook->api('/me?fields=feed,likes');
$friends = $facebook->api('/me/friends');
$feed = 'https://graph.facebook.com/me/feed? access_token='.$access_token.'';
} catch (FacebookApiException $e)
{
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if($user)
{
$logoutUrl = $facebook->getLogoutUrl();
} else
{
$loginUrl = $facebook->getLoginUrl();
}
// Save the user's info as variables
$full_name = $user_profile['name'];
$first_name = $user_profile['first_name'];
$last_name = $user_profile['last_name'];
$relationship = $user_profile['relationship_status'];
$partner_id = $user_profile['significant_other_id'];
$id = $user_profile['id'];
$link = $user_profile['link'];
function get_url($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$tmp = curl_exec($ch);
curl_close($ch);
return $tmp;
}
$wall = get_url($feed);
print_r(json_decode($wall, true));
?>
However, an empty array is displayed. Any suggestions?
You should definitly try to find a better solution for handling the access token! Where are you setting this $_SESSION['fb_..._access_token']? Who says that 188687744521977 is always the userid of the logged in user? Why do you have spaces in your feed url?
The first thing you should do is delete the json_decode() and just var_dump() the $wall. I think your access token is not valid, maybe you also get a 401 Unauthorized or 403 Forbidden response?
Related
I want to get latest posts from fb and need to display on my site(magento). I have registerd one app in facebook and try to getting posts by using the url but it's giving empty array
require_once(Mage::getBaseDir('lib') . '/facebook/facebook.php');
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxx',
));
$fbid = "xxxxxxxxxx";
$secret = "xxxxxxxxxxxxxxxxxxxxxxx";
$token = 'https://graph.facebook.com/oauth/access_token?client_id='.$fbid.'&client_secret='.$secret.'&grant_type=client_credentials';
$token = file_get_contents($token);
$posts = json_decode(
file_get_contents('https://graph.facebook.com/' . $fbid . '/feed?
access_token=' . $token
)
);
But it's giving an empty array and could you help me to get the results and why it is giving empty?
In order to read the Feed from Facebook, you must log the user into Facebook and ask the user for the read_stream permission.
The feed will be the logged-in user's feed and may not be appropriate for all users of your website, unless each user of your website sees their own feed...
If you have a valid access token, you can get feed from any public page using php graph api.You can call api using file_get_contents or curl method.
function curl_get_file_contents($URL) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 400);
$contents = curl_exec($ch);
$err = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
$contents=json_decode($contents,true);
if ($contents) return $contents;
else return FALSE;
}
$access_token = 'your accesstoken';
$url = " https://graph.facebook.com/$page_id/feed?access_token=$access_token";
$posts = curl_get_file_contents($url);
Now $posts will have all the recents posts from the page and you can use foreach to get each post.
Create App Developer Facebook Page.
Live Access token you can get via graph. Then code exmaple:
<ul>
<?php
$page_name = '{PAGE_NAME}'; // Example: http://facebook.com/{PAGE_NAME}
$page_id = '{PAGE_ID}'; // can get form Facebook page settings
$app_id = '{APP_ID}'; // can get form Developer Facebook Page
$app_secret = '{APP_SECRET}'; // can get form Developer Facebook Page
$limit = 5;
function load_face_posts($page_id, $page_name, $app_id, $app_secret, $limit, $message_len) {
$access_token = "https://graph.facebook.com/oauth/access_token?client_id=$app_id&client_secret=$app_secret&grant_type=client_credentials";
$access_token = file_get_contents($access_token); // returns 'accesstoken=APP_TOKEN|APP_SECRET'
$access_token = str_replace('access_token=', '', $access_token);
$limit = 5;
$data = file_get_contents("https://graph.facebook.com/$page_name/posts?limit=$limit&access_token=$access_token");
$data = json_decode($data, true);
$posts = $data[data];
//echo sizeof($posts);
for($i=0; $i<sizeof($posts); $i++) {
//echo $posts[$i][id];
$link_id = str_replace($page_id."_", '', $posts[$i][id]);
$message = $posts[$i][message];
echo ($i+1).". <a target='_blank' href='https://www.facebook.com/AqualinkMMC/posts/".$link_id."'>".$message."</a><br>";
}
}
load_face_posts($page_id, $page_name, $app_id, $app_secret, $limit, $message_len);
?>
</ul>
I have read about facebook opengraph connection - as far as I have understood, the login procedure is made within 3 steps:
Get the login url from the facebook api call in order to create a custom login button
Upon clicking on the link we are redirected to the facebook login page
Do the actual login and get redirected to the site we have defined in the app facebook developer page
In this page we have to deal with the actual result. Here comes the problem: I've understood that we have to use the token and make a new request to the fb page in order to validate the token (see below).
After this, I assume we get the user actual details but I never manage to execute this token request and therefore I'm not sure in how to proceed.
$ch = curl_init("http://graph.facebook.com/oauth/access_token? client_id=".$facebook_config['appId']."
&client_secret=".$facebook_config['secret']."
&redirect_uri=".urlencode(SITE_DOMAIN)."/facebook_login_processor.php
&code=".$_GET['code']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 30000);
$data = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
if ($curl_errno > 0)
{
echo "cURL Error ($curl_errno): $curl_error\n";
}
else
{
echo $data;
}
I'm getting an error regarding the redirect_uri - somehow it is not getting validated.
{"error":{"message":"Missing redirect_uri parameter.","type":"OAuthException","code":191}}
Bear in mind that I'm trying this on a non public website (domain is only registred in the server and in my hosts file). Does this impose a problem?
I appreciate any help and thank you for your attention and help
Ricardo
Ps.: sorry about any error - I'm on the phone
Based on facebook php sdk, the script below simply works well on my website.
<?php
require_once "lib/facebook.php";
$scope = "create_note,email friends_groups,friends_interests";
$redirecturl = "https://www.mysite.com/callback.php";
$facebook = new Facebook(array('appId' => APP_ID,'secret' => APP_SECRET));
$authurl = $facebook->getLoginUrl( array( 'scope' => $scope, 'redirect_uri' => $redirecturl );
header("Location:$authurl");
?>
then on callback.php
<?php
require_once "lib/facebook.php";
$facebook = new Facebook(array('appId' => APP_ID,'secret' => APP_SECRET));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
if (!empty($user_profile)) {
print_r($user_profile);
// or do something here
}
}
?>
Note: You should define APP_ID and APP_SECRET.
How can we check user liked the facebook application or not?
I am trying to create a Facebook app, in it there are two different pages , if user liked then page_1 will be show, otherwise page_2 show.
<?php
$user = $facebook->getUser();
if ($user) {
try{
$user_profile = $facebook->api('/me');
$likeID = $facebook->api(array( 'method' => 'fql.query',
'query' => 'SELECT url FROM url_like WHERE user_id = "'.$user_profile['id'].'" AND url="myurl/"'; ));
}
catch(FacebookApiException $e) { }
}
if(count($likeID)>0) echo "User likes this page";
else echo "User doesn\'t like this page";
?>
credible and/or official sources:
http://www.zuberi.me/2011/how-to-check-if-user-liked-the-application-or-page.html
http://www.chilipepperdesign.com/2011/02/15/reveal-fan-gate-like-gate-facebook-iframe-tab-tutorial-with-php
How to check if a user likes my Facebook Page or URL using Facebook's API
Facebook how to check if user has liked page and show content?
Facebook Check if user "Liked" the page
A better approach to the problem can be:
// to generate user access token after the user is logged in
$USER_ACCESS_TOKEN = $facebook->getExtendedAccessToken();
$isFan = curl("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . $USER_ACCESS_TOKEN . "&page_id=" . $FACEBOOK_PAGE_ID);
function curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
require 'facebook.php';
$app_id = "your app id";
$app_secret = "your app secret";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true,
));
$signed_request = $facebook->getSignedRequest();
$like_status = $signed_request["app"]["liked"];
if ($like_status == 1){
echo 'User likes this page';
}
else{
echo 'User doesn\'t like this page';
}
Maybe you should try somethng like this, check Facebook's PHP SDK reference page for the exact approach.
Can you tell me with steps how can I do a like button in my site (php) to like a page photo on facebook?
I know that I have to use the GRAPH API and have to do the POST via HTTP to /likes .. but I dont know how can I do it with PHP code.
Somebody have an example?
Thank you
As long as you have obtained the publish_stream permission from the user you can like any photo you need to. If you are attempting to like the photo as a page be sure you have an access_token for the page (obtained via the /accounts connection on the user account).
Once you have the access token the like is as simple as issuing an HTTP POST to a URL that looks similar to this:
https://graph.facebook.com/PHOTO_ID/likes?access_token=ACCESS_TOKEN
Photo_ID = Photo ID in Facebook
Access_Token = Access token obtained from Facebook with the publish_stream permission.
UPDATE
PHP Sample Code based on PHP Form CURL Post
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/PHOTO_ID/likes");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'Access_Token' => 'token_value'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
I would check this though as I'm not sure how accurate it is since I don't normally code PHP. In any manner, the post should be a raw HTTP POST request.
Fabio here is the php post snippet that i was able to get working. Snippet includes a curl to get application access token and the api post to like an object, in this case a post on my app.
The Sample post is here: Shows the post to be liked
https://shawnsspace.com/plugins/TimeLinePost.php?pageid=135669679827333&postid=135669679827333_151602784936066&type=feed&fh=750
The Like Page is here: Should Return whether the user likes or not, or login if not connected.
https://shawnsspace.com/plugins/TheLike.php?postid=135669679827333_151602784936066
Getting the Application Access Token.
function GetCH(){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT_MS,20000);
if(substr($url,0,8)=='https://'){
// The following ensures SSL always works. A little detail:
// SSL does two things at once:
// 1. it encrypts communication
// 2. it ensures the target party is who it claims to be.
// In short, if the following code is allowed, CURL won't check if the
// certificate is known and valid, however, it still encrypts communication.
curl_setopt($ch,CURLOPT_HTTPAUTH,CURLAUTH_ANY);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
}
$sendCH = curl_exec($ch);
curl_close($ch);
return $sendCH;
};
$app_access_token = GetCH();
Looking in url for postid parameter then liking id
if($_GET['postid']){
$postid = $_GET['postid'];
}else{
$postid = '135669679827333_151602784936066';
}
if($user){
$pageLike = $facebook->api('/'.$postid.'/likes?access_token='.$access_token.'&method=post', 'POST');
}
You can get permissions by building an array of perms for login url. below i am requesting read_stream,publish_stream,publish_actions,offline_access in the scope for permissions.
NOTE: app access token needed for logout url.
<?php
$url = (!empty($_SERVER['HTTPS'])) ? 'https://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'APPID',
'secret' => 'APP-SECRET',
'cookie' => true, // enable optional cookie support
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
//$pageInfo = $facebook->api('/'.$pageid.'?access_token='.$_SESSION['fb_112104298812138_access_token].');
//$pageInfoUser = $user_profile[id];
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
/* */
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$params = array(
scope => 'read_stream,publish_stream,publish_actions,offline_access',
redirect_uri => $url
);
$loginUrl = $facebook->getLoginUrl($params);
}
$access_token = $_SESSION['fb_135669679827333_access_token'];
?>
<?php
if(!$user){
echo ' : Login ';
}else{
echo 'Logout';
}
?>
I have created a simple Facebook application in PHP, that greets user by there user name,
I also want there Email id, to be displayed. But i am not able to do that. the code that i am using is,
require_once('facebook.php');
require_once('config.php');
$facebook = new Facebook(APIKEY, SECRETKEY);
$user=$facebook->require_login();
echo $user; // displaying the ID
<div style="padding: 10px;" id="greeting">
<fb:if-is-app-user uid="loggedinuser">
<h2>Hi <fb:name firstnameonly="true" uid="loggedinuser" useyou="false"/>! welcome to facebook</h2>
<fb:else>
<h2>Hi <fb:name firstnameonly="true" uid="loggedinuser" useyou="false"/>! welcome to facebook</h2>
</fb:else>
</fb:if-user-has-added-app>
</div>
the Output that i am getting is,
1000002020202020
Hi User! welcome to facebook
I want the Email address to be displayed along with the user name, i searched many code but did not get any solution. and if you any good facebook tutorial site please post the links too..
You can get the Email Address, directly without using the FQL.
// initialize facebook
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET));
$session = $facebook->getSession();
if ($session) {
try {
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
else
{
echo "You are NOT Logged in";
}
//getting the login page if not signned in
if (!$fbme) {
$loginUrl = $facebook->getLoginUrl(array('canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,user_birthday,publish_stream',
'next' => CANVAS_PAGE,
'cancel_url' => CANVAS_PAGE ));
echo '<fb:redirect url="' . $loginUrl . '" />';
} else {
// $fbme is valid i.e. user can access our app
echo "You can use this App";
}
// getting the profile data
$user_id = $fbme[id];
$name=$fbme['name'];
$first_name=$fbme['first_name'];
$last_name=$fbme['last_name'];
$facebook_url=$fbme['link'];
$location=$fbme['location']['name'];
$bio_info=$fbme['bio'];
$work_array=$fbme['work'];
$education_array=$fbme["education"];
$email=$fbme['email'];
$date_of_birth=$fbme['birthday'];
This code worked for me..and i go all the information needed with the Email ID.
NOTE: User has to allow us to get their Information during the Approval of Application.
You need to ask for extended permissions when the user authorizes your application, so you can have access to the user email.
Here's an example using the new PHP SDK and the Graph API:
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/includes/config.php');
// initialize facebook
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET));
$user = $facebook->getUser();
$session = $facebook->getSession();
// in case we don't have a valid session, we redirect asking for email extended permissions
if ($user == null || $session == null) {
$params = array();
$params["canvas"] = "1";
$params["fbconnect"] = "0";
$params["next"] = CANVAS_URL;
$params["req_perms"] = "email";
$loginUrl = $facebook->getLoginUrl($params);
echo '<fb:redirect url="' . $loginUrl . '"/>';
exit();
}
// get user email via the new graph api, using the fql.query method
$url = "https://api.facebook.com/method/fql.query";
$url .= "?access_token=" . $session['access_token'];
$url .= "&query=SELECT email FROM user WHERE uid={$user}";
$userData = simplexml_load_file($url);
$userEmail = $userData->user->email;
echo 'The user ID is: ' . $user;
echo 'The user name is: <fb:name uid="' . $user . '" />';
echo 'The user email is: ' . $userEmail;
Thanks for all the help. I finally figure out how to do that.
first, I need to get the access token, NOT the user session one, but the one for admin.
So, here is the code:
$url = 'https://graph.facebook.com/oauth/access_token';
$ch = curl_init();
$params = array(
'grant_type'=>'client_credentials',
'client_id'=>$appId,
'client_secret'=>$secret,
);
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
// set URL and other appropriate options
curl_setopt_array($ch, $opts);
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$adminAccessToken = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
And then, I can use the facebook API to get any user who accept the application and the extended permission like that:
$fql = "select name, hometown_location, sex, pic_square, email from user where uid=1000000001";
$param = array(
'method' => 'fql.query',
'query' => $fql,
'access_token' =>$adminAccessToken ,
'callback' => ''
);
$fqlResult2 = $facebook->api($param);
with the access token, i can also post things onto user's wall. :)