Create Facebook event as Page with rGraph API - facebook

I am trying to create an event on Facebook on behalf of the page i own with Graph API.
From FB documentation i read that it is done like this:
POSTing name and start_time (other things are optional) to
https://graph.facebook.com/{Page_ID}/events
with proper premissions (create_event, manage_pages)
playing around with this in Graph API Explorer i do get event created but it is done under my own profile rather than Page.
So is it possible to create the event under the Page i own rather than my profile?
PS i double checked the page id so it is not my profile id
PPS I know there are allready many discussions about this here, but unfortunatley i couldnt find a straightforward answer to my question.

So i figured this out myself. I needed to post it with page access token. heres the code
$page_info = $this->fb->api('/' . $page_id . '?fields=access_token');
if (!empty($page_info['access_token'])) {
$path = realpath(APPPATH . '../path/to/img');
$args = array(
'access_token' => $page_info['access_token'],
'start_time' => $start_time,
'description' => $description
'name' => $name,
'location' => $loaction
);
$img = 'img.jpg';
if ($upload) {// if picture is needed
$args['#' . $img] = '#' . $path . '/' . $img;
$this->fb->setFileUploadSupport(true);
}
$res = $this->fb->api("/" . $this->input->post('fb_event'), "post", $args); // should give back event id
}

Related

Create charts for a facebook page via open graph and php

I have created a FB App that grants the following permissions from the user:
1. manage_pages
2. read_insights
By using the app, the user can create a new tab on a page and delete it when this is necessary.
Apart from that, I want to give the option to the user to see some basic stats regarding the page(s) that she creates the tab(s).
For example, I want to retrieve the page views for a certain page for a specific period.
In order to do this I used the following code:
$today = date("Y-m-d");
$until = strtotime($today);
$since = strtotime("2013-08-01");
$pageID = "123";
$page_info = $facebook->api("/$pageID?fields=access_token");
$access_token = $page_info['access_token'];
$params = array(
'access_token' => $access_token,
'since' => $since,
'until' => $until,
);
$insights = $facebook->api("/{$pageID}/insights/page_views/",
"GET",
$params
);
print_r($insights);
The problem is that the result is...somehow empty. More precisely, I receive the following:
Array
(
[data] => Array
(
)
[paging] => Array
(
[previous]=>https://graph.facebook.com/123/insights/page_views/since=1370059200&until=1375329600
[next]=>https://graph.facebook.com/123/insights/page_views/since=1380600000&until=1385870400
)
)
When I use, the same logic to receive insights for my app (without using $token in the $params array), I receive the right data.
In addition to that, I was wondering if there is a way to create charts with this data (directly from FB).
Thx,
Antonis
I managed to solve the problem.
The returning array was empty, because I forgot to check if the user is logged in through facebook...
Regarding the charts, I didn't find any solution directly from facebook, so I used the Charts.js plugin.

Facebook API post to friends wall

I'm building application to post statuses from authenticated users like that one.
The problem is the application posting from my profile on friends wall who authenticated the application from my profile.
I'm using Facebook API with CodeIgniter.
the code
$userId = $this->facebook->getUser();
$IDs = $this->facebook_data->get_IDs();
if(isset($_POST['link'])){
$args = array(
'from' => array('name'=>'Resala','id'=>'294357147348261'),
'application'=>array('name'=>'XXXX','id'=>'XXXXX'),
'name' =>'XXXX',
'message' => $_POST['status2'],
'link' => $_POST['link']
);
}else{
$args = array(
'from' => array('name'=>'Resala','id'=>'294357147348261'),
'application'=>array('name'=>'Resala','id'=>'XXXXX'),
'name' =>'XXXX',
'message' => $_POST['status1']
);
}
foreach($IDs->result() as $row){
$ID=$row->user_id;
$this->facebook->api("/$ID/feed", "post", $args);
}
The right docs for creating a post are:
http://developers.facebook.com/docs/reference/api/user/#posts
There you can see the params "from" and "application" don't exist and "name (can only be used if link is specified)".
It's not possible to post in the name of an app. You can only post in the name of an page (that may be assosiated with the app).
Therefor you have to use the page access token instead of the user access token.
See: http://developers.facebook.com/docs/reference/api/page/#page_access_tokens

posted images in wall disappear

i'm posting some images using the following command:
$url_facebook = "https://api.facebook.com/method/stream.publish?message=".$messaggio."&attachment={\"name\":\"".$title."\",\"href\":\"".$action_link."\",\"caption\":\"".$caption."\",\"description\":\"".$description."\",\"media\":[{\"type\":\"image\",\"src\":\"".$image."\",\"href\":\"".$action_link."\"}]}&action_links=[{\"text\":\"".$link_name."\",\"href\":\"".$action_link."\"}]&target_id=".$target_uid."&uid=".$source_uid."&".$site_token."";
simplexml_load_file("".$url_facebook."");
the image i post in the wall (a group) is generated on the fly from PHP.
this is what happens:
i generate an image and save it to a folder
i post it with the code upon
i exit from the script
the next time a run the script (each hour) i delete all the old
created images , than repeat wath sayid upon
i noticed that the images just when published, are present and existing on the FB wall
BUT
the next time i launch the script (and so the images are deleted from my site) they disappear also from facebook
i understood that the images where uploaded to facebook, so they were not needed anymore on my space....
isn't so ?
i've this doubt also because, if i see on the red x on facebook (in the place of the images)
and i right click "proprerties", i can read :
"https://s-platform.ak.fbcdn.net/www/app_full_proxy.php?app=164286063695472&v=1&size=z&cksum=17f253305254403324260843c7a6989a&src=http%3A%2F%2Fwww.graficisismici.it%2FV6_00%2Ffacebook%2Ffacebook_link_285790.jpg%3F285790"
so it's seem that it's really a link to the original image
can you solve my doubt ?
meanwhile I modified the script to use the new Graph Api
<?php
$user = null;
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true
));
$user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.
if($user == 0) {
/**
* Get a Login URL for use with redirects. By default, full page redirect is
* assumed. If you are using the generated URL with a window.open() call in
* JavaScript, you can pass in display=popup as part of the $params.
*
* The parameters:
* - redirect_uri: the url to go to after a successful login
* - scope: comma separated list of requested extended perms
*/
$login_url = $facebook->getLoginUrl($params = array('scope' => "publish_stream"));
echo ("<script> top.location.href='".$login_url."'</script>");
} else {
$user_message = "Message";
$titolo = "Titolo";
$caption = "Caption";
$link_name = "Link Name";
$action_link = "Action Link";
$testo = "Text";
$image = "Image Link";
$target_uid = "XXXXXXXX"; // ID where to publish
//HTTP POST request to PAGE_ID/feed with the publish_stream
$post_url = '/'.$target_uid.'/feed';
try {
$params = array(
'message' => $user_message,
'name' => $titolo,
'caption' => $caption,
'link' => $action_link,
'description' => $link_name,
'picture' => $image,
'actions' => array(
array(
'name' => $testo,
'link' => $action_link
)
)
);
$post = $facebook->api($post_url,"POST",$params);
}
catch (FacebookApiException $e) {
$result = $e->getResult();
}
}
?>
I just would like to have a clarification about the image question.
Does the image have to still exist ?
Or once posted, I can delete them, as they still live on Fb ?
My questione born from the fact that i see (while using the old script in the top of this post) on the error log of my site a lof of row of 404 error (related to the missed images searched from Fb)
i understood that the images where uploaded to facebook, so they were not needed anymore on my space....
This is not the case. Facebook simply caches your content in their CDN. If you delete the source photos, when the content falls out of their cache, their attempt to refresh / re-fill the cache will fail and your users will get a broken image icon.
Does the image have to still exist ? Or once posted, I can delete them, as they still live on Fb ?
You should not delete them.

Facebook graph API: Upload page image

Is it possible to upload an image to a facebook page as the page picture (not a photo album picture) through the graph api? And then is it possible to also define the offsets to create the miniature picture when a user writes posts as this page?
Yes below worked for me in many places
$file = '#' . realpath('path_to_image');
// Fill in your arguments.
$args = array(
'access_token' => $token,
'image' => $file,
'aid' => $albumid
);
// Send the api request.
$data = $facebook->api('/'.$pageid.'/photos', 'post', $args);

Facebook Graph Api - Posting to Fan Page as an Admin

I've setup a script which allows users to post messages to a fan page on Facebook. It all works but there's one small issue.
The Problem:
When the post is added to the page feed it displays the posting user's personal account.
I would prefer it to show the account of the page (like when you're admin of the page it says it came from that page). The account I'm posting with have admin rights to the page, but it still shows as a personal post.
HTTP POST
$url = "https://graph.facebook.com/PAGE_ID/feed";
$fields = array (
'message' => urlencode('Hello World'),
'access_token' => urlencode($access_token)
);
$fields_string = "";
foreach ($fields as $key => $value):
$fields_string .= $key . '=' . $value . '&';
endforeach;
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
To post as Page not as User, you need the following:
Permissions:
publish_stream
manage_pages
Requirements:
The page id and access_token (can be obtained since we got the required permissions above)
The current user to be an admin (to be able to retrieve the page's access_token)
An access_token with long-lived expiration time of one of the admins if you want to do this offline (from a background script)
PHP-SDK Example:
<?php
/**
* Edit the Page ID you are targeting
* And the message for your fans!
*/
$page_id = 'PAGE_ID';
$message = "I'm a Page!";
/**
* This code is just a snippet of the example.php script
* from the PHP-SDK <http://github.com/facebook/php-sdk/blob/master/examples/example.php>
*/
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'app_id',
'secret' => 'app_secret',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_info = $facebook->api("/$page_id?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => $message
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
} else {
$permissions = $facebook->api("/me/permissions");
if( !array_key_exists('publish_stream', $permissions['data'][0]) ||
!array_key_exists('manage_pages', $permissions['data'][0])) {
// We don't have one of the permissions
// Alert the admin or ask for the permission!
header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream, manage_pages")) );
}
}
} 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(array('scope'=>'manage_pages,publish_stream'));
}
// ... rest of your code
?>
Here the connected $user is supposed to be the admin.
Result:
More in my tutorial
As far as I know, all you have to do is specify a uid (that is, the page's ID) in your call to stream.publish
EDIT
Have a look at impersonation
Because the is the only relevant posting in the google results for "facebook graph won't post to page as page" I want to make a note of the solution I found. You need an access token with manage_pages permissions. Then call
https://graph.facebook.com/<user_id>/accounts?access_token=<access_token>
This will list all the pages the user has access to and will provide the access tokens for each. You can then use those tokens to post as the page.
The Graph API expects the parameter page_id (The Object ID of the Fan Page) to be passed in as an argument to API calls to get the events posted in a Fanpage wall. Not mentioned anywhere in the official Graph API documentation, but it works. I have tested it successfully with the Official PHP SDK v3.0.1
The required application permissions would be create_event and manage_pages
An Example would look something like this:
//Facebook/Fan Page Id
$page_id = '18020xxxxxxxxxx';
//Event Start Time
$next_month = time() + (30 * 24 * 60 * 60);
//Event Paramaeters
$params = array(
'page_id' => $page_id, // **IMPORTANT**
'name' => 'Test Event Name',
'description' => 'This is the test event description. Check out the link for more info: http://yoursite.com',
'location' => 'Kottayam, Kerala, India',
'start_time' => $next_month
);
$create_event = $facebook->api("/$page_id/events", "post", $params);
The answer lies with acquiring a permission of "manage_pages" on the FB:login button, like so:
<fb:login-button perms="publish_stream,manage_pages" autologoutlink="true"></fb:login-button>`
When you get those permissions, you can then get a structured list back of all the pages the logged-in user is an Admin of. The URL to call for that is:
https://graph.facebook.com/me/accounts?access_token=YourAccessToken
I HATE the Facebook documentation, but here is a page with some of the information on it: https://developers.facebook.com/docs/reference/api/
See the 'Authorization' and 'Page Login' sections in particular on that page.
A great resource to put all of this together (for Coldfusion Developers) is Jeff Gladnick's CFC on RIA Forge: http://facebookgraph.riaforge.org/
I added the following UDF to Jeff's CFC if you care to use it:
<cffunction name="getPageLogins" access="public" output="true" returntype="any" hint="gets a user's associated pages they manage so they can log in as that page and post">
<cfset var profile = "" />
<cfhttp url="https://graph.facebook.com/me/accounts?access_token=#getAccessToken()#" result="accounts" />
<cfif IsJSON(accounts.filecontent)>
<cfreturn DeserializeJSON(accounts.filecontent) />
<cfelse>
<cfreturn 0/>
</cfif>
</cffunction>
What this returns is a structure of all the pages the logged-in user is an Admin of. It returns the page NAME, ID, ACCESS_TOKEN and CATEGORY (not needed in this context).
So, VERY IMPORTANT: The ID is what you pass to set what page you are posting TO, and the ACCESS_TOKEN is what you pass to set who you are POSTING AS.
Once you have the list of pages, you can parse the data to get a three-element array with:
ID - ACCESS_TOKEN - NAME
Be careful though, because the Facebook ACCESS_TOKEN does use some weird characters.
Let me know if you need any additional help.
You must retrieve access_tokens for Pages and Applications that the user administrates.
The access tokens can be queried by calling /{user_id}/accounts via the Graph API.
More details:
https://developers.facebook.com/docs/facebook-login/permissions/v2.0 -> Reference -> Pages
This is how I do it with PHP SDK 4.0 and Graph API 2.3:
/**
* Posts a message, link or link+message on the page feed as a page entity
*
* #param FacebookSession $session (containing a page admin user access_token)
* #param string $pageId
* #param string $message - optional
* #param string $link - optional
*
* #return GraphObject
*/
function postPageAsPage( $session, $pageId, $message = '', $link = '' ){
// get the page token to make the post request
$pageToken = ( new FacebookRequest(
$session,
'GET',
"/$pageId" . "?fields=access_token"
))->execute()->getGraphObject();
return ( new FacebookRequest(
$session,
'POST',
"/$pageId/feed",
array(
'access_token' => $pageToken->getProperty( 'access_token' ),
'message' => $message,
'link' => $link,
)
))->execute()->getGraphObject();
}