How to check if user/app can post on target group wall? - php

I can post on group / page and user wall, but i don't want my app to show error when posting on selected wall, if the selected wall doesn't allow posting so is there any way to know that are we able to post on target wall?
Note: I found two similar questions but they do not pertain to exactly what i want
1 Application able to post on user's Wall
2 How to check the permission whether a friend allow me to post on his wall or not using php sdk
Please discuss in comment before taking any negative action.
Thanks.

AFAIK, there's no way to check exactly the way you want, coz the privacy varies, as you have already said. The only privacy setting that can be queried is the OPEN, CLOSED, or SECRET of group, which can be done by calling the graph api:
`http://graph.facebook.com/$Group_id`
That returns json data that has a field privacy, which will be one of OPEN, CLOSED, or SECRET.
But on top of that you have settings for groups where you can restrict posting to only group admins. And that permission can not be checked.
So i think what you'll have to do is check the returned value, i.e $response after making the post. If the permission is not given, then the returned data looks like this:
{
"error": {
"type": "Exception",
"message": "You do not have permission to post in this group."
}
}
Hence you can check if $response has "error" field, and inform the user accordingly. Somewhat like this: if(isset($response['error'])).
Also check the fql table that represents groups for more info, if you haven't already.

Do you mean how to check if a user has given permission to post on their wall?
try {
// Get the permissions this user has
$call = $this->facebook->api("/me/permissions");
// If they have the permission we require ('publish_stream')
if($call['data'][0]['publish_actions']){
try{
// Do your magic here...
// Also include your access token in the array
$params = array('message'=> 'hello world');
$call = $this->facebook->api('/me/feed','POST',$params);
}catch(FacebookApiException $e) {
$result = $e->getResult(); // prob no permissions
}
}
} catch(FacebookApiException $e) {
$result = $e->getResult();
}
So basically, first check to see if the user has permissions for a particular action, then if they do $call[data][0]['publish_action'] will be a set to 1 (int).
Example output of $call = $this->facebook->api("/me/permissions");
[installed] => (int) 1
[email] => (int) 1
[publish_actions] => (int) 1
I have the above permissions from the user through facebook.

Related

How to identify callback from Facebook

Having an issue with the Facebook PHP API/SDK, let me begin by describing:
I made a website where you can enter 'quotes' (short messages) and then after saving the quote in the website (read; too a mysql db behind it) you can decide to share the quote with Facebook to be able to win stuff.
The flow (how it should work) is this:
User opens my site, PHP gets a login url from the Facebook PHP API/SDK
PHP reads & memorizes the 'state' url variable from the login url from the above step (which several sites mention would be a valid way to identify users)
A user saves a quote, I store the state variable from above in the db record of that quote so I can use it again later to match returning users with saved quotes.
The user decides to want to win, so he/she clicks the Facebook share button, which points their browser too the Facebook login url from step 1
The user's browser is now looking at some Facebook pages where they have to allow access for the app and allow that it can post to their wall
Once the user has given said access, they return to the callback url of my site (which happens to be the same as the 'origin url' from step 4)
PHP on my site finds the state variable in the returned url variables(?), goes trough the database to find a matching quote record, and if found, it stores some Facebook user data (userid and path to avatar) in the related db record.
PHP continues to post their earlier saved quote to the user's Facebook wall.
In essence, things work, but the most important bit, step 7, identifying who comes back via the state variable, does not. The problem is that I just get some lengthy 'code' GET variable back, and not the 'state' GET variable, and nowhere in the API docs or on StackOverflow or via Google do I find how to change it so I do get the 'state' GET variable returned again...?
So to recap, basically what I'm looking for is an ability to send some sort of identifier to Facebook that then gets included in the callback-url, and to my knowledge, that's what the 'state' variable seems best for, if it would work that is.
I'm using the currently latest API (facebook-php-sdk-v4-5.0.0.zip from this morning) Below I've shared all relevant code I use to interface with the Facebook PHP API/SDK, all this code resides in the index.php in public_html dir of my site, the callback url of my app is this same index.php
This code is pieced together from several examples, and essentially works, I just don't get the needed state variable back.
require_once __DIR__ . '<PATH-TOO-FB-API>/src/Facebook/autoload.php';
session_start();
$fbStateCode = ""; // used to memorize state code
$fbLoginUrl = ""; // user to memorize login url
// Init the API
// If you go end up testing this, dont forget too change <APP-ID> & <APP-SECRET>
$fb = new Facebook\Facebook([
'app_id' => '<APP-ID>',
'app_secret' => '<APP-SECRET>',
'default_graph_version' => 'v2.4',
'default_access_token' => isset($_SESSION['facebook_access_token']) ? $_SESSION['facebook_access_token'] : '<APP-ID>|<APP-SECRET>'
]);
// login helper
$helper = $fb->getRedirectLoginHelper();
// try get an accesstoken (wich we only have if user returned from facebook after logging in)
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
//echo 'Graph returned an error: ' . $e->getMessage(); // When Graph returns an error
} catch(Facebook\Exceptions\FacebookSDKException $e) {
//echo 'Facebook SDK returned an error: ' . $e->getMessage(); // When validation fails or other local issues
}
if (isset($accessToken)) {
// User is logged in!
try {
// Now we look up some details about the user
$response = $fb->get('/me?fields=id,name');
$facebook_user = $response->getGraphUser();
exit; //redirect, or do whatever you want
} catch(Facebook\Exceptions\FacebookResponseException $e) {
//echo 'Graph returned an error: ' . $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
//echo 'Facebook SDK returned an error: ' . $e->getMessage();
}
// if facebook_user has an id, we assume its a user and continue
if(isset($facebook_user['id'])) {
$avatarUrl = "http://graph.facebook.com/".$facebook_user['id']."/picture";
// THE BELOW 8 LINES HANDLE LOADING A QUOTE FROM DB WITH MATCHING STATE AND SAVING
// ADDITIONAL DATA TOO IT, THE ONLY ISSUE HERE IS THAT $_GET['state'] DOESNT EXIST
// THE REST OF THIS PROCESS HAS ALREADY BEEN TESTED AND PROOFED TO BE WORKING
$curr_quote = Quotes::getQuoteByFbStateCode($_GET['state']);
$curr_quote_data = $curr_quote->getData();
$curr_quote->updateData(array(
"fb_access_token" => $accessToken,
"fb_uid" => $facebook_user['id'],
"fb_avatar_path" => $avatarUrl
));
// Save it
if($curr_quote->save()) { // Success! quote in db was updated
// Now that we are logged in and have matched the returned user with a saved quote, we can post that quote too facebook
$_SESSION['facebook_access_token'] = (string) $accessToken; // storing the access token for possible use in the FB API init
// This is the data we post too facebook
$msg_data = array (
'message' => $curr_quote_data['quote']
);
$response = $fb->post('/me/feed',$msg_data,$accessToken); // do the actual post (this, like everything else besides state variable, works)
} else { // Fail! quote in db was NOT updated?!
// handle errors
}
}
} else {
// User is NOT logged in
// So lets build up a login url
$permissions = ['public_profile','publish_actions']; // we want these permissions (note, atm im the only tester, so while the app still needs to be reviewed for the 'publish_actions' permission, it works cuz i own the app and test with same fb account)
$fbLoginUrl = $helper->getLoginUrl('http://<WEBSITE-URL>/index.php', $permissions); // get the login url from the api providing callback url and permissions array
$fbLoginUrlParams = array();
parse_str($fbLoginUrl, $fbLoginUrlParams); // store the url params in a new array so that we can (read next comment below)
$fbStateCode = $fbLoginUrlParams['state']; // read out and store the state url variable
}
Below here is logic for saving a new quote to database based on user interaction, and making use of $fbStateCode, this part of the process functions fine as well, quotes get saved with their own unique state values like they should.
So that's the story, I'm trying to do something which I'm pretty sure isn't anything special, it's just poorly documented or something?
Ended up rewriting the lot, now it works fine, not sure whats different now vs what i had, so cant really provide an awnser for others running into similair issues, sorry bout that.
#Cbroe; forwarded the headsup you gave me too the customer, got literally told 'not our problem, but the problem of the company that made the concept', so time will tell if this ever even goes online lol, still, thanks for the headsup :P
Read the docs about the state variable here:
The state parameter is a value which is provided by the client prior to the login wen redirecting to the login url. If it's available then, it get's send back in the callback url.
So, unless you provide any state variable in your step1, you won't get any from FB (and any other oAuth2 implementing API). There will not be any "magic" making that appear other than providing it with a feasable state of your PHP app in step 1.
Actually, the state parameter is to give any client the ability to restore a context, whenever the callback "happens". So the content of the state variable may be a session id, a user id or any other value which helps restoring the (php)apps context again after receiving a callback
EDIT
I assume, that the state variable needs to be added somewhere in this function here:
$helper = $fb->getRedirectLoginHelper();

Twitter - Already have OAuth database, how do I know who the user is?

I've already got a database set up with a table that is successfully populated with the final (permanent?) OAuth User Token and OAuth User Secret. The thing I don't understand is how I'm supposed to know what the current user's ID is, especially when it's been 2 weeks since their last login. My app is authorized by all of its users, so theoretically Twitter can look at the list of authorized apps for the current user and share the Twitter User ID, right? Isn't there some good way of requesting (on behalf of the current user) what his ID is? I feel like the temporary tokens should be able to facilitate this somehow... If it helps, every user in my app is just a Twitter account with some extra info. I'm just looking for the best way to utilize the tokens and secrets that are in my database...
I'm using PHP (libraries: Codebird-PHP & tmhOAuth) so if you could show an example in PHP that'd be nice, but really I just want to know how I'm supposed to use this information that I'm storing.
Thanks!
I'm assuming you store the data together with some username or user id that identifies the users of your website and links them to their proper twitter id. In order to get the basic info of your user, after authorization, you have to use the endpoint https://api.twitter.com/1.1/account/verify_credentials.json with a GET.
The documentation for the 1.1 API can be found here.
This returns an array. You find the username uder "screen_name" and the user id under "id" or "id_string".
The question is a possible duplicate of Get current user's info from Twitter API, but I've added an answer because that discussion points to the deprecated API. The code you find there, nevertheless, is still useful (it appears to use Abraham William's library, but the steps are basically the same). Replace the classes and functions with those you have in Matt Harris' library. I don't know codebird, sorry!
EDIT: I am also providing a code sample (tested and working, although I have issues with tmhOAuth, so I use it occasionally only for myself. I have noticed that, when I try to post, it sometimes returns some weird error codes and I can't figure out why):
// Authentication page, with button. You have already connected to your database
$mywebsiteuser = $_SESSION['website_user_id'];
$query= "SELECT * FROM `table_where_you_store_twitter` WHERE website_user_id ='$mywebsiteuser'";
$sql= $mysqli->query($query) or die($mysqli->error.__LINE__); // or whatever else to check is the query fails.
if ($sql->num_rows != 0){
//etc. retrieve data and set the sessions.
// already got some credentials stored?
if ( isset($_SESSION['access_token']) ) {
$tmhOAuth->config['user_token'] = $_SESSION['access_token']['oauth_token'];
$tmhOAuth->config['user_secret'] = $_SESSION['access_token']['oauth_token_secret'];
$code = $tmhOAuth->request('GET', $tmhOAuth->url('1/account/verify_credentials'));
if ($code == 200) {
$resp = json_decode($tmhOAuth->response['response']);
echo $resp->screen_name;
echo $resp->id;
//Etc. Instead of printing them you it's a good idea to store them in the db.
} else {
outputError($tmhOAuth);
}
// we're being called back by Twitter
} elseif (isset($_REQUEST['oauth_verifier'])) {
$tmhOAuth->config['user_token'] = $_SESSION['oauth']['oauth_token'];
$tmhOAuth->config['user_secret'] = $_SESSION['oauth']['oauth_token_secret'];
$code = $tmhOAuth->request('POST', $tmhOAuth->url('oauth/access_token', ''), array(
'oauth_verifier' => $_REQUEST['oauth_verifier']
));
if ($code == 200) {
//etc.
Anyhow, all in all, in order to get the info of a user you need them to authorize your app first. I check if I have something from my user with the user's session variables on my website, not through twitter. If I have nothing stored, I ask them to authorize the app. I hope this helps.
Access Token : 1274865264-QiVY50RGnmJz6AU9IPRxxiXfv4DYqo0nj6wg8hS
Access Token Secret : fZQnHSuSpwARicIdLqkqQLy1JeG9LxrbNIRKypWcGR
First part of Access Token is user id

PHP Facebook API Post on page's wall

I know, this question was asked hundred times, but none of the given solutions works for me.
I'm trying to post on the wall of every page the current user owns. So, I first get the permissions to publish_actions, read_stream, manage_pages and offline_access. Then I check via /me/permissions, that the user really granted those permissions.
Then, I try to get all pages of the user and post on the wall of the page, if the user is the admin:
$accounts = $facebook->api("/me/accounts", "GET", array("access_token"=>$facebook->getAccessToken()));
$data = $accounts["data"];
foreach ($data as $page)
{
if (isset($page["perms"]) && in_array("CREATE_CONTENT", $page["perms"])))
{
$facebook->api("/".$page["id"]."/feed", "POST", array("link"=>$link, "access_token"=>$page["access_token"]));
}
}
But, posting on the wall of the page fails, with the well known error message
Uncaught OAuthException: (#200) The user hasn't authorized the application to perform this action
Any ideas? Where's my fault?
If you can make the same call via the Graph API Explorer or cURL for one of the pages then your logic is right. So I would place a try/catch on the page/id call to see if a specific page is messing up the loop.
try {
$facebook->api("/".$page["id"]."/feed", "POST", array("link"=>$link, "access_token"=>$page["access_token"]));
} catch (FacebookApiException $e) {
error_log($e . " for: " .$page["id"] );
}
}

How to check if a user installed the app?

I have an app on facebook, which is kind of a competition between users. Each user gains points and the one with most points wins.
I keep the IDs of the users in a table in my database. When a user enters the app, there's a script that checks if he is already in the table, and if not, it adds the user id to the table.
Then, I have a page that shows all of the users and how many points they have. I get through the graph api the user's name by his ID, and then shows it on a nice table.
The only problem is: when a user that used the application once deletes it from his installed application on facebook, I can't get his name anymore, and I get an uncaught OAuth exception.
How can I check if the user has installed the app, so I can display his name only if the app is currently installed on his facebook?
Basically, here is what you would need to do.
<?php
include_once("facebook.php");
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET
));
$user = $facebook->getUser();
try {
$user_profile = $facebook->api('/me');
} catch(FacebookApiException $e) {
$user = null;
}
if($user) {
// authenticated user
$name = $user_profile['name'];
}
This makes an API request for the current logged in user and, provided it fails, catches the exception and sets the $user variable to null. Then you can do a simple check to see if $user exists.
Hopefully this will point you in the right direction.
I would like to suggest to check this client side.
Then when a user returns you can execute this to see if the permissions are still available, and if not request them again:
FB.getLoginStatus(function(response){
if(response.status == 'connected'){
appisinstalled-actonthis();
}else{
// request permissions
FB.login(function(response){
if(response.status == 'connected'){
appisinstalled-actonthis();
}else{
handlethecancelpermissions();
}
});
}
});
Within your appisinstalled-actonthis function you can then add there name and/or profile pic
Just my two cents!

PHP function to get Facebook status?

I'm looking for a good, simple PHP function to get my latest Facebook status updates. Anyone know of one?
Thanks!
EDIT: I've added a half-solution below.
Or if anyone knows a good way to read in the RSS feed and spit out the recent status update?
A quick check on PEAR found Services_Facebook
This is an incomplete answer, but this is what I've gotten so far:
First: add the developer application on FB. Then create a new application. Call it whatever you want.
Second: Download the PHP client. Dump it somewhere on your webhost, i.e. /facebook/
Third: Copy the following beginner code to get yourself started into a php file:
<?php
require_once('facebook/php/facebook.php');
$facebook = new Facebook("YOUR_API_KEY","YOUR_SECRET_KEY");
$result = $facebook->api_client->fql_query("SELECT status FROM user WHERE uid = YOURIDNUMBER");
// OR --- they both get the same data
$result = $facebook->api_client->users_getInfo(YOURIDNUMBER,'status');
print_r($result);
echo "<pre>Debug:" . print_r($facebook,true) . "</pre>"; // debug info
?>
Other info:
You must be logged in and have the
application added. OR you give the
application offline_access
permissions and have the
aapplication added.
You can add offline_access by typing
in the following url:
http://www.facebook.com/authorize.php?api_key=YOUR_API_KEY&v=1.0&ext_perm=offline_access
more info on permissions found here: http://wiki.developers.facebook.com/index.php/Extended_permissions
I'm at a stopping point: anything my
program calls the fql query or
users_getInfo, my page stops
executing the php? I'm guessing
there are a limited amount of calls
for new applications? I've never
done any FB development so I'm
completely new to it. Maybe make
the call and save your recent status
(or most recent statuses) in your
own DB to prevent excessive calls to
the API?
I hope this helps someone get started!
EDIT: It seems that FB won't let you access someones status, even if the offline_access is on, unless you are that person or their friend (depending on their privacy settings).
I did however, finally manage to find the RSS feed in the new profile version: http://www.new.facebook.com/minifeed.php?filter=11
I have found a way to fetch your latest facebook status. This is how you do it:
1) Create a facebook app, and copy your application secret and application id.
2) Grant the app read_stream and offline_access to your profile. (http://developers.facebook.com/docs/authentication/permissions) To fetch your latest status the app needs an access_token. With offline_access granted the access_token should "never" expire. The easiest way to do this is to click the button generated by this code: (be sure to fill in 'your app id' and set cookie to true!)
<fb:login-button perms="read_stream,offline_access"></fb:login-button>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>FB.init({appId: 'your app id', status: true, cookie: true, xfbml: true});</script>
3) Now try to find out what access_token it is using. The access_token is saved in the fbs_appId cookie. Locate it using your browser or using $_COOKIE['fbs_appId']. Look for access_token=....
4) Now that you have a (hopefully) never expiring access_token you can use the following code:
$access_token='xxxxxxxxxxxxxxxxxxxx';
$appId='123456789132456789';
$appSecret='xxxxxxxxxxxxxxxxxxxx';
$profileId='123456789';
//http://github.com/facebook/php-sdk/blob/master/src/facebook.php
require 'facebook.php';
$facebook = new Facebook(array('appId' => $appId,'secret' => $appSecret));
$response = $facebook->api('/'.$profileId.'/feed?limit=1&access_token='.$access_token);
5) The message part should be located: $response['data'][0]['message']
I don't know HOW long the access token is valid. Facebook says:
Enables your application to perform authorized requests on behalf of the user at any time. By default, most access tokens expire after a short time period to ensure applications only make requests on behalf of the user when the are actively using the application. This permission makes the access token returned by our OAuth endpoint long-lived.
Here is a REALLY simple function if you just want to get the latest status. It doesn't depend on the Facebook SDK or anything. You just need CURL and JSON support.
Simple PHP function to get facebook status
I never seem to get along with PEAR, but if you have better luck than I, then the PEAR solution seems the best route long term.
Another idea is to explore the Facebook Developer API library and see if that might give you anything you are looking for.
Lastly, there used to be a way to get an RSS feed... but I can't seem to find any instructions that work anymore, but you might poke around Facebook help if that interests you. Mine ends up looking something like this:
http://www.new.facebook.com/feeds/status.php?id=[idnumber]&viewer=[viewer]&key=[key]&format=rss20
I got it working using Jens' post to retrieve a valid access_token. Then, I extracted the status messages and the time of posting from the xml file using the following code (you can change $limit to display more or less status messages, or use a form to change it).
Be sure to put in your Facebook ID and the access token you got from the app you created (see Jens' post). You can check the output of this script here.
Have fun!
<?php
if(isset($_POST['limit'])) {
$limit = $_POST['limit'];
}
else {
$limit = 3; // number of status messages to display
}
$f = fopen ("https://api.facebook.com/method/status.get?uid=YOUR_FACEBOOK_ID&limit=".$limit."&access_token=YOUR_ACCESS_TOKEN", "r");
while ($line= htmlentities(fgets($f))) {
if ($line===FALSE) print ("FALSE\n");
else
{
$content = $content." ".$line;
}
}
fclose ($f);
$message = explode("<message>", $content); // search for the <message> tag
$message_cnt = count($message);
$msg_index = 0;
$time = explode("<time>", $content); // search for the <time> tag
for($i=1; $i<$message_cnt; $i++)
{
$tmp = explode("</message&gt", $message[$i]);
$msg[$msg_index] = $tmp[0]; // status message
$tmp2 = explode("</time&gt", $time[$i]);
$t[$msg_index++] = $tmp2[0]; // time of posting
}
for($i=0; $i<$msg_index; $i++)
{
echo("<span class=\"status\">".preg_replace('!\015\012|\015|\012!','<br>',$msg[$i])."</span><br>\n
<span class=\"date\">on ".date("d.m.Y", $t[$i])." at ".date("H:i",$t[$i])."</span><br><br>\n");
}
?>
I have tried loads of tutorials over the last few days and none of them have worked. I think it may be due to facebook changing their api requirements. This is the only one I found that works at the moment:
http://www.deanblog.co.uk/article/13/adding-a-facebook-status-feed-to-your-website-with-php
Just use PHPforFB framework (www.phpforfb.com/en/) for the fastest way.
The code looks like this:
require_once('phpforfb_framework.php');
$structInit = array('app_id' => APP_ID,'app_name' => APP_NAME,'sec_key' => APP_SECKEY);
$FacebookAPP = new PHPforFB($structInit);
if($FacebookAPP->lastErrorCode>0){
//Creation failed => Display error message and exit
echo "PHPforFB Error: ".$FacebookAPP->lastErrorCode." -> ".$FacebookAPP->lastError;
}else{
//PHPforFB framework established
if($FacebookAPP->userLoggedIn === TRUE){
//If the user is logged in at Facebook:
//Here you can determine if the user has at least once before
//granted basic permissions to your application.
if($FacebookAPP->userAuthenticated === FALSE){
//The user has not yet granted permissions
//**your code here**
}else{
//The user has already granted permissions, therefore his Facebook ID
//is known to us. It is always available in $FacebookAPP->userID:
$userID = $FacebookAPP->userID;
//**your code here**
}
}
}
Since I couldn't use the API route, I went with the RSS found at: http://www.new.facebook.com/minifeed.php?filter=11
And used the following PHP function, called StatusPress, with some of my own modifications, to parse the RSS feed for my Facebook status. Works great!
<?php
// see http://github.com/facebook/php-sdk/blob/master/facebook.php
require './facebook.php';
// Create our Application instance.
// see http://www.youtube.com/watch?v=jYqx-RtmkeU for how to get these numbers
$facebook = new Facebook(array('appId' => 'XXX','secret' => 'XXX'));
// This call will always work since we are fetching public data.
// this could be /username or /username/friends etc...
// see developer api for FQL for examples
$status = $facebook->api('/haanmc/feed?limit=1');
?>
<p><?php print $status['data'][0]['message']; ?></p>
<p>Likes: <?php print $status['data'][0]['likes']; ?> | Comments: <?php print count($status['data'][0]['comments']['data']); ?></p>
<textarea style="width: 95%; height: 600px;"><?php print_r($status); ?></textarea>

Categories