Post to user's wall as if it is them posting - facebook

I have an app and I am able to post to a user's wall when they allow it. However, when the app makes a wall post, it shows that it is from me (the administrator of the app) posting on the user's wall. I want it to look like it was the actual user posting on their own wall... (using VS 2008, .Net 3.5)
Here is my code...
Dim oFB As Facebook.FacebookClient
Dim sAppId As String = "my app id"
Dim sAppSecret As String = "it's a secret"
Dim webClient As System.Net.WebClient = New System.Net.WebClient()
Dim result As String = webClient.DownloadString("https://graph.facebook.com/oauth/access_token?client_id=" & sAppId & "&client_secret=" & sAppSecret & "&grant_type=client_credentials")
'- Access token changes every hour
oFB = New Facebook.FacebookClient(sAppId, sAppSecret)
oFB.AccessToken = result.Substring(result.IndexOf("=") + 1)
Dim oPost As Collections.Generic.IDictionary(Of String, Object)
oPost = New Collections.Generic.Dictionary(Of String, Object)
oPost.Add("message", "(websitepipeline test post) Check out this new product!") '- This is the wall post / the description input for the DM function
oPost.Add("link", "http://www.example.com/content/somepage.html")
oPost.Add("from", "the user who authenticated")
oFB.Post("the user who authenticated/feed", oPost)

Here's a link to a library someone made for .NET that it wraps around ;) [link]http://www.lagorio.net/windows/facebook/) Obviously you will need to present a FBDialog asking the user for his credentials of course! :) Not too sure what library your using but maybe the string for "from" is incorrect or needs to be a user token of some sort
Use the .setStatus command w/ this API.

Related

Send an email from access via Lotus iNotes installed on intranet

I just need to be pointed in the right direction, on how
to send an email using VBA. I have Lotus as an email system which is embedded into our intranet system.
As a try, this code prepares an email and send it via Lotus (installed on pc) :
Dim ns As New NotesSession
Dim db As NotesDatabase
Dim doc As NotesDocument
Dim sender, recipient As String
'sender = Forms![LogIn]![TxtEmail]
If (Not IsNull(DLookup("Email", "Users", "UserName ='" & Me.Affectation.Value & "'"))) Then
recipient = DLookup("Email", "Users", "UserName ='" & Me.Affectation.Value & "'")
MsgBox "recipient *" & recipient & "*"
Else
MsgBox " recipient null"
End If
If Not (ns Is Nothing) Then
Call ns.InitializeUsingNotesUserName("CN=MyuserName/O=Cmpany", "password")
Set db = ns.GetDatabase("ServerName", "mail\MyuserName.nsf", False)
If (Not (db Is Nothing)) Then
Set doc = db.CreateDocument()
doc.Form = "Memo"
doc.SendTo = recipient
doc.subject = "Email Subject"
Dim rt As NotesRichTextItem
Set rt = doc.CreateRichTextItem("Body")
rt.AppendText ("Body text")
doc.Send (False)
Set rt = Nothing
Set doc = Nothing
MsgBox "Message Sent."
Else
MsgBox "db Is Nothing"
End If
Set db = Nothing
Set ns = Nothing
Else
MsgBox "ns Is Nothing"
End If
My question here is how set this code to make the target Lotus the one on our intranet: my login is such "39398C#mycompany.com" and the application is accessed by "http://mail.mycompany.com/mail/username.nsf..."
Unfortunately this is not possible this way. This "embedded" Lotus Notes as you call it is a simple website. It is called "iNotes" and does not have any dlls installed on your client (unless you install the ActiveX control for IE, but that does not help anything with your problem).
For sending eMails via iNotes you need a complete new method and you need your Domino administrator to help you with it: You could either use a webservice to send your mail (this has to be enabled on the server) or you can use DIIOP (again: DIIOP- Task has to be loaded on server).
To at least compose an email, you could use the mailto: protocol, but you need to set iNotes to be your mailto- protocol- handler:
Open Internet Explorer browser and log into iNotes (http://mail.mycompany.com/mail/username.nsf). Please note that this option is not available at this time to Firefox browser users.
Click the "Preferences" button located in the top right corner.
Find "Default Mail Client" section on the "Basics" tab of the iNotes preferences.
Click the button "Make Default".
Using this approach you cannot send the mail directly but need the user to press "Send".
I am not sure what you mean by "I have Lotus as an email system which is embedded into our intranet system".
You need the Notes client installed locally to be able to use COM in your own code. Use the ID file (must be local in the Notes Data directory) for your corporate account amd point to the server on the network for your mailfile.
But you can't point your program to a iNotes instance on a web server, it has to be on a Domino server accessed with a Notes client.
What you could do is to create a new web application on the server, where you have an agent that will read HTTP POST data, create an email and send it out.
Then you simply make a HTTP post from your application.
Here are a couple of blog entries I wrote that might help you:
http://blog.texasswede.com/free-code-class-to-read-url-name-value-pairs/
http://blog.texasswede.com/parse-url-in-domino-agent/
You should probably change your code to send mail via SMTP instead of using the Notes API objects. Microsoft provides an object model called CDO that I think will help you. See the answer to theis question for details. You will just need the hostname or IP address information to connect to a Domino server in your infrastructure that supports inbound SMTP.
Not sure about it, because that code is pretty old as we know use Outlook and I haven't use it in a long while, but that might be some insight :
I seem to remember that if you add doc.From = ns.CommonUserName, this will choose your session automatically!
And the full code :
Dim session As Object
Dim db As Object
Dim doc As Object
Dim attachme As Object
Dim EmbedObj As Object
Dim attachment() As String
Dim i As Integer
Set session = CreateObject("notes.notessession")
Set db = session.GetDatabase("", "")
Call db.OPENMAIL
Set doc = db.CreateDocument
With doc
.Form = "Memo"
.sendto = MailDestinataire
'.copyto = MailDestinataire2
.Subject = Sujet
.Body = CorpsMessage
.From = session.CommonUserName
.posteddate = Now
.SaveMessageOnSend = True
End With

Facebook Private Messaging

It is said, that it is not possible to initiate new conversation through the API alone, except using Facebook's own Form integrated in the app. Is this correct, or is there some new API, which enables me to initiate a new conversation?
To reply to an existing conversation, I retrieved the conversations id using the following FQL Query "SELECT thread_id, . WHERE viewer_id={0} AND folder_id=0". Afterwards I retrieved the PageAccessToken for my app page using my user Access token, and tried to use this call:
*You can reply to a user's message by issuing an HTTP POST to /CONVERSATION_ID/messages with the following parameters [conversation id, message]. A conversation ID look like t_id.216477638451347.*
My POST Call looked like this (this is not a valid thread id): /t_id.2319203912/messages with message parameter filled. But it always said "Unknown method". Can you help me out with this one? Is there a parameter missing? I passed in the page's Access Token to call this one.
Is there some API out (except Facebook's Chat API), that I am missing, which can send private messages to users?
Edit:
What I wonder about is, that the code below only returns a single page, the application's page. Is this correct, or is there another page token required? This is what bugged me the most about the returned page.
The FacebookClient uses my UserToken to perform the next following task.
This is the code to retrieve my Page Access Token:
dynamic pageService = FacebookContext.FacebookClient.GetTaskAsync("/"+UserId+"/accounts").Result;
dynamic pageResult = pageService.data[0];
_pageId = pageResult["id"].ToString();
return pageResult["access_token"].ToString();
Now the code to retrieve my ConversationÍd:
dynamic parameters = new ExpandoObject();
parameters.q = string.Format("SELECT thread_id, folder_id, subject, recipients, updated_time, parent_message_id, parent_thread_id, message_count, snippet, snippet_author, object_id, unread, viewer_id FROM thread WHERE viewer_id={0} AND folder_id=0", FacebookContext.UserId);
dynamic conversations = FacebookContext.FacebookClient.GetTaskAsync("/fql",parameters).Result;
The following code is executed using the access token retrieved from the code above (page access token request).
Now the Code used to send the reply:
dynamic parameters = new ExpandoObject();
parameters.message = CurrentAnswer;
string taskString = "/t_id." + _conversationId + "/messages";
dynamic result = FacebookContext.FacebookClient.PostTaskAsync(taskString,parameters).Result;
return true;
I also tried it with facebook's graph API Debugger using the token, which is returned by my first part of code. But with the same error message.

Facebook Registration | Custom Fields Not Returning

I'm attempting to create a Facebook Registration process for our website that will create an account for the user in our CRM - to this end I require the use of a few custom fields in the registration form.
I have the registration form appearing properly on the site, however, when I process the signed_request the JSON only returns the decoded standard items and not my custom fields:
{
"algorithm": "HMAC-SHA256",
"code": "2.AQDp0sgWRw3TWrII.3600.1330650000.1100001862544007|LwjvMjADtPxaIzxizYuIivNdi7w",
"issued_at": 1330644064,
"user_id": "<my user id>"
}
This is a .NET implementation but I am not using the Facebook C# SDK as none of the documentation seems to be available anymore on their site and I'm just not clever enough to figure it out. I tried using the new 6.x beta of the Facebook C# SDK and the Facebook.Client() parse method but didn't have any luck determining what to do with it once the thing was parsed.
So - this stolen code is what I used to get the results posted above:
//client_payload = the signed_request from Facebook
string[] sB64String = client_payload.Split('.');
string payload = client_payload.Replace((sB64String[0] + "."), string.Empty);
var encoding = new UTF8Encoding();
var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
var json = encoding.GetString(base64JsonArray);
var jObject = JObject.Parse(json);
response.write(Convert.ToString(jObject)); // rw for debugging
Maybe I'm missing something?
I've resolved this on my own by modifying the way I was going about it.
I ended up using the tag and client side cookie as found here:
https://developers.facebook.com/docs/plugins/registration/advanced/
All of my custom fields end up in the cookie that I can then parse and send to my .NET webservice. Kind of a round-about way of doing it but it's getting the job done now.

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