I am writing a script to automatically retrieve a .png file from a directory and post it to my Facebook page with a bunch of hashtags as its message.function
publish($filename, $card_type, $message){
$filename = "http://www.mywebsite.com/sandboxassets/img/burrocards/" . $card_type . "/" . $filename;
echo 'publish this file: ' . $filename;
// retrieve fb credentials
$config_vals = parse_ini_file("../../../nicethings.ini");
$appid = $config_vals['fbappid'];
$token = $config_vals['fbtoken'];
$secret = $config_vals['fbsecret'];
// initialize Facebook class using your own Facebook App credentials
$fb = new Facebook\Facebook([
'app_id' => $appid,
'app_secret' => $secret,
'default_graph_version' => 'v2.8',
]);
// define your POST parameters (replace with your own values)
$params = array(
"access_token" => $token,
"message" => $message,
"link" => "http://www.mywebsite.com",
"picture" => $filename
);
// post to Facebook
try {
$post = $fb->post('/MyPage/feed', $params);
$post = $post->getGraphNode()->asArray();
echo 'Successfully posted to Facebook';
} catch(Exception $e) { echo $e->getMessage(); }
}
This script runs just fine except that I don't want to link the posted image to any site. I just need to post it as an unlinked image. But when I remove the following line from the function, Facebook refused the call saying I must define a link for an image post:
"link" => "http://www.mywebsite.com",
Is there any way to accomplish what I want to? There must be because I regularly post images to my page manually without having to link it to anything.
Related
I'm having real issues posting links to a Facebook Page via the Facebook SDK for PHP (v5.4). I'm using v2.6 of the Facebook Graph API.
I'm using a user who has admin access to the page.
I've got an access token that never expires, with the following permissions: user_managed_groups, user_photos, user_posts, email, manage_pages, publish_pages, pages_show_list, publish_actions, public_profile.
This is my code:
use \Facebook\Facebook;
use \Facebook\Exceptions\FacebookResponseException;
use \Facebook\Exceptions\FacebookSDKException;
$app_id = '123';
$app_secret = 'ABC';
$access_token = 'XXX';
$page_id = '123';
$fb = new Facebook\Facebook([
'app_id' => $app_id,
'app_secret' => $app_secret,
'default_graph_version' => 'v2.6',
'access_token' => $access_token,
]);
$helper = $fb->getRedirectLoginHelper();
try {
$response = $fb->get('/' . $page_id . '?fields=access_token', $access_token);
// This returns the same access token as I've already got,
// so I don't know if that's a problem,
// or if there's just no point doing this.
$page_access_token = $response->getAccessToken();
$response = $fb->post('/' . $page_id . '/feed', [
'message' => 'Test message with link',
'link' => 'http://example.com',
], $page_access_token);
} catch (FacebookResponseException $exception) {
echo '<p>Graph returned an error: ' . $exception->getMessage() . '</p>';
exit;
} catch (FacebookSDKException $exception) {
echo '<p>Facebook SDK returned an error: ' . $exception->getMessage() . '</p>';
exit;
}
At the moment, I'm getting the following exception:
Graph returned an error: (#200) Permissions error
Any help with this would be really appreciated. It feels like I'm so close.
I use facebook-php-sdk-v3.2 to upload video from my website to a Facebook account.
This is my code:
<?php
require 'src/facebook.php';
$file = "movie.mp4";
$post_type = '/me/videos';
$post_params = array(
'access_token' => '***************************',
'title' => 'title of the image',
'source' => '#' . $file,
);
$facebook = new Facebook(array(
'appId' => '1061864210567772',
'secret' => '***************************'
));
print $facebook->getUser();
$facebook->setFileUploadSupport(true);
try{
$fbpost = $facebook->api($post_type, 'POST', $post_params);
print($fbpost);
} catch (Exception $e) {
echo $e->getMessage();
}
This question is already asked before and I saw all of them, but none of them worked for me. The output of this code is 0
$uid = $facebook->getUser();
But the error is
An active access token must be used to query information about the current user
I have the below snippet and it works and posts to a Facebook page as my own user account on Facebook.
The values FACEBOOK_* are defined earlier in the codebase.
// SDK Version 5.0
$fb = new Facebook\Facebook([
'app_id' => FACEBOOK_APP_ID,
'app_secret' => FACEBOOK_APP_SECRET,
'default_graph_version' => 'v2.4',
]);
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/'.FACEBOOK_PAGE_ID.'/feed', $postData, FACEBOOK_ACCESS_TOKEN);
$postId = $response->getGraphNode();
Now my question is how can I get it to post as the actual page and not my account which is the admin of the page.
I've had a look at the SDK documentation and I've been going around in circles, there are many examples of v4 but as it's deprecated I'm trying to use v5 and just can't seem to figure it out, any links to post attribution or impersonation I find are dead links in v5 of the SDK.
From what I can see I need to make a call to /{user-id}/accounts to get an access token for the page from my user, https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens
But to get a {user-id} I have to query the user, with something like the below example from the SDK documentation:
// Make sure to load the Facebook SDK for PHP via composer or manually
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
if($session) {
try {
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo "Name: " . $user_profile->getName();
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
The issue here is that I have no idea how to get a session which I need to get the user data for which gives me the access token to allow me pass the access token into my code snippet above that works, that's if I understand it all correctly!?
Any help greatly appreciated!
I work with classes, so I adapted my code to your examples above. Tested and working code.
After getting your user access token using the method you use (see the guide here), we have to obtain a long-lived access token. Add this to your code :
session_start();
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// There was an error communicating with Graph
echo $e->getMessage();
exit;
}
if (isset($accessToken)) {
$client = $fb->getOAuth2Client();
try {
$accessToken = $client->getLongLivedAccessToken($accessToken);
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo $e->getMessage();
exit;
}
$response = $fb->get('/me/accounts', (string) $accessToken);
foreach ($response->getDecodedBody() as $allPages) {
foreach ($allPages as $page ) {
if (isset($page['id']) && $page['id'] == $pageId) { // Suppose you save it as this variable
$appAccessToken = (string) $page['access_token'];
break;
}
}
}
$response = $fb->post(
'/'.$pageId.'/feed',
array(
"message" => "Message",
"link" => "http://www.example.com",
"picture" => "http://www.example.net/images/example.png",
"name" => "Title",
"caption" => "www.example.com",
"description" => "Description example"
),
$appAccessToken
);
// Success
$postId = $response->getGraphNode();
echo $postId;
} elseif ($helper->getError()) {
var_dump($helper->getError());
var_dump($helper->getErrorCode());
var_dump($helper->getErrorReason());
var_dump($helper->getErrorDescription());
exit;
}
Explanations : You have to know which pages you are administrator :
$response = $fb->get('/me/accounts', (string) $accessToken);
Then search the table to retrieve the access token of the page that interests us (I have chosen to take the id of the page referenced).
Finally, simply run the post function provided by the SDK :
$response = $fb->post(
'/'.$pageId.'/feed',
array(
"message" => "Message",
"link" => "http://www.example.com",
"picture" => "http://www.example.net/images/example.png",
"name" => "Title",
"caption" => "www.example.com",
"description" => "Description example"
),
$appAccessToken
);
On my page I want post feeds with an image in the text of message and not like a link/url, is possible add to text message something like htmltags or bbcode?
$msg = "<img src=\"urlimg or facebook\" >\nMy text here";
$args = array(
'message' => $mgs,
);
$myfeed = $facebook->api($pageid . '/feed', 'post', $args);
update:
i've found a solution but if i post 2 times in a row they will be groupped in the same box in timeline
$args = array(
'message' => $msg,
'image' => '#'.$path,
'aid' => $album_id,
'access_token' => $token
);
$photo = $facebook->api($album_id . '/photos', 'post', $args);
exist a setting to stop auto-group that? or there is another way to post it like feed with image?
You can't publish an image in the middle of the text message, Facebook do not allow it.
But you can attach an image to the message, it will appear on the left of the message in this way:
$msg = "My text here";
imgUrl = "http://urltotheimage.com/path/image.jpg";
$args = array(
'message' => $mgs,
'picture' => $imgUrl
);
$myfeed = $facebook->api($pageid . '/feed', 'post', $args);
So I spent 30 seconds searching around the PHP Facebook API, which really is what you should be doing, and found the following example:
<?
// 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('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'fileUpload' => true,
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
$photo = './mypic.png'; // Path to the photo on the local filesystem
$message = 'Photo upload via the PHP SDK!';
?>
<html>
<head></head>
<body>
<?
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$ret_obj = $facebook->api('/me/photos', 'POST', array(
'source' => '#' . $photo,
'message' => $message,
)
);
echo '<pre>Photo 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' => 'photo_upload'
));
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
echo '<br />logout';
} else {
// No user, print a link for the user to login
// To upload a photo to a user's wall, we need photo_upload 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' => 'photo_upload') );
echo 'Please login.';
}
?>
</body>
</html>
Take note of the $config variable values and the $facebook->api() call.
I finally got facebooks graph api to post messages on my fan PAGE as page
How do i get it to post large images as a post, not as a link?
'source' => $photo seems to create a thumbnail
this is what i have so far
<?php
$page_id = 'YOUR-PAGE-ID';
$message = "I'm a Page!";
$photo = "http://www.urlToMyImage.com/pic.jpg";
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'YOUR-APP-ID',
'secret' => 'YOUR-SECRET-ID',
));
$user = $facebook->getUser();
if ($user) {
try {
$page_info = $facebook->api("/$page_id/?fields=access_token");
if( !empty($page_info['access_token']) ) {
$facebook->setFileUploadSupport(true); // very important
$args = array(
'access_token' => $page_info['access_token'],
'message' => $message,
'source' => $photo
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
}
} 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(array( 'next' => 'http://mydomain.com/logout_page.php' ));
} else {
$loginUrl = $facebook->getLoginUrl(array('scope'=>'manage_pages,publish_stream'));
}
?>
The problem here is that you are in actual fact not posting a photo. What you are doing is posting a link to that photo so what you see is indeed a thumbnail preview image that Facebook retrieved from that URL.
What you'll want to do is provide a full path to a file on your server prefixed with the # symbol. The topic has been discussed on the site quite a bit so I'll just point you in the direction of a canonical post dealing with uploading of images to Facebook with the PHP SDK
Upload Photo To Album with Facebook's Graph API
The code looks like this -
$facebook->setFileUploadSupport(true);
$params = array('message' => 'Photo Message');
$params['image'] = '#' . realpath($FILE_PATH);
$data = $facebook->api('/me/photos', 'post', $params);