How to Publish on Facebook Page automatic from php server scripts? - php

My client has a e-commerce website where they sell their products and they also have facebook page for that website. I want to to publish wall post on that page when ever the product price is reduced or new product is lunched. But i want to make this automatic, so i want to authorize facebook automatic, means that i don't want any login dialog box. the script should authorize itself. now the code i am using is as below but it ask me for log in. and also tell me which method is good(easy) to publish page wall post?
require 'API_Library/Facebook/src/facebook.php';
$page_id = '111111111111111';
$appId = '111111111111111';
$appSecret = 'aaaaaaaaaaaaaaaaaaaaa22222222222';
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $appSecret,
'cookie' => true
));
$session = $facebook->getAccessToken();
$me = NULL;
if($session)
{
try
{
$me = $facebook->api('/me');
$facebook->api('me/feed', 'post', array(
'message' => 'Hello World!'
));
}
catch(FacebookApiException $e)
{
echo $e->getMessage();
}
}
OUTPUT:
(#200) The user hasn't authorized the application to perform this action

In order to post something to a page, you will need the administrator of the page to be authenticated with the application. You cannot post to a page without being authenticated. So there will be some user interaction required before you can set this up automatically.
The process would be as follows:
Setup a Facebook App to get a App ID and app secret - you'll need this to query the API and post updates to the page
As the page administrator, login to your app with the manage_pages permission.
After logging in, an API call to /me/accounts will give you an access_token to access the page and publish updates
Using the page's accesss_token, you can then POST updates using /{page_id}/feed
Hope this helps.

Related

How get access token from other users

I need to read the posts on facebook. I had create the application and the program works if I log with my credential. But when I log with another credential ( like another profile that I have just created) the program doesn't work anymore. This is my login page:
$config = array(
'appId' => APPID,
'secret' => APPSECRET,
'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if(!empty($_SESSION)) {
if($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
$login_url = $facebook->getLoginUrl(array('scope' => 'user_posts'));
$access_token=$facebook->getAccessToken();
$facebook->setAccessToken($access_token);
} catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
}
}
} else {
$login_url = $facebook->getLoginUrl(array('scope' => 'user_posts'));
header("Location: ".$login_url);
}
when I login I obtain the access token and I call graph api:
https://graph.facebook.com/******/posts?access_token=**
This is operation work if I m who is logged in the application. If another login in the app this is not work.
Maybe it's a authentication problem. Maybe I forget some operation that I must do to authentica with another account. Anyone can help me?
You need to submit your App to Facebook then Facebook will check and pass you app then you can access you app other account. If you want to check App Functionality you can use Facebook App test user Id. Below I have Explained how to get test user
Goto App Page.
Click on Roles.
Click on to Right Corner Test users.
It will show your test user details.
Use this details and access you App.
You have to make your app public for all users from here: https://developers.facebook.com
have a look on it:
Use /me/feed instead of /me in your API call
see example below
Permissions
Your app needs user_posts permission from the person who created the post or the person tagged in the post. Then your app can read:
Timeline posts from the person who gave you the permission.
The posts that other people made on that person Timeline.
The posts that other people have tagged that person in.
If you attempt to read data from a feed that your app has not been authorized to access, the call will return an empty array.
please read this thread https://stackoverflow.com/questions/30719556/read-post-from-facebook-home/30732874#30732874
READING
/* PHP SDK v4.0.0 */
/* make the API call */
$request = new FacebookRequest(
$session,
'GET',
'/me/feed'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */

Codeigniter and facebook php sdk autopost to company wall

I have built a site with codeigniter and implemented facebook login for users. Everything is working great there. App is connected user tokens beig saved the whole nine yards. What I am having trouble doing is having the website itself NOT the logged in user post to the connected company facebook page on a user post completion. essentially the user posts a listing. the website then on submit of that posting posts to my facebook company page NOT the logged in users facebook wall. (i have that working already. Can i leave the website logged into Facebook to post to the wall while a user is logged on as well?
You will need to get the Appid, App secret and an access token. You can extend the access token so that it doesn't expire.
$graphUrl = 'https://graph.facebook.com/oauth/access_token?client_id='.APPID .'&client_secret='.APPSECRET.'&grant_type=fb_exchange_token&fb_exchange_token='.ACCESS_TOKEN;
$accessToken = #file_get_contents($graphUrl);
parse_str($accessToken); //get the access_token param in the string and would be named $access_token
if(!$access_token) $access_token = $accessToken; //if cannot be extended then just return the access token with 2 hours expiry
In order to post as your company page, you will need their page id.
Here is part of my script that I used to get all this working. Its not codeigniter, but you will be able to see how it works.
$config = array(
'appId' => APPID,
'secret' => APPSECRET,
);
$facebook = new Facebook($config);
$facebook->setAccessToken(ACCESS_TOKEN);
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_id = '************'; //
$page_info = $facebook->api("/$page_id?fields=access_token");
if(!empty($page_info['access_token']) ) {
// do your code stuff
}
} catch etc etc
Hope this is helpful to you

Posting testimonials to Facebook business page from website cms

Sorry if this has been dealt with before, but my website guy is having issues getting this to work.
I am using facebook open graph api to post a testimonial from my PHP website CMS to my facebook business page.
I have a facebook profile and created a business page from my profile.
I have also created an app under my profile to get an app id and secret key which is used for the graph api to post on behalf of me from my website to my facebook businness page. The issue is I need the post to go directly to my business page and be posting as my business, not as or on behalf of me. Currently the api is sending the posts directly to my profile wall showing as me sharing a link via my business page and it doesn't appear on the business page at all. I need a way to post the testimonial to my business page directly rather than on my profile wall. How do I do that? My understanding is he has used the personal ID & App secret and also the business page app ID & secret, but seem to get the same result.
The code below is what is being used, any assistance would be greatly appreciated;
<?php
$facebook = new Facebook(array(
'appId' => 'myappid',
'secret' => 'mysecrectkey',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try
{
$user_profile = $facebook->api('/me');
$AccessToken = $facebook->getAccessToken();
$data = array("message" => $pdes,"link" => "http://www.website.com.au/testimonial.php", "name" => $name);
$share = $facebook->api("/me/feed", "POST", $data);
}
catch (FacebookApiException $e)
{
error_log($e);
$user = null;
}
}
?>
Well, your problem is here:
$share = $facebook->api("/me/feed", "POST", $data);
This code sends message to your wall, instead of the page. In order to post on your Facebook page on behalf of your page, first, your app needs to get manage_pages and publish_stream permissions. Once you have it you need to do is get the access token of the page you want to post on:
$pages = $facebook->api('/me/accounts');
foreach($pages as $page)
{
if($page['id'] == YOUR_PAGE_ID)
$data['access_token'] = $page['access_token'];
}
Once you have page access token you must use it to send message on your page's wall:
$facebook->api(YOUR_PAGE_ID . '/feed', 'POST', $data);

Post to Facebook Page Wall without logged in user

I have a Facebook app that I want to use to post on my customer's Facebook Page Walls on their behalf. I have it setup now so that when they authenticate my app I get the Access token, but when I go to post to the wall I am getting the following error: "OAuthException: Error validating access token: The session is invalid because the user logged out."
How can I post from my script without being logged in?
Here is my code:
include_once('fb-php-sdk/src/facebook.php');
$facebook = new Facebook(array(
'appId' => 'XXX',
'secret' => 'XXX',
));
try {
$page_id = '215133535279290'; //page id of the customer's facebook page
$args = array(
'access_token' => 'XXX', //access token received when user authenticated app
'message' => 'A test message'
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
} catch (FacebookApiException $e) {
echo "Error:" . $e;
}
The new facebook API has what is called an extended access token (it replaces offline access: https://developers.facebook.com/roadmap/offline-access-removal/ I think) which I believe lasts upto 60 days (or something like that). To use it simply get the access token when the logs in through your website:
$token = $facebook->getAccessToken();
Save it to Db and use this token later:
$facebook = new Facebook();
$facebook->setAccessToken($accessTokenFromDB);
Then you should be able to continue as though the user is logged in.
As for the user being logged out part, make sure you are using the latest version of the API and not an old version and also make sure the stuff under the "Scenario 2: If you have been previously requesting offline_access - updated 4/30/2012" heading of the page I linked.
You could carry on using offline_access until 3rd of October, but then why if it's being turned off for real in 2 months time and would have to rewrite your code.
Get the publish_stream extended permission. Once you have this permission you can post feed stories using your app access token while the user is offline. There is no need for offline_access permissions or saving and using a user access token in this scenario.

Can I store Facebook access token and use it later?

I am building a web app (PHP) that uses FB connect. I successfully register / sign in user with the help of the PHP lib provided by facebook. Also I can post to wall, using this code
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;
$facebook = new Facebook(array(
'appId' => $fb_key,
'secret' => $fb_secret,
'cookie' => true, // enable optional cookie support
));
$session = $facebook->getSession();
if ($session)
{
$facebook->api('/me/feed', 'POST', array('message'=>$message, 'link'=>$link['href'], 'name'=>$link['text']));
}
However, if I manually go to my browser's cookie manager and delete the cookie that stores FB session, the code doesn't work. The only thing I have is user's FB ID which I store in DB. Is there any way to post to user's wall even if FB sessions is lost? Does it make sense to store user's FB access token in DB to post to wall later or is the access token relatively short-lived?
Here's an example situation that might happen in my app:
user clicks fb button, authorizes my app, gets redirected back to my site where I automatically create an account based on data provided by FB, also I store user's FB ID so that I could sign in this user later. Now he browses site, enters some info and this info gets posted to his wall. Everything is fine so far because user's browser holds the cookie created by FB. Now user leaves the site and contacts site admin. Admin opens his own browser, goes to admin interface and posts something on behalf of this user. Now, having that user's FB ID and assuming that user hasn't revoked permissions, can I still post this to his wall?
With the Facebook PHP SDK v3 (see on github), it is pretty simple to ask and use a user offline access token. Here is how you do that.
Get the offline access token
First you check if the user is logged in or not :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
If he is not, you generate the "Login with Facebook" URL asking for the offline_access permission :
if (!$user) {
$args['scope'] = 'offline_access';
$loginUrl = $facebook->getLoginUrl($args);
}
And then display the link in your template :
<?php if (!$user): ?>
Login with Facebook
<?php endif ?>
Then, when the user is logged in, you can retrieve the offline access token and store it. To get it, call :
if ($user) {
$token = $facebook->getAccessToken();
// store token
}
Use the offline access token
To use the offline access token when the user is not logged in :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$facebook->setAccessToken("...");
And now you can make API calls for this user :
$user_profile = $facebook->api('/me');
Hope that helps !
UPDATE: This answer is no longer valid as offline_access is deprecated.
You need to request the offline_access permission. Check the permissions doc.
EDIT Per the update and comments - some info on the removal of the offline_access can be found here.

Categories