This does not let the app post to Facebook php - php

I am creating a Facebook app through php. I am using the following code for users to add the app:
$config = array();
$config['appId'] = '532241193565136';
$config['secret'] = '19de17575ad3d245c8cc32f5b623e310';
$config['cookie'] = true;
$config['fileUpload'] = true; // optional
$fb = new Facebook($config);
$user = $fb->getUser();
$loginUrl = $fb->getLoginUrl(
array(
'scope' => 'publish_actions'
)
);
This should allow users to post to Facebook through the app. The problem I'm having is the Permissions popup does not allow users to select the type of Publish Permission - Public, Custom, Only Me etc. I always get This does not let the app post to Facebook
Posts are being added to the Facebook Page but obviously they are private to the user who added the post.
Not sure if I'm missing something here...
Update:
I've tried deleting the application and adding a new, did not make any difference though.
Update 2:
I've just tried using the application from an Admin User of the Page...The following permissions have not been approved for use and are not being shown to people using your app: publish_actions
Information Update:
Just in case someone stumbles on this question. Facebook's Review Guidelines states that "The review time estimate will range between 7 to 14 business days." Always important to consider these delays :)

You're missing nothing here. From v2.0 onwards, the permissions other than public_profile, email and the user_friends need to the submitted for review before you can make your app live; until then, only the testers/admin/developers of the app will be able to test app with those permissions.
Since you are the admin of your app, you can test the publishing but-
it will be visible to you or other admins/testers/developers only
you'll not see the provacy setting option because that does not makes sense
For the login submission (after your app is ready to be live) see this link.

If your submission was rejected you can post using the Feed Dialog, the Requests Dialog or the Send Dialog. Your app does not need to request the publish_actions permission for that. It's an alternative. (see the publish_actions permission reference).
function publish() {
FB.api('/<albumid>/photos', 'POST',
{"url": 'example.com/image.jpeg',
"caption": 'text'
},
function(response) {
if (!response || response.error) {
// Error trying post method - now trying a feed dialog
FB.ui({message: text,
method: 'feed',
link: 'example.com',
picture: 'example.com/image.jpeg',
caption: text,
}, function(response){
//successful feed dialog without publish_actions permission
});
} else {
//successful post with publish_actions permission
}
});
}

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

Facebook Php Api basics

Im getting started with the php sdk, and struggling to understand a few things (I have a basic example below - but everytime the pic goes to MY wall and not the fan page)
Code:
require_once("facebook.php"); // set the right path
$config = array();
$config['appId'] = 'app id';
$config['secret'] = 'app secret';
$config['fileUpload'] = true; // optional
$fb = new Facebook($config);
$params = array(
// this is the access token for Fan Page
"access_token" => "I create this via the graph api (select App and click get token), I select publish stream and photo_upload permissions.",
"message" => "test message",
"source" => "#" ."photo.png", // "#" .
);
try {
// **** is Facebook id of Fan page
$ret = $fb->api('/****/photos', 'POST', $params);
echo 'Photo successfully uploaded to Facebook Album';
} catch(Exception $e) {
echo $e->getMessage();
}
the picture keeps going to MY wall (logged in user) and not the fan page, is that because im getting a token for the currently logged in user (me) instead of the fan page? and if so how do i generate a token for the fan page whilst logged in as the developer? (is it by putting the fan page id into the Get bar?)
Apologies for the noob questions but the facebook documentation sucks (until u understand the core functionality of course). Most tutorials work once u know how to use the graph API - none ive looked actually EXPLAIN how to use the graph to generate correct tokens, etc.
\POST /<ID>/photos — this will post on the <ID>'s wall only, so please double-check the <ID> that you are using.
The access token will depict that on behalf of whom the photo would be posted on the <ID>'s wall. If you use the user access token, the photo will be published on behalf of the user and if page access token is used, it will be published on the page's behalf itself.
You can get the page access token of your pages by-
\GET /me/accounts?fields=access_token
(permission required: manage_pages)
Demo

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.

Facebook deauthorize my app

Can I use Facebook PHP SDK to deauthorize my app for a particular user, basically I like to have a toggle so the user can link or unlink their facebook account to my site, I have the link part working, now just need the unlink part.
Thanks
Now Graph API has a way to do this: https://developers.facebook.com/docs/reference/api/user/#permissions
Delete
You can de-authorize an application entirely, or just revoke a specific permission on behalf of a user by issuing an HTTP DELETE to USER_ID/permissions or USER_ID/permissions/PERMISSION_NAME
respectively. This request must be made with a valid user access_token or an app access token for the current app.
Using the graph API, this works fine:
$ret = $this->Facebook->api('/me/permissions', 'DELETE');
Not using the currently supported Graph API: as currently setup there is no interface in the Graph API (or even the legacy APIs) to deauthorize an application. The user has to explicitly choose to do it themselves through the Facebook settings pages.
However...
The legacy REST api has http://developers.facebook.com/docs/reference/rest/auth.revokeAuthorization/, which SOUNDS like it does what you want.
Let me know if that works for you: I'm curious.
Please note Facebook in the process of deprecating the REST API, and have adding equivalent support to the Graph API User object for "auth.revokeAuthorization" method.
For delinking or deauthorization the user by making app call:
$user_id = $this->facebook->getUser();
$access_token=$this->facebook->getAccessToken();
$result = $this->facebook->api(array(
'method' => 'auth.revokeAuthorization',
'uid' =>$user_id,
'access_token'=>$access_token
));
Using the JS API an app can be deauthorized like this:
FB.api('/me/permissions', 'DELETE', function(res){
if(res === true){
console.log('app deauthorized');
}else if(res.error){
console.error(res.error.type + ': ' + res.error.message);
}else{
console.log(res);
}
});
Or delete a specific permission:
FB.api('/me/permissions/user_birthday', 'DELETE', function(res){
if(res === true){
console.log('permission removed');
}else if(res.error){
console.error(res.error.type + ': ' + res.error.message);
}else{
console.log(res);
}
});
If you go to Facebook Developer, then select your application, then under the "Advanced" menu there is a field called "Deauthorize Callback". Set this as a URL on your domain which is pinged when a user deauthorizes themselves, there is some documentation on the format of the data it requests here.

An open source Facebook app. for a valid cause :)

I own a couple of pages against Child abuse and now I'm developing a Facebook application for fighting against Child Abuse.
I'm somewhat a newbie, and I found many wonderful resources on the net, however, I don't seem to find what I really want.
I know to build a basic app that accesses a user's basic information(using fb_sig_user). However, I need the code to publish static content to my users' wall, request permissions for the same, (would be nice if it publishes each time they interact with my page).
It would also be nice if the app can post to the user's friends too..but its not a must.
Can someone help me? I have these files with me (its an FBML app,btw) and I'm stuck :
tab.php
<?php
if (isset($_REQUEST['name'])){
$uidc2 = $_REQUEST['fb_sig_user'];
echo $uidc2;
?>
<div id="update"></div>
<form action="" id="frm_test" method="post" onsubmit="return false;">
<input type="hidden" name="name" size="50" />
<input name="name" type="button" clickrewriteurl='http://somewebsite.com/fb/tab.php' clickrewriteform='frm_test' clickrewriteid='update' value="submit"/>
</form>
index.php
<?php
require 'facebook.php';
$app_id = 'xyzzy';
$application_secret = 'abc';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $application_secret,
'cookie' => true, // enable optional cookie support
));
if ($facebook->getSession()) {
echo 'Logout';
$user = $facebook->getUser();
} else {
echo 'Login';
}
?>
Any help a this point is really much appreciated. Thank you.
You can use the stream.publish method to publish stream to users of your app. If you want to post to users' wall even if they are not logged in, you need to ask them for the publish_stream extended permission first.
Update:
Getting Permissions
To get permissions, have a look at:
Create Facebook PopUp Authentication Window using PHP and javascript
Alternatively,
In your main config or header file , put code like this:
$facebook = new Facebook($appapikey, $appsecret);
$user = $facebook->require_login();
$facebook->redirect('https://graph.facebook.com/oauth/authorize?
client_id=[YOUR APP ID]&
redirect_uri=[YOUR APP URL]&
scope=publish_stream, offline_access');
Replace [YOUR APP ID] with application id that you can see from application settings where you created the site in Facebook Developers section. Also replace the [YOUR APP URL] with your app url.
To Publish Steam
There is another javascript sdk method named FB.ui. Using the code you can prompt user for stream publish or share your page. Checkout streamPublish() and share() methods defination in my demo’s source code .
Have a look at this tutorial for more info:
Graph api & javascript base Facebook Connect tutorial
Or You can use this function to publish the steam:
function publish() {
var attachment = {
'name': 'App Name',
'href': 'http://apps.facebook.com/someapp/', 'caption': '{*actor*} perfomed an action!!',
'description': 'The description goes here',
"media": [{ "type": "image", "src": "http://www.example.net/images/logo.png", "href": "http://apps.facebook.com/someapp/"}]
};
var action_links = [{ 'text': 'World Winner 2010', 'href': 'http://apps.facebook.com/world_winner/'}];
Facebook.streamPublish('', attachment, action_links);
}
Change the settings in above function as per your requirements and call it like this when you need to publish the stream:
publish();
More Resources:
Facebook Graph API — getting access tokens
How to retrieve facebook user’s friendlist
How to get mutual friends in facebook
And you can find good facebook-related tutorials at this site:
thinkdiff.net
You can check out https://github.com/brennannovak/codeigniter-facebook-oauth which lets you upload a CodeIgniter setup with a basic example application. It replaces the old php-sdk.

Categories