Post to page via Facebook API - php

I'm the admin of FB app and FB page (but this page on a separate account). How do I can post something to this page's wall via this FB app using FB API and PHP (in order to be able to do it with CRON)? Is that possible? Thank you in advance for your answers!

Yes it is possible.
First of all, to post on a page on its behalf is done using the page access token.
Get a normal token from your app (may be using Graph API Explorer directly by selecting your app from top-right drop down menu) with the permission: manage_pages, then follow the steps I've mentioned here: https://stackoverflow.com/a/18322405/1343690 - this will get you a never-expiring page access token.
Save it somewhere and use with your cron-job while posting. Code for posting-
$url = 'https://graph.facebook.com/{page-id}/feed';
$attachment = array(
'access_token' => $page_access_token,
'message' => '{your-message}'
);
$result = PostUsingCurl($url, $attachment);
$result = json_decode($result, TRUE);
if( isset($result['error']) ) {
echo "Error: ".$result['error']['message']."<br/>";
}
else{
echo "Feed posted successfully!<br/>";
}
function PostUsingCurl($url, $attachment)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close ($ch);
return $result;
}

I use this personally. Though you will need to already have an access_token generated. If you do not, you could use Facebook's Graph Explorer tool to grant your account the appropriate permissions.
$attachment = array(
"access_token" => $fb_token,
"link" => "$postLink",
"name" => "$postName",
"description" => "$postDescription",
"message" => "$postMessage",
"fb:explicitly_shared" => true
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://graph.facebook.com/'.$fb_page_id.'/feed');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //to suppress the curl output
$result = curl_exec($ch);
curl_close ($ch);
Hope this helps out!

Add Api to your page
<script id="facebook-jssdk" src="//connect.facebook.net/en_US/all.js#xfbml=1"></script>`
click function to call fb page
$('#facebook').click(function(){
FB.init({
appId: 12345, // your app ID
status: true,
cookie: true
});
FB.ui({
method: 'feed',
name: "post name",
link: "http://postlink.com,
//picture: "http:/imageurl.com,
description: "this is the body of the text"
});
})

Related

How do I fix this Bitly oAuth 'single header' error?

Context: I have a WordPress plugin that allows users to authenticate with Bitly so that they can use link shortening features if they desire to do so.
Bitly requires one callback URL to be stored in the app settings, so I created a standalone script on my server that processes the authentication process. The overall handshake actually looks something like this:
The user clicks a link taking them to the Bitly authorization page for my app.
If they agree, they are forwarded to my script with a code.
My script exchanges that code to Bitly for another code.
Once the codes are all acquired, it reaches out to the user's domain to store the codes and to retreive the URL of the options page on that user's URL so that we can redirect the user back home.
We then redirect the user back to the options page that they had just clicked away from.
Problem: However, a very small handful of users are getting the following error just prior to the authentication process being complete:
Warning: Header may not contain more than a single header, new line
detected in /home/warfarep/public_html/bitly_oauth.php on line 72.
Sample Code:
function sw_file_get_contents_curl($url){
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FAILONERROR, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$cont = #curl_exec($ch);
$curl_errno = curl_errno($ch);
curl_close($ch);
if ($curl_errno > 0) {
return 0;
}
return $cont;
}
// Check if this is the first pass and we have the generic code
if(isset($_GET['code'])):
// Retreive the information
$code = $_GET['code'];
$client_ID = 'blahblahblah';
$client_secret = 'blahblahblah';
$redirect_url = 'blahblahblah';
$state = $_GET['state'];
$url = 'https://api-ssl.bitly.com/oauth/access_token';
$fields = array(
'code' => urlencode($code),
'client_id' => urlencode($client_ID),
'client_secret' => urlencode($client_secret),
'redirect_uri' => urlencode($redirect_url),
'state' => urlencode($state)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HTTPHEADER, array('Accept: application/json'));
//execute post
$response = curl_exec($ch);
//close connection
curl_close($ch);
$response = json_decode($response , true);
$ajax_url = $state .= '?action=sw_bitly_oauth&access_token='.$response['access_token'].'&login='.$response['login'];
$wp_response = sw_file_get_contents_curl($ajax_url);
$wp_response = rtrim($wp_response , '0');
header('Location: '.$wp_response);
^^^^^^ This is line 72 from the error message
endif;
Question: Is there anything that you can see that would prevent headers from already being sent prior to the redirect on line 72? How do I fix this Bitly oauth "single header" error? Thanks!

How to post on user's wall in facebook after getting permission from user?

Is there any good tutorial that teaches how to post on user's wall with API? This is the flow:
The user will come on my website and click on post to facebook button at the end of article.
He is shown sign in dialog from facebook, after sign in he will give permission to my application to post on his wall on his behalf.
After authorization, his shared link will be posted on his wall.
Upon future shares, he will not be asked for permissions since he has already given permission to post on his behalf. So in future when he clicks 'Post to Facebook' button under the article then that item will be posted to his wall without opening facebook login dialog.
I have searched a lot on tutorials but have not found any that meets my requirement.
I am very new to facebook API and have not worked with it before.
Any suggestions or link to tutorials?
Thank You!
I've code to help you to post status with an image to an user's timeline.
After user has given permission to your app , you might have received a query string parameter called 'code' , using this code , we can post to user's timeline.
$code = #$_REQUEST["code"];
if(!empty($code))
{
// Start : Get live user access token ------------------------------------------ //
$token_url= "https://graph.facebook.com/oauth/"
. "access_token?"
. "client_id=" . FACEBOOK_APP_ID
. "&redirect_uri=" . urlencode( FACEBOOK_POST_LOGIN_URL)
. "&client_secret=" . FACEBOOK_APP_SECRECT
. "&code=" . $code;
$token = $this->get_app_access_token(FACEBOOK_APP_ID,FACEBOOK_APP_SECRECT,$token_url);
$access_token = $token;
// End : Get live user access token ------------------------------------------- //
// Start : Create album ------------------------------------------------------ //
$graph_url = "https://graph.facebook.com/me/albums?"
. "access_token=". $access_token;
$uri = 'https://graph.facebook.com/albums?access_token='.$access_token;
$post_fields = array('name' => trim( FACEBOOK_ALBUM_NAME ));
$curl = curl_init( $uri );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curl, CURLOPT_POST, TRUE );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $post_fields );
$raw_data = curl_exec($curl);
curl_close( $curl );
$created_album_id = json_decode( $raw_data, $assoc = TRUE );
// End : Create album ---------------------------------------------------------- //
$facebook_share_image_url = FACEBOOK_SHARE_IMAGE_PATH;
$facebook_status_text = 'The status text';
$graph_url= "https://graph.facebook.com/me/photos";
$postData = "url=" . urlencode($facebook_share_image_url)
. "&message=" . urlencode($facebook_status_text)
. "&access_token=" .$access_token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $graph_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$output = curl_exec($ch);
curl_close($ch);
// End : Add photos ------------------------------------------------------------- //
}
and the function to get app access token
function get_app_access_token($app_id, $secret,$token_url)
{
$url = 'https://graph.facebook.com/oauth/access_token';
$token_params = array(
"type" => "client_cred",
"client_id" => FACEBOOK_APP_ID,
"redirect_uri" => urlencode(FACEBOOK_POST_LOGIN_URL),
"client_secret" => FACEBOOK_APP_SECRECT
);
$a1 = $this->file_get_contents_curl($token_params,$token_url);
$a2 = str_replace("access_token=","",$a1);
$a3 = explode("&expires",$a2);
return $a3[0];
}
The other function access graph url
function file_get_contents_curl($params,$url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
$headers = array(
"Cache-Control: no-cache",
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
Hope it helps..!!
You can use simple facebook sharer URL:
https://www.facebook.com/sharer/sharer.php?u=YOURPAGEURL
Where YOURPAGEURL is the page URL which you want to share.. Hope this helps.
you have to permission pubish_stream on your app and then try this using curl:-
Also you need a user access token then send access token with curl call
$attachment = array(
'access_token' => $access_token,
'message' => 'i m success to using graph api for post wall',
'name' => 'Wall Post using graph api',
'link' => 'www.mysite.com',
'description' => 'Using the Graph API, any Facebook users Wall feed may be accessed by using this URL:',
'picture'=>'http://example.com/images/noimage.png'
);
$url = "https://graph.facebook.com/$facebook_id/feed";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //to suppress the curl output
$result = curl_exec($ch);
curl_close ($ch);
print_r($result)
For more :- Graph API new feed post object-Attachment not showing
Post to a Facebook user's wall with cURL PHP

Post a feed on facebook after a form on my website

I have a news form on my website. After creating this news message I want to publish it on Facebook. I tried alot of things, but nothing was working. Here is my class:
<?php
class Facebook {
const FACEBOOK_APP_ID = 'MY_APP_ID';
const FACEBOOK_APP_SECRET = 'MY_APP_SECRET';
const FACEBOOK_ACCESS_TOKEN_URI = 'https://graph.facebook.com/oauth/access_token';
const FACEBOOK_FEED_URI = 'https://graph.facebook.com/app/feed';
private function getAccessToken() {
$params = array(
'client_id' => self::FACEBOOK_APP_ID,
'client_secret' => self::FACEBOOK_APP_SECRET,
'grant_type' => 'client_credentials',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::FACEBOOK_ACCESS_TOKEN_URI);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$data = curl_exec($ch);
curl_close($ch);
return substr($data, strpos($data, '=') + 1);
}
public function sendFeed() {
$params = array(
'access_token' => $this->getAccessToken(),
'message' => $message,
'name' => $name,
'link' => $url,
'description' => $description,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::FACEBOOK_FEED_URI);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close ($ch);
return $data;
}
}
If I call the method sendFeed() it returns the following:
{"id":"404322099626551_404397542952340"}
I think the submit was successfull, but when I visit my page on facebook, there is no new feed. What am I doing wrong? I searched the complete day and couldn't get it to work. I thank you for your help.
What you are doing here is posting it on your user's feed. You are using a user access token. What you want to use is a page access token.
You'll need the manage_pages permission to perform tasks on behalf of your page.
In addition you should consider using the official PHP SDK, it'll make accessing Facebook's API much easier and improve readability.

Is there a Facebook API to publish content to the FaceBook page using PHP?

I have a travel site and whenever I publish a new offer, I want to automatically update our sites FaceBook page.
Is there an API I can use for this?
Are there any recommended tutorials showing how to do this?
Our content is published with PHP.
Yes there are many ways for doing the same.
The most common one is to create a Facebook App for your Website.
https://developers.facebook.com/apps
Download the Facebook Development Kit from this URL based on the language you are using for development.
https://developers.facebook.com/docs/sdks/
This SDK will have the required Classes and functions call to help you submit contents from your web-page to your Facebook Page.
Go Ahead and have a look.
Try this example
$data = array(
"link" => $link,
"access_token" => $pages,
"picture" => $image,
"name"=> $title,
"description"=> $description
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/".$pageID."/feed");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$op = curl_exec($ch);
if (!$op) {
echo "Curl Error : ".curl_error($ch);
curl_close($ch);
exit;
}
curl_close($ch);
$res = get_object_vars(json_decode((string)$op));
print_r($res);

Uploading a picture to facebook

I am trying to upload a image to a gallery on a facebook fan page, here is my code thus far,
$ch = curl_init();
$data = array('type' => 'client_cred', 'client_id' => 'app_id','client_secret'=>'secret_key',' redirect_uri'=>'http://apps.facebook.com/my-application/'); // your connect url here
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/oauth/access_token');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$rs = curl_exec($ch);
curl_close($ch);
$ch = curl_init();
$data = explode("=",$rs);
$token = $data[1];
$album_id = '1234';
$file= 'http://my.website.com/my-application/sketch.jpg';
$data = array(basename($file) => "#".realpath($file),
//filename, where $row['file_location'] is a file hosted on my server
"caption" => "test",
"aid" => $album_id, //valid aid, as demonstrated above
"access_token" => $token
);
$ch2 = curl_init();
$url = "https://graph.facebook.com/".$album_id."/photos";
curl_setopt($ch2, CURLOPT_URL, $url);
curl_setopt($ch2, CURLOPT_HEADER, false);
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch2, CURLOPT_POST, true);
curl_setopt($ch2, CURLOPT_POSTFIELDS, $data);
$op = curl_exec($ch2);
When I echo $token, I seem to be getting the token, but when I run the script, I get this error, {"error":{"type":"OAuthAccessTokenException","message":"An access token is required to request this resource."} , I have NO idea why it is doing this!
Basically what I am doing in that code is getting the access token with curl, and then, uploading the photo to my album also via curl, but I keep getting that error!
Any help would be appreciated, thank you!
Ok, got it working, here is the code, assuming that you have a valid session going.
$token = $session['access_token'];
//upload photo
$file= 'photo.jpg';
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath($file);
$ch = curl_init();
$url = 'https://graph.facebook.com/me/photos?access_token='.$token;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
This will upload the specified image to the session holders gallery, it will create a album if there is not one present, also you can access the token via the session array as demonstrated above.
Hope this helps someone out.
Probably your application doesn't have needed permissions.
To request permissions via OAuth, use
the scope argument in your
authorization request, and include a
comma separated list of all the
permissions you want to request.
http://developers.facebook.com/docs/authentication/permissions

Categories