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

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

Related

Facebook login - what on earth am I doing wrong

I'm tearing my hair out here.
We've got a web app that is hosted on a bunch of different domains and we have a facebook login on the page. This works just peachy. Most of them run of our root domain eg newsite.ourplatform.com and we reuse the same facebook app and add a new domain in.
We've had a request to set up a new site on a different url. In the past, this hasn't really been a problem. We set up a new facebook app, add the appid to out config and voila, facebook login working. (we don't do this so often, so I've potentially broken it)
This time around. I've set up a new app id and plugged it in, but whenever I call the facebook login, it authenticates me, but I get a useless response from facebook.
eg. On a working site I call
FB.api("/me/", function(response){console.log(JSON.stringify(response));});
and get response
"{id":"12345678910","email":"my#email.com","first_name":"My Name","gender":"male","last_name":"Myname","link":"https://www.facebook.com/app_scoped_user_id/12345678910/","locale":"en_GB","name":"My Name","timezone":10,"updated_time":"2014-01-19T10:44:20+0000","verified":true}
but on the broken site I do the same call and get a response
{"name":"MyName","id":"12345678910"}
Which is sort of good, but I need their email. As far as I can tell, I'm not asking for any permissions beyond email,public_profile and user_friends
Because of the way the app setup works, we have different apps running 2.1, 2.2 and 2.4 and this new one on 2.4 doesn't work. I'm not sure if that's a red herring or if I've got a misconfigured facebook app.
(edit - removed the sites affected to protect the innocent)
As #CBroe said you really need to checkout the v2.4 changelog for the API. In version 2.4 of the API Facebook introduced 'declarative fields'. This means that when you make a base request, like to /me you will only get a small amount of info back, e.g. 'name' and 'id'.
You have two options to get more fields:
Option One
FB.api('/me?fields=first_name,last_name,gender', function(response) {
console.log(response)
});
Option Two
FB.api('/me', function(response) {
console.log(response)
}, {'fields': 'first_name, last_name, gender'})
This will return a response that looks like the following:
{"first_name":"First", "last_name":"Last", "gender":"gender", "id":"ID"}
The key in the request above is specifying the fields URL parameter in your request and is documented in the link #CBroe linked and I have linked above.

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.

How do I remove the Facebook login prompt when displaying images pulled with graph api on a page?

I recently started playing around with Facebook graph API and wanted to integrate images pulled from my Facebook page to display on my website. I have the images displaying properly but my problem is whenever anyone tries to view the page they are asked to log into Facebook first. Is there any way to display the images without prompting the user to log into Facebook?
Here is what I am using to make the session:
$app_id = 'id';
$app_secret = 'secret';
$redirect = 'my webpage';
// init app with app id and secret
FacebookSession::setDefaultApplication($app_id,$app_secret);
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper($redirect);
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
Any help would be appreciated.
Step one: familiarize yourself with the API. Read the docs, and play around with the Graph API Explorer
Step two: the code you provided has nothing to do with what you are trying to achieve (displaying page photos). That code is basically the getting started code used in the docs. If you need help, post the relevant code.
Step three: as mentioned by #CBroe, authenticating the visitor is not needed to display photos from a page. What you might want to explore:
The page admin authenticating your app with the right permissions (maybe manage_pages)
with the user access token you just got, you extend it to long-lived one
then you query the API to get a page access token that won't expire
you store this access token and query the API to get the relevant data and store it (GET /{PAGE-ID}/photos or GET /{PAGE-ID}/albums ... etc)
you show the stored data to your visitors
Notes:
Do not make these calls on client-side ... i.e. reveal your page access token, since you can do this in the backend.
Use the realtime updates to get notified when you should query the API and get new photos instead of periodically querying the API to pull new photos, or even worst, querying the API on each user visit.

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 API For Pulling Reviews

Has anyone seen a full example of how to pull facebook reviews using the graph api.
According to the docs:
A page access token is required to retrieve this data.
I have code that asks a user to login already and gets an auth token which I can use to post a message to their facebook feed. Is there an additional step I need to do to be able to read their reviews/ratings?
Here is an example of the code to post to their feed/page.
response = Curl.post("https://graph.facebook.com/#{page_id}/feed", {
:message => message,
:access_token => auth_token
})
Thanks
If you're referring to Page Ratings (different from App Reviews!), then the endpoint is
GET /{page_id}/ratings
as described here: https://developers.facebook.com/docs/graph-api/reference/page/ratings You'll need a Page Access Token for this.
Where I get a little bit confused is that you mention that you want to
read their reviews/ratings
In that case it's something else, because afaik it's currently not possible to query the User's Page ratings via Graph API or FQL. It's was only possible to query App Reviews via FQL (see https://developers.facebook.com/docs/reference/fql/review/) (Update: FQL is no longer available since 2016)
You need to set permission in the app to access the {GET /{page_id}/ratings} API. The permission is common for
/page/comments,
/page/posts,
/page/ratings,
/page/tagged,
and the permission name is "pages_read_user_content"
https://developers.facebook.com/docs/permissions/reference/pages_read_user_content