How to select facebook 'notes' posted via application - facebook

There is an application using FQL. Is there an opportunity to select notes posted by the application with the known id? As far as I know, there is no field 'app_id' in the 'note' table.

You can use graph api to get the notes of an app by app_id. http://developers.facebook.com/docs/reference/api/note/ you have to use any valid access token.
Example using php-sdk 3.1.1
<?php
$app_access = "https://graph.facebook.com/oauth/access_token?client_id=AppId&client_secret=YOURSECRET&grant_type=client_credentials";
$app_access_token = file_get_contents($app_access);
$pageid="your_app_or_page_id";
$MEnotes = $facebook->api('/'.$pageid.'/notes/?$app_access_token');
foreach ($MEnotes as $key=>$value) {
foreach ($value as $fkey=>$fvalue) {
$noteID=$fvalue[id];
$noteSubject=$fvalue[subject];
$noteMessage=$fvalue[message];
echo ''.$noteID.'<b> '.$noteSubject.'</b><br />'.$noteMessage.'<hr />';
}};
?>

Related

How to get images from FB to website

I'm working on publishing posts from our FB page on our website. Each new post and photos we added into our FB page I need to show in our website too.
I have this code, but don't working as I need.
require 'php-graph-sdk-5.x/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '...',
'app_secret' => '{app-secret}', // don't know where to find app_secret for my page, I've found that just for apps, not pages
'default_graph_version' => 'v2.10'
]);
$access_token = '...'; // generated in developers, but with just for 12 hours, than this token is expired... :-(
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('me?fields=id,name,feed,data', $access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
foreach ($graphNode as $node) {
foreach ($node as $items) {
print_r($items);
// when access token was valid, I got posts from out FB page. But with no images, didn't find how to get add images to this feed...
}
}
So, my questions are:
where I can find app-secret for FB page? I'm not able to connect to my FB page without that, I think
how to generate permanent access token, or if it's not possible, how to make i other way?
how to add images (new, shared, etc.) to my feed?
Thanks.
There is no App Secret per Page, there is only the App Secret per App. You can find it in your App Settings.
Extended/Permanent Tokens: https://developers.facebook.com/docs/facebook-login/access-tokens/ or http://www.devils-heaven.com/facebook-access-tokens/ - for getting the feed entries of unrestricted Page, you can just use an App Access Token and you can hardcode it in your PHP code.
Getting images in the feed, not just messages: You need to specify which fields you want to get, or you will only get default ones. It is called "Declarative Fields": https://developers.facebook.com/docs/graph-api/changelog#v2_4 - also, check out the API reference: https://developers.facebook.com/docs/graph-api/reference/post

Facebook Marketing API and Ads Insight Access

I'm building a small program that works with various APIs to automate reporting services we offer some clients.
One of the things we report on is Facebook Ads performance.
I've been building out this program using the Facebook Marketing API & Ads Insight APi https://developers.facebook.com/docs/marketing-apis
I've gone through the whole process of setting up a Facebook 'App' and getting the relevant app tokens.
However, I've hit a wall since development access only allows for 5 Ad Accounts.
To apply for basic access, the marketing API is asking for the development platform and a whole bunch of other things that aren't relevant to my program. I'm not building an 'app' intended for public release in the traditional sense; rather, I just want to integrate with these APIs on a basic level to automate some internal tasks.
It seems mind-boggling to me that I wouldn't be able to do something like this, but this is what the Facebook documentation seems to be suggesting.
If anyone else has familiarity with this kind of issue, I'd love to know if there is a workaround.
Submit your app for review to get more than 10 ad accounts. Use the "Platform" of Website. Select Native or desktop app; app secret NOT embedded in the client. The rest of it can be mostly ignored, but you will need to include some screen shots of your app and a description of how it works and what it does. A real human will review it, and you can get help in the Facebook Developers group here:
https://www.facebook.com/groups/fbdevelopers
Youwill get a pass/fail only...no comments. Don't be surprised if they reject it first time around. Do not resubmit and hope for a better response the second time around -- they'll eventually lock you out for a few days. Post a help question to the group.
Derks, I currently am building dashboard with over 40 clients and I am able to display everyone of them and their insights data etc. with basic development level. I have code if you want to take a look only thing I am trying to accomplish now is making a date range picker but, you are more than welcome enough to take a look at what I have just to get a general idea.
Here are the Use objects from Facebook
<?php
require_once __DIR__ . '/vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Object\AdUser;
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\AdsInsightsFields;
use FacebookAds\Object\Ad;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\AdCampaign;
use FacebookAds\Object\Fields\AdFields;
use FacebookAds\Object\Fields;
use FacebookAds\Object\Fields\AdImageFields;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\AdSet;
use FacebookAds\Object\AdCreative;
use FacebookAds\Object\Fields\AdCreativeFields;
use FacebookAds\Object\Fields\AdCreativePhotoDataFields;
use FacebookAds\Object\AdCreativeLinkData;
use FacebookAds\Object\Fields\AdCreativeLinkDataFields;
use FacebookAds\Object\Fields\CampaignFields;
use FacebookAds\Object\Page;
use FacebookAds\Object\Fields\AdPreviewFields;
use FacebookAds\Object\Values\AdPreviewAdFormatValues;
use FacebookAds\Object\AdVideo;
?>
Here is the general code I am trying
<?php
// Init PHP Sessions
session_start();
$fb = new Facebook([
'app_id' => 'xxxxxxxxx',
'app_secret' => 'xxxxxxxxxxx',
]);
$helper = $fb->getRedirectLoginHelper();
if (!isset($_SESSION['enter api key here'])) {
$_SESSION['enter api key here'] = null;
}
if (!$_SESSION['enter api key here']) {
$helper = $fb->getRedirectLoginHelper();
try {
$_SESSION['enter api key here'] = (string) $helper->getAccessToken();
} catch(FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}
if ($_SESSION['enter api key here']) {
//echo "You are logged in!";
// Initialize a new Session and instantiate an API object
Api::init(
'xxxxxxxxx', // App ID
'xxxxxxxxx', //app_secret
$_SESSION['enter api key here'] // Your user access token
);
?>
<div id="fbdata"></div> <?php
$account = new AdAccount('act_xxxxxxxxxx');
$params = array(
'date_preset'=> 'last_28d',
'thumbnail_width' => 200,
'thumbnail_height' => 150,
'level' => 'campaign',
'limit' => '15'
);
$fields = array(
AdsInsightsFields::CAMPAIGN_NAME,
AdsInsightsFields::CAMPAIGN_ID,
AdsInsightsFields::IMPRESSIONS,
AdsInsightsFields::CLICKS,
AdsInsightsFields::REACH,
AdsInsightsFields::SPEND,
AdsInsightsFields::CPM,
AdsInsightsFields::CPC,
AdsInsightsFields::ACTIONS,
);
$field = array(
AdCreativeFields::TITLE,
AdCreativeFields::THUMBNAIL_URL,
AdCreativeFields::BODY,
);
$params1 = array(
'time_range' => array(
'since' => (new \DateTime($beginDate))->format('Y-m-d'),
'until' => (new \DateTime($lastDate))->format('Y-m-d'),
),
'thumbnail_width' => 200,
'thumbnail_height' => 150,
'level' => 'ad',
'limit' => '5'
);
$adcreatives = $account->getAdCreatives($field, $params1);
?>
<table class="fbtable">
<tr>
<th>Title</th>
<th>Ad Image</th>
<th>Ad Body</th>
</tr>
<?php
foreach($adcreatives as $t2){
echo"<tr>
<td>$t2->title</td>
<td><img src='$t2->thumbnail_url'/></td>
<td>$t2->body</td>
</tr>";
}
$insights = $account->getInsights($fields, $params);?>
<table class="fbtable">
<tr>
<th>Campaign ID</th>
<th>Campaign Name</th>
<th>Impressions</th>
<th>Clicks</th>
<th>Reach</th>
<th>Spend</th>
<th>Total Actions</th>
<th>CPM</th>
<th>CPC</th>
</tr>
<?php
foreach($insights as $i) {
$impress = number_format((float)$i->impressions);
$reach = number_format((float)$i->reach);
$totalAction = number_format((float)$i->actions);
$cpc = number_format($i->cpc, 2, '.', '');
$cpm = number_format($i->cpm, 2, '.', '');
echo"<tr class='fbtable'>
<td>$i->campaign_id</td>
<td>$i->campaign_name</td>
<td>$impress</td>
<td>$i->clicks</td>
<td>$reach</td>
<td>$$i->spend</td>
<td>$totalAction</td>
<td>$$cpm</td>
<td>$$cpc</td>
</tr>";
}
}else {
$permissions = ['ads_management'];
$loginUrl = $helper->getLoginUrl('http://where you want login to be.com', $permissions);
echo 'Log in with Facebook';
}
?>
I will help much as I can #Derks and I believe the only thing you may need to do is figure out way for the program or whatever your building know who is who.

Create Facebook event as Page with rGraph API

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
}

Facebook iFrame app - how to fetch Preload FQL result using PHP SDK?

since few years I have an FBML app (a small Flash game) which I'm now trying to convert to an iFrame app. Unfortunately there aren't many docs for Facebook iFrame apps yet.
For my game I need the user's first name, picture, gender and the city.
In my old version I had this preload FQL (created once by a PHP script):
$fql = array('info' => array('pattern' => 'facebook',
'query' => 'SELECT first_name, sex, pic_big, current_location
FROM user WHERE uid={*user*}'));
$fb->api_client->admin_setAppProperties(
array('preload_fql' => json_encode($fql)));
and then my FBML app script had been as simple as:
<?php
require_once('facebook.php');
define('FB_API_ID', 'XXX');
define('FB_AUTH_SECRET', 'YYY');
$fb = new Facebook(FB_API_ID, FB_AUTH_SECRET);
$viewer_id = $fb->require_login();
$data = json_decode($fb->fb_params['info'], true);
$first_name = $data[0][0];
$last_name = $data[0][2];
$female = ($data[0][3] != 'male');
$avatar = $data[0][3];
$city = $data[0][4]['city'];
# and then I'd just construct flashvars attribute
# for the <fb:swf ...> tag and print it
?>
Does anybody please have hints on how to recreate the same script for the iFrame version - i.e. how can I fetch the result of Preload FQL by my iFrame app?
According to an older Facebook blog entry Preload FQL should be accessible by the iFrame apps.
Thank you!
Alex
My own answer after long searching is that Preload FQL results aren't sent to iframe Facebook apps.
That is why Facebook performance doc says:
"Preload FQL Query and Multiquery.
This section applies to FBML canvas pages, but not to websites or IFrame canvas pages."
As Facebook said for Preload FQL
"Facebook will send the result of these FQL queries as JSON-encoded POST parameters to your Canvas URL"
print_r your $_POST and see which variable is the "json-encoded results". You convert json into php object using json_decode
JSON looks like this: {"var":"val","var":"val"}
Also, Facebook already has great docs for iframes. Then you might have missed these great docs:
Facebook Docs Home
http://developers.facebook.com/docs/
Authentication
http://developers.facebook.com/docs/authentication/
Signed Request
http://developers.facebook.com/docs/authentication/signed_request/
iFrame Canvas Apps
http://developers.facebook.com/docs/guides/canvas/
PHP SDK
https://github.com/facebook/php-sdk
Graph API
http://developers.facebook.com/docs/reference/api/
You don't need to call any FQL for the information you are getting. For iFrame you just need to do following steps
Download the PHP SDK of graph api https://github.com/facebook/php-sdk/
Create the object and authorize the app from user
$fbconfig['appid' ] = "your application id";
$fbconfig['api' ] = "your application api key";
$fbconfig['secret'] = "your application secret key";
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
// User location extended permission allow you to get user's current location
$loginparams = array('canvas' => 1,'fbconnect' => 0,'req_perms' => 'user_location');
$loginUrl = $facebook->getLoginUrl($loginparams);
// We may or may not have this data based on a $_GET or $_COOKIE based session.
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();
$fbme = null;
// Session based graph API call.
if ($session) {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
d($e);
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
// You can found all the data in this array.
print_r($fbme);
For more detail you can follow this tutorial http://thinkdiff.net/facebook/php-sdk-graph-api-base-facebook-connect-tutorial/
Hope it works for you

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