testing facebook real time updates / user comments - facebook

I'm trying to integrate realtime updates for user pages. I have a callback running on a given HOST url. Having this the subscription creation is:
G = facebook.GraphAPI()
app_token = config['FACEBOOK_APP_ID'] + '|' + config['FACEBOOK_SECRET']
path = config['FACEBOOK_APP_ID'] + '/subscriptions'
post_args = {'access_token' : app_token, 'callback_url' : HOST, 'fields' : 'feed', 'object' : 'page', 'verify_token' : 'token'}
G.request(path, post_args=post_args)
This seems to work just fine and a subscription is created. After this, for a given user I get oauth credentials with perms = ["publish_stream", "offline_access", "manage_pages", "publish_actions", "read_stream"]
Using this access token, I do a subscribe by adding the app to the page tabs:
G = facebook.GraphAPI(access_token)
path = "/%s/tabs" % page['id']
G.request(path, post_args={'app_id' : config['FACEBOOK_APP_ID']}
Now things work.... sort of. First thing is I'm not sure exactly how facebook testing should work in practice. Basically I created a bunch of test users using the app settings on developers page. Then using one of these users, I create two separate pages Page1, Page2 and I registered the app as a tab on these pages. Posts issued from the test users, or from the real user I created the app with are picked up. But I try to find one of the pages from some other real user (so not a test one and not the one I created the app with) and I cant. Even if I copy paste the entire URL, I just get a redirect to the first page. Are those pages only visible inside my own test app/users context ? Should I create a page from my real account and test with that? I'm just curious on how would I go around testing this in a real setup. Would I get ALL comments / posts on that page regardless of the user who does the posting or just posts from the Page / Admins of the page ?
Another separate problem I'm having is creating a comment from some user. So I'm using the exact same access token I've got above, and having a post from someone come it, I want to issue a reply in the form of a comment on that post. I have the facebook post id, so I just:
graph = facebook.GraphAPI(access_token)
graph.put_comment(facebook_post_id, message)
Say I issue this command using the access token I got from TestUser1 on a post that came on his own page Page1 . I would expect that the comment be posted on behalf of TestUser1 but instead it gets posted on behalf of Page1 . Is this expected as a side effect of the token I'm using? I've read here https://developers.facebook.com/docs/facebook-login/access-tokens/ that there are user access tokens and page access tokens; but I've tried the exact same thing with a token without the 'manage_pages' perms and still get the same thing.
Cheers, Bogdan

Related

Generate access token Instagram API, without having to log in?

So I am building a restaurant app and one of the features I want is to allow a user of the app to see photos from a particular restaurant's Instagram account.
And I want a user to be able to see this without having to login to their Instagram account, so they shouldn't even need an Instagram account for this to work.
So I have read this answer How can I get a user's media from Instagram without authenticating as a user?
And I tried what it said and used the client_id(which I recieved when I registered my app using my personal Instagram account), but I still get an error back saying :
{
meta: {
error_type: "OAuthAccessTokenException",
code: 400,
error_message: "The access_token provided is invalid."
}
}
The endpoint I am trying to hit is :
https://api.instagram.com/v1/users/search?q=[USERNAME]&client_id=[CLIENT ID]
So do I absolutely need an access token for this to work(and thus have to enforce a user to log in) ?
If I do, then is there way to generate an access token somehow without forcing the user log in?
I believe there is a way around this, as the popular dating app Tinder has this desired functionality I am looking for, as it allows you to see photos from people's Instagram account without having to log in! (I have just verified this 5 minutes ago!)
Any help on this would be much appreciated.
Thanks.
Edit April 2018: After facebook privacy case this endpoint is immediately put out of service. It seems we need to parse the JSON embedded in <script> tag directly within the profile page:
<script type="text/javascript">window._sharedData = {"activity_counts":...
Any better ideas are welcome.
You can use the most recent link
GET https://www.instagram.com/{username}/?__a=1
to get latest 20 posts in JSON format. Hope you put this to good use.
edit: other ways aren't valid anymore:
https://www.instagram.com/{username}/media/
Instagram used to allow most API requests with just client_id and without access_token, the apps registered back in the day still work with way, thats how some apps are able to show instagram photos without user login.
Instagram has changes the API specification, so new apps will have to get access_token, older apps will have to change before June 2016.
One way you can work around this is by using access_token generated by your account to access photos. Login locally and get access_token, use this for all API calls, it should not change, unless u change password,if it expires, regenerate and update in your server.
Since the endpoints don't exist anymore I switched to a PHP library -
https://github.com/pgrimaud/instagram-user-feed
Installed this lib with composer:
composer require pgrimaud/instagram-user-feed "^4.0"
To get a feed object -
$cache = new Instagram\Storage\CacheManager();
$api = new Instagram\Api($cache);
$api->setUserName('myvetbox');
$feed = $api->getFeed();
Example of how to use that object -
foreach ($feed->medias as $key => $value) {
echo '<li><img src="'.$value->thumbnailSrc.'"></li>';
}

Get posts from page that hasn't setup a custom alias?

I'm visiting a number of Facebook pages and collecting information about their posts. When the Facebook page has created a custom username / alias, I can simply query their page like so, using their ID:
$accessToken = FACEBOOK_APP_ID.'|'.FACEBOOK_APP_SECRET;
$url = 'https://graph.facebook.com/104958162837/?access_token=' . $accessToken;
However, if they didn't bother to setup a custom username / alias, then it won't work, even if I specify:
The default alias that FB gave them when they created the page (looks something like My-Page-Name-104958162837).
The numerical ID of their page.
What gives?
Works fine for me that way, if use a User Token:
/129319107123637
/129319107123637/feed
Just try it in the API Explorer, after authorization: https://developers.facebook.com/tools/explorer/145634995501895?method=GET&path=129319107123637&version=v2.5
It only does not work with an App Token if the Page is restricted by age or location. In that case, you have to use a User Token of a User who is allowed to see the Page, of course.

Facebook UserId returned from Azure Mobile Services keeps changing within the same Windows Phone app

I'm a newbie to app development. I am building a Windows Phone 8.1 app and have followed the tutorial here: http://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-dotnet-backend-windows-store-dotnet-get-started-users-preview/ to add authentication using Facebook. Everything seems to work fine, except that every now and again it appears to stop bringing back any data from my Azure database. Further investigation revealed that the UserId that is being shown from the code below, changes periodically (although I can't quite work out how often it changes).
// Define a member variable for storing the signed-in user.
private MobileServiceUser user;
...
var provider = "Facebook";
...
// Login with the identity provider.
user = await App.MobileService.LoginAsync(provider);
// Create and store the user credentials.
credential = new PasswordCredential(provider,
user.UserId, user.MobileServiceAuthenticationToken);
vault.Add(credential);
...
message = string.Format("You are now logged in - {0}", user.UserId);
var dialog = new MessageDialog(message);
dialog.Commands.Add(new UICommand("OK"));
await dialog.ShowAsync();
This code is identical to the code in the tutorial. The Facebook app settings (on the Facebook developers site) confirm that I am using v2.3 of their API so I should be getting app-scoped UserIds back. I have only ever logged in with one Facebook account, so I would expect the UserId to be the same each time, but they're not. The UserId is prefaced with 'sid:', which someone on the Facebook developers group on Facebook itself says stands for Session ID, which they would expect to change, but if that's the case, I can't work out where to get the actual UserId from that I can then store in my database and do useful things with. I'm sure I must be doing something basic wrong, but I have spent hours Googling this and cannot (unusually) find an answer.
Any help would be greatly appreciated.
Thanks!
So dug deeper. This is how Mobile Apps work (I was thinking from a Mobile Services perspective). The issue here is that the Gateway doesn't provide static SIDs, which is what User.userId provides. The work around to this is listed in the migration doc.
You can only get the Facebook AppId on the server.
ServiceUser user = (ServiceUser) this.User;
FacebookCredentials creds = (await user.GetIdentitiesAsync()).OfType< FacebookCredentials >().FirstOrDefault();
string mobileServicesUserId = creds.Provider + ":" + creds.UserId;
You should note, that this Id is directly connected with your Facebook App registration. If you ever want to migrate your App to a new Facebook App, you'd have to migrate them. You can also use the Facebook AppId to look up the user's global facebook Id via the Facebook Graph API, which you could use between applications. If you don't see yourself using multiple apps, etc., you can use the Facebook AppId just fine.
Hard to tell what's going on to cause you to use a SID instead of the Faceboook token (which like Facebook:10153...).
It may be faster to rip out the code and reimplement the Auth GetStarted. Maybe you missed a step or misconfigured something along the way. If you have the code hosted on github, I can try to take a look.
Another thing you can do is to not trust the user to give you their User id when you save it to a table. On your insert function, you can add it there.
function insert(item, user, request) {
item.id = user.userId;
request.execute();
}
That should, theoretically, be a valid Facebook token. Let me know if that doesn't work; can dig deeper.

MVC5 Facebook get users photos

I am building a website app in MVC5 that allows a user to login using Facebook/Twitter. Once they are logged in we will look through their photos for ones marked with a certain hashtag.
I have the login working for both FB and Twitter - and using Linq2Twitter I can get the and post photos.
However with Facebook I am having some problems. My understanding with Facebook is that after the login I have to make a second call to https://graph.facebook.com/oauth/access_token in order to get a short lived access token.
However this call requires a "code" and a returnUri. I am unsure what this code is or how to get it, and what return URI to use.
My startup.Auth.cs looks like this
var facebookOptions = new FacebookAuthenticationOptions();
facebookOptions.Scope.Add("user_photos");
facebookOptions.AppId = ConfigurationManager.AppSettings["facebookAppId"];
facebookOptions.AppSecret = ConfigurationManager.AppSettings["facebookAppSecret"];
app.UseFacebookAuthentication(facebookOptions);
And everything logs in fine and I end back at ExternalLoginCallback
So where do I go from here. How do I find this code and what returnUri do I use in order to get the access code.
Once I have this access code I plan to call (https://developers.facebook.com/docs/graph-api/reference/v2.1/user/photos)
Hopefully I am going about this the correct way and my question makes sense
Many thanks.
Okay - This solves my problem
http://blogs.msdn.com/b/webdev/archive/2013/10/16/get-more-information-from-social-providers-used-in-the-vs-2013-project-templates.aspx

Facebook OAuth Login - access_token API returning "This authorization code has been used"

This question has been asked a few times on Stack, but there have been no real answers. Let me try to explain my situation anyways.
We use an application that uses Facebook OAuth2 login. This login used to work fine till last week, and all of a sudden it is troubling us now.
Application Flow:
Step 1: User presses login with Facebook button on our website
Step 2: Redirected to Facebook login/authorization page
Step 3: On authorizing the app, the callback comes to our application, with a short lived "code" param.
Step 4: This "code" param would be exchanged for a 60 day Access token using "https://graph.facebook.com/oauth/access_token" URL.
Error in Step 4:
When we try to exchange the short living "code" for the access token, we get this error from Facebook.
{"error":{"message":"This authorization code has been used.","type":"OAuthException","code":100}}
Observation:
For users who are newly coming to the application, the above-said error does not occur.
For a returning user this call fails with the above-said error.
Our application is live for more than 9 months now, and this error has come only in the past 7-10 days. We have had thousands of users using it successfully prior to that.
What I already got from Forums:
Here is my interpretation of what I read. May be inaccurate.
Facebook has some weird policy that necessitates the app developer to maintain the temporary 10 minute code until the 60 day code that was obtained during the first login expires. So we should create a cookie with the Access token on the user's browser. I was even able to see people modifying their code in order to create the cookies.
What's really bothering me?
The suggested solutions assumes that the cookie that they create would be present in the user's browser always. This is a bad assumption to make, as the cookie may be erased at any time.
I have another app Id/app secret that I use for my development (i.e localhost), and that works perfectly. The login happens fine out there, But its only the product machine that has the problem.
This problem didn't happen on the production machine for nearly 10 months since we launched the app, and it has come all of a sudden. Worst of all, I am unable to get any record of recent changes that breaks this flow.
Edit:
Platform: Python, Google Appengine. We do not use any Facebook SDKs, we make direct HTTP Calls to all the login URLs.
Call that fails : https://graph.facebook.com/oauth/access_token - we are passing the appId, secret and code (obtained from facebook) within 20 seconds of the first call happening.
Hope there is enough information here to show that our code is not totally incorrect. Any tips/pointers from people who have encountered and solved this problem is Welcome. If its a Facebook bug, and the Facebook dev comes to notice, I would be even happier.
I got round this issue by using a random GUID which is appended to each callback url i pass into facebook. It seems the code that facebook returns is made up of a few parts including the redirect_uri parameter you have to specify. By using this GUID trick, your app continues to work but facebook thinks it's a different URL hence generating a new code.
If you store that GUID in a temporary session, it's always the same. Here's a very cut down version of what I mean. I'm using C# but the solution will be the same:
Before i start the oauth process:
Session["facebook_buster"] = System.Guid.NewGuid().ToString();
Then to kick off the login:
var facebook = new FacebookClient();
var loginUrl = facebook.GetLoginUrl(new
{
client_id = ...,
redirect_uri = ..."/facebook/oauthcallback?buster=" + Session["facebook_buster"].ToString(),
display = "popup",
scope = "publish_stream,user_photos"
});
And then in my callback method, when I want to exchange that code for a new access_token:
var facebook = new FacebookClient();
dynamic result = facebook.Post("oauth/access_token", new
{
client_id = ...,
client_secret = ...,
redirect_uri = ..."/facebook/oauthcallback?buster=" + Session["facebook_buster"].ToString(),
code = Request["code"] // this is the returned code from the first method
});
Note in that second method i'm using the same session key so that the authorization code is successful.
Been testing this all morning by revoking permissions / manually changing my stored access_token (in my db) / removing my stored access_token completely and it works every time.
Hope this helps!
I struggled with this today for a while too. Not sure if you're using the Facebook PHP class (from what you wrote, it seems you don't), however, it could be a pointer anyways - the problem was that the Facebook PHP library seems to obtain the token from the code automatically and I was trying to do it again.