API facebook don't publish feed on page - php

I want to publish feeds on the Facebook Page by API. I have followed the facebook documentation creating app in the facebook developer. Before I have registered a account facebook (example: test_account) and after that I have created the page for the business activity (example: test_page) where the manage admin is "test_account".
I have gone to the API by Graph API Explorer
https://developers.facebook.com/tools/explorer
I have granted the "publish_actions" and taken the access token generated by interface tool as followed image
After that I have tried the call POST request to test the publish feeds on the page facebook (test_page) by
https://graph.facebook.com/{id_page_business}/feed?message=test_message&access_token={access_token_APP}
and I have received the new ID_feed and I have seen the feed on facebook page and OK, but the access token the day after was expired. How can I have the access token that don't expired ?
I have tried another solution to obtain the access token from the call GET request (as documentation)
(STEP 1)
so I have obtained access token associated to the APP (see below)
access_token={APP_ID}|xxxxxxxxxxxxxxxxxxxxxjw
(STEP 2) I have sended call GET request
https://graph.facebook.com/{APP_ID}/accounts?access_token=APP_ID}|xxxxxxxxxxxxxxxxxxxxxjw
and I have obtained the followed response:
{
data: [1]
0: {
id: "xxxxxxxx"
login_url: "https://developers.facebook.com/checkpoint/test-user-login /132173517148280/"
access_token: "123456........"
}
paging: {
cursors: {
before: "yMTczNTE3MTQ4Mjgw"
after: "yMTczNTE3MTQ4Mjgw"
}
}
}
(STEP 3) So I have tried the call POST request to publish the feed on the facebook page with the last access token (123456........) and I have received
{
id: "1256xxxxxx_133346xxxxxx"
}
but in the page business I don't see the feed... WHY?
IMPORTANT:I have noticed if I call the request GET API to obtain all feeds page (https://graph.facebook.com/ID_PAGE/feed?access_token=CAAPG1DFdxrs...........) I can see the feeds published, but into the facebook interface timeline I don't see the feed.
I have noticed that the feed publish by API return:
message: "test"
created_time: "2015-11-29T16:39:44+0000"
id: "APP_ID_138999329797136"
The second part the id is different respect when I publish the feed with access token get from the API Graph.

You need to have extended token on page access token to post on the page. App access token will provide you all read access to the page but will not allow you to post.
Below steps must help -
Get the page access token using -
https://graph.facebook.com/{APP_ID}/accounts?access_token={APP_ID}|xxxxxxxxxxxx
Using the page access token obtain the extended token, below is how I had implemented using VB.NET
Dim parameters As Object = New ExpandoObject()
parameters.client_id = FB_APP_ID
parameters.client_secret = FB_APP_SECRET
parameters.grant_type = "fb_exchange_token"
parameters.fb_exchange_token = short_token 'FBClient.AccessToken
Dim result As Object = FBClient.Get("oauth/access_token", parameters)
Use this extended token to post on page. It worked for me, hope it helps you.

Related

Facebook PHP - posting error to timeline but not to page

I am trying to post to a Facebook account (with permissions) using the PHP
API. I am giving our users two options - posting to the Feed, and posting
to a specific facebook page. I am getting an error in the first case, but
not in the second case. In the code below:
$access_token is the access token I got back from linking to my app. It's of type
"User", and has the following permissions:
email
pages_show_list
business_management
pages_read_engagement
pages_manage_metadata
pages_read_user_content
pages_manage_ads
pages_manage_posts
pages_manage_engagement
public_profile
Where $page_token is, well, a "Page" type token, with the same set of permissions.
When I post to the page, it works fine. But when I try to post to the timeline, I get
the error:
Graph Error 200 : [Timeline]: [(#200) If posting to a group, requires app being
installed in the group, and either publish_to_groups permission with user token,
or both pages_read_engagement and pages_manage_posts permission with page token;
If posting to a page, requires both pages_read_engagement and pages_manage_posts
as an admin with sufficient administrative permission]
I'm not trying to post to a group, I'm posting to an account's timeline. And, per the
access token debugger, I have the permissions requested anyway. What's going on?
My code is below:
$linkData = [
'link' => $link_to_post,
'appsecret_proof' => $app_secret_proof
];
if ( POSTING TO TIMELINE )
{
$token = $access_token;
$post_to = "/me/feed";
}
else
{
$page_id = $page_id;
$token = $page_token;
$post_to = "/$page_id/feed";
}
// THIS THROWS THE EXCEPTION:
$response = $this->fb->post($post_to, $linkData, $token);
You can not post to a personal timeline via API any more, that was removed ages ago already. (With introduction of API v2.4, if I remember correctly.)
You can only use the Share or the Feed dialog, to offer the user a way to actively share / make a post themselves, https://developers.facebook.com/docs/sharing/web

SammyK LaravelFacebookSdk - can't obtain an access token

I've searched for a Laravel Facebook SDK and I found this package that works with Laravel 4.2 (my laravel app version). I use this just to get my facebook page posts but I got into a problem, my access token expires every 2 hours or in some cases because of other reasons like facebook logout, etc.
I found out that there are 2 ways to handle expired access tokens, either to extend the access token, either to request a new one using the old access token.
The questions is how to request a new access token because I store it into my database and I need to get my facebook page posts all the time?
I've followed this instructions but for me it does not work.
When I use this code:
try
{
$token = Facebook::getTokenFromRedirect();
echo "Success<br>";
print_r($token);
}
catch (FacebookQueryBuilderException $e)
{
// Failed to obtain access token
echo 'Error:' . $e->getMessage();
}
the only thing what I see on the screen is Success and that is all, it's like the $token is empty.
I've also checked Facebook Query Builder which is included into SammyK LaravelFacebookSdk and tried to use getTokenFromCanvas() insted of getTokenFromCanvas() but I get this error: Method getTokenFromCanvas does not exist.
Any idea to make this work?
By default Facebook will return a user access token that expires after 2 hours. You can extend it for a long-lived access token that'll last 60 days.
Once you obtain an AccessToken entity in Laravel Facebook SDK 1.2, you can extend it like it shows in the example:
try {
$token = $token->extend();
} catch (SammyK\FacebookQueryBuilder\FacebookQueryBuilderException $e) {
dd($e->getPrevious()->getMessage());
}
In your GitHub issue you mentioned:
What I want to achieve is to get the posts from my facebook page
You can use a page access token to grab your page posts. You can obtain a page access token from the /me/accounts endpoint.
If you use a long-lived user access token to obtain the page access token, the page access token will never expire so it's ideal to store in your database to pull posts from a page.
See more about handling access tokens. Good luck! :)

Displaying a Facebook newsfeed/timeline on a website

I have a client who wants their company's Facebook newsfeed/timeline to be displayed on their website. It's not a personal timeline/newsfeed, but an organisation's.
Everything I've read seems a few years old, but the upshot appears to be: Facebook wants to keep all its data on its own servers -- they don't want people exporting it, and people have been banned for trying. (As I say, this information was several years old.)
The closest current thing I've found is the Activity Feed Plugin, but that only registers other user's interactions with the site or a FB app.
Has anyone had any success exporting their public updates to an external website, or do I have to tell my client that it can't be done?
Thanks for any help!
AFAIK, it is possible, in a way. The simplest solution, but not best for your situation could be the Like Box plugin:
The Like Box enables users to:
See how many users already like this Page, and which of their friends like it too
Read recent posts from the Page
Like the Page with one click, without needing to visit the Page
Better solution: use their Graph API, however you can only read the data(as JSON), not have the stream exactly replicated on your client's website, don't expect to be able to apply the styles that facebook uses(i.e you won't be able to scrape it), you'll have to either replicate it, or create your own styles.
Now if the page is public and can be read by all, as in there are no privacy rules, then you can simply call the url with any valid access_token(can be app access_token also):
https://graph.facebook.com/<clientpagename_OR_id>/feed
or
https://graph.facebook.com/<clientpagename_OR_id>/posts
depending on what exactly you need, try the graph api explorer to check that(and also see the kind of data being returned). When there are lots of posts, there will be pagination urls, which you'll be able to notice in the explorer too.
Incase the page is not public, you'll need an access_token with the read_stream permission, hence you'll need to create a facebook app, of type website. Then get your client's page's admin to authorize the app, with read_stream permission. After that you can call the urls with the access_token that you receive after authentication and can continue reading the stream.
https://graph.facebook.com/<clientpagename_OR_id>/posts?access_token=thetoken
In this case use the PHP SDK, to simplify authentication and calling the graph api.
Important Links: Authentication Guide , Real-time-updates.
Good luck.
Edit: you do need an access token to access the feed or posts connections, but you do not necessarily need an access token to read the page object itself, as given in this documentation.
Note from the doc:
For connections that require an access token, you can use any valid access token if the page is public and not restricted. Connections on restricted pages require a user access token and are only visible to users who meet the restriction criteria (e.g. age) set on the page.
You can retrieve the organization's newsfeed using Facebook's Graph API. Timeline can't be retrieved via public API.
There is no plugin to do this. You would need to call
https://graph.facebook.com/USER_ID/home
which gives you a JSON response.
You then need to parse the JSON into a new layout on the organization's web page.
Confusingly, calling
https://graph.facebook.com/USER_ID/feed
doesn't retrieve the newsfeed, but a user's wall posts, which may or may not be what you want.
Here is a tutorial that goes through the basics of setting up a newsfeed on a website with php.
The easiest way to do this is to read the Facebook timeline RSS:
function FacebookFeed($pagename, $count, $postlength) {
$pageID = file_get_contents('https://graph.facebook.com/?ids='.$pagename.'&fields=id');
$pageID = json_decode($pageID,true);
$pageID = $pageID[$pagename]['id'];
ini_set('user_agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9');
$rssUrl = 'http://www.facebook.com/feeds/page.php?format=rss20&id='.$pageID;
$xml = simplexml_load_file($rssUrl);
$entry = $xml->channel->item;
for ($i = 0; $i < $count; $i++) {
$description_original = $entry[$i]->description;
$description_striphtml = strip_tags($description_original);
$description = substr($description_striphtml, 0, $postlength);
$link = $entry[$i]->link;
$date_original = $entry[$i]->pubDate;
$date = date('d-m-Y, H:i', strtotime($date_original));
$FB_feed .= $description."…<br>";
$FB_feed .= "<small><a href='".$link."'>".$date."</a></small><br><br>";
}
return $FB_feed;
}
Yes, it can be done. First register the web site at facebook's developer page. Than you can use any suitable API for interacting with FB. Sometimes ago I used SpringSocial (since I was working tightly with Spring)... You can use FB's own api which is also very useful you can read the tutorial here
It can definitely be done. You just need to get an access token through facebook and then you can access a JSON feed of posts through the facebook API.
You need to go to the facebook developer site and click on Apps at the top. Follow the steps to get an app secret and client ID. Then just put them into the following URL and it will return your access token:
https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET
Step by step instructions here: http://smashballoon.com/custom-facebook-feed/access-token/
This document details the steps to obtain the facebook access tokens and the using the tokens to fetch FB feeds.
Example:
A live example is available in
https://newtonjoshua.com
Introduction to Graph API:
The Graph API is the primary way to get data in and out of Facebook's platform. It's a low-level HTTP-based API that you can use to query data, post new stories, manage ads, upload photos and a variety of other tasks that an app might need to do.
FaceBook Apps:
https://developers.facebook.com
Create a Facebook app. You will get an App_Id and App_Secret
Graph API Explorer:
https://developers.facebook.com/tools/explorer/{{App_Id}}/?method=GET&path=me%2Ffeed&version=v2.8
You will get an access_token which is short lived. So this will be our short_lived_access_token.
note: while creating access token select all the fb fields that you require.This will give permission to the access token to fetch those fields.
Access Token Extension:
https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id={{App_Id}}&client_secret={{App_Secret}}&fb_exchange_token={{short-lived-access_token}}
You will get an access_token with a validity of 2 months.
Access Token Debugger:
https://developers.facebook.com/tools/debug/accesstoken?q={{access_token}}&version=v2.8
you can check check the details of the access_token.
Facebook SDK for JavaScript:
Include the below JavaScript in your HTML to asynchronously load the SDK into your page
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
Graph API:
Let's make an API call to get our FB id, profile pic, cover pic and feeds.
window.fbAsyncInit = function () {
FB.init({
appId: '{{App_Id }}',
xfbml: true,
version: 'v2.7'
});
FB.api(
'/me',
'GET', {
fields: 'id,picture{url},cover,feed',
access_token: {{access_token}}
},
function (response) {
if (response.error) {
console.error(response.error.message);
}
if (response.picture.data.url) {
profilePic = response.picture.data.url;
}
if (response.cover.source) {
coverPic = response.cover.source;
}
if (response.feed.data) {
feeds = response.feed.data;
feeds.forEach(function (feed) {
// view each feed content
});
}
if (response.feed.paging.next) {
nextFeedPage = response.feed.paging.next;
// a request to nextFeedPage will give the next set of feeds
}
}
);
};
Use the Graph API Explorer to design your query that should be entered in the 'fields' (eg: 'id,picture{url},cover,feed')
Now you can fetch your Facebook data from Facebook Graph API using your access_token.
Refer to https://developers.facebook.com/docs/graph-api/overview/
Note: Your access_token will expire in 2 months. Create a new access_token after that.

Problem with access token while creating Facebook Test Users

I'm trying to create test users for my Facebook application. They announced this functionality in this blog post in November (http://developers.facebook.com/blog/post/429) and it is documented here (http://developers.facebook.com/docs/test_users/). I could not find the answer to this elsewhere...
According to the documentation, "You can create a test user associated with a particular application using the Graph API with the application access token." This links to the section "Autenticating as an Application" and describes this CURL script:
curl -F grant_type=client_credentials \
-F client_id=your_app_id \
-F client_secret=your_app_secret \
https://graph.facebook.com/oauth/access_token
So far, so good. I ran this and get the following:
access_token=1182...18|nTI...r5Q
So now I want to POST this token to the graph api test user URL:
POST /1182...18/accounts/test-users?installed=true&permissions=read_stream&access_token=1182...18|nTI...r5Q
When I do this (both using the Facebook PHP SDK and just typing it into the browser) I get:
{
"error": {
"type": "OAuthException",
"message": "Invalid OAuth access token."
}
}
So the questions are:
Why am I getting this error message?
Am I using the wrong access token (despite Facebook explicitly telling me to use this one?)
Do I need to parse the access token somehow?
Thank you for your help.
Here is some working code that will allow you to create a test user with the PHP SDK.
Ensure your access token is properly urlencoded when passing back to facebook.
I was getting this error until I removed some parameters from example code I saw floating around. Here is an example in python using requests that I finally managed to get working:
# Get the access token
resp = requests.get(
'https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id={app_id}&client_secret={app_secret}'.format(
app_id=APP_ID, # Your app id (found in admin console)
app_secret=APP_SECRET # Your app secret (found in admin console)
)
)
# Parse the token
token = resp.content.split('=')[-1]
# Create the user
data = {'access_token': str(token)}
resp = requests.post(
'https://graph.facebook.com/{app_id}/accounts/test-users?installed=true'.format(
app_id=APP_ID
),
data=data
)
print resp.content

Authorizing a Facebook Fan Page for Status Updates

I'm able to update the status on my PROFILE wall using this code:
require_once 'facebook-platform/php/facebook.php';
$facebook = new Facebook('APP API KEY','APP SECRET KEY');
$user_id = 'MY USER ID';
$facebook->api_client->users_setStatus('This is a new status');
...after authorizing using this address:
http://facebook.com/authorize.php?api_key=MYAPPAPIKEY&v=1.0&ext_perm=publish_stream
This code, however, does not work to update the status on my Facebook PAGE Wall. Are there additional parameters that I can add to the authorize.php url to specify authorizing the PAGE and not just my profile?
Or, are there better ways to post updates to Fan Page Walls?
Thanks!
I solved the problem by consulting the Facebook desktop application documentation (even though this is a web application).
I first had to authorize offline access with this url (replacing 'MYAPIKEY'):
http://www.facebook.com/login.php?api_key=MYAPIKEY&connect_display=popup&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true&session_key_only=true&req_perms=read_stream,publish_stream,offline_access
Then, I needed to grant 'publish_stream' permissions to the PAGE with this url (replacing 'MYAPIKEY' and 'THEPAGEID'):
http://www.facebook.com/connect/prompt_permissions.php?api_key=MYAPIKEY&v=1.0&next=http://www.facebook.com/connect/login_success.html?xxRESULTTOKENxx&display=popup&ext_perm=publish_stream&enable_profile_selector=1&profile_selector_ids=THEPAGEID
I could then use the following code to publish to the Fan Page wall:
require_once 'facebook-platform/php/facebook.php';
$facebook = new Facebook(MYAPIKEY, MYAPISECRET);
try{
$facebook->api_client->stream_publish('INSERT_STATUS_HERE',null,null,null,'THEPAGEID');
}catch(Exception $o ){
print_r($o);
}
Based on the above, i tried out a couple of querystring parameters on the graph API authorize URL, and it appears this works:
https://graph.facebook.com/oauth/authorize?client_id=[APP_ID]&redirect_uri=[REDIRECT_URL]&scope=publish_stream&enable_profile_selector=1&profile_selector_ids=[PAGE_IDS]
EDIT: Never mind, the above displays all the UI correctly, but still get the "(#200) The user hasn't authorized the application to perform this action" error --- it's clear it doesn't work because the access token contains my USER id but not the page's ID.

Categories