Facebook Php Api basics - php

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

Related

Posting to a Facebook page is showing on the "POSTS TO PAGE" panel

I got the code below from another website which seems to be working fine. The only problem is that posts appear on the "POSTS TO PAGE" section of the Facebook page instead of appearing on the page timeline directly.
Any idea why?
Also, the code works when I use the access token, not the app access token. When using app access token, I get an error message saying: "(#200) The user hasn't authorized the application to perform this action"
<?php
// require Facebook PHP SDK
// see: https://developers.facebook.com/docs/php/gettingstarted/
require_once("/YOUR_PATH_TO/facebook_php_sdk/facebook.php");
// initialize Facebook class using your own Facebook App credentials
// see: https://developers.facebook.com/docs/php/gettingstarted/#install
$config = array();
$config['appId'] = 'YOUR_APP_ID';
$config['secret'] = 'YOUR_APP_SECRET';
$config['fileUpload'] = false; // optional
$fb = new Facebook($config);
// define your POST parameters (replace with your own values)
$params = array(
"access_token" => "YOUR_ACCESS_TOKEN", // see: https://developers.facebook.com/docs/facebook-login/access-tokens/
"message" => "Here is a blog post about auto posting on Facebook using PHP #php #facebook",
"link" => "http://www.pontikis.net/blog/auto_post_on_facebook_with_php",
"picture" => "http://i.imgur.com/lHkOsiH.png",
"name" => "How to Auto Post on Facebook with PHP",
"caption" => "www.pontikis.net",
"description" => "Automatically post on Facebook with PHP using Facebook PHP SDK. How to create a Facebook app. Obtain and extend Facebook access tokens. Cron automation."
);
// post to Facebook
// see: https://developers.facebook.com/docs/reference/php/facebook-api/
try {
$ret = $fb->api('/YOUR_FACEBOOK_ID/feed', 'POST', $params);
echo 'Successfully posted to Facebook';
} catch(Exception $e) {
echo $e->getMessage();
}
?>
You need to change the page settings to fix the POSTS TO PAGE issue:
Please make sure that the Recent Posts by Others is turned on and the
post visibility setting is set to "Allow posts by other people on my
Page timeline."
You can learn more about these settings in our Help Center:
https://www.facebook.com/help/356113237741414/?ref=u2u
In order to post "as Page", you need to authorize the user with publish_pages and manage_pages and use a Page Access Token, as you can read in the Facebook docs: https://developers.facebook.com/docs/graph-api/reference/v2.3/page/feed#publish
Analyze the Token in the debugger to see if the page shows up: https://developers.facebook.com/tools/debug/
Of course you can´t post with an App Access Token, that one does not even require authorization.
More information about Access Tokens in general:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/

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);

Managing Facebook Pages using PHP

I'm looking to integrate my current website more deeply with Facebook using a Fan Page (notice: I did noticed the Open Graph protocol that Facebook support but i'm looking to create a website-wide fan page).
I know that you can create and manage Fan Pages using Facebook, but I'm looking for a way to do that using a PHP script - for example, post to the Fan Page wall, create events using the Fan Page and ideally - create secondary Fan Pages on the fly.
After looking around in Facebook's developer section I didn't find a method to do those tasks from outside using the Facebook API.
So my question is: how would you accomplish that?
Thanks!
Publishing posts to your Page, and creating Events, are both relatively trivial tasks. You can use the Graph API to do that.
Check out the area about Publishing specifically. It gives you the general overview of how publishing works, and this can be applied all over the Graph.
Also, the documentation about the Events portion of the Graph API has an example cURL post for how to create a new event via the Graph API.
Posting anything to your Facebook page is going to require you have the manage_pages extended permission, and it's probably a good idea to get the offline_access permission also.
An example of both posting to your Page wall and creating an event (in php) would look a lot like this:
<?php
require 'facebook.php';
$fb = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
'cookie' => true
));
$your_page_id = '123123123';
//get the access token to post to your page via the graph api
$accounts = $fb->api("/me/accounts");
foreach ($accounts['data'] as $account)
{
if ($account['id'] == $your_page_id)
{
//found the access token, now we can break out of the loop
$page_access_token = $account['access_token'];
break;
}
}
try
{
//publish a story to the page's wall (as the page)
$post_id = $fb->api("/{$your_page_id}/feed", "POST", array(
'message' => "Hello to all my fans, I love you!"
'access_token' => $page_access_token;
));
echo "Post published. ID: {$post_id}<br>";
//create a new event.
$event_id = $fb->api("/{$your_page_id}/events", "POST", array(
"name" => "My Totally Awesome Event, You Better Show UP!",
"start_time" => time(), //it starts now...duh!
"location" => "Anywhere, USA"
));
echo echo "Event created. ID: {$event_id}<br>";
}
catch (Exception $e)
{
var_dump($e);
}
As for creating Pages on the fly, the only way you can do that is by using the Open Graph Protocol. The only restriction here is that pages have to have unique URLS. So you can assign each of your Open Graph objects a unique ID, and give them a URL like http://www.mysite.com/pages?id=123456. This will let you output the Open Graph tags required to generate the page on FB. You can then use the Graph API to get the ID of the Open Graph object after someone likes it like so: http://graph.facebook.com/?ids=http://www.mysite.com/pages?id=123456.
You can publish to these Open Graph objects the same exact way you'd publish to a standard Facebook Page.
Hope that helps!

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