Facebook Graph API PHP SDK posting on page as page - php

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

Related

PHP Discord OAUTH2 code sample not working

So this code I found below doesn't work I get to the authenticate screen then when t redirects me it just says Not logged in, Login in again. Does anyone know what I have to do to fix this? I am not very good at OATH2 and would like someone to walk me through.
I used the code from this gist.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('max_execution_time', 300); //300 seconds = 5 minutes. In case if your CURL is slow and is loading too much (Can be IPv6 problem)
error_reporting(E_ALL);
define('OAUTH2_CLIENT_ID', '1234567890');
define('OAUTH2_CLIENT_SECRET', 'verysecretclientcode');
$authorizeURL = 'https://discord.com/api/oauth2/authorize';
$tokenURL = 'https://discord.com/api/oauth2/token';
$apiURLBase = 'https://discord.com/api/users/#me';
session_start();
// Start the login process by sending the user to Discord's authorization page
if(get('action') == 'login') {
$params = array(
'client_id' => OAUTH2_CLIENT_ID,
'redirect_uri' => 'https://yoursite.location/ifyouneedit',
'response_type' => 'code',
'scope' => 'identify guilds'
);
// Redirect the user to Discord's authorization page
header('Location: https://discordapp.com/api/oauth2/authorize' . '?' . http_build_query($params));
die();
}
// When Discord redirects the user back here, there will be a "code" and "state" parameter in the query string
if(get('code')) {
// Exchange the auth code for a token
$token = apiRequest($tokenURL, array(
"grant_type" => "authorization_code",
'client_id' => OAUTH2_CLIENT_ID,
'client_secret' => OAUTH2_CLIENT_SECRET,
'redirect_uri' => 'https://yoursite.location/ifyouneedit',
'code' => get('code')
));
$logout_token = $token->access_token;
$_SESSION['access_token'] = $token->access_token;
header('Location: ' . $_SERVER['PHP_SELF']);
}
if(session('access_token')) {
$user = apiRequest($apiURLBase);
echo '<h3>Logged In</h3>';
echo '<h4>Welcome, ' . $user->username . '</h4>';
echo '<pre>';
print_r($user);
echo '</pre>';
} else {
echo '<h3>Not logged in</h3>';
echo '<p>Log In</p>';
}
if(get('action') == 'logout') {
// This must to logout you, but it didn't worked(
$params = array(
'access_token' => $logout_token
);
// Redirect the user to Discord's revoke page
header('Location: https://discordapp.com/api/oauth2/token/revoke' . '?' . http_build_query($params));
die();
}
function apiRequest($url, $post=FALSE, $headers=array()) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
if($post)
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$headers[] = 'Accept: application/json';
if(session('access_token'))
$headers[] = 'Authorization: Bearer ' . session('access_token');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
return json_decode($response);
}
function get($key, $default=NULL) {
return array_key_exists($key, $_GET) ? $_GET[$key] : $default;
}
function session($key, $default=NULL) {
return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
}
?>
EDIT: Basically in the if statement it doesn't go into the logged-in part.
Here is a working solution
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
$SecretHERE = "";
$IDHERE = "";
if (isset($_GET["error"])) {
echo json_encode(array("message" => "Authorization Error"));
} elseif (isset($_GET["code"])) {
$redirect_uri = "https://www.devtest.net/v4/login.php";
$token_request = "https://discordapp.com/api/oauth2/token";
$token = curl_init();
curl_setopt_array($token, array(
CURLOPT_URL => $token_request,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
"grant_type" => "authorization_code",
"client_id" => $IDHERE,
"client_secret" => $SecretHERE,
"redirect_uri" => $redirect_uri,
"code" => $_GET["code"]
)
));
curl_setopt($token, CURLOPT_RETURNTRANSFER, true);
$resp = json_decode(curl_exec($token));
curl_close($token);
if (!isset($_SESSION['user']) || !isset($_SESSION['userguilds'])) {
if (isset($resp->access_token)) {
$access_token = $resp->access_token;
$info_request = "https://discordapp.com/api/users/#me";
$info_request_guilds = "https://discord.com/api/users/#me/guilds";
$info = curl_init();
curl_setopt_array($info, array(
CURLOPT_URL => $info_request,
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer {$access_token}"
),
CURLOPT_RETURNTRANSFER => true
));
$user = json_decode(curl_exec($info));
curl_close($info);
// GUILDS REQUEST
$info_guilds = curl_init();
curl_setopt_array($info_guilds, array(
CURLOPT_URL => $info_request_guilds,
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer {$access_token}"
),
CURLOPT_RETURNTRANSFER => true
));
$guilds = json_decode(curl_exec($info_guilds));
curl_close($info_guilds);
$_SESSION['user'] = $user;
if ($_SESSION['user']->verified == 1) {
$_SESSION['userguilds'] = $guilds;
$_SESSION['avatar'] = "https://cdn.discordapp.com/avatars/" . $user->id . "/" . $user->avatar . ".png";
header("Location: https://www.devtest.net/v4/fork.php");
die();
}else{
print_r("Please verify your Discord Account.");
session_destroy();
die();
}
} else {
echo json_encode(array("message" => "Authentication Error"));
}
} else{
// They are already logged in so redirect them to fork.php
header("Location: https://www.devtest.net/v4/fork.php");
die();
}
} else {
// Redirect to Discord Oauth2 URL (CAN BE FOUND IN DISCORD DEV PORTAL)
header('location: https://discord.com/api/oauth2/authorize?client_id=CLIENTIDHERE&redirect_uri=https%3A%2F%2Fwww.devtest.net%2Fv4%2Flogin.php&response_type=code&scope=identify%20email%20connections%20guilds%20guilds.join');
die();
}
?>

Go to webinar custom landing page

I using gotowebinar service to register user from custom landing page:
API LINK https://goto-developer.logmeininc.com/
How to create the right flow to register user into webinar?
and how to get organizer_id ??
thanks
here my code.
$webinar_id = "336-174-566";
$gtwPost = array(
"firstName" => $contact_data['FirstName'],
"lastName" => $contact_data['LastName'],
"email" => $contact_data['Email']
);
$gtwHeaders = array(
"Accept:application/vnd.citrix.g2wapi-v1.1+json",
"Content-Type:application/json",
"Authorization:OAuth oauth_token=xxxxxxxxxx"
);
$this->data['gtw'] = array(
'post' => $gtwPost,
'headers' => $gtwHeaders
);
//Set POST URL for GoToWebinar
$gtw_url = "https://api.citrixonline.com/G2W/rest/organizers/".$organizer_id."/webinars/".$webinar_id."/registrants";
//Start GoToWebinar submission
$curl = #curl_init();
#curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($gtwPost));
#curl_setopt($curl, CURLOPT_URL, $gtw_url);
##curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#curl_setopt($curl, CURLOPT_POST, 1);
#curl_setopt($curl, CURLOPT_HTTPHEADER, $gtwHeaders);
#curl_exec($curl);
$info = #curl_getinfo($curl);
#curl_close($curl);
//End GoToWebinar registrant submission
Solution here, in git hub
https://github.com/zakir-hyder/Citrix-GoToWebinar-PHP-Library
you have to create application first, after provide details to the script:
$citrix = new Citrix('API Key');
$citrix->set_organizer_key('organizer_key');
$citrix->set_access_token('access_token');
code example:
<?php
include "citrix.php";
$citrix = new Citrix('API Key');
$citrix->set_organizer_key('organizer_key');
$citrix->set_access_token('access_token');
try
{
$organizer_key = $citrix->get_organizer_key();
$citrix->pr($organizer_key);
}catch (Exception $e) {
$citrix->pr($e->getMessage());
}
try
{
$webinars = $citrix->citrixonline_get_list_of_webinars() ;
$citrix->pr($webinars);
}catch (Exception $e) {
$citrix->pr($e->getMessage());
}
try
{
$response = $citrix->citrixonline_create_registrant_of_webinar('webinar id', $data = array('first_name' => 'First Name', 'last_name' => 'Lastnmae', 'email'=>'email#email.com')) ;
$citrix->pr($response);
}catch (Exception $e) {
$citrix->pr($e->getMessage());
}
try
{
$webinars = $citrix->get_registrants_of_webinars('webinar id') ;
$citrix->pr($webinars);
}catch (Exception $e) {
$citrix->pr($e->getMessage());
}
try
{
$citrix->citrixonline_delete_registrant_of_webinar('webinar id', 'registrant id') ;
}catch (Exception $e) {
$citrix->pr($e->getMessage());
}

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

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

Posting to facebook page with cron 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' ) );

Categories