FB development - Upload a photo into user's profile - php

Can you tell me what I do wrong. I use PHP. Try to upload the photo into users profile.. I get permissions and it works. But uploading doesn't work, I tryed many ways. So what do I do wrong?
<?php
include_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'ID',
'secret' => 'SECRET',
'cookie' => true,
'domain' => 'DOMAIN',
'fileUpload' => 'true'
));
$session = $facebook->getSession();
if (!$session) {
$loginUrl = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 1,
'display' => 'page',
'req_perms' => 'user_likes, publish_stream',
'next' => 'NEXTURL'
));
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
} else{
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$token = $session['access_token'];//here I get the token from the $session array
$album_id = 'ALBUM ID'; /// what should I write here?
//upload your photo
$file= 'logo.png';
$args = array(
'message' => 'Photo from app',
);
$args[basename($file)] = '#' . realpath($file);
$ch = curl_init();
$url = 'https://graph.facebook.com/'.$album_id.'/photos?access_token='.$token;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
//returns the id of the photo you just uploaded
print_r(json_decode($data,true));
} catch(FacebookApiException $e){
echo "Error:" . print_r($e, true);
}
}
?>
Thanks in advance

You must add the property fileUpload==true to the Facebook-Object:
$facebook = new Facebook(array(
'appId' => 'ID',
'secret' => 'SECRET',
'cookie' => true,
'domain' => 'DOMAIN',
'fileUpload' => true
));
UPDATE:
I always use this code to upload photos:
$photo= $facebook->api(array('method'=>'photos.upload',
'caption'=>SOME_TEXT,
'file'=>'#'.$file));

You can try this :
$args = array('message' => $mess,
);
$args['image'] = '#' . realpath($file.".jpeg");
$facebook->setFileUploadSupport(true);
try
{
if(!isset($_GET['a']))
{
$data = $facebook->api('/me/photos', 'post', $args);
}
// echo "<br/>Image posted. Click here to view. Thanks for using this application.";
}
catch(FacebookApiException $e)
{
var_dump($e);
}
This is a direct excerpt from a working code.

try this
$args = array('message' => 'Photo Upload');
$args['image'] = '#' . realpath($FILE_PATH);
$data = $facebook->api("/{$album_id}/photos", 'post', $args);
Note: if you want to create a new album name same as the app name and upload there then you have to use
$facebook->api("/me/photos", 'post', $args);

Related

Error access token with LinkedIn

After many tests, I cannot retrieve the access token. It gives me every time this error:
"error_description":"missing required parameters, includes an invalid parameter value, parameter more than once. : Unable to retrieve access token : authorization code not found","error":"invalid_request"
I totally distraught. For a few days I cannot solve my problem.
Here is the code of my application :
Route::get('login/linkedin', function()
{
$lk_credentials = Config::get('linkedin.public0');
$provider = new LinkedIn($lk_credentials);
if(!Input::has('code')){
$provider->authorize();
}else{
$code = Input::get('code');
if(strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with LinkedIn');
try{
$params = array(
'response_type' => 'code',
'client_id' => '*************',
'redirect_uri' => urlencode(url('login/linkedin')),
'state' => $_GET['state'],
);
$postdata = http_build_query($params);
$url = '/uas/oauth2/authorization?'.$postdata;
$context = stream_context_create(array('https' => array('method' => 'GET')));
$t = $provider->getAccessToken('authorization_code', array('code' => $_GET['code']));
Session::put('oauth2_access_token', $t->accessToken);session(['oauth2_access_token' => $t->accessToken]);
try{
if(count($_POST) > 0){
print_r($_POST);
exit('post');
}
$params = array(
'grant_type' => 'authorization_code',
'code' => Session::get('oauth2_access_token'), //$_GET['code'],
'redirect_uri' => urlencode(url('login/linkedin')),
'client_id' => '123456789',
'client_secret' => '123456789',
);
$postdata = http_build_query($params);
$c = curl_init();
curl_setopt($c, CURLOPT_URL, 'https://www.linkedin.com/uas/oauth2/accessToken');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_POST,true);
curl_setopt($c, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($c, CURLOPT_POSTFIELDS,$postdata);
curl_setopt($c, CURLOPT_HEADER, false);
curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded',));
$output = curl_exec($c);
if($output === false){
trigger_error('Erreur curl : '.curl_error($c),E_USER_WARNING);
exit('Erreur');
}else{
var_dump($output);
//exit('Affiche');
}
curl_close($c);
}catch(Exception $e){
return 'Unable to get Request Token';
}
}catch(Exception $e){
return 'Unable to get user authorization_code';
}
try{
$resource = '/v1/people/~:(id,emailAddress,firstName,lastName,pictureUrl,dateOfBirth,location)';
$params = array(
'oauth2_access_token' => Session::get('oauth2_access_token'),
'format' => 'json',
);
$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
$context = stream_context_create(array('http' => array('method' => 'GET')));
$response = file_get_contents($url, false, $context);
$data = json_decode($response);
Session::put('data', $data);session(['data' => $data]);
return redirect('/')->with('data',$data);
}catch(Exception $e){
return 'Unable to get user details';
}
}
});
Does anyone could help me?
For information; I use Laravel5 and for the authentication is OAuth2.
Thank you in advance, David.

Facebook Invalid OAuth access token signature trying to post an attachment to group wall from PHP

I am an administrator (manager role) of a Facebook Group. I created an app, and stored its id and secret.
I want my app to be able to post something on the Facebook group's feed. But when I attempt to post, I get the error 190 Invalid OAuth access token signature, even though I able to successfully obtain the access_token with publish_stream and offline_access scopes. It has the form of NNNNNNNNNNNNNNN|XXXXXXXXXXXXXXXXXXXXXXXXXXX, where N is a number (15) and X is a letter or a number (27).
What should I do more to get this accomplished? Here is the code I am using:
public static function postToFB($message, $image, $link) {
//Get App Token
$token = self::getFacebookToken();
// Create FB Object Instance
$facebook = new Facebook(array(
'appId' => self::fb_appid,
'secret' => self::fb_secret,
'cookie' => true
));
//$token = $facebook->getAccessToken();
//Try to Publish on wall or catch the Facebook exception
try {
$attachment = array('access_token' => $token,
'message' => $message,
'picture' => $image,
'link' => $link,
//'name' => '',
//'caption' => '',
'description' => 'More...',
//'actions' => array(array('name' => 'Action Text', 'link' => 'http://apps.facebook.com/xxxxxx/'))
);
$result = $facebook->api('/'.self::fb_groupid.'/feed/', 'post', $attachment);
} catch (FacebookApiException $e) { //If the post is not published, print error details
echo '<pre>';
print_r($e);
echo '</pre>';
}
}
Code which returns the token
//Function to Get Access Token
public static function getFacebookToken($appid = self::fb_appid, $appsecret = self::fb_secret) {
$args = array(
'grant_type' => 'client_credentials',
'client_id' => $appid,
'client_secret' => $appsecret,
'redirect_uri' => 'https://www.facebook.com/connect/login_success.html',
'scope' => 'publish_stream,offline_access'
);
$ch = curl_init();
$url = 'https://graph.facebook.com/oauth/access_token';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
try {
$data = curl_exec($ch);
} catch (Exception $exc) {
error_log($exc->getMessage());
}
return json_encode($data);
}
If I uncomment $token = $facebook->getAccessToken(); in the posting code, it gives me yet another error (#200) The user hasn't authorized the application to perform this action.
The token I get using
developers.facebook.com/tools/explorer/ is of another form, much longer and with it I am able to post to the group page feed.
How do I do it without copy/paste from Graph API Explorer and how do I post as a group instead of posting as a user?
Thanks.

php - Facebook Video Upload Curl

To upload the video to Facebook using the following lines.
$video = "http://xxx.com/video.mp4";
$data = array('name' => 'file', 'file' => $video,
'access_token' => $access_token, '_title' => $video_title,
'description' => $video_desc);
$post_url = "https://graph-video.facebook.com/" . $page_id . "/videos";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$res = curl_exec($ch);
I received an error:
"error":{"message":"(#353) You must select a video file to
upload.","type":"OAuthException","code":353}}
If I change curl to form post it works. Any ideas on why is it so?
Use the path to the video on server instead of the url. So:
$video = "uploads/video.mp4";
Then:
$data = array('name' => 'file', 'file' => '#'.realpath($video),
'access_token' => $access_token, '_title' => $video_title,
'description' => $video_desc);
Notice the use of realpath() following the '#' symbol. Haven't tested with your code but I have a similar implementation and works great. Should do the trick!
For FB SDK4: (see the hardcoded video path, and the encoding).
FB requests the video file to be passed encoded as form-data:
https://developers.facebook.com/docs/graph-api/reference/user/videos/
private function postFBVideo($authResponse, $fileObj, $formData)
{
FacebookSession::setDefaultApplication('yourAppkey', 'yourAppSecret');
$ajaxResponse = '';
try {
$session = new FacebookSession($authResponse->accessToken);
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
$ajaxResponse = 'FB Error ->' . json_encode($ex) ;
} catch (\Exception $ex) {
// When validation fails or other local issues
$ajaxResponse = 'FB Validation Error - ' . json_encode($ex) ;
}
if ($session) {
$response = (new FacebookRequest(
$session, 'POST', '/me/videos', array(
'source' => new CURLFile('videos/81JZrD_IMG_4349.MOV', 'video/MOV'),
'message' => $formDataMessage,
)
))->execute();
$ajaxResponse = $response->getGraphObject();
}
return json_encode($ajaxResponse);
}

Facebook- Publishing a story to user's wall

I am using facebook-php-sdk and my requirement is to post a story to the user's wall. My app requests the user for 'publish_stream' permission at the time of signup/login. After user has allowed the permission and logged in, somehow I am not able to publish to facebook wall a new comment created by the user on my app. This is the error I get:
Invalid OAuth access token signature
This is what I do:
$facebook = new Facebook(array(
'appId' => "$fb_app_id",
'secret' => "$fb_secret",
'cookie' => true
));
try {
$fb_user_id = $facebook->getUser();
$access_token = $facebook->getAccessToken();
$facebook->api("/me/feed", 'post', array(
'access_token' => $access_token,
'message' => 'I love SO',
'link' => 'http://mydomain.com',
'picture' => 'http://thinkdiff.net/ithinkdiff.png',
'name' => 'iOS Apps & Games',
'description'=> 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'
)
);
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
}
Do share your thoughts please
You can use the following code to post into facebook wall , just call the function with proper arguments
Try this ,
<?php
function doWallPost($postName='',$postMessage='',$postLink='',$postCaption='',$postDescription='')
{
$FB_APP_ID='xxxxxxxxxxxxxxxxxxxxxxxx';
$FB_APP_SECRET='xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$APP_RETURN_URL=((substr($_SERVER['SERVER_PROTOCOL'],0,4)=="HTTP")?"http://":"https://").$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
$code = $_REQUEST["code"];
if(empty($code))
{
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=".$FB_APP_ID."&redirect_uri=".$APP_RETURN_URL."&scope=publish_stream";
header("Location:$dialog_url");
}
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$FB_APP_ID."&redirect_uri=".urlencode($APP_RETURN_URL)."&client_secret=".$FB_APP_SECRET."&code=".$code;
$access_token = file_get_contents($token_url);
$param1=explode("&",$access_token);
$param2=explode("=",$param1[0]);
$FB_ACCESS_TOKEN=$param2[1];
$url = "https://graph.facebook.com/me/feed";
$attachment = array( 'access_token' => $FB_ACCESS_TOKEN,
'name' => $postName,
'link' => $postLink,
'description' => $postDescription,
'message' => $postMessage,
'caption' => $postCaption,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
$result=curl_exec($ch);
header('Content-type:text/html');
curl_close($ch);
return $result
}
?>
install app again through https://developers.facebook.com/tools/explorer/
select your app & click on Get access token
if you still have problem go to your developer dashboard
https://developers.facebook.com/apps
click on Edit settings & check up you set correct URL
in Site URL: field

Facebook API: How to post to own application wall without login

I want to post to my own application wall a text with a script but without to login first because it should be done automatically. How could I do that? I tried already:
$fb = new Facebook(array(
'appId' => 'appid',
'secret' => 'appsecret',
'cookie' => true
));
if ($fb->getSession()) {
// Post
} else {
// Logger
// Every time I get in here :(
}
What do I have to do to get the access to post to my the own app wall with a script?
If you want to post to your own Application wall, all you need is an application Access Token, and if you want to publish to an user wall without login, you also need this user long live access token, for that you have to ask for Offline access permission.
To publish to your application wall :
1- Curl this link to get your application access token :
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials
2- Publish to wall without checking for the session
Example :
<?php
require_once 'facebook.php'
//Function to Get Access Token
function get_app_token($appid, $appsecret)
{
$args = array(
'grant_type' => 'client_credentials',
'client_id' => $appid,
'client_secret' => $appsecret
);
$ch = curl_init();
$url = 'https://graph.facebook.com/oauth/access_token';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
return json_encode($data);
}
// Create FB Object Instance
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => false,
));
//Get App Token
$token = get_app_token($appid, $appsecret);
//Try to Publish on wall or catch the Facebook exception
try {
$attachment = array('message' => '',
'access_token' => $token,
'name' => 'Attachment Name',
'caption' => 'Attachment Caption',
'link' => 'http://apps.facebook.com/xxxxxx/',
'description' => 'Description .....',
'picture' => 'http://www.google.com/logo.jpg',
'actions' => array(array('name' => 'Action Text',
'link' => 'http://apps.facebook.com/xxxxxx/'))
);
$result = $facebook->api('/'.$appid.'/feed/', 'post', $attachment);
}
//If the post is not published, print error details
catch (FacebookApiException $e) {
echo '<pre>';
print_r($e);
echo '</pre>';
}
Check APP LOGIN part in this page for more informations :
http://developers.facebook.com/docs/authentication/
I cant leave this as a comment as I dont have the points, but if any one has a similar issue - if McSharks answer doesnt work, remove the json_encode as its encoding quotation marks and it should work.

Categories