Posting to facebook page with cron php - php

I have a job site where 100 jobs posting daily. i also have a Facebook page. i want to post 10 jobs each hour to My Facebook page with cron jobs.
I am using the following code to post to Facebook face by accessing the URL Manually.
<?php
require_once 'facebook_sdk/src/facebook.php';
// configuration
$appid = 'xxxxxxx';
$appsecret = 'xxxxxxx';
$pageId = 'xxxxx';
$msg = 'test';
$title = 'pagetitle';
$uri = 'http://google.com/';
$desc = 'description here';
$pic = 'http://google.com/test/2.png';
$action_name = 'Go to my site';
$action_link = 'http://www.google.com';
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => false,
));
$user = $facebook->getUser();
// Contact Facebook and get token
if ($user) {
// you're logged in, and we'll get user acces token for posting on the wall
try {
$page_info = $facebook->api("/$pageId?fields=access_token");
if (!empty($page_info['access_token'])) {
$attachment = array(
'access_token' => $page_info['access_token'],
'message' => $msg,
'name' => $title,
'link' => $uri,
'description' => $desc,
'picture'=>$pic,
'actions' => json_encode(array('name' => $action_name,'link' => $action_link))
);
$status = $facebook->api("/$pageId/feed", "post", $attachment);
} else {
$status = 'No access token recieved';
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else {
// you're not logged in, the application will try to log in to get a access token
header("Location:{$facebook->getLoginUrl(array('scope' => 'photo_upload,user_status,publish_stream,user_photos,manage_pages'))}");
}
echo $status;
?>
It working fine. but i want to post the jobs automatically with corn jobs. how can i do it.
does anyone have any advice?

Please see the codes below and edit/complete it according to yours
class Facebook
{
/**
* #var The page id to edit
*/
private $page_id = '_PAGE_ID_';
/**
* #var the page access token given to the application above
*/
private $page_access_token = '_ACCESS_TOKEN_';
/**
* #var The back-end service for page's wall
*/
private $post_url = '';
/**
* Constructor, sets the url's
*/
public function Facebook()
{
$this->post_url = 'https://graph.facebook.com/'.$this->page_id.'/feed';
}
public function renew_access()
{
$url = 'https://graph.facebook.com/oauth/access_token?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&display=popup&code=_CODE_&redirect_uri=THIS_FILE_FULL_URL'; // THIS_FILE_FULL_URL = like http://site.com/fb.post.php
// request this url to renew access token to send posts when offline. get the access_token and set self::$page_access_token = _ACCESS_TOKEN_
}
private function getcode()
{
$url = 'https://www.facebook.com/dialog/oauth?client_id=CLIENT_ID&redirect_uri=THIS_FILE_FULL_URL'; // THIS_FILE_FULL_URL = like http://site.com/fb.post.php
// request this url to get _CODE_ to send posts when offline. then get the access_token and set self::$page_access_token = _ACCESS_TOKEN_
}
private function want_to_send()
{
// check for somethings if you want to send or you don't
// for eg. check for time or any other check if sent before, or just return true to pass
return true;
}
public function message($data)
{
// need token
$data['access_token'] = $this->page_access_token;
if(!$data['properties'])
$data['properties'] = '{"TITLE":"DESC"}';
try{
if(self::want_to_send())
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$this->post_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, $data);
curl_setopt($ch, CURLOPT_USERAGENT , 'facebook-php-3.1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //to suppress the curl output
$return = curl_exec($ch);
curl_close ($ch);
}
}
catch ( exception $e){
//throw new Exception($e);
// or
error_log(json_encode($data));
}
//return $return; // if you want return
}
}
$facebook = new Facebook();
// make a simple post test
$facebook->message(array( 'message' => 'The status header',
'link' => 'http://cekirdek.com.tr',
'picture' => 'http://domain.com/picture_url.png',
'name' => 'Name of the picture, shown just above it',
'description' => 'Full description explaining whether the header or the picture' ) );

Related

PHP auto post on facebook page

I am trying to auto post on Facebook page using my app it works fine if I replace my-page-numeric-id with my profile numeric id, but when I put my page numeric id instead of my-page-numeric-id and put valid access token it won't publish on Facebook page I tried to submit review permission that are as follow "manage_pages, publish_actions" but Facebook team mentioned that you don't need it all because you own this page and your currently admin of it, these permission are necessary when any other person need to authorize with your app.
Now my question is, my code works perfectly for publishing post on my profile's wall but i am unable to auto post on my page what is the problem behind it i am unable to figure out here is my code
<?php
require_once 'src/facebook.php';
class FacebookApi {
var $consumer;
var $token;
var $method;
var $http_status;
var $last_api_call;
var $callback;
var $connection;
var $access_token;
function __construct($data){
$config = array();
$config['appId'] = $data['consumer_key'];
$config['secret'] = $data['consumer_secret'];
$this->connection = new Facebook($config);
}
function share($title, $targetUrl, $imgUrl, $description, $access_token){
$this->connection->setAccessToken($access_token);
$params["access_token"] = $access_token;
if(!empty($title)){
$params["message"] = $title;
$params["name"] = $title;
}
if(!empty($targetUrl)){
$params["link"] = $targetUrl;
}
if(!empty($imgUrl)){
$params["picture"] = $imgUrl;
}
if(!empty($description)){
$params["description"] = $description;
}
// post to Facebook
try {
$ret = $this->connection->api('/my-page-numeric-id/feed', 'POST', $params);
} catch(Exception $e) {
$e->getMessage();
}
return true;
}
function getLoginUrl($params){
return $this->connection->getLoginUrl($params);
}
function getContent($url) {
$ci = curl_init();
/* Curl settings */
curl_setopt($ci, CURLOPT_URL, $url);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ci, CURLOPT_HEADER, false);
curl_setopt( $ci, CURLOPT_CONNECTTIMEOUT, 10 );
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ci);
curl_close ($ci);
return $response;
}
}
$access_token = 'long-live-token-here';
$facebookData = array();
$facebookData['consumer_key'] = 'app-id-here';
$facebookData['consumer_secret'] = 'app-secret-here';
$title = "Demo Content Posted on Timeline";
$targetUrl = "http://www.demo_url.com/1234-post";
$imgUrl = "http://www.demo_url.com/1234-post-image.png";
$description = "demo_description_here";
$facebook = new FacebookApi($facebookData);
$facebook->share($title, $targetUrl, $imgUrl, $description, $access_token);
?>
With API v2.3, they have split the publishing permission into two separate ones:
publish_actions is for anything you want to publish as a user
if you want to publish as a page however, you need publish_pages permission (in addition to manage_pages)
now it's time for facebook v5 sdk
$fb = new Facebook\Facebook([
'app_id' => 'app_id',
'app_secret' => 'app_secret',
'default_graph_version' => 'v2.8',
]);
// facebook auto post
$params = array(
"message" => "$title in $merchant $short",
"link" => "http://pickmyoffers.com/",
"picture" => "http://Pickmyoffers.com/images/searched/Flipkart.png",
"name" => "www.Pickmyoffers.com",
"caption" => "www.pickmyoffers.com",
"description" => "Submit Coupon and earn money through Pickmyoffers.com | Deals,Coupons and offers."
);
$post = $fb->post('/Page_id/feed',$params, $access_token);
$post = $post->getGraphNode()->asArray();
}
hope it's help

getting latest posts from fb using graph api

I want to get latest posts from fb and need to display on my site(magento). I have registerd one app in facebook and try to getting posts by using the url but it's giving empty array
require_once(Mage::getBaseDir('lib') . '/facebook/facebook.php');
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxx',
));
$fbid = "xxxxxxxxxx";
$secret = "xxxxxxxxxxxxxxxxxxxxxxx";
$token = 'https://graph.facebook.com/oauth/access_token?client_id='.$fbid.'&client_secret='.$secret.'&grant_type=client_credentials';
$token = file_get_contents($token);
$posts = json_decode(
file_get_contents('https://graph.facebook.com/' . $fbid . '/feed?
access_token=' . $token
)
);
But it's giving an empty array and could you help me to get the results and why it is giving empty?
In order to read the Feed from Facebook, you must log the user into Facebook and ask the user for the read_stream permission.
The feed will be the logged-in user's feed and may not be appropriate for all users of your website, unless each user of your website sees their own feed...
If you have a valid access token, you can get feed from any public page using php graph api.You can call api using file_get_contents or curl method.
function curl_get_file_contents($URL) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 400);
$contents = curl_exec($ch);
$err = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
$contents=json_decode($contents,true);
if ($contents) return $contents;
else return FALSE;
}
$access_token = 'your accesstoken';
$url = " https://graph.facebook.com/$page_id/feed?access_token=$access_token";
$posts = curl_get_file_contents($url);
Now $posts will have all the recents posts from the page and you can use foreach to get each post.
Create App Developer Facebook Page.
Live Access token you can get via graph. Then code exmaple:
<ul>
<?php
$page_name = '{PAGE_NAME}'; // Example: http://facebook.com/{PAGE_NAME}
$page_id = '{PAGE_ID}'; // can get form Facebook page settings
$app_id = '{APP_ID}'; // can get form Developer Facebook Page
$app_secret = '{APP_SECRET}'; // can get form Developer Facebook Page
$limit = 5;
function load_face_posts($page_id, $page_name, $app_id, $app_secret, $limit, $message_len) {
$access_token = "https://graph.facebook.com/oauth/access_token?client_id=$app_id&client_secret=$app_secret&grant_type=client_credentials";
$access_token = file_get_contents($access_token); // returns 'accesstoken=APP_TOKEN|APP_SECRET'
$access_token = str_replace('access_token=', '', $access_token);
$limit = 5;
$data = file_get_contents("https://graph.facebook.com/$page_name/posts?limit=$limit&access_token=$access_token");
$data = json_decode($data, true);
$posts = $data[data];
//echo sizeof($posts);
for($i=0; $i<sizeof($posts); $i++) {
//echo $posts[$i][id];
$link_id = str_replace($page_id."_", '', $posts[$i][id]);
$message = $posts[$i][message];
echo ($i+1).". <a target='_blank' href='https://www.facebook.com/AqualinkMMC/posts/".$link_id."'>".$message."</a><br>";
}
}
load_face_posts($page_id, $page_name, $app_id, $app_secret, $limit, $message_len);
?>
</ul>

PHP - Posting video on Facebook through Graph API using a valid access token

I have a video exist on my server,
I need to post that video on Facebook using Graph API.
Here is the code suggested by Team Facebook.
What I am doing is as below.
1) From an Android device I am getting an access token
2) Recognizing user by passing that access token to Facebook and get email id and through email id recognize user
3) Posting user's video from my server to Facebook through Graph API.
4) Returning a video id to android device as an API response.
I am approaching this route because in Android device it is 2 step process to post video on Facebook.
1) Download the video first
2) Post to Facebook
This is time consuming.
Here is the code that I am trying
define("FB_WEB_APP_ID","********");
define("FB_WEB_SECRET","********");
define("FB_WEB_REDIRECT_URI","<< redirect url >>");
$GLOBALS["all_user_dir_path"]="/var/www/proj/web/video/user_videos/";
define("FB_WEB_SCOPE","user_friends,email,public_profile,user_hometown,user_location,user_photos,user_videos,publish_actions,read_friendlists,publish_stream,offline_access");
define("FB_WEB_RESPONSE_TYPE","code%20token");
$GLOBALS["fb_app_creds"]=array();
$GLOBALS["fb_app_creds"]['appId']= FB_WEB_APP_ID;
$GLOBALS["fb_app_creds"]['secret']=FB_WEB_SECRET;
$GLOBALS["fb_app_creds"]['response_type']=FB_WEB_RESPONSE_TYPE;
$GLOBALS["fb_app_creds"]['redirect_uri']=FB_WEB_REDIRECT_URI;
$GLOBALS["fb_app_creds"]['scope']=FB_WEB_SCOPE;
$GLOBALS["facebook"] = new Facebook($GLOBALS["fb_app_creds"]);
class DefaultController extends Controller
{
// some code....
/**
* #Route("/gk",name="_fb")
* #Template()
*/
public function gkAction(Request $request){
$facebook = $GLOBALS["facebook"];
$access_token=$request->query->get("access_token");
if(!$access_token){
die("give access token in url.......");
}
echo "<pre>";
$facebook->setAccessToken($access_token);
$user = $facebook->getUser();
$me=$facebook->api("/me");
$email=$me['email'];
$all_user_dir_path=$GLOBALS["all_user_dir_path"];
$user_directory = str_replace(array(".","#"), "_",$email);
$user_dir_abs_path=$all_user_dir_path.$user_directory;
print_r($me);
$video_file_path=$user_dir_abs_path."/video.mp4";
if(file_exists($video_file_path))
{
echo "file exists...";
}else{
die("not exist");
}
$video_title="Test";
$video_desc="Test";
$access_token=$request->query->get("access_token");
$file = "#".$video_file_path;
$data = array('name' => 'file', 'file' => $file);
$post_url = "https://graph-video.facebook.com/me/videos?"
. "title=" . $video_title. "&description=" . $video_desc
. "&". $access_token
;
echo "<hr>TRY 1<hr>";
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$res = curl_exec($ch);
$video_id=0;
if( $res === false ) {
}else{
$res=json_decode($res,true);
/* $video_id = $res['id'];*/
echo ":::: ";print_r($res);
}
curl_close($ch);
}catch(\Exception $e){
echo " Exception generated in Try 1 : ".$e->getMessage();
}
echo "<hr>TRY 2<hr>";
$params = array(
"access_token" => $access_token,
"name"=>"file",
"file" => "#".$video_file_path,
"title" => $video_title,
"description" => $video_desc
);
try {
$ret = $facebook->api('/me/videos', 'POST', $params);
print_r($ret);
} catch(\Exception $e) {
echo " Exception generated in Try 2 : ".$e->getMessage();
}
die("</pre>");
}
}
Output I am getting is An active access token must be used to query information about the current user. error and (#353) You must select a video file to upload.
Look at this image
Please tell me how to solve this problem ??
New code tried...................................................
/* code with sdk - object oriented way */
$file=$GLOBALS["all_user_dir_path"].$user_directory."/video.mp4";
$source = array();
$source['name']="video.mp4";
$source['type'] = "video/mp4";
$source['tmp_name'] = $file;
$source['error'] = 0;
$source['size'] = filesize($file);
echo "<br><br>$file<br><br>";
$params = array(
"access_token" => $access_token,
"source" => $source,
"title" => "testvideo",
"description" => "testvideo"
);
try {
$ret = $facebook->api('/me/videos', 'POST', $params);
echo 'Successfully posted to Facebook';
echo "<pre>";print_r($ret);echo "</pre>";
} catch(Exception $e) {
echo $e->getMessage();
}
but this gives (#353) You must select a video file to upload error
Here is the answer
public function shareSocialgrationFB($access_token,& $exception){
$video_id=0;
try{
$config = array();
$config['appId'] = FB_WEB_APP_ID;
$config['secret'] = FB_WEB_SECRET;
$config['fileUpload'] = true;
$config['cookie'] = true;
$facebook = new Facebook($config);
$facebook->setFileUploadSupport(true);
$facebook->setAccessToken($access_token);
$me=$facebook->api("/me");
$email=$me['email'];
$user_directory = str_replace(array(".","#"), "_",$email);
$file = $GLOBALS["all_user_dir_path"].$user_directory."/video.mp4";
$usersFacebookID=$facebook->getUser();
$video_details = array(
'access_token'=> $access_token,
'message'=> 'Testvideo!',
'source'=> '#' .realpath($file),
'title'=>'Test'
);
$post_video = $facebook->api('/'.$usersFacebookID.'/videos', 'post', $video_details);
$video_id=$post_video['id'];
}catch(\Exception $e){
//echo "Exception generated :: ".$e->getMessage();
$exception=$e->getMessage();
// extra code to handle exception
}
return $video_id;
}
Reference : How to POST video to Facebook through Graph API using PHP
I don't know why the info about configurations
$config['fileUpload'] = true;
$config['cookie'] = true;
is not mentioned at below official docs of APIs
https://developers.facebook.com/blog/post/493/
https://developers.facebook.com/docs/graph-api/reference/v2.0/user/videos#publish
However solution given above, worked fine for me.
file is not a valid parameter. Instead of parameter file, use source.
Reference
For FB SDK4+Composer: (see the hardcoded video path, and the encoding).
Doc: https://developers.facebook.com/docs/php/gettingstarted/4.0.0
FB requests the video file to be passed encoded as form-data:
https://developers.facebook.com/docs/graph-api/reference/user/videos/
use Facebook\FacebookSession;
use Facebook\GraphSessionInfo;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
private function postFBVideo($authResponse, $filePath, $formDataMessage)
{
FacebookSession::setDefaultApplication('yourAppkey', 'yourAppSecret');
$ajaxResponse = '';
try {
$session = new FacebookSession($authResponse->accessToken);
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
$ajaxResponse = 'FB Error ->' . json_encode($ex) ;
} catch (\Exception $ex) {
// When validation fails or other local issues
$ajaxResponse = 'FB Validation Error - ' . json_encode($ex) ;
}
if ($session) {
$response = (new FacebookRequest(
$session, 'POST', '/me/videos', array(
'source' => new CURLFile('videos/81JZrD_IMG_4349.MOV', 'video/MOV'),
'message' => $formDataMessage,
)
))->execute();
$ajaxResponse = $response->getGraphObject();
}
return json_encode($ajaxResponse);
}

Box.com shared link on folder

I'm using this php class for box.com
https://github.com/golchha21/BoxPHPAPI
I have made my own function to share a folder like this
public function share_folder($folder_id) {
$url = $this->build_url("/folders/".$folder_id);
$params = array('shared_link' => array('access' => 'open', 'permissions' =>
array('can_download' => 'true', 'can_preview' => 'true')));
return json_decode($this->post($url, json_encode($params)), true);
}
I'm having the same issue as this post.
Access denied error message when trying to create a shared link to a folder in Box
Does anyone have a fix for this or know why it's happening?
Update
I figured it out:
public function share_folder($folder_id) {
$url = $this->build_url("/folders/".$folder_id);
$params = array('shared_link' => array('access' => 'open', 'permissions' =>
array('can_download' => true, 'can_preview' => true)));
return json_decode($this->put($url, $params), true);
I have to change it to put and take off the json_encode
Hope this help someone else
The API is now updated with the sharing function.
<?php
include('library/BoxAPI.class.php');
$client_id = 'CLIENT ID';
$client_secret = 'CLIENT SECRET';
$redirect_uri = 'REDIRECT URL';
$box = new Box_API($client_id, $client_secret, $redirect_uri);
if(!$box->load_token()){
if(isset($_GET['code'])){
$token = $box->get_token($_GET['code'], true);
if($box->write_token($token, 'file')){
$box->load_token();
}
} else {
$box->get_code();
}
}
// Share folder
$params['shared_link']['access'] = 'ACCESS TYPE'; //open|company|collaborators
print_r($box->share_folder('FOLDER ID', $params));
// Share file
$params['shared_link']['access'] = 'ACCESS TYPE'; //open|company|collaborators
print_r($box->share_file('File ID', $params);
?>
Have a look here
Download: BoxPHPAPI

Facebook Graph API PHP SDK posting on page as page

It's final try with PHP, if it fails, I'll try with JS. So my goal is to post on FB page as "Page name" through PHP: this is what I want to get
But all I get is shown pic below. Also, it's visible ONLY to this profile (not to friends/ppl who like/etc.).
This is my current code
function post_facebook($data=null, $redir = null){
$result = "";
require_once (ROOT. "/apps/configuration/models/ConfigurationItem.php");
require_once (ROOT . "/components/facebook/facebook.php");
$this->ConfigurationItem = new ConfigurationItem($this->getContext());
$row=$this->ConfigurationItem->findByCatKeyItemKey('system','facebook_login');
$apiid=$row['value']; <= Correct apiid
$row=$this->ConfigurationItem->findByCatKeyItemKey('system','facebook_pass');
$secret=$row['value']; <= Correct secret key
$facebook = new Facebook(array(
'appId' => $apiid,
'secret' => $secret,
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
$message=$data['facebook_text'];
$attachment = array(
'message' => $data['facebook_text'],
'name' => $data['name'],
'link' => $this->getLinkToLatestNews(),
'description' => '',
);
try {
$facebook->api('/PAGE ID/feed/', 'post', $attachment);
$result = "Facebook: Sent";
} catch (FacebookApiException $e) {
$result = "Facebook: Failed";
error_log($e);
}
} else {
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
exit;
}
echo $result;
exit;
//return $result;
}
What I'm doing wrong? I couldn't find anything in API documentation/top google results, only for JS. Thanks for help!
You'll need to make sure you're requesting the 'manage_pages' permission for the user. Once you've got that you can do $facebook->api('/me/accounts') and you'll receive a token back (along with the page info) that you can use to post on the page as the page.
I struggled with this most of the day, then found that not using setAccessToken(page_access_token) was the only thing preventing it from working for me. I found that in a stackoverflow post from 18 months ago. I'll put my solution here, for anyone who has this question in the future:
protected $scope = "email,publish_stream,manage_pages";
$url = "{$api_url}/{$fbusername}/accounts?access_token=".$access_token;
$response = json_decode(file_get_contents($url));
foreach($response->data as $data) {
try
{
$res = $this->SDK->setAccessToken($data->access_token);
$res = $this->SDK->api(
"{$data->id}/feed",
"POST",
array('link' => 'www.example.com',
'message' => 'This is a test message from php',)
);
log::debug(__FUNCTION__, print_r($res,true));
}
catch (Exception $e)
{
log::debug(__FUNCTION__, $e->getType().": ".$e->getMessage());
}
}
$feed = '/v2.8/' . $pageID . '/' . "feed";
$params = array(
"access_token" => AQUI TU TOKEN // see: https://developers.facebook.com/docs/facebook-login/access-tokens/
);
$params[ "link" ] = "https://zapatillasnewbalancebaratas.blogspot.com/2018/11/zapatilla-new-balance-ml515-col.html";
$params[ "message" ] = "Zapatilla New Balance Ml515 Col";
$params[ "method" ] = POST;
$graph_url = "https://graph.facebook.com" . $feed;
$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, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$output = curl_exec($ch);
echo $output;
curl_close($ch);

Categories