getting latest posts from fb using graph api - php

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>

Related

PHP Laravel Callback upon API authentication

I am trying to implement a call back method in PHP. I am successfully calling an instagram API to authorise the user but I do not know how to capture the token after the user authorises.
Below is my code:
public function oAuthBasic()
{
$instagramBasic = new InstagramBasicDisplay([
'appId' => 'xxx',
'appSecret' => 'xxx',
'redirectUri' => 'xxx'
]);
session()->forget('instagramErrorMessage');
$faceBookLoginUrl = $instagramBasic->getLoginUrl();
return response()->json(['redirectUrl' => $faceBookLoginUrl]);
}
This successfully brings up the sign in pop up. However after authorisation, how can I capture the user access token?
Any help is greatly appreciated.
I managed to fix the issue with the help of #CBore's comment:
Created a new route in my web.php
Route::get('linkinstagramBasic','InstagramController#linkBasic')->name('instagram.linkBasic');
Included the URL under Valid OAuth Redirect URIs on facebook app settings page.
Finally wrote the callback:
/*
* Function that works as the call back after Instagram basic display api authorisation
* Get the code and call access_token API
* AUTHOR : DON
* DATE : 12/10/2022
*/
public function linkBasic(InstagramLinkRequest $instagramRequest) {
if (isset($_GET['code'])) {
// Get the OAuth callback code
$code = $_GET['code'];
$ig_atu = "https://api.instagram.com/oauth/access_token";
$ig_data = [];
$ig_data['client_id'] = Config::get('instagram_basic.app_id');
$ig_data['client_secret'] = Config::get('instagram_basic.app_secret');
$ig_data['grant_type'] = 'authorization_code';
$ig_data['redirect_uri'] = Config::get('instagram_basic.redirect_uri');
$ig_data['code'] = $code;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $ig_atu);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($ig_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ig_auth_data = curl_exec($ch);
curl_close($ch);
$ig_auth_data = json_decode($ig_auth_data, true);
dd($ig_auth_data);
//$accessTok = $ig_auth_data['access_token'];
//$UID = $ig_auth_data['user_id'];
//echo "<script>window.close();</script>";
}
}

PHP auto post on facebook page

I am trying to auto post on Facebook page using my app it works fine if I replace my-page-numeric-id with my profile numeric id, but when I put my page numeric id instead of my-page-numeric-id and put valid access token it won't publish on Facebook page I tried to submit review permission that are as follow "manage_pages, publish_actions" but Facebook team mentioned that you don't need it all because you own this page and your currently admin of it, these permission are necessary when any other person need to authorize with your app.
Now my question is, my code works perfectly for publishing post on my profile's wall but i am unable to auto post on my page what is the problem behind it i am unable to figure out here is my code
<?php
require_once 'src/facebook.php';
class FacebookApi {
var $consumer;
var $token;
var $method;
var $http_status;
var $last_api_call;
var $callback;
var $connection;
var $access_token;
function __construct($data){
$config = array();
$config['appId'] = $data['consumer_key'];
$config['secret'] = $data['consumer_secret'];
$this->connection = new Facebook($config);
}
function share($title, $targetUrl, $imgUrl, $description, $access_token){
$this->connection->setAccessToken($access_token);
$params["access_token"] = $access_token;
if(!empty($title)){
$params["message"] = $title;
$params["name"] = $title;
}
if(!empty($targetUrl)){
$params["link"] = $targetUrl;
}
if(!empty($imgUrl)){
$params["picture"] = $imgUrl;
}
if(!empty($description)){
$params["description"] = $description;
}
// post to Facebook
try {
$ret = $this->connection->api('/my-page-numeric-id/feed', 'POST', $params);
} catch(Exception $e) {
$e->getMessage();
}
return true;
}
function getLoginUrl($params){
return $this->connection->getLoginUrl($params);
}
function getContent($url) {
$ci = curl_init();
/* Curl settings */
curl_setopt($ci, CURLOPT_URL, $url);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ci, CURLOPT_HEADER, false);
curl_setopt( $ci, CURLOPT_CONNECTTIMEOUT, 10 );
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ci);
curl_close ($ci);
return $response;
}
}
$access_token = 'long-live-token-here';
$facebookData = array();
$facebookData['consumer_key'] = 'app-id-here';
$facebookData['consumer_secret'] = 'app-secret-here';
$title = "Demo Content Posted on Timeline";
$targetUrl = "http://www.demo_url.com/1234-post";
$imgUrl = "http://www.demo_url.com/1234-post-image.png";
$description = "demo_description_here";
$facebook = new FacebookApi($facebookData);
$facebook->share($title, $targetUrl, $imgUrl, $description, $access_token);
?>
With API v2.3, they have split the publishing permission into two separate ones:
publish_actions is for anything you want to publish as a user
if you want to publish as a page however, you need publish_pages permission (in addition to manage_pages)
now it's time for facebook v5 sdk
$fb = new Facebook\Facebook([
'app_id' => 'app_id',
'app_secret' => 'app_secret',
'default_graph_version' => 'v2.8',
]);
// facebook auto post
$params = array(
"message" => "$title in $merchant $short",
"link" => "http://pickmyoffers.com/",
"picture" => "http://Pickmyoffers.com/images/searched/Flipkart.png",
"name" => "www.Pickmyoffers.com",
"caption" => "www.pickmyoffers.com",
"description" => "Submit Coupon and earn money through Pickmyoffers.com | Deals,Coupons and offers."
);
$post = $fb->post('/Page_id/feed',$params, $access_token);
$post = $post->getGraphNode()->asArray();
}
hope it's help

How to check user like the facebook Application or not?

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.

Like button to a page photo

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';
}
?>

Graph API wont display profile feed

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?

Categories