i want for my app to post on a user's wall on behalf (for advertising e.g.). I think about creating a php script, which i will execute with a cron job on my server every week.
I have the userids in my database.
Now i want that the script gets an userid and then posts on the wall of the user. (of course if the user has got still installed the app and granted the publish stream permission)
is it possible to create a script that triggers this?
$post = $facebook->api("/$user1/feed","POST",$params); or
$post = $facebook->api("/$user2/feed","POST",$params); etc...?
Thank for advise
<?php
require 'src/facebook.php';
$app_id = 'yourappid';
$app_secret = 'yourappsecret';
$app_namespace = 'appname';
$app_url = 'https://apps.facebook.com/' . $app_namespace . '/';
$scope = 'email,publish_actions';
// Init the Facebook SDK
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
// Get the current user
$user = $facebook->getUser();
// If the user has not installed the app, redirect them to the Auth Dialog
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => $scope,
'redirect_uri' => $app_url,
));
print('<script> top.location.href=\'' . $loginUrl . '\'</script>');
}
else {
try {
$params = array(
'message' => "your message",
'name' => "hello world",
'description' => "hello world",
'link' => "hello world",
'picture' => "hello world",
);
$post = $facebook->api("/$user/feed","POST",$params);
echo "";
}
catch (FacebookApiException $e) {
$result = $e->getResult();
}
}
?>
To solve your problem , I will share my code with you .
this worked for me .
You need just to to write some loop while to select all users id from your database .
<?php
//// publish as status
//// publish post to users
require_once("facebook.php");
$app_id = "xxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxx";
$my_url = "http://t.xxxxx.net/facebook/publish.php/"; // refer number
///
$config = array();
$config['appId'] = 'xxxxxxxx';
$config['secret'] = 'xxxxxxxxxxxx';
$config['fileUpload'] = false; // optional
$facebook = new Facebook($config);
///
////
function getAccessToken() {
if ($this->accessToken !== null) {
return $this->accessToken;
}
$this->setAccessToken($this->getApplicationAccessToken());
$user_access_token = $this->getUserAccessToken();
if ($user_access_token) {
$this->setAccessToken($user_access_token);
}
return $this->accessToken;
}
function getApplicationAccessToken() {
return $this->appId.'|'.$this->appSecret;
}
/////////////////////////////// Update status Function
//xxxxxxxx
$session = $facebook->getUser();
// New SDK
$facebook->api ( array(
'method' => 'users.setStatus',
'status' => 'Hi
this new status by my app
',
'uid' => '21511',/// user_id
'session'=>$session,
) );
?>
Related
Years ago I've developed apps for Facebook, but now seems not working old method to get user's information (id, name, etc) and post data on user's wall.
I've used like this, but for now It returns me blank screen:
require_once('FacebookAPI/Facebook.php');
$facebook = new Facebook(array(
'appId' => 'xxxxx',
'secret' => 'xxxxx',
));
$user = $facebook->getUser();
if ($user)
{
try
{
#Code below to post data on user's wall
# Photo Caption
$photoCaption = 'Just used app';
$imageUrl = ('http://example.com'); // Example URL
$link = ('http://www.facebook.com/page/app_xxxx?ref=ts');
# Post Data for Photos API
$post_data = array(
'message' => $photoCaption,
'link' => $link,
'caption' => 'Caption text'
);
$apiResponse = $facebook->api('/me/feed', 'POST', $post_data);
?>
#Code below to show app
<html>
<body bgcolor="#ffffff">
<center>
// link to my app
</center>
</body>
</html>
// Code below to get user's information (name, id)
<?php
$user_profile = $facebook->api('/me');
$coded = $_REQUEST['code'];
$name = $user_profile['name'];
$id = $user_profile['id'];
session_start();
$_SESSION['name'] = $name;
$_SESSION['id'] = $id;
}
catch (FacebookApiException $e)
{
$user = null;
error_log($e);
}
}
else
{ # Code below to get access from user
$redirectUri = 'http://www.facebook.com/mypage/app_xxxx?ref=ts';
$loginUrl = $facebook->getLoginUrl( array(
'scope' => 'publish_stream,photo_upload',
'redirect_uri' => $redirectUri
));
echo("<script>top.location.href = '" . $loginUrl . "';</script>");
}
Could someone help me out to get successfully user's name, id?
You can try this code. Hope you have downloaded latest php-sdk, you have appid,app des
include_once "php-sdk/src/facebook.php";
$app_id = 'your app id';
$facebook = new Facebook(array(
'appId' => 'your app id',
'secret' => 'your app secret'
));
$user = $facebook->getUser();
if ($user) {
$me = $facebook->api('/me');
$name= $me['name'];
$fid=$me['id'];
}
else
{
$loginUrl = "http://www.facebook.com/dialog/oauth?client_id=" .
$app_id . "&redirect_uri=" . urlencode($app_url) . "&scope=email";
echo("<script> top.location.href='" . $loginUrl . "'</script>");
}
I need to create a system that when the cliente publish something in his website it will be published in his facebook, but to do this i need to get the access token because the account need to still logged to my system.
I made my app and tested it in my own facebook and when i try to login by my system it work, but when i try to login with the system in the client facebook, return this error:
An error has occurred. Try again later.
My code to generate the AccessToken is this:
require_once("php-sdk/src/facebook.php"); //Up-to-date SDK files from Git
$app_id = "APP_ID"; //ID do APP
$app_secret = "APP_SECRET"; //Secret do APP
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret
));
$page_id = 'PAGE_ID';
$message = "Teste de integração";
$token_url = 'https://graph.facebook.com/oauth/access_token?'
. 'client_id=' . $app_id
. '&client_secret=' . $app_secret
. '&grant_type=client_credentials';
$token_response = file_get_contents_curl($token_url);
$params = null;
parse_str($token_response, $params);
$app_access_token = $params['access_token'];
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_info = $facebook->api("/$page_id/?fields=access_token");
//print_r($page_info);
if( !empty($page_info['access_token']) ) {
//if(!empty($app_access_token)) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => $message
);
// print_r($args);
// $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, offline_access'));
}
?>
<?php if (!$user): ?>
Login with Facebook
<?php endif ?>
I already try to reconfig the user and all the config from the user is the same from the another account that didnt return the error.
I have this script:
This code should post a Text and a Link to a WebSite
<?
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('facebook.php');
$c = array(
'appId' => '4102137023*****',
'secret' => '*****c4a60cb08*****7c0333*****',
);
$facebook = new Facebook($c);
$uid = $facebook->getUser();
echo "Userid: " . $uid;
echo "<BR>";
?>
<html>
<head></head>
<body>
<?
if($uid){
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'angel-craft.de',
'message' => 'Wenn ihr das hier seht freut euch auf ein Game'
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl( array(
'scope' => 'publish_stream'
));
echo 'Please login.';
echo $e->getType();
echo $e->getMessage();
}
// Give the user a logout link
echo '<br />logout';
} else {
// No user, so print a link for the user to login
// To post to a user's wall, we need publish_stream permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here.
$login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
echo 'Please login.';
}
?>
</body>
</html>
This should post a link with a text
but the Userid($uid) stays empty.
And YES this is the Demo script from FB dev.
I've used this successfully.
<?php
require 'src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '-----',
'secret' => '-----',
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$Name = $me['first_name'];
$properties = array(
array(
'text'=>'Property Link',
'href'=>'http://www.yahoo.com'
),
array(
'text'=>'Property Link',
'href'=>'http://www.yahoo.com'
)
);
// Link that is adjacent to "Like" and "Comment" at the very bottom of the post.
$action_links = array(
'name'=>'Test',
'link'=>'http://www.yahoo.com'
);
// Dictates who can see the post.
$privacy = array(
'value'=>'ALL_FRIENDS'
);
// api('/me/feed', 'post',... = Wall Post.
$wallPost = $facebook->api('me/feed', 'post', array(
'message'=> 'Testing',
'link'=> 'http://www.yahoo.com',
'properties'=>$properties,
'actions'=>$action_links
)
);
} catch (FacebookApiException $e) {
error_log($e);
}
}
$par = array();
$par['req_perms'] = "email, publish_stream";
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl($par);
}
?>
I found the bug, The cert was old. Thanks to all :)
<?php
session_start();
$appid = 'xxxxxxxx'; //Application ID
$appsec = 'xxxxx'; // Application secret
$redirectUrl = 'http://test/tester/'; //Facebook redirects back to this page
$permissions = 'publish_stream,offline_access,read_stream,manage_pages'; // Permissions we will need
$access_token = '';
if(isset($_POST['FacebookPageID']) && strlen($_POST['FacebookPageID'])>10)
{
$_SESSION['FacebookPageID']=$_POST['FacebookPageID'];
$_SESSION['FacebookMessage']=$_POST['FacebookMessage'];
$_SESSION['Facebooktitle']=$_POST['Facebooktitle'];
// $_SESSION['image']=$_POST['image'];
}
if(!is_numeric($_SESSION['FacebookPageID']) || strlen($_SESSION['FacebookPageID'])<5)
{
session_destroy();
die("<meta http-equiv=\"refresh\" content=\"2;URL=".$redirectUrl."\" />");
}
else
{
if(!isset($_GET["code"]))
{
$_SESSION['state'] = md5(uniqid(rand(), TRUE));
$RedirectToFacebook = "https://www.facebook.com/dialog/oauth?client_id=".$appid;
$RedirectToFacebook .="&redirect_uri=".urlencode($redirectUrl.'process.php');
$RedirectToFacebook .="&state=".$_SESSION['state'];
die("<script type=\"text/javascript\">top.location.href='" . $RedirectToFacebook . "';</script>
<noscript><a href='".$RedirectToFacebook."'>Needs Permissioins</a></noscript>");
}
else
{
############## Facebook Page ID ############
$facebookPageID = $_SESSION['FacebookPageID'];
//$target_path = $_SESSION['image'];
############## Wall Message ############
$facebookMessage = (empty($_SESSION['FacebookMessage']) || strlen($_SESSION['FacebookMessage'])<5)?"Nice Facebook Wall Posting Script!":$_SESSION['FacebookMessage'];
if($_GET['state'] == $_SESSION['state'])
{
$AccessTokenUrl = "https://graph.facebook.com/oauth/access_token?client_id=".$appid;
$AccessTokenUrl .="&redirect_uri=".urlencode($redirectUrl.'process.php');
$AccessTokenUrl .="&client_secret=".$appsec;
$AccessTokenUrl .="&code=".$_GET["code"];
$ReturnedString = file_get_contents($AccessTokenUrl);
$params=null;
parse_str($ReturnedString, $params);
$OurAccessToken = $params['access_token']; //access token
//---------------
require_once('src/facebook.php' ); //Include our facebook Php Sdk
$post_url = '/'.$facebookPageID.'/feed';
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsec,
));
//the Posting Parameters
$PostData = array(
'message' => 'uffcaffnews.com',
'name' => $Facebooktitle,
'caption' => "test.fff.com",
'link' => 'http://www.fff.com/assets/ajax-post-on-page-wall',
'description' => $facebookMessage,
'picture' => "http://test.c/images/desc.jpg",
'access_token' =>$OurAccessToken,
'actions' => array(
array(
'name' => 'Saaraan',
'link' => 'http://www.saaraan.com'
)
)
);
try {
$pageID = '3xxx';
$result = $facebook->api($post_url, 'post', $PostData);
if($result)
{
session_destroy();
echo 'Done..';
die("<meta http-equiv=\"refresh\" content=\"2;URL=".$redirectUrl."?");
}
}
i want to post stories to facebook page from my website admin without logging in to the facebook account.please help mei want to post stories to facebook page from my website admin without logging in to the facebook account.please help me
You don't need the offline_access permission to post content to Facebook. Only the publish_stream permission is needed.
Even if no user login is required. Once the user authorize your app with the publish_stream permission, you can start posting content on his behalf without the need of him to login!
You may refer here.
I need my application to publish a post on my Wall page automatically and for that use PHP-SDK, but the publication does not appear. Until the notification that the publication occurred, but it does not appear in the Wall page. In the same script, if I change the page_id by "me" the publication is made in the wall of my profile perfectly.
See code:
$fb_page_id = 'xxxxxxxxxx';
$fb_app_id = 'xxxxxxxxxxxxxxxxxxxx';
$fb_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$fb_app_url = 'https://apps.facebook.com/application/';
$fb_app_baseUrl ="http://www.mysite.com/app/application/";
$msg = array(
'message' => 'date: ' . date('Y-m-d') . ' time: ' . date('H:i')
);
//construct the message/post by posted data
$msg['message'] = 'Test';
$msg['link'] = $link;
$msg['picture'] = "http://www.mysite.com/app/facebook/icone_75_75.jpg";
$msg['name'] = $titulo;
$msg['caption'] = '';
$msg['description'] = $texto;
$msg['actions'] = array( array('name' => 'test', 'link' => 'http://www.mysite.com'));
//Create facebook application instance.
$facebook = new Facebook(array(
'appId' => $fb_app_id,
'secret' => $fb_secret
));
try {
$facebook->api('/'.$fb_page_id.'/feed', 'POST', $msg);
} catch (FacebookApiException $e) {
print_r($e);
}
thanks.
Now I created a database for storing received tokens. I used the token to post, but did not work!