I am currently trying to upload photos to pages and groups through an app. I have these codes:
try
{
$facebook->setFileUploadSupport(true);
$args = array('message' => 'This is my image caption',);
$args['image'] = '#'.realpath('./uploads/terragarden1.png');
$response = $facebook->api('/GROUP_ID/photos/','POST',$args);
}
catch(FacebookApiException $e)
{
echo "Error: ".$e;
}
The value of $args['image'] would be something like this:
#/home/publica/public_html/AutoPost/uploads/terragarden1.png
The problem is that it throws an OAuthException: An unknown error has occurred. I don't quite know what to do with this kind of error.
Additional:
When I try to post image using the same code and just changing
$response = $facebook->api('/GROUP_ID/photos/','POST',$args);
into $response = $facebook->api('/me/photos/','POST',$args);, the image would successfully be posted on the user's wall. What might be the problem here?
This works fine for me on pages:
$attachements = array(
'access_token' => $page->getToken(),
'message' => $post_pub['title'],
'url' => 'http://site.com/images/your_image.png' );
try{
$result = $facebook->api('/'.$page->getIdFacebook().'/photos', 'POST', $attachements, function(){
});
}
catch(Exception $e){ }
Might want to try switching from 'image' to 'url'
I got the same issue.
There is a topic about it here: https://developers.facebook.com/bugs/1430985030446221?browse=external_tasks_search_results_527428908614f7c36099745
I've been tried to do this with js sdk, with the same error response.
Related
I'm trying to publish a picture to an album belonging to a Facebook page, using the Facebook PHP SDK v5.
I've already checked the (many) similar questions, however they are all related to prior versions of the SDK, when publish_actions was still allowed.
My Setup:
My app is properly configured and I was able to retrieve my access token
I was able to run a few test API queries with no issues
I'm the admin of this page and my access token has the following permissions ['manage_pages','publish_pages','user_photos']
The SDK was properly initialized with 'fileUpload' => true as a parameter
Code publishing the picture to the album
It is based on the example provided in the SDK documentation.
<?php
require_once __DIR__.'/vendor/autoload.php';
$fb = new Facebook\Facebook(['app_id' => '123456', 'app_secret' => '123456', 'default_graph_version' => 'v3.3', 'fileUpload' => true]);
$picture = 'https://www.example.com/pic.jpg';
$album_id = '123456';
$access_token = 'mytoken';
try {
$response = $fb->post('/'.$album_id.'/photos', array ('url' => $picture), $access_token);
}
catch(Facebook\Exceptions\FacebookResponseException $e) {
die('Graph returned an error: ' . $e->getMessage());
}
catch(Facebook\Exceptions\FacebookSDKException $e) {
die('Facebook SDK returned an error: ' . $e->getMessage());
}
$graphNode = $response->getGraphNode();
Here's the error I'm getting
Graph returned an error: (#200) This endpoint is deprecated since the
required permission publish_actions is deprecated
Indeed, changes introduced in April 2018 removed the ability to use publish_actions however it seems the documentation has not been updated accordingly.
What is the new way to publish a picture to a page's album?
Your help is much appreciated!
After several hours of researching alternate solutions, I was able to find a workaround.
Apparently I was using an User Access Token instead of the Page Access Token.
Solution
1 - First, verify if your token is a User/Page Access token
2 - If it is an User Token, you need to request the Page Access Token instead:
$user_access_token = 123456;
$page_id = 123456; // Can be retrieved via right click on your page logo + Copy link address
$response = $fb->get('/'.$page_id.'?fields=access_token', $user_access_token);
$page_access_token = json_decode($response->getBody())->access_token;
echo $page_access_token;
3 - Finally, post the picture on the Page using the Page Access Token
Full code
<?php
require_once __DIR__.'/vendor/autoload.php';
$fb = new Facebook\Facebook(['app_id' => '123456', 'app_secret' => '123456', 'default_graph_version' => 'v3.3', 'fileUpload' => true]);
$picture = 'https://www.example.com/pic.jpg';
$album_id = '123456';
$user_access_token = 'mytoken';
$page_id = 123456;
try {
$response = $fb->get('/'.$page_id.'?fields=access_token', $user_access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
die('Graph returned an error: ' . $e->getMessage());
} catch(Facebook\Exceptions\FacebookSDKException $e) {
die('Facebook SDK returned an error: ' . $e->getMessage());
}
$page_access_token = json_decode($response->getBody())->access_token;
try {
$response = $fb->post('/'.$album_id.'/photos', array ('url' => $picture), $page_access_token);
}
catch(Facebook\Exceptions\FacebookResponseException $e) {
die('Graph returned an error: ' . $e->getMessage());
}
catch(Facebook\Exceptions\FacebookSDKException $e) {
die('Facebook SDK returned an error: ' . $e->getMessage());
}
$graphNode = $response->getGraphNode();
I hope this helps!
i have put last 3 posts in web page , if user loged in he can add comment / like , problem is if user loged in and try add like or comment he is getting an permission error #200 , if i loged in i can add like or comment (application is for me) , am getting the all permission nedded from the user , so how can i give him permission to add like / comment.
CODE :
$facebook = new Facebook(array(
'appId' => '',
'secret' => '',
'cookie' => true,
));
$user = $facebook->getUser();
if ($user) {
if (session_id()) {
} else {
session_start();
}
$access_token = $facebook->getAccessToken();
//check permissions list
$permissions_list = $facebook->api(
'/me/permissions', 'GET', array(
'access_token' => $access_token
)
);
//check if the permissions we need have been allowed by the user
//if not then redirect them again to facebook's permissions page
$permissions_needed = array('publish_stream', 'read_stream', 'manage_pages');
foreach ($permissions_needed as $perm) {
if (!isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1) {
$login_url_params = array(
'scope' => 'publish_stream,read_stream,manage_pages',
'fbconnect' => 1,
'display' => "page",
'redirect_uri' => 'http://localhost/fb/index.php',
);
$login_url = $facebook->getLoginUrl($login_url_params);
header("Location: {$login_url}");
exit();
}
}
}else {
//if not, let's redirect to the ALLOW page so we can get access
//Create a login URL using the Facebook library's getLoginUrl() method
$login_url_params = array(
'scope' => 'publish_stream,read_stream,manage_pages',
'fbconnect' => 1,
'display' => "page",
'redirect_uri'=>'http://localhost/fb/index.php',
);
$login_url = $facebook->getLoginUrl($login_url_params);
//redirect to the login URL on facebook
header("Location: {$login_url}");
exit();
}
$logoutUrl = $facebook->getLogoutUrl();
and if the user click on like button :
jQuery('ul.fb_list a').click(function(){
var comm_id = jQuery(this).attr("class");
jQuery.post('https://graph.facebook.com/'+comm_id+'/likes/',{
access_token : "<?php echo $access_token ?>"
});
});
Double check and make sure your variable comm_id is formated with both the user id of the person who posted the post, and then the id of the post itself, with an underscore in between, like this - USERID_POSTID. This is how facebook gives it you if you call to the graph api
$post_url = "https://graph.facebook.com/" . $user_id . "/posts?access_token=". urlencode($access_token);
Not sure if you're getting comm_id from another source or not. Also noticed in your code
access_token : "<?php echo $access_token ?>"
You forgot a semi-colon after the echo call. Should be this
access_token : "<?php echo $access_token; ?>"
Hope this helps. I see you're using a lot of jquery to do the like functionality. I like to stick w/ server side code for stuff like this, I feel that it's more stable for some reason.
This is how I did it. I have a like button like this -
echo '<div id="like_container-'.$i.'">
<div id="like_count">'.$num_likes.'</div>'
<div class="unliked"></div>
</div>';
and fb_Like() is an ajax call, something like this -
function fb_Like(post_id, token, num_likes, id){
$.ajax({
type: "GET",
url: "likepost.php",
data: 'id='+post_id+'&token='+token+'&likes='+num_likes,
success: function(html)
{
$("#like_container-"+id).empty().html(html);
}
});
}
And the likepost.php page is a script similar to the one on this page
Like a Facebook Post externally using Graph Api - example
This worked really well for me. It also let's me update the number of likes that the post has on the front end right above the like button if a like has been made. Good luck!
UPDATE
If you want to check if the user already likes a post, it's pretty simple w/ the facebook graph api
//Create Post Url
$post_url = "https://graph.facebook.com/" . $Page/User_id . "/posts?access_token=". urlencode($access_token);
//Get Json Contents
$resp = file_get_contents($post_url,0,null,null);
//Store Post Entries as Array
$the_posts = json_decode($resp, true);
foreach ($the_posts['data'] as $postdata) {
foreach ($postdata['likes']['data'] as $like){
if($like['id']==$user){
$liked=1;
}else{continue;}
}
if($liked==1){
//do something
}
}
This assumes that you already have a facebook user id for the logged in user, in this example, stored in the variable $user.
I have an array that looks as follows:
$userImages = array(
'100000000000001' => array(
'..../image01.jpg',
'..../image02.jpg',
'..../image03.jpg',
),
'100000000000002' => array(
'..../image04.jpg',
'..../image05.jpg',
'..../image06.jpg',
),
);
which contains FB user ids as keys, and then an array of images to upload to each users account.
My upload code looks as follows:
/** #var FacebookSessionPersistence $facebook */
$facebook = $this->container->get('fos_facebook.api');
$facebook->setFileUploadSupport(true);
$count = 1;
foreach ($userImages as $userId => $images) {
$batch = array();
$params = array();
foreach ($images as $image) {
$request = array(
'method' => 'post',
'relative_url' => "{$userId}/photos",
'attached_files' => "file{$count}",
'access_token' => $this->getUserAccessToken($userId)
);
$batch[] = json_encode($request);
$params["file{$count}"] = '#' . realpath($image);
$count++;
}
}
$params['batch'] = '[' . implode(',', $batch) . ']';
$result = $facebook->api('/', 'post', $params);
return $result;
I've added user access tokens to each image, under access_token, but when $facebook-api() is called, I get the following back from Facebook:
Does anyone know why, I'm getting these errors? Am I adding the user access token in the wrong place?
The access_token had to be added to the $params associative array, in the root, not to each image item!
Your logic is good, but you need to put the access token inside the body for every individual request.
For example:
...
$request = array(
'method' => 'post',
'relative_url' => "{$userId}/photos",
'attached_files' => "file{$count}",
'body' => "access_token={$this->getUserAccessToken($userId)}",
);
...
Does anyone know why, I'm getting these errors? Am I adding the user access token in the wrong place?
Have you made sure, you’ve actually added access tokens at all, and not perhaps just a null value?
The error message does not say that you used a wrong or expired user access token, but it says that a user access token is required.
So I’m guessing, because you did not really put actual tokens into your separate batch request parts in the first place, then the fallback to your app access token occurs, and hence that particular error message.
Sorry for my English, I'll try to explain my problem.
With this code I can publish feed on the wall of the users without prompts (I need extended permissions..)
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'www.example.com',
'message' => 'Posting with the PHP SDK!'
));
But How can I use PHP SDK to prompts the user to publish as can be done with this code (using Javascript SDK)
<script src='http://connect.facebook.net/en_US/all.js'></script>
<p><a onclick='postToFeed(); return false;'>Post to Feed</a></p>
<p id='msg'></p>
<script>
FB.init({appId: "YOUR_APP_ID", status: true, cookie: true});
function postToFeed() {
// calling the API ...
var obj = {
method: 'feed',
link: 'https://developers.facebook.com/docs/reference/dialogs/',
picture: 'http://fbrell.com/f8.jpg',
name: 'Facebook Dialogs',
caption: 'Reference Documentation',
description: 'Using Dialogs to interact with users.'
};
function callback(response) {
document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
}
FB.ui(obj, callback);
}
</script>
Thanks to all!
Seems you will need to cUrl the dialog end point to get the effect you desire.
I would suggest using a button or link and opening a new page which will cUrl the endpoint and redirect back to that page with a close tab or page button.
example endpoint link https://www.facebook.com/dialog/feed?app_id=135669679827333&link=https://developers.facebook.com/docs/reference/dialogs/&picture=http://fbrell.com/f8.jpg&name=Facebook%20Dialogs&caption=Reference%20Documentation&description=Using%20Dialogs%20to%20interact%20with%20users.&redirect_uri=http://anotherfeed.com/?pid=facebook
Refer to: https://developers.facebook.com/docs/reference/dialogs/#display
examples: under construction.
<?php
require 'facebook.php';
// Create our application instance
// (replace this with your appId and secret).
$app_id = "APP_ID";
$secret = "APP_SECRET";
$app_url = "APP_URL";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
'cookie' => true,
));
// Get User ID
$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;
}
$access_token = $facebook->getAccessToken();
}
?>
Is anyone else noticing that facebook and twitters APIs aren't working?
For facebook even if I allow my application to have access to my wall
$facebook->getUser()
Is always 0... When I try to open getLoginUrl it just open pop-up and redirect it instantly to success return link...
Here is code:
require_once 'src/base_facebook.php';
require_once 'src/facebook.php';
$app_id = 'xxx';
$app_secret = 'xxx';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'oauth' => true,
'cookie' => true
));
$req_perms = "publish_stream";
$user = $facebook->getUser();
if (!$user)
{
$loginUrl = $facebook->getLoginUrl(array('display' => 'popup', 'redirect_uri' => 'http://xxxx.com/return_close.php?success=1', 'cancel_url' => 'http://xxxx.com/return_close.php?success=0','req_perms' => $req_perms, 'scope' => $req_perms));
}
And for twitter it's like someone mistyped return link...
When I open getAuthorizeURL and when I log in it redirects me to this URL:
https://twitter.comoauth_callback/?oauth_token=yA2xjLsVRm9tIuVEysXnCV8R7TISW8tF94uznn7zlw&oauth_verifier=Io1N2I8zOEzJeBWI77WXFMqmMRNDfCrXZGQxXmxJLbI
Yes, https://twitter.comoauth_callback/ is right, there is no / after .com, it's together, so I get not found page...
It's like both APIs have serious problems... Facebook sometimes work and sometimes doesn't, it's buggy a lot...
Facebook library downloaded from OFFICIAL GitHub page. Tried versions:
v3.1.1
v3.1.0
v3.0.1
And none of those work...
Update
Return URL ( redirect_uri ) MUST have facebook class included in file...
There is so many examples/documentations and none of those had this explained...
So, Facebook fixed... Twitter still not working...
Well, nothing is broken in the API. Where did you get the above code? and if you come up with it then based on what resource?
First of all, take a look at the example of the OFFICIAL PHP-SDK, you'll notice the following:
Only the facebook.php file has been included, why not base_facebook.php? well because it's included in the facebook.php file!
Developers used to use req_perms but now to request permissions you just need to use scope
Take a look inside base_facebook.php for the params the Facebook() class expect: appId, secret and fileUpload ONLY
Only use the display parameter if you know what you are doing!
Use proper indentation with your code, it makes your life (and others!) much easier!
This been said, this is a rewrite of your code:
require 'src/facebook.php';
$app_id = 'xxx';
$app_secret = 'xxx';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret
));
$req_perms = "publish_stream";
$user = $facebook->getUser();
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array('display' => 'popup', 'redirect_uri' => 'http://xxxx.com/return_close.php?success=1', 'cancel_url' => 'http://xxxx.com/return_close.php?success=0', 'scope' => $req_perms));
}