Facebook- Publishing a story to user's wall - php

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

Related

php publish video to facebook wall

I'm trying to create an app that will upload & publish a video to user's wall.
following the api docs there are no examples of publishing
https://developers.facebook.com/…/reference/v2.2/user/videos
I've looked up for similar questions in here but they're all old referring to fb api.
the API returns a message that I should use curl, when I'm using curl
it returns false.
is there any php example of publishing video?
example of my code:
$url = 'https://graph-video.facebook.com/me/videos';
$cfile = new CURLFile('test.mp4','video/mp4','video');
$post_params = array(
'title' => "myTitle",
'name' => "blahblah",
'source' => $cfile,
'access_token' => $token
);
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
//execute post
$result = curl_exec($ch);
Thanks!
I found the answer for that using FB API & CURLFile, hope it would help someone else
$url = 'https://graph-video.facebook.com/me/videos';
$cfile = new CURLFile(realpath('test.flv'),'video/x-flv');
$movie_data = array('file' => $cfile);
$post_params = array(
'title' => "ffff",
'name' => "tablished businesses”",
'source' => $cfile,
'access_token' => $token
);
$request = new FacebookRequest(
$session,
'POST',
'/me/videos',
$post_params
);
$response = $request->execute();
the $response contains the id of the video.
enjoy

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.

FB development - Upload a photo into user's profile

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);

Google API OAuth 2.0 CURL returning "Required parameter is missing: grant_type"

I'm trying to implement Google's OAuth 2.0 authentication for a web server application.
I can obtain the code from Google ok, but when I post this back to try and get an access token, it always give me the error "Required parameter is missing: grant_type. Error 400" even though the grant_type is there.
Also if I specify the content-length to be anything other than 0, it throws other errors.
Here's the code that's doing this curl post:
$url = 'https://accounts.google.com/o/oauth2/token';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-length: 0'
));
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code='. urlencode($code),
'client_id=' . urlencode($clientID),
'client_secret=' . urlencode($clientSecret),
'redirect_uri=http%3A%2F%2Flocalhost%2Fexperiments%2FnewGALogin.php',
'grant_type=authorization_code'
));
try
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code' => $code,
'client_id' => $clientID,
'client_secret' => $clientSecret,
'redirect_uri' => 'http%3A%2F%2Flocalhost%2Fexperiments%2FnewGALogin.php',
'grant_type' => 'authorization_code'
));
or
curl_setopt($ch, CURLOPT_POSTFIELDS,
'code=' . urlencode($code) . '&' .
'client_id=' . urlencode($clientID) . '&' .
'client_secret=' . urlencode($clientSecret) . '&' .
'redirect_uri=http%3A%2F%2Flocalhost%2Fexperiments%2FnewGALogin.php' . '&' .
'grant_type=authorization_code'
);
I was trying to use the PHP code in the original question plus answers provided here and kept getting complaints from the Google token server about a missing "grant_type", even though it was definitely being passed in. It turns out the issue was the CURLOPT_HTTPHEADER didn't like/need the 'Content-length: 0'. Hopefully this complete working code will save someone else the same headache...
// This is what Google's OAUTH server sends to you
$code = $_GET['code'];
// These come from your client_secret.json file
$clientID = "your client id.apps.googleusercontent.com";
$clientSecret = "your client secret";
$redirectURI = "your redirect URI";
$token_uri = 'https://accounts.google.com/o/oauth2/token';
$ch = curl_init($token_uri);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
// Build the URLEncoded post data
$postFields = http_build_query(array(
'client_secret' => $clientSecret,
'grant_type' => 'authorization_code',
'redirect_uri' => $redirectURI,
'client_id' => $clientID,
'code' => $code
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$response = curl_exec($ch);
// Save response, especially the "refresh_token"
$pathToAccessToken = "/your/path/to/access_token.json";
file_put_contents($pathToAccessToken, $response);
FYI, the response JSON looks something like this:
{
"access_token" : "xxxWhateverGibberish",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "yyyMoreGibberish"
}
After that I could successfully query the Calendar (the API scope my original OAuth request called for) using code like the following:
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfigFile(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$pathToAccessToken = "/your/path/to/access_token.json";
$accessToken = file_get_contents($pathToAccessToken);
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
file_put_contents($pathToAccessToken, $client->getAccessToken());
}
return $client;
}
$client = getClient();
$service = new Google_Service_Calendar($client);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
if (count($results->getItems()) == 0) {
print "No upcoming events found.\n";
} else {
print "Upcoming events:\n";
foreach ($results->getItems() as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)\n", $event->getSummary(), $start);
}
}
After researching into this problem, it seems like the grant_type is not accepted in the array format. (Yes, the query string method works but it's messy to build.)
Adding http_build_query() to the array works if you are keen on keeping the POST fields in an array.
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
'code' => $code,
'client_id' => $clientID,
'client_secret' => $clientSecret,
'redirect_uri' => 'http%3A%2F%2Flocalhost%2Fexperiments%2FnewGALogin.php',
'grant_type' => 'authorization_code'
)));
Please read the documentation for CURLOPT_POSTFIELDS carefully:
... as an array with the field name as key and field data as value
You do just something but not that. Try:
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code' => $code,
'client_id' => $clientID,
...
You don't need to urlencode in this case.
I didn't want to believe it, but strangely enough, simply switching from CURLOPT_POSTFIELDS from an array to a '&' concatenated string (with the same data!) let my OAuth server finally recognize the grant_type.
The core issue with the original question and some of the answers is the different values accepted in the curl_setopt call when using the key CURLOPT_POSTFIELDS.
When the input is an array the resulting Content-Type will be multipart/form-data which is not compliant with the OAuth 2.0 spec and the server will ignore it. When the input is a query-encoded string (e.g built using http_build_query) the Content-Type: will be application/x-www-form-urlencoded, which is what the spec requires.
See the "Notes" section at: http://php.net/manual/en/function.curl-setopt.php

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