Facebook FQL page_user - facebook

Right i have a problem which i have done so much research for that i still cant be able to solve the problem. What i am trying to achieve is when a facebook user LIKES my page not an app, i want to be able to retrieve all the users that have liked the facebook page.
I am using FQL but having no luck at all, if i do an FQL based on the admins of the page it brings the data up.
SELECT first_name, last_name FROM user WHERE uid IN (SELECT uid FROM page_fan WHERE page_id = [your page id])
the above FQL should work. But nothing is being displayed, is this a facebook bug that has not been flagged or fixed?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCFacebookTestApp.Models;
using Facebook;
using Facebook.Web;
namespace MVCFacebookTestApp.Controllers
{
public class HomeController : Controller
{
public FacebookSession FacebookSession
{
get { return (FacebookWebContext.Current.Session); }
}
public ActionResult Index()
{
string request = Request.Form["signed_request"];
string accessToken = "";
if (Request.Form["access_token"] != null)
{
accessToken = Request.Form["access_token"];
}
FacebookApplication app = new FacebookApplication();
FacebookSignedRequest result = FacebookSignedRequest.Parse(app.InnerCurrent, request);
if (String.IsNullOrWhiteSpace(accessToken))
{
accessToken = result.AccessToken;
}
dynamic data = result.Data;
bool liked = data.page.liked;
//bool liked = true;
if (!liked)
{
Home h = Home.NotLiked();
return View(h);
}
else
{
Home h = Home.Liked();
FacebookWebClient fb = null;
if (String.IsNullOrWhiteSpace(accessToken))
{
var fbRequest = FacebookWebContext.Current;
if (fbRequest.IsAuthorized())
fb = new FacebookWebClient(fbRequest);
}
else
{
fb = new FacebookWebClient(accessToken);
}
if (fb != null)
{
dynamic r = fb.Get("/me");
h.TestString2 += " Ha! We captured this data about you!";
h.TestString2 += " Name: " + r.name;
h.TestString2 += " Location: " + r.location;
h.TestString2 += " Birthday: " + r.birthday;
h.TestString2 += " About Me: " + r.aboutme;
h.ImgUrl = "http://graph.facebook.com/" + r.id + "/picture?type=large";
string fqlResult = "";
var fbApp = new FacebookClient(accessToken);
//basic fql query execution
dynamic friends = fbApp.Query("SELECT uid FROM page_admin WHERE page_id='160828267335555'");
//SELECT uid FROM page_fan WHERE page_id = 160828267335555
//"SELECT uid FROM page_fan WHERE uid=me() AND page_id=<your page id>";
//loop through all friends and get their name and create response containing friends' name and profile picture
foreach (dynamic friend in friends)
{
fqlResult += friend.uid + "<br />";
//fqlResult += friend.name + "<img src='" + friend.pic_square + "' alt='" + friend.name + "' /><br />";
}
ViewBag.Likes = fqlResult;
}
else
{
//Display a message saying not authed....
}
return View(h);
}
}
}
}
is there a solution out there that actually works? Please do get back to me ASAP your help would be much appreciated, will save me from losing all my hair with the stress LOL
Thanks in advance.

You can make a GET request to /USER_ID/likes/PAGE_ID (replacing the caps part with the relevant IDs) to check if a particular user is a fan of your page. This is the replacement for the old 'pages.isFan' API method.
There's no way to retrieve a list of users that like your page.

Related

TypeError: Cannot read property 'getChild' of null - Apps Script

I am a newbie and am trying to use a script to send our school website's feeds
to our Google Chat (Google Workspace for Edu).
I found a code here that works like a charm with the testing Url (https://cloudblog.withgoogle.com/products/gcp/rss/),
but returns me an error when I point to our school's website.
TypeError: Cannot read property 'getChild' of null
Here is the code and below the Debug error
// URL of the RSS feed to parse
var RSS_FEED_URL = "https://www.icriccardomassa.edu.it/agid/feed/";
// https://cloudblog.withgoogle.com/products/gcp/rss/"; <- this works!
// Webhook URL of the Hangouts Chat room
var WEBHOOK_URL = "https://chat.googleapis.com/v1/spaces/AAAAueQ0Yzk/messages?key=AI [..]";
// When DEBUG is set to true, the topic is not actually posted to the room
var DEBUG = false;
function fetchNews() {
var lastUpdate = new Date(PropertiesService.getScriptProperties().getProperty("lastUpdate"));
var lastUpdate = new Date(parseFloat(PropertiesService.getScriptProperties().getProperty("lastUpdate")) || 0);
Logger.log("Last update: " + lastUpdate);
Logger.log("Fetching '" + RSS_FEED_URL + "'...");
var xml = UrlFetchApp.fetch(RSS_FEED_URL).getContentText();
var document = XmlService.parse(xml);
// var items = document.getRootElement().getChild('channel').getChildren('item').reverse();
var items = document.getRootElement().getChild('channel').getChildren('item').reverse();
Logger.log(items.length + " entrie(s) found");
var count = 0;
for (var i = 0; i < items.length; i++) {
var pubDate = new Date(items[i].getChild('pubDate').getText());
var og = items[i].getChild('og');
var title = og.getChild("title").getText();
var description = og.getChild("description").getText();
var link = og.getChild("url").getText();
if(DEBUG){
Logger.log("------ " + (i+1) + "/" + items.length + " ------");
Logger.log(pubDate);
Logger.log(title);
Logger.log(link);
// Logger.log(description);
Logger.log("--------------------");
}
if(pubDate.getTime() > lastUpdate.getTime()) {
Logger.log("Posting topic '"+ title +"'...");
if(!DEBUG){
postTopic_(title, description, link);
}
PropertiesService.getScriptProperties().setProperty("lastUpdate", pubDate.getTime());
count++;
}
}
Logger.log("> " + count + " new(s) posted");
}
function postTopic_(title, description, link) {
var text = "*" + title + "*" + "\n";
if (description){
text += description + "\n";
}
text += link;
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify({
"text": text
})
};
UrlFetchApp.fetch(WEBHOOK_URL, options);
}
Thank you in advance for your help!
Debugger errors

Web API Returns Wrong Values after being Published to IIS

Please help me. The API I created works fine when I launch it with Visual Studio but (the POST methods) has issues I deployed to IIS.
It returns wrong values and sometimes, null values. If i go back to test it in debug mode it works well.
THIS IS WHERE I'M CALLING THE API
try
{
string apiToken = "DEFAULTAPI";
EmployeeObject EmployeeObject = new EmployeeObject()
{
username = "John Doe"
password = "12345"
apiToken = apiToken
};
var emp = JsonConvert.SerializeObject(EmployeeObject);
string url = "http://localhost/PublishVersion/api/Company";
//the url variable holds the published version link
var response = client.PostAsync(url, new StringContent(emp, Encoding.UTF8, "application/json"));
response.Wait();
var result = response.Result;
if (result.IsSuccessStatusCode)
{
Uri employeeUrl = result.Headers.Location;
var statusMessage = result.Content.ReadAsStringAsync().Result;
if (statusMessage == "yes")
{
status = true;
}
else if (statusMessage == "no")
{
status = false;
}
}
return status;
}
AND THIS IS THE API
public string Post([FromBody] Employees employees)
{
string message = "no";
if (employees != null)
{
string emp = employees.username;
string password = employees.password
string apiToken = employees.apiToken
APIToken token = _dbContext.MyTable.Where(x => x.apitoken == apitoken).FirstOrDefault();
//APIToken is a table which has properties company and boss (both string)
if (token != null)
{
string company = token.company;
string boss = token.boss;
return message = "yes" + " " + company + "" + boss;
}
else
{
return message = "invalid token";
}
}
return message + employee.username;
}
The api returns "no John Doe" to the caller, which shouldn't be that way, since it displayed the username value which shows that the employee object is not null. Why doesn't it go into the block of code since it passed the null check? This issue only comes up when I deploy the API project to the IIS (version 10). Works fine in Visual Studio debug mode.
Also, the API and Winsform(where i'm calling it from) are on the same machine.
Thank you.

authentication using yammer

i am integrating my CRM application to Yammer for that i have create an App inside Yammer and by using ClientID, Client Secret and redirect URL i am authenticating an Yammer user to app.
Problem is, that whenever user changes password or any other user trying to login through app it asks to allow permission or not. I just dont want this if any user logging in to yammer by using my app it should automatically allow. please help me regarding this i am posting my code also
referalUrl = oauthUrl + clientId;
oauthUrl =oauthUrl+ clientId + "&redirect_uri=" + redirUrl; //For authentication to Yammer
//referalUrl = oauthUrl + clientId;
accessTokenUrl = accessTokenUrl + "client_id=" + clientId + "&client_secret=" + clientSecret + "&code=";
string qsCode = string.Empty;
string accessToken = "";
string postResults = string.Empty;
string response = string.Empty;
string firstName = string.Empty;
string lastName = string.Empty;
//string currentUser = string.Empty;
object yammerUserId = this.PrimaryDataRow[YammerUserTable.Field.YammerUserId];
object currentUserId = this.SystemClient.UserProfile.EmployeeId;
if (string.IsNullOrEmpty(accessToken))
{
while (string.IsNullOrEmpty(qsCode))
{
response = YammerAPIRequest.MakeGetRequest(oauthUrl, null, true);
//look for authenticity token
string authToken = YammerAPIRequest.GetAuthenticityToken(response);
if (!string.IsNullOrEmpty(authToken))
{
string f = System.Web.HttpUtility.UrlEncode(authToken);
userName = System.Web.HttpUtility.UrlEncode(userName);
//password = System.Web.HttpUtility.UrlEncode(password);
string postBody = "utf8=%E2%9C%93&authenticity_token=" + System.Web.HttpUtility.UrlEncode(authToken) + "&network_permalink=aptean.com&login=" +
userName + "&password=" + password + "&remember_me=on";
postResults = YammerAPIRequest.MakeLoginPostRequest(postBody, loginUrl, f, null, referalUrl);
}
qsCode = postResults;
if (qsCode.IndexOf("code") == -1 && qsCode.IndexOf("redirect_uri")==-1)
{
PivotalMessageBox.Show("Please enter Correct Username or Password");
return false;
}
else
{
PivotalMessageBox.Show("You have Logged in to Yammer");
string postreq = "utf8=%E2%9C%93&authenticity_token=" + System.Web.HttpUtility.UrlEncode(authToken) + "&allow=Allow";
string allowurl="https://www.yammer.com/aptean.com/oauth2/decision?client_id=BAUC8GdiEZ5ximkabWM9Q&redirect_uri=https%3A%2F%2Fwww.yammer.com%2Faptean.com%2F&response_type=code";
string allow = YammerAPIRequest.AllowtoApp(postreq, allowurl, authToken, null, null);
if (allow != "")
{
qsCode = allow;
}
I just dont want this if any user logging in to yammer by using my app
it should automatically allow
This is by design and can't be altered/bypassed from your code. Users must be given the option to Allow or Deny the use of yammer third party applications.
You may consider using the impersonation endpoint if it suits your use case - https://developer.yammer.com/docs/impersonation

Facebook follow button does not display error message?

I'm using this https://developers.facebook.com/docs/plugins/follow-button and it's working fine. But what if I enter a facebook url that doesn't exist? It doesn't display any error message and just disappears. I want to display an error message when the user enters a wrong URL. Following is my code:
function wpfollow_func() {
var checkURL = jQuery("#profileCheck").hasClass("has-error");
if (!checkURL) {
var faces = jQuery('#facey').is(':checked');
var layout = jQuery('input[name=layout]:checked').val();
var url = jQuery('#profile').val();
if (url == '' || url == null) {
url = 'https://www.facebook.com/zuck';
}
var token = url.indexOf('http://');
if (token == -1) {
token = url.indexOf('https://');
}
if (token == -1) {
url = 'http://' + url;
}
var data = '<div class="fb-follow" data-href="' + url + '" data-layout="' + layout + '" data-show-faces="' + faces + '"></div>';
console.log(data);
jQuery('.fb-button').html(data);
FB.XFBML.parse();
return false;
}
I hope this is what you are looking for:
FB.XFBML.parse(document.getElementById('some_element'), function() {
alert('I rendered');
});
Following url may help you:
https://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse

Getting user access_token from Facebook

I'm building an application that allows users to post message to their facebook from the application. To problem I'm having that I don't know how to get the user access_token for the publish_stream permission.
This is what I've got so far:
var fb = new FacebookClient();
dynamic result = fb.GetLoginUrl(new
{
client_id = AppID,
client_secret = AppSecret,
grant_type = "client_credentials",
scope = "publish_stream",
state = "http://localhost:17578/Facebook.aspx",
redirect_uri = "http://localhost:17578/Facebook.aspx"
});
That works fine and it returns a 'code' in the querystring. However, I'm not sure what to do with that code.
The 'old' Facebook C# sdk contained the FacebookOAuthClient class which had the ExchangeCodeForAccessToken() method, but I don't know what the replacement of this static method is in the new SDK.
So the question really is: How to exchange the code that is returned for an access_token?
After you get the code query string parameter you must make a call to the Facebook Graph API to get the access token.
https://developers.facebook.com/docs/howtos/login/server-side-login/
FacebookClient client = new FacebookClient();
dynamic result = client.Get("oauth/access_token", new { client_id = Settings.Social_Facebook_App_Id, client_secret = Settings.Social_Facebook_Secret_Key, code = Request.QueryString["code"], redirect_uri = Settings.Social_Facebook_Login_Redirect_URI });
if (result.error == null)
{
Session["AccessToken"] = client.AccessToken = result.access_token;
dynamic user = client.Get("me", new { fields = "name,username,email" });
string userName = user.username;
mu = Membership.GetUser(userName);
if (mu == null) // Register
{
RegisterModel rm = new RegisterModel();
rm.Email = user.email;
rm.UserName = userName;
return View("Register", rm);
}
else
{
FormsAuthentication.SetAuthCookie(userName, true);
return RedirectToAction(MVC.Home.Index());
}
}