How to delete a notification from a game request - facebook

I am trying to delete an application notification on application load.
So when I invite my friend he gets a notification and requests "ok" and if he clicks on it then it should be deleted. How? I have tried multiple ways but haven't succeeded.
$REQIDs=$_REQUEST['request_ids'];
$user_profile = $facebook->api('/me');
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=XXXXXXXX&client_secret=XXXXXXX&grant_type=client_credentials";
$access_token = file_get_contents($token_url);
if($REQIDs){
$requests = explode(',',$REQIDs);
foreach($requests as $request_id){
$deleted = file_get_contents("https://graph.facebook.com/$request_id?$access_token&method=delete");
//not working ->> {"error":{"type":"GraphMethodException","message":"Unsupported delete request."}}
$deleted = file_get_contents("https://graph.facebook.com/".$user_profile['id']."_".$request_id."?".$access_token);
//not working ->> false
$deleted = $facebook->api($request_id."?".$access_token, "DELETE");
//not working ->> Fatal error: Uncaught GraphMethodException: Unsupported delete request.
}
}
Anyone have some ideas or see the error?

Take a look at this topic here >>> Topic. It explains pretty fully how to handle apprequests.
Your code should look like this:
$reqId = $_GET['request_ids']; // Get the id of the current request
$requests = $facebook->api('/me/apprequests/?request_ids='.$reqId); //Get the request. Not sure if this is correct for specific request
$itemData = $requests[data][0][data]; //Get the data that was originally sent in the request
//Some code here to do whatever with the data
$delete_url = "https://graph.facebook.com/".$reqId."?access_token=".$token."&method=delete";
$result = file_get_contents($delete_url); //Delete the request so there is only one there next time.
This is supposed to do the work.
Good luck!

Facebook will pass you the request ids when your user clicks through. You can then make a call to this url to delete the request:
https://graph.facebook.com/[request_ids]?access_token=[your_app_accessToken]&method=delete
Note that if your application has sent a few requests to a single user, when they click the Notification Jewel in their FB header menu, your code will be sent all request ids in a comma separated string. You will need to code around this fact. I think I'm right in saying that the order of the ids in this string is oldest -> newest so to delete the most recent, you need to parse out the last id in the string and delete it.

Related

Facebook Request Dialog with data

I read this article.
So, I tried it and I put a number in the data property.
FB.ui({
method: 'apprequests',
message: 'Come join me and play at MyWebSite!',
data: '12345',
redirect_uri: 'myWebSite'
});
I get the request_ids, but how do I get the data part (the 12345 number)?.
on server side, you can do something like:(using php here)
$request_ids = $_GET['request_ids'];
$request_ids = explode(",", $request_ids);
foreach($request_ids as $request_id)
{
$request_object = $facebook->api($request_id);
if(isset($request_object['data'])) $req_data = $request_object['data']; //$req_data will be '12345' as per your request data set.
// after getting the data, you may like to delete the request.
$full_request_id = $request_id."_".$fbid; //$fbid is current user facebook id
$facebook->api("$full_request_id","DELETE");
}
Did you try Facebook's documentation too?
https://developers.facebook.com/docs/requests/ has more documentation; if a data parameter was added in the call to the requests dialog, the same value should also be there when requesting the Request details via the API (i.e. a call to /REQUEST_ID)
See the facebook developer site documentation for more details
http://developers.facebook.com/docs/reference/dialogs/requests/
Note:
data:Optional, additional data you may pass for tracking. This will be stored as part of the request objects created. The maximum length is 255 characters.

Retrieve User ID of Facebook App Invitor

In the context of a given Facebook app, suppose User A invited user B to start using it. Once User B accepts to use the app, is there any way to retrieve the ID of User A programmatically (via either PHP/JS SDK) ? This doesn't seem quite documented.
For what it's worth, A/B users are friends, if it's any use.
when user comes following the app request, you can get request id's using
$_GET['request_ids']
then retrieve all the request ids with which you can call graph api to get the corresponding request details like below:
if(isset($_GET['request_ids']))
{
$request_ids = $_GET['request_ids'];
}
$request_ids = explode(",", $request_ids);
foreach($request_ids as $request_id)
{
$request_object = $facebook->api($request_id);
//this $request_object have sender facebook id in the field uid_from
}
If you look here:
http://developers.facebook.com/docs/reference/dialogs/requests/
You can see the object layout. Of note is the data property:
Optional, additional data you may pass for tracking. This will be
stored as part of the request objects created. The maximum length is
255 characters.
In this object you can add your referring UserId and then when the request is claimed, you can then process it on your end.
Hope this helps.

Has the response from FB.ui requests changed?

It used to be that the response from a request gave us an array of request ids (as described here http://developers.facebook.com/docs/reference/dialogs/requests/) but it seems now the response variable returns two items insead 'to' and 'request'. To being a comma delimited string of user ids and request being a request id. Is this correct? I have seen nothing about this anywhere but it is the behavior I am seeing currently.
Update
Here is a super simplified version of my call:
FB.ui({method: 'apprequests', message: 'My Great Request'}, requestCallback);
function requestCallback(response) {
for(var key in response){
console.log(key);
console.log(response[key]);
}
}
When I make a request to one person the variable response has two keys: request and to. Request is a request id, to is the id of the person I'm sending the request to. If I make a call to the graph api using the provided request id, however, I find that the user under both 'to' and 'from' are equal to the sender's name and fbid.
Alternatively, if I request to multiple people request is equal to a single request id and to is an array containing all the fbids of the users that had requests sent to them. When I make a call to the graph api, however, I once more find that both 'to' and 'from' contain the user id and name of the requesting user.
I faced similar issue yesterday. Had to fix my code. But today request_ids were back in the response. So I updated the code again. But this time to work with both type of objects.
I found the documentation here (move down to the "Performance improvements" section)
http://developers.facebook.com/blog/post/569/
But it still doesn't explains why they reverted the change today. Or was it accidently released yesterday.
As in the documentation, the new callback will receive an object (response) that contains an array (request_ids) of request ids:
{
"request_ids": [
0: [request_id]
1: [request_id]
...
]
}
So I suppose you can loop using this modified code:
function requestCallback(response) {
for( var k in response.request_ids ) {
console.log(k);
console.log(response.request_ids[k]);
}
}
There is already a bug filed here
http://developers.facebook.com/bugs/129565473812085
There is no clear information yet whether the response is really changed or its a bug.

Facebook Credits Example on App Engine?

Are there any examples of using facebook credits on Google App Engine?
I found this blog post , but it's not complete
http://blog.suinova.com/2011/01/integrating-facebook-credits-api-into.html
I got the sample runwithfriends example working on the App Engine, tried to expand it with Credits, no luck so far.
Also searched for the FB developer forums, got nothing.
Any resources you can point me to?
What's not working:
1) When I click on the "pay with Facebook" button, I get an "Application Error" , without any error code.
-Checked the javascript console
-Checked the fb app settings
-Tried on local server and production server
2) The callback.py isn't complete, because i could not parse the signed request (no code available in py for me to learn from)
3) What I basically did was to add code from Suinova Designs (link above) to the existing Run With Friends app code. Didn't turn out as expected.
my code so far:
//payment_page.html
<html>
<table>
<tr><th>Name</th><th>Price</th><th> </th></tr>
<tr><td>Something to buy</td><td>10 FC</td><td><a href="" onclick="return buyit();">
<img src="http://www.facebook.com/connect/button.php?app_id=215638625132268&feature=payments&type=light_l" />
</a></td></tr>
</table>
// javascript
function buyit(){
FB.ui({
method:'pay',
purchase_type:'item',
order_info:{
item_id:'myitem',
title:'Something to buy',
price:2,
description:'Whatever',
image_url:'http://www.facebook.com/images/gifts/21.png',
product_url:'http://www.facebook.com/images/gifts/21.png'}
},
function(resp){
if(resp.order_id) window.top.location='http://apps.facebook.com/runwithfriends trial'; else alert(resp.error_message);
});
return false;
}
//callback.py
class FacebookPaymentRequest(webapp.RequestHandler):
def post(self):
signed_request = parse_signed_request(self.request.get('signed_request'),conf.FACEBOOK_APP_SECRET)
payload = signed_request['credits'] #credits:{buyer:int,order_id:int,order_info:{},receiver:int}
order_id = payload['order_id']
method = web.request.get('method')
return_data = {'method':method}
if method == 'payments_get_items':
order_info = payload['order_info'] #order_info:{item_id:'',title:'',description:'',price:0,image_url:'',product_url:''}
item = simplejson.loads(order_info) #needs to convert JSON string to dict
#check item,price,etc and reply
return_data['content'] = [item]
elif method == 'payments_status_update':
status = payload['status']
return_data['content'] = {'status':'settled','order_id':order_id}
if status == 'placed':
#just return settled status to Facebook, this may be called twice
order_details = simplejson.loads(payload['order_details'])
#check and log here
elif status == 'settled':
order_details = simplejson.loads(payload['order_details'])
#order_details:{order_id:0,buyer:0,app:0,receiver:0,amount:0,update_time:0,time_placed:0,data:'',items:[{}],status:'placed'}
buyer = order_details['buyer']
item = order_details['items'][0]
#now save this transaction into our database
else:
#may be refunded, canceled, log the activity here
return_data['content']['status'] = status
self.response.out.write(simplejson.dumps(return_data))
Your python code looks fairly normal so I would guess that you are simply having trouble with your authorization. Depending upon how you authorize (a process a fair amount more complicated that the credits system), you are likely being given a signed request that is only partially authorized... meaning you are authorized to access only certain parts of facebook, but generally not authorized to access the active/logged-in user (i.e. me).
You can verify this by determining if you signed_request is a full 80+ characters (as opposed to around 40). Generally I try to authenticate by deciphering the profile (signed_request), if that fails then I try to use a previously stored cookie, then if that fails I try to relogin the user. I determine failure by placing try/except around my calls to get a "me" object through the GraphAPI.

Find Facebook user (url to profile page) by known email address

I have an email address and want to find out if there is a Facebook user linked to this address. If there is, then I want to retrieve the url to this users profile page and save it somewhere.
I do not have a facebook application, but, if necessary, I would use existing account data to login to facebook and perform the task.
I thought this would be an easy task, but somehow it's not. I read through the Graph API documentation and there you find instructions on how to search public data. It says the format is:
https://graph.facebook.com/search?q=QUERY&type=OBJECT_TYPE
But trying this with an email address in the q param and user in the type param without further information results in an OAuthException saying "An access token is required to request this resource."
However, if you click the example search links Facebook generates a url with the mentioned access token related to the currently logged on user. Performing searches with this token gives the expected results. But i cannot figure out how to get this user session access token after logging in. Every time I search on how to get an access token I only find information regarding Facebook apps and retrieving permissions for basic or specific data access. This is, as I mentioned, not what I am looking for, as I don't have and don't need a facebook app.
Since Facebook gives me the needed token in the example links I thought it shouldn't be a problem to get it too. Or do they only have it because of home advantage?
Also, the Outlook Social Connector Provider for Facebook is able to retrieve Facebook data just via an email address (and the account data provided). So I thought, if Microsoft can do this stuff I should be also possible to do simliar things.
Last but not least this is the more frustrating since I, theoretically and practically, am already able to find users profile url just by searching for the email address. I don't even have to be logged on to Facebook. And it's not the official API way.
If I perform a web request to http://www.facebook.com/search.php?init=s:email&q=example#domain.com&type=users I get the expected search result. The problem is that I have to parse the HTML code and extract the url (that's okay) and that the result page is possibly subject to change and could easily break my method to extract the url (problematic).
So does anybody has an idea what's the best way to accomplish the given task?
The definitive answer to this is from Facebook themselves. In post today at https://developers.facebook.com/bugs/335452696581712 a Facebook dev says
The ability to pass in an e-mail address into the "user" search type was
removed on July 10, 2013. This search type only returns results that match
a user's name (including alternate name).
So, alas, the simple answer is you can no longer search for users by their email address. This sucks, but that's Facebook's new rules.
Simply use the graph API with this url format:
https://graph.facebook.com/search?q=zuck#fb.com&type=user&access_token=... You can easily create an application here and grab an access token for it here. I believe you get an estimated 600 requests per 600 seconds, although this isn't documented.
If you are doing this in bulk, you could use batch requests in batches of 20 email addresses. This may help with rate limits (I am not sure if you get 600 batch requests per 600 seconds or 600 individual requests).
In response to the bug filed here: http://developers.facebook.com/bugs/167188686695750 a Facebook engineer replied:
This is by design, searching for users is intended to be a user to user function only, for use in finding new friends or searching by email to find existing contacts on Facebook. The "scraping" mentioned on StackOverflow is specifically against our Terms of Service https://www.facebook.com/terms.php and in fact the only legitimate way to search for users on Facebook is when you are a user.
Maybe this is a little bit late but I found a web site which gives social media account details by know email addreess. It is https://www.fullcontact.com
You can use Person Api there and get the info.
This is a type of get : https://api.fullcontact.com/v2/person.xml?email=someone#****&apiKey=********
Also there is xml or json choice.
I've captured the communication of Outlook plugin for Facebook and here is the POST request
https://api.facebook.com/method/fql.multiquery
access_token=TOKEN&queries={"USER0":"select '0', uid, name, birthday_date, profile_url, pic, website from user where uid in (select uid from email where email in ('EMAIL_HASH'))","PENDING_OUT":"select uid_to from friend_request where uid_from = MY_ID and (uid_to IN (select uid from #USER0))"}
where
TOKEN - valid access token
EMAIL_HASH - combination of CRC32 and MD5 hash of searched email address in format crc32_md5
MY_ID - ID of facebook profile of access token owner
But when I run this query with different access token (generated for my own application) the server response is: "The table you requested does not exist" I also haven't found the table email in Facebook API documentation. Does Microsoft have some extra rights at Facebook?
Andreas,
I've also been looking for an "email-to-id" ellegant solution and couldn't find one.
However, as you said, screen scraping is not such a bad idea in this case, because emails are unique and you either get a single match or none. As long as Facebook don't change their search page drastically, the following will do the trick:
final static String USER_SEARCH_QUERY = "http://www.facebook.com/search.php?init=s:email&q=%s&type=users";
final static String USER_URL_PREFIX = "http://www.facebook.com/profile.php?id=";
public static String emailToID(String email)
{
try
{
String html = getHTML(String.format(USER_SEARCH_QUERY, email));
if (html != null)
{
int i = html.indexOf(USER_URL_PREFIX) + USER_URL_PREFIX.length();
if (i > 0)
{
StringBuilder sb = new StringBuilder();
char c;
while (Character.isDigit(c = html.charAt(i++)))
sb.append(c);
if (sb.length() > 0)
return sb.toString();
}
}
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
private static String getHTML(String htmlUrl) throws MalformedURLException, IOException
{
StringBuilder response = new StringBuilder();
URL url = new URL(htmlUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("GET");
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
BufferedReader input = new BufferedReader(new InputStreamReader(httpConn.getInputStream()), 8192);
String strLine = null;
while ((strLine = input.readLine()) != null)
response.append(strLine);
input.close();
}
return (response.length() == 0) ? null : response.toString();
}
This is appeared as pretty easy task, as Facebook don't hiding user emails or phones from me. So here is html parsing function on PHP with cURL
/*
Search Facebook without authorization
Query
user name, e-mail, phone, page etc
Types of search
all, people, pages, places, groups, apps, events
Result
Array with facebook page names ( facebook.com/{page} )
By 57ar7up
Date 2016
*/
function facebook_search($query, $type = 'all'){
$url = 'http://www.facebook.com/search/'.$type.'/?q='.$query;
$user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36';
$c = curl_init();
curl_setopt_array($c, array(
CURLOPT_URL => $url,
CURLOPT_USERAGENT => $user_agent,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_SSL_VERIFYPEER => FALSE
));
$data = curl_exec($c);
preg_match_all('/href=\"https:\/\/www.facebook.com\/(([^\"\/]+)|people\/([^\"]+\/\d+))[\/]?\"/', $data, $matches);
if($matches[3][0] != FALSE){ // facebook.com/people/name/id
$pages = array_map(function($el){
return explode('/', $el)[0];
}, $matches[3]);
} else // facebook.com/name
$pages = $matches[2];
return array_filter(array_unique($pages)); // Removing duplicates and empty values
}
Facebook has a strict policy on sharing only the content which a profile makes public to the end user.. Still what you want is possible if the user has actually left the email id open to public domain..
A wild try u can do is send batch requests for the maximum possible batch size to ids..."http://graph.facebook.com/ .. and parse the result to check if email exists and if it does then it matches to the one you want.. you don't need any access_token for the public information ..
in case you want email id of a FB user only possible way is that they authorize ur app and then you can use the access_token thus generated for the required task.
Maybe things changed, but I recall rapleaf had a service where you enter an email address and you could receive a facebook id.
https://www.rapleaf.com/
If something was not in there, one could "sign up" with the email, and it should have a chance to get the data after a while.
I came across this when using a search tool called Maltego a few years back.
The app uses many types of "transforms", and a few where related to facebook and twitter etc..
..or find some new sqli's on fb and fb apps, hehe. :)
WARNING: Old and outdated answer. Do not use
I think that you will have to go for your last solution, scraping the result page of the search, because you can only search by email with the API into those users that have authorized your APP (and you will need one because the token that FB provides in the examples has an expiry date and you need extended permissions to access the user's email).
The only approach that I have not tried, but I think it's limited in the same way, is FQL. Something like
SELECT * FROM user WHERE email 'your#email.com'
First I thank you. # 57ar7up and I will add the following code it helps in finding the return phone number.
function index(){
// $keyword = "0946664869";
$sql = "SELECT * FROM phone_find LIMIT 10";
$result = $this->GlobalMD->query_global($sql);
$fb = array();
foreach($result as $value){
$keyword = $value['phone'];
$fb[] = $this->facebook_search($keyword);
}
var_dump($fb);
}
function facebook_search($query, $type = 'all'){
$url = 'http://www.facebook.com/search/'.$type.'/?q='.$query;
$user_agent = $this->loaduserAgent();
$c = curl_init();
curl_setopt_array($c, array(
CURLOPT_URL => $url,
CURLOPT_USERAGENT => $user_agent,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_SSL_VERIFYPEER => FALSE
));
$data = curl_exec($c);
preg_match('/\{"id":(?P<fbUserId>\d+)\,/', $data, $matches);
if(isset($matches["fbUserId"]) && $matches["fbUserId"] != ""){
$fbUserId = $matches["fbUserId"];
$params = array($query,$fbUserId);
}else{
$fbUserId = "";
$params = array($query,$fbUserId);
}
return $params;
}