When i type this url direct into browser i get the post sent to user feed wall
https://graph.facebook.com/xx facebook uid xx/feed?access_token=xx app access token xx&message=Welcome%20to%20App!&method=post
But it gives me this error OAuthException: Invalid OAuth access token signature. when i automate the post with this code
<?PHP
include_once "inc/facebook.php";
require_once 'inc/config.php';
// Create our application instance
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
$dbh = new PDO('mysql:dbname='.$db_name.';host='.$db_host.';charset=utf8', $db_username, $db_password );
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare('SELECT fb_id FROM offline_access_users');
$stmt->execute();
$body = array(
'message' => 'Test Multiple Messages',
'link' => '',
'picture' => '',
'name' => '',
'description'=> ''
);
$batchPost=array();
$i=1;
foreach ($stmt as $value) {
$id = $value['fb_id'];
$batchPost[] = array(
'method' => 'POST',
'relative_url' => "/" . $id . "/feed?access_token=" . $access_token,
'body' => http_build_query($body) );
if($i++ == 50) {
try {
$multiPostResponse = $facebook->api('?batch=' . urlencode(json_encode($batchPost)), 'POST');
echo "Success";
} catch(FacebookApiException $e) {
error_log($e);
echo($e);
}
unset($batchPost);
$i=1;
}
}
if(isset($batchPost) && count($batchPost) > 0 ) {
try{
$multiPostResponse = $facebook->api('?batch=' . urlencode(json_encode($batchPost)), 'POST');
echo "Success";
} catch(FacebookApiException $e){
error_log($e);
echo($e);
}
}
$db = null;
?>
I really don't know how to come over this issue. Please help me
Related
I am using this code to post to the user's wall :
require 'fb/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxx',
));
$params = array(
'canvas' => 1,
'scope' => 'publish_stream,email,user_about_me,user_birthday,user_website',
'redirect_uri' => 'urlhere',
);
$fb_session = $facebook->getUser();
// Session based API call.
if ($fb_session)
{
try
{
$args = array(
'message' => $_GET['by'],
'link' => 'linkhere/',
'caption' => $_GET['test']
);
$post_id = $facebook->api("/me/feed", "post", $args);
}
catch (Exception $e)
{
$fb_login_url = $facebook->getLoginUrl($params);
echo $e->getMessage();
}
}
else
{
$fb_login_url = $facebook->getLoginUrl($params);
}
The code is working till the point uuer clicks on login part to post. After that the url contains a code = xxxzz and a state =yyy but the $fb_session is 0.
This works sometimes without any changes. Please help!
You should include the access token when you try to post to some User Facebook wall.
First get access token:
$fbToken = NULL;
$fbToken = $facebook->getAccessToken();
right after $fb_session = $facebook->getUser();
and then include it in the $args array:
'access_token' => $fbToken
if session is NOT created or access token is not valid, you should redirect the user back to re-authorize your Facebook App.
So in ELSE, you should add
header("Location: $fb_login_url ");
after $fb_login_url = $facebook->getLoginUrl($params);
assuming that everything else is correct, but the access_token is not valid, you should also include header("Location: $fb_login_url "); before echo $e->getMessage();
in both cases you are using getloginurl
shouldn't it be
if ($fb_session) {
try {
$args = array(
'message' => $_GET['by'],
'link' => 'linkhere/',
'caption' => $_GET['test']
);
$post_id = $facebook->api("/me/feed", "post", $args);
} catch (Exception $e) {
$fb_logout_url = $facebook->getLogoutUrl;
.
.
.
I have facebook application that posts to its users timeline as status update. I am using the code below to initiate and post the message to all users, but my issue is the post "via name" on all mobile devices (iphone & BB, Samsung).The post appears on feed wall as if the user posted it himself not the application.
<?PHP
require_once '../scripts/config.php';
require_once '../inc/facebook.php';
$facebook = new Facebook(array(
'appId' => $fb_app_id,
'secret' => $fb_secret,
'cookie' => 'true',
));
$dbh = new PDO('mysql:dbname='.$db_name.';host='.$db_host.';charset=utf8', $db_username, $db_password );
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlid = "SELECT SQL_CALC_FOUND_ROWS * FROM offline_access_users";
$sqlmsg = "SELECT message FROM fb_messages WHERE msg_id = (SELECT MAX(msg_id) FROM fb_messages WHERE sent = 'No')";
try {
$userid = $dbh->prepare($sqlid);
$userid->execute();
$id = $userid->fetchAll(PDO::FETCH_COLUMN, 1);
$msg = $dbh->prepare($sqlmsg);
$msg->execute();
$txt = $msg->fetchColumn();
}
catch(PDOException $e)
{
echo $e->getMessage();
die();
}
$counter = 0;
foreach($id as $fbid){
$counter++;
$body = array(
'access_token' => $access_token,
'app_id' => $fb_app_id,
'from' => $fb_app_id,
'message' => $txt,
'display' => "touch",
'redirect_uri' => "http://mydomain.com",
'link' => "",
'picture' => "",
'name' => "",
'caption' => "",
'description' => "",
);
$batchPost=array();
$batchPost[] = array('method' => 'POST', 'relative_url' => "/".$fbid."/feed", 'body' => http_build_query($body));
try {
$multiPostResponse = $facebook->api('?batch='.urlencode(json_encode($batchPost)), 'POST');
$poststs = "Sent Successfully";
}
catch(FacebookApiException $e){
echo $e->getMessage();
error_log($e);
die();
}
}
unset($batchPost);
$dbh = null;
What $access_token are you using? where did the you generate the $access_token?Which $access_token are you using?
The creator of the post (the via...) is whoever created that $access_token - the "from" will always be the owner of the Facebook account regardless of what you place there.
i get an error while trying to automatically post a link with Facebook Graph API
My php code
<?
$config = array();
$config['appId'] = '3545XXXXXXX6207';
$config['secret'] = '60068XXXXXXXXXXXe45a426';
$facebook = new Facebook($config);
$retour_login = json_decode(stripslashes($_GET['session']), true);
$uid = $retour_login['uid'];
$access_token = $retour_login['access_token'];
$me = null;
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
if(!isset($_GET['session'])) { // Asking permissions
$params = array(
'locale' => 'fr_FR',
'display' => 'popup',
'req_perms' => 'email,user_about_me,user_birthday,user_location',
'ext_perms' => 'publish_stream,share_item,manage_pages'
);
header("Location: ".$facebook->getLoginUrl($params));
}
$args = array(
'message' => "XXXX",
'link' => 'XXXX',
'name' => 'XXXX',
'picture' => 'XXXX',
"caption"=> "lien.com",
"type"=> "link");
$post_id = $facebook->api("/me/links", "post", $args); // execute this to automatically post on FB
?>
I get this error : OAuthException: (#282) Requires extended permission: share_item thrown
Any ideas ?
Thanks!
What are 'req_perms' and 'ext_perms' there? the permissions should be in a 'scope' parameter according to the documentation - https://developers.facebook.com/docs/reference/dialogs/oauth/ and https://developers.facebook.com/docs/authentication/
Check you're not working from an outdated example or tutorial - always check the official documentation first
Here is My code :
<?
session_start();
require_once($_SERVER['DOCUMENT_ROOT'].'/admin/config.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/admin/fonctions.php');
include '../api/facebook.php';
include '../api/xhttp.php';
$config = array();
$config['appId'] = '35455XXXXXXX207';
$config['secret'] = '6006855f3aXXXXXXXXX9bce45a426';
$config['fileUpload'] = false; // optional
$facebook = new Facebook($config);
$args = array(
'message' => 'Hello from my App!',
'link' => 'http://www.masteringapi.com/',
'caption' => 'Visit MasteringAPI.com For Facebook API Tutorials!',
'access_token' => $access_token
);
$retour_login = json_decode(stripslashes($_GET['session']), true);
$uid = $retour_login['uid'];
$access_token = $retour_login['access_token'];
$post_id = $facebook->api("/me/feed", "post", $args);
?>
But it returns : Uncaught OAuthException: An active access token must be used to query information about the current user.
Any ideas ?
Thanks!
Here is My new code :
<?
$config = array();
$config['appId'] = '3545XXXXXXX6207';
$config['secret'] = '60068XXXXXXXXXXXe45a426';
$facebook = new Facebook($config);
$retour_login = json_decode(stripslashes($_GET['session']), true);
$uid = $retour_login['uid'];
$access_token = $retour_login['access_token'];
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
if(!isset($_GET['session'])) {
$params = array(
'locale' => 'fr_FR',
'display' => 'popup',
'req_perms' => 'email,user_about_me,user_birthday,user_location',
'ext_perms' => 'publish_stream,share_item,manage_pages'
);
header("Location: ".$facebook->getLoginUrl($params));
}
$args = array(
'message' => "XXXX",
'link' => 'XXXX',
'name' => 'XXXX',
'picture' => 'XXXX',
"caption"=> "lien.com",
"type"=> "link");
$post_id = $facebook->api("/me/links", "post", $args);
?>
This time i get this error : OAuthException: (#282) Requires extended permission: share_item thrown
Any ideas ?
Thanks!
You're not passing it the access token.
Check out getAccessToken().
From your code sample it looks like you are trying to use the variable $access_token to create your $args array, before you define the $access_token variable. I would switch the order of variable definitions:
$retour_login = json_decode(stripslashes($_GET['session']), true);
$uid = $retour_login['uid'];
$access_token = $retour_login['access_token'];
$args = array(
'message' => 'Hello from my App!',
'link' => 'http://www.masteringapi.com/',
'caption' => 'Visit MasteringAPI.com For Facebook API Tutorials!',
'access_token' => $access_token
);
This is assuming $retour_login['access_token'] contains a valid Facebook access token. Otherwise you will need to fetch the current user's access token using the Facebook SDK:
$access_token = $facebook->getAccessToken();
Further to Post to users wall upon facebook app submission (my old question), I have came up with the following code however it doesn't seem to be working?? I thought best to open a new question as it is a new question.
What am I doing wrong? Also, where should this code go?
<?php
$session = $facebook->getSession();
//Is user logged in and has allowed this app to access its data
if (!$session) {
$loginUrl = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'next' => 'enter.php',
'cancel_url' => 'index.php',
));
// use the $loginUrl created on the enter button to request permission;
}
$user_id = $facebook->getUser();
//post to wall
$attachment = array('message' => '<message>',
'name' => '<name here>',
'caption' => '<caption here>',
'link' => '<link to app>',
'description' => '<enter description >',
'picture' => '<enter image url>',
'actions' => array(array('name' => '<enter action label>',
'link' => '<enter action url>')
);
$permissions = $facebook->api("/me/permissions");
if( array_key_exists('publish_stream', $permissions['data'][0]) ) {
// Permission is granted!
// Do the related task
try {
$post_id = $facebook->api('/me/feed', 'post', $attachment);
} catch (CurlException $e) {
//timeout so try to resend
$post_id = $facebook->api('/me/feed', 'post', $attachment);
}
catch (FacebookApiException $e) {
error_log($e);
}
} else {
// We don't have the permission
// Alert the user or ask for the permission!
}
// store the post id in-case you need to delete later
?>
I'll just post the code I'm using that works. Hope it helps
fbClass.php
public function __construct() {
// Naredimo instanco
$facebook = new Facebook(array(
'appId' => $this->fbid,
'secret' => $this->fbsecret,
'cookie' => true,
));
$this->facebook = $facebook;
}
function authUser($facebook) {
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if (!($user)) {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'user_about_me, user_birthday, email, publish_stream',
'redirect_uri' => 'http://apps.facebook.com/myappname/',
));
echo("<script> top.location.href='" . $loginUrl . "'</script>");
} else {
return true;
}
}
process.php
$facebook = $fbClass->facebook;
$fbAuth = $fbClass->authUser($facebook);
if ($fbAuth) {
$res = $facebook->api('/me/feed/', 'post', array(
'message' => MESSAGE,
'name' => NAME,
'caption' => '',
'description' => DESC,
'picture' => PIC,
'link' => 'http://www.facebook.com/myapp/',
'actions' => array('name' => 'Test', 'link' => 'http://apps.facebook.com/myapp/')
));
}
You need a Facebook access token for this code to work. Add your token where My Access token here is in the following code:
$attachment = array(
'access_token' => 'My Access token here',
'message' => '',
'name' => 'My Wall Post Header/Title Here',
'caption' => 'Small caption here',
'link' => 'http://www.mywebsite.org',
'description' => 'Wall Post Details Here',
'picture' => "http://www.mywebsite.org/images/logo.gif",
);
You can get access tokens here.