Identifying Facebook Messenger user with UserID from a Facebook Login - facebook

I am trying out the new Facebook Messenger Platform and have hit a bit of a problem.
When a user first chats with my Bot, I want to use the sender.id to lookup the user in my DB and verify whether they're a customer or not and offer a more tailored UX.
User's sign up to my service using Facebook Login, but unfortunately it appears my App's Facebook ID & my Bot's Facebook ID are different due to IDs being limited to App-scopes.
Is there any way associate the 2 IDs to allow me to find a user in my DB?
UPDATE (4/20/2016):
We got around this by asking users on first contact via messenger to click a link to login to their account so we could associate their messenger_id with their account in our DB.
Would be awesome if facebook instead included PAGE_SCOPED IDs in the ids_for_business endpoint.
UPDATE: (6/1/2016):
Facebook's latest update includes a new "Account Linking" functionality that appears to solve this issue. See https://developers.facebook.com/docs/messenger-platform/account-linking

Facebook's latest update includes a new "Account Linking" functionality that appears to solve this issue. See https://developers.facebook.com/docs/messenger-platform/account-linking

Unfortunately, there's no way of doing that currently. Asking them to login for new threads is the best way of linking accounts.

Yes. You can get details like first name, last name, profile pic url, locale, timezone, gender from an api. Only you have to pass is their recipient id/sender id and acccess_token of your messenger bot.
https://graph.facebook.com/v2.6/USER_ID?fields=first_name,last_name,profile_pic,locale,timezone,gender&access_token=TOKEN

I solved it different way but it works perfectly by graph API,i read mailbox of my page so that when any one can interact by messenger bot than i read pages inbox and iterate through,
Step 1:
Do a HTTP get request by graph API ,
you want a PAGE_UNIQUE_ID from Graph API ,
GET REQUEST
https://graph.facebook.com/v2.6/<PAGE_UNIQUE_ID>?fields=conversations.limit(10){participants,updated_time,id}&access_token=<PAGE_ACCESS_TOKEN>
PAGE_UNIQUE_ID Hints:
Go ===> https://developers.facebook.com/tools/explorer/ ==> Press "Get Token" ===> Select your desired page ===>Finally Submit , You show a id on output that is PAGE_UNIQUE_ID in here.
Check on browser for resoponse.
Step 2:
After doing above http request ,you get a JSON object that will show latest 10 conversation of pages where desired facebook id included.
Step 3:
Do iteration through by user full name or you can use lodash or underscore at your choice,
getUserID(response,'Zahid Rahman')
function getUserID(response, fullname) {
if (response && response.conversations && response.conversations.data) { //Check response is correct
var conversations = response.conversations.data; //Get all conversations
for (var j = 0; j < conversations.length; j++) {
var conversationsParticipants = conversations[j].participants.data;
for (var k = 0; k < conversationsParticipants.length; k++) { //Get all particiapnts of a single conversation.
var conversationsParticipantsEach = conversationsParticipants[k];
if (conversationsParticipantsEach.name === fullname) { //Check fullname match or not
console.log("Desired Facebook User ID : " + conversationsParticipants[k].id);
return conversationsParticipants[k].id;
}
}
}
}
}
Hope it will help you.

This is probably what you want: https://developers.facebook.com/docs/apps/for-business
It allows you to get all of the app-scoped user ids on a per-business basis.

Related

Facebook Graph API get First and Last name from PSID?

I have setup a FB Webhook to notify my technicians when a user messages my business page. The notification works and I get the message and the sender's ID (PSID) but I can't seem to get the sender's first and last name per the documentation found here :
https://developers.facebook.com/docs/messenger-platform/identity/user-profile
I have been granted Advanced Access with the "Business Asset User Profile Access" as required.
The App is in Live mode (not development mode)
Messaging permissions are granted
I need to turn the returned "Sender ID (PSID)" into a First and Last name. According to the documentation, I need to send a request like this :
curl -X GET "https://graph.facebook.com/<PSID>?fields=first_name,last_name,profile_pic&access_token=<PAGE_ACCESS_TOKEN>"
So my code looks like this :
function get_basic_info($id, $access) {
$url = 'https://graph.facebook.com/'.$id.'?fields=first_name,last_name,profile_pic&access_token='.$access;
$info = json_decode(file_get_contents($url), true);
return $info;
}
I would then call the function using : $fbuser = get_basic_info($sender, $fb_access_token);
This will ALWAYS return NULL when messaging my business page from any Facebook account.... except from my personal account which owns the business page. If I message my business account from my personal account that owns the business, this is what I get back :
{"first_name":"Tim","last_name":"My_Last_Name","profile_pic":"Profile_Picture_URL","id":"My_FB_ID"}
The access token I am using is generated from the App Dashboard > My_App > Messenger (under Products, left side) > Settings > Access Tokens > Generate Token (Next to the Business Page I own).
What am I doing wrong? It works when I personally message my own business page, but not when anyone else messages. Thank you for ANY help!
So to update this with an answer for those who may be looking, here it goes.... Don't use the Sender ID (PSID) as the documentation states, use the Message ID.
function get_basic_info($id, $access) {
$url = 'https://graph.facebook.com/'.$id.'?fields=from&access_token='.$access;
$info = json_decode(file_get_contents($url), true);
return $info;
}
Usage :
$fbuser = get_basic_info($message_id, $FB_PAGE_ACCESS_TOKEN);
$fb_name = $fbuser['from']['name'];
Unfortunately, you cannot get the Profile Picture, but this is as far as I needed to get anyways.
Enjoy!

Ionic with Backand social login: profile picture

I'm developing an application with ionic and Backand and I'm using the sign in with social accounts with the Backand service.
The social login process is OK, but I want to get the ID from Facebook and Google plus in order to get the profile picture.
I was talking with the support of Backand and I know that in Security and Auth there is an action "beforesocialSignUp" and I have not commented the line to get the data:
'use strict';
function backandCallback(userInput, dbRow, parameters, userProfile) {
// get facebook id and put in fuid field that you need to add to your user object
userInput.fuid = parameters.socialProfile.additionalValues.id;
// get gender from facebook and put in gender field that you need to add to your user object
// userInput.gender = parameters.socialProfile.additionalValues.gender;
}
And I have created the fuid field in my user object, but, when I make a login with Facebook or Google+ It doesn't save nothing. The login is OK but I can't get the ID data.
Any idea?
I had exactly the same problem.
The solution was to set the where condition of the BeforeSocialSignUp function from false to true.
This is nowhere in the documentation explained.
It took me 3 day ro figure this out :-(
Now the login works as expected and the fuid field gets assigned.
My next step is to get the profile picture from the FB Account, but therefore I have to make an API request to facebook with a user access token which I dont know how to get from backand.

Facebook Open Graph - Filtering custom actions by custom parameter

I am building a facebook app where a user can 'love' 'pics' (those are the action and object names) from our library of user submitted photos for each of our products. Whenever a user loves a pic, I also send a (required) custom parameter which is the product id.
Is there a way to retrieve the current user's love actions for a particular product id? I am using the javascript fb sdk. I am trying to keep as much facebook related stuff off out of my back end system, so I would prefer to not store user data in my database.
Thanks for any help/advice,
Tom
You'll need to do the filtering yourself, but yes, you can do this. Try something like
// This will return everything the user has loved
FB.api('/me/<your app namespace>:love', function(response) {
for(var i = 0; i < response.data.length; i++) {
var post = response.data[i];
// Make sure that this is a post about loving a pic
// and that the product_id is what we're looking for
if(post.data.hasOwnProperty('pic') &&
post.data.hasOwnProperty('product_id') &&
post.data.product_id == desiredProductId) {
// This is a post for loving a pic for the desired product id
}
}
});

Cannot get page "like" status using Facebook C# SDK

I am using the latest Facebook C# SDK (v5.0.40 at time of writing) from here: http://facebooksdk.codeplex.com/.
I have created a test iFrame app in Facebook and got the CSASPNETFacebookApp sample running so that it displays the name of the currently logged in user within Facebook.
What I would now like to do is display different content in my iFrame depending on whether the user has "liked" the page. However the signed_request never seems to contain that information. From what I can see in the FacebookSignedRequest.cs I will only get the payload which contains the page information if the algorithm is AES-256-CBC HMAC-SHA256 but I only ever get HMAC-SHA256 returned.
What am I doing wrong? How do I get it to return the page information? Is it a problem with the setup of my app in Facebook or a configuration issue with the .NET app?
Thanks in advance.
var fb = new FacebookClient("access_token");
dynamic parameters = new ExpandoObject();
parameters.method = "pages.isFan";
parameters.page_id = "{you page id}";
dynamic result = fb.Get(parameters);
bool isFan = result == true;
Neil Knight's answer is technically correct, you can use FQL to look up whether a user has liked a page and it did help to set me on the right path. However my issue was actually more one of set up rather than code. What I didn't understand is that you only receive the "like" information in the signed request if your app is running within the "context of a page". If you set it up correctly then Facebook will pass your app the like flag without the user needing to "Allow" your app.
The steps are:
(1) Create your iframe application in Facebook
(2) Set up a tab url for your app in the app settings. This is what the parent page will use when it generates a link in the left hand column to go to your app.
(3) Go to your "App profile page", the URL will be something like this: http://www.facebook.com/apps/application.php?id=12345 Where 12345 is your app ID.
In the left hand column below the logo image there should be a link "Add to Page". If you click on that link you will be presented with a list of pages that you are the admin for. Select the page you want to like in your app.
Now if you navigate to your page you should get a link to your app in the left hand column. It is only when clicking on that link that you will get the page id and like status passed through to your application.
Hope this helps someone having the same issue.
You could use FQL in order to achieve this. I have just done this using the following statement:
var the_query = FB.Data.query("SELECT uid FROM page_fan WHERE page_id = {0} and uid={1}", page_id, user_id);
In order for this to work, I had to ask the user to "Allow" my application so that I had permission to check to see if they liked the page. Then, it was a simple case of checking the result and displaying the necessary <div>:
the_query.wait(function (rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#myLikeContent").show();
} else {
$("#myNoLikeContent").show();
}
});

Facebook status update with PHP

My requirement was to update members status from my site, i am also thinking about displaying their friends photos and their last status update.
I have looked all over the docs and cant decide which works for my need. RESTful API, JavaScript API, FQL, XFBML, FBML, FBJS ?? whcin one works best? or best way?
It should be like, when they first go to the page,there will be nothing but a login option. when they click on it, a pop up should appear and when they are authorized, we display a text area to post update. Here, i wanted to show their friends pics too
when they came back later, they should able to post right away, must not ask for login again.
Can some one help me with the code?? I dont expect you to write everything, get the friends pic and their last update into a PHP array would be nice.
Many thanks
If u need to update users data stored at ur database so u will use the facebook API to check user signed in and get his data. i have an ifram application at facebook and i am using C# code (asp.net application) and when the user request the application i authenticate that he is signed in to facebook and check if he is already exist in my database? if not so i get his information(by using facebook API) and add the user in my data base and each time he visits the application i update his information.
With respect to his friends i get all facebook ids of the user friends and then loop these IDs and get the pic of each ID.
Download Facebook Developer Toolkit that enables u communicate with facebook and use facebook API to get user information.
hope that is will help u
Visit my application in facebook and u will see these features at the following link :
http://apps.facebook.com/hanggame/
Getting the session Key :
protected void Page_Load(object sender, EventArgs e)
{
//Facebook code for integration with facebook users:
_fbService.ApplicationKey = "Application Key";
_fbService.Secret = "Secret Key";
_fbService.IsDesktopApplication = false;
string sessionKey = (string)Session["Facebook_session_key"];
if (Session["Facebook_userId"] != null)
userId = (long)Session["Facebook_userId"];
// When the user uses the Facebook login page, the redirect back here will will have the auth_token in the query params
string authToken = Request.QueryString["auth_token"];
if (!String.IsNullOrEmpty(sessionKey))
{
_fbService.SessionKey = sessionKey;
_fbService.uid = userId;
}
else if (!String.IsNullOrEmpty(authToken))
{
_fbService.CreateSession(authToken);
Session["Facebook_session_key"] = _fbService.SessionKey;
Session["Facebook_userId"] = _fbService.uid;
Session["Facebook_session_expires"] = _fbService.SessionExpires;
}
else
{
Response.Redirect(#"http://www.Facebook.com/login.php?api_key=" + _fbService.ApplicationKey + #"&v=1.0");
}
userId = _fbService.uid;
//End of Facebook code
}