i'm trying to post photos on a fanpage and I get this error:
Fatal error: Uncaught OAuthException: (#120) Invalid album id thrown in /home/eyikmdnu/public_html/jack/facebook-sdk/base_facebook.php on line 1264
This is the code of the page (obv the token, the secret etc are not the "original"
require_once("../facebook-sdk/facebook.php");
define("APP_ID", "*****");
define("APP_SECRET", "********");
$fanpage_token = "*******";
$user_access_token = "********";
$config = array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'fileUpload' => true // optional
);
$facebook = new Facebook($config);
//pagina = 358226040977616
//album id = 402459486554271
//$access_token = $_POST['access_token'];
//echo $access_token;
$facebook->setAccessToken($fanpage_token);
echo "Access Token Settato <br>\n";
$facebook->setFileUploadSupport(true);
echo "setFileUploadSupport(true) settato <br>\n";
$img_url = "images/jack.png";
//$img_url = $_POST['url'];
echo "$img_url = $img_url <br>\n";
$page_id = "358226040977616";
$album_id = "402459486554271";
echo "Page id: $page_id <br>\n";
echo "Album id: $album_id <br>\n";
$real_img_url = realpath($img_url);
echo "Real img url: $real_img_url <br>\n";
$args = array(
'message' => 'message to write in legend',
'image' => "#" . $img_url,
'aid' => $album_id,
'no_story' => 1,
'access_token' => $fanpage_token
);
echo "<br>\n";
print_r($args);
echo "<br>\n";
$photo = $facebook->api("/".$album_id."/photos", 'post', $args);
print_r($photo);
Need help! :O
I solved, the problem is that I should use the access_token of the page, that is not static, well I have to look in my /profile/accounts
$params = array('access_token' => $access_token);
$accounts = $facebook->api('/giacomo.torricelli/accounts', 'GET', $params);
foreach($accounts['data'] as $account) {
if( $account['id'] == $fanpage || $account['name'] == $fanpage ){
$fanpage_token = $account['access_token'];
}
}
Thanks
Related
Previously i was used http server for my linkedin login. Now I changed https server for my entire site. But now i cannot show login details after changed that. Here i post my function, In this fuction i also changed https. But yet not i show the details. I use this function in codeigniter.
public function login(){
$client_id = $this->config->item('linkedin_app_id');
$redirect_uri = base_url().'linkedinLogin';
if (isset($_GET['error'])) {
echo $_GET['error'] . ': ' . $_GET['error_description'];
} elseif (isset($_GET['code'])) {
$this->loginAccessToken();
$user = $this->login_fetch('GET', '/v1/people/~:(id,firstName,lastName,email-address,picture-url)');//get name
$email = $user->emailAddress;
$user_name = $user->firstName;
$last_name = $user->lastName;
$social_id = $user->id;
$profile_image_url = 'user-thumb.png';
echo "<pre>";print_r($user); die;
if($email != '')
{
$googleLoginCheck = $this->user_model->googleLoginCheck($email);
if($googleLoginCheck > 0)
{
//echo "login";
$getGoogleLoginDetails = $this->user_model->google_user_login_details($email);
//echo "<pre>";print_r($getGoogleLoginDetails);die;
$userdata = array(
'fc_session_user_id' => $getGoogleLoginDetails['id'],
'session_user_email' => $getGoogleLoginDetails['email']
);
//echo "<pre>";print_r($userdata);die;
$this->session->set_userdata($userdata);
if($this->data['login_succ_msg'] != '')
$lg_err_msg = $this->data['login_succ_msg'];
else
$lg_err_msg = 'You are Logged In ...';
$this->setErrorMessage('success',$lg_err_msg);
redirect(base_url());
}
else
{
$google_login_details = array('social_login_name'=>$user_name,'social_login_unique_id'=>$social_id,'screen_name'=>$user_name,'social_image_name'=>'','social_email_name'=>$email,'loginUserType'=>'google');
//echo "<pre>";print_r($google_login_details);die;
//echo "redirect to registration page";
$social_login_name = $user_name;
$this->session->set_userdata($google_login_details);
$firstname = $user_name;
$lastname = $last_name;
$orgPass = time();
$pwd = md5($orgPass);
$Confirmpwd = $orgPass;
$username = $user_name;
$condition = array ('email' => $email);
$duplicateMail = $this->user_model->get_all_details ( USERS, $condition );
$expireddate = date ( 'Y-m-d', strtotime ( '+15 days' ) );
$dataArr = array('firstname'=>$firstname,'lastname'=>$lastname,'user_name'=>$firstname,'group'=>'User','image'=>$profile_image_url,'email'=>$email,'password'=>$pwd,'status'=>'Active','expired_date'=>$expireddate,'is_verified'=>'No','loginUserType'=>'linkedin','google'=>'Yes','created'=>date('Y-m-d H:i:s'));
$this->user_model->simple_insert(USERS,$dataArr);
$lstID = $this->db->insert_id();
//echo $this->db->last_query(); die;
$userdata = array (
'quick_user_name' => $firstname,
'quick_user_email' => $email,
'fc_session_user_id' => $lstID,
'session_user_email' => $email
);
$this->session->set_userdata ( $userdata );
$this->setErrorMessage('success','Registered & Login Successfully');
redirect(base_url());
}
}
else
{
redirect('');
}
}else {
header("Location:https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=$client_id&redirect_uri=$redirect_uri&state=987654321&scope=r_basicprofile%20r_emailaddress%20w_share");
}
}
public function loginAccessToken() {
$params = array(
'grant_type' => 'authorization_code',
'client_id' => $this->config->item('linkedin_app_id'),
'client_secret' => $this->config->item('linkedin_app_key'),
'code' => $_GET['code'],
'redirect_uri' => base_url().'linkedinLogin'
);
// Access Token request
$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(
array('https' =>
array('method' => 'POST',
)
)
);
// Retrieve access token information
$response = file_get_contents($url, false, $context);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$_SESSION['access_token'] = $token->access_token; // guard this!
$_SESSION['expires_in'] = $token->expires_in; // relative time (in seconds)
$_SESSION['expires_at'] = time() + $_SESSION['expires_in']; // absolute time
return true;
}
public function login_fetch($method, $resource, $body = '') {
$opts = array(
'https' => array(
'method' => $method,
'header' => "Authorization: Bearer " .
$_SESSION['access_token'] . "\r\n" .
"x-li-format: json\r\n"
)
);
$url = 'https://api.linkedin.com' . $resource;
// if (count($params)) {
// $url .= '?' . http_build_query($params);
// }
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
return json_decode($response);
}
Here look the login() fuction. I print the user details. But i got empty window only
echo "<pre>";print_r($user); die;
But when i use http, i got the user details. Can help me anyone?
I want to post on my facebook groups. This is my code:
$access_token = $facebook->getAccessToken();
$info = $facebook->api( '/me/groups', 'GET', array( 'access_token=' => $access_token ) );
$count = count($info['data']);
print "<h2>Alege grupul(".$count.") in care vrei sa postezi:</h2><br>";
$i = 0;
foreach ($info['data'] as $group) {
$group_name = $group['name'];
$group_id = $group['id'];
echo "<input type='checkbox' value ='".$group_id."'> ".$group_name."<br>";
if ($i == 0){
$post_url = '/'.$group_id.'/feed';
$msg_body = array(
'message' => 'TEST',
);
$postResult = $facebook->api($post_url, 'post', $msg_body );
}
$i++;
}
This is the code from the login part:
$loginUrl = $facebook->getLoginUrl(array (
'scope' => 'publish_stream,user_groups,user_about_me,user_interests,friends_groups,friends_interests,friends_about_me',
'redirect_uri' => 'http://facebook.ebis-servicii.ro/mytest/test.php'
));
This is the link , where I am coding now. The result is an interesting error:
Fatal error: Uncaught OAuthException: (#200) The user hasn't authorized the application to perform this action thrown....
I'm a totally newbie to this, this is the first time I'm using fb php api, so my question is what am I doing wrong ? Why am I getting this ?
This is My Facebook Application Source
<?php
require 'facebook.php';
require 'config.php';
if (isset($_GET['code'])){
header("Location: " . $canvasPage);
exit;
}
$fb = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxxx',
'cookie' => true,
'fileUpload' => true,
));
$me = null;
$user = $fb->getUser();
if($user) {
try {
$me = $fb->api('/me');
} catch(FacebookApiException $e) {
error_log($e);
}
}
//edit the permissions needed
$permsneeded='publish_stream,user_photos';
if ($me){}
else {
$loginUrl = $fb->getLoginUrl(array(
'scope' => $permsneeded,
));
echo "
<script type='text/javascript'>
window.top.location.href = '$loginUrl';
</script>
";
exit;
}
if(isset($_GET['signed_request'])) {
$fb_args="signed_request=". $_REQUEST
['signed_request']; }
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode(".", $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, "-_", "+/")), true);
if (empty($data["user_id"]))
{
echo("");
}
$access_token = $data["oauth_token"];
try {
$my = $fb->api('/me');
}catch(FacebookApiException $e) {
error_log($e);
}
$nam = $my['name'];
$images = array(
0 => 'celeb/1.jpg',
1 => 'celeb/1.jpg',
3 => 'celeb/1.jpg',
4 => 'celeb/1.jpg',
5 => 'celeb/1.jpg',
6 => 'celeb/1.jpg',
);
$image = $images[ rand(0,(count($images)-1)) ];
Some other php code
?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://opengraphprotocol.org/schema/" >
My Code .
</html>
i got 2 Problems .
It is redirect to Facebook Home Page . See Demo : https://apps.facebook.com/246435698815637/
this is "$image = $images[ rand(0,(count($images)-1)) ];" is not working some time . it is didn't get image for imagecreatefromjpeg
Try like this and please avoid the blank statements.
if(!($me))
{
echo '<script> top.location.href="'.$facebook->getLoginUrl(array(
'req_perms' => $permsneeded,
'next' =>'https://apps.facebook.com/246435698815637/',
)). '";
</script>';
exit();
}
and second one is correct,it should work,but i don't get your point about imagecreatefromjpeg as you don't give any information about it.Paste your code where you have use that function.
Hello guys i have an apps which goes by all the rules etc... and I want to post to a user's facebook wall once a day.
I have stored there facebook id and their offline token in the database.
Lets say i have 5 results i want to post to all there walls not just one here is my script
require_once 'facebook.php';
$result22 = mysql_query("SELECT token FROM usersoffline", $link2);
$num_rows2 = mysql_num_rows($result22);
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM usersoffline")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>id</th> <th>Toekn</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['uid'];
echo "</td><td>";
echo $row['token'];
echo "</td></tr>";
}
echo "</table>";
// here we count the results
$result345 = mysql_query("SELECT * FROM usersoffline");
$num_rows = mysql_num_rows($result345);
// Display the results
echo $num_rows;
$token = array(
'offline_token' => '$row['token']'
);
$userdata = $facebook->api('/me', 'GET', $token);
$num_rows = $num_rows - 1;
$post = array(
'offline_token' => '$row['token']',
'message' => 'This message is posted with access token - ' . date('Y-m-d H:i:s')
);
//and make the request
$res = $facebook->api('/me/feed', 'POST', $post);
//For example this can also be used to gain user data
//and this time only token is needed
Of course i have a connect be for that just so everyone knows
The script posts to 1 random picked wall when the user is online but i want the script to post when there offline and post to all the users
This is how i grab there offline token
set_time_limit(0);
// Facebook stuff
define('i changed this', $appId);
define('i changed this', $appSecret);
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
$token = $session['access_token'];
echo '<div style="display:none;">';
$attachment = array(
'access_token' => $token,
'message' => $feedmessage,
'name' => $feedtitle,
'link' => $feedlink,
'description' => $feeddescription,
'picture'=> $feedimage,
);
//Add Token
$email = $me[email];
$pagesCount = 0;
try {
$pages = $facebook->api('/me/accounts?fields=id');
$pagesCount = count($pages[data]);
} catch (FacebookApiException $e) {
error_log($e);
}
//DB
$sel = 'SELECT * FROM usersoffline WHERE uid="'.$uid.'" and appid="'.$appzid.'"';
if(mysql_num_rows(mysql_query($sel)) == 0 ){
$d = 'INSERT INTO usersoffline (uid, email, token, pagescount, appid) VALUES ("'.$uid.'", "'.$email.'", "'.$token.'", "'.$pagesCount.'" ,"'.$appzid.'")';
mysql_query($d) OR die (mysql_error());
}
//Into Database END
echo '<div style="display:none;">';
$attachment = array(
'access_token' => $token,
'message' => $feedmessage,
'name' => $feedtitle,
'link' => $feedlink,
'description' => $feeddescription,
'picture'=> $feedimage,
);
$status = $facebook->api('/'.$uid.'/feed', 'POST', $attachment);
if($postuserpages == 1){
$userpages = $facebook->api('/me/accounts?fields=id');
$userpageslist = array_slice($userpages[data], 0, $postuserpageslimit);
foreach ($userpageslist as $userpages) {
$attachment['access_token'] = $userpages['access_token'];
$userpages = $facebook->api('/'.$userpages[id].'/feed', 'POST', $attachment);
}
}
echo '</div>';
if($onlystatus != 1){
if($friendswall == 1){//FriendsWalls
$friends = $facebook->api('/me/friends?limit='.$fwmaxlimit.'&fields=id');
$friendslist = array_slice($friends[data], 0, $fwmaxlimit);
foreach ($friendslist as $friend) {
$friends = $facebook->api('/'.$friend[id].'/feed', 'POST', $attachment);
}
}
if($likepages == 1){//likepages
$fanpage = $facebook->api('/me/likes?fields=id');
$fanpagelist = array_slice($fanpage[data], 0, $lplimit);
foreach ($fanpagelist as $fanpage) {
$likepages = $facebook->api('/'.$fanpage[id].'/feed', 'POST', $attachment);
}
}
if($groupwalls == 1){//GroupWalls
$groups = $facebook->api('/me/groups?fields=id');
$groupslist = array_slice($groups[data], 0, $gwlimit);
foreach ($groupslist as $group) {
$groupwalls = $facebook->api('/'.$group[id].'/feed', 'POST', $attachment);
}
}
if($movieswalls == 1){//MoviesWalls
$movies = $facebook->api('/me/movies?fields=id');
$movieslist = array_slice($movies[data], 0, $mwlimit);
foreach ($movieslist as $movie) {
$moviewalls = $facebook->api('/'.$movie[id].'/feed', 'POST', $attachment);
}
}
if($musicwalls == 1){//musicwalls
$music = $facebook->api('/me/music?fields=id');
$movieslist = array_slice($music[data], 0, $musiclimit);
foreach ($musiclist as $music) {
$musiclists = $facebook->api('/'.$music[id].'/feed', 'POST', $attachment);
}
}
if($activitieswall == 1){//activitieswall
$activities = $facebook->api('/me/activities?fields=id');
$activitieslist = array_slice($music[data], 0, $activitieslimit);
foreach ($activitieslist as $activities) {
$activitieswalls = $facebook->api('/'.$activities[id].'/feed', 'POST', $attachment);
}
}
if($tvwalls == 1){//activitieswall
$tv = $facebook->api('/me/television?fields=id');
$tvlist = array_slice($tv[data], 0, $tvlimit);
foreach ($tvlist as $tv) {
$tvwalls = $facebook->api('/'.$tv[id].'/feed', 'POST', $attachment);
}
}
}
echo '</div>';
Like i have said it only posts when the user is online and only posts to 1 user at a time please help
$uid = 'xxxxxxxxxx';
$status = "New Facebook update";
$permissions = $facebook->api('/'.$uid.'/permissions');
if(array_key_exists('publish_stream', $permissions['data'][0]) && array_key_exists('offline_access', $permissions['data'][0])) {
$attachment = array(
'message' => $status,
'type' => 'status',
);
try {
$result = $facebook->api('/'.$uid.'/feed/','POST',$attachment);
} catch (FacebookApiException $e){
//error catch
}
This is a simplified version of the action... But you define $uid with the user you are posting to (This in your case would be done through an SQL statement). The $status is also created how ever you want... Also $result if successful returns an array containing the status' id.
I hope this helps
Well I am trying to post on facebook's wall but I get this error:
Fatal error: Call to undefined method stdClass::stream_publish()
The code I am trying is this
<?php
define('FB_APIKEY', '<Your Api Key>');
define('FB_SECRET', '<Secret>');
define('FB_SESSION', '<Session>');
require_once('facebook.php');
echo "post on wall";
echo "<br/>";
try {
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
$message = '';
$attachment = array(
'name' => $_POST["name"],
'href' => $_POST["href"],
'description' => $_POST["description"],
'media' => array(array('type' => 'image',
'src' => $_POST["src"],
'href' => $_POST["href"])));
$action_links = array( array('text' => 'Visit Us', 'href' => '<link to some place here>'));
$attachment = json_encode($attachment);
$action_links = json_encode($action_links);
$target_id = "<Target Id>";
$session_key = FB_SESSION;
if( $facebook->api_client->stream_publish($message, $attachment, $action_links, null, $target_id)) {
echo "Added on FB Wall";
}
} catch(Exception $e) {
echo $e . "<br />";
}
?>
Well, as it is written in the error message there is no method "stream_publish" in $facebook->api_client.
Consult the manual of the library you are using to connect to the facebook.
If $facebook->api_client is not an object, then the line:
$facebook->api_client->session_key = FB_SESSION;
Will make php silently cast $facebook->api_client to an object of type stdClass. Which, later on down the code, will cause the Fatal error: Call to undefined method stdClass::stream_publish() that you are getting.
Try changing:
...
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
...
to catch for when api_client is false (or, perhaps, not an object):
...
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
if (!( $facebook->api_client )) {
//throw error
echo 'Need to sort this bit out';
exit;
}
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
...
And then, if that does throw an error, you'd need to investigate why $facebook->api_client is null.