How can I get email id of the google user while using playgameservices sdk in Unity 3D? - unity3d

I am using playgameservices sdk for unity in my game. However, I am not able to get the email id of logged in user on iOS. Do I need to define any permission while initialising the playgamesserviceplatform class? Please let me know the correct procedure to get email id.
Thanks

I found this link that might be helpful. Below is the process described in the link
In order to access the player's email or access token, you need to configure a web app associated with your game in the Play Game Console. If your game does not use a custom back-end application, you can set the launch URL to be https://localhost.
Copy the client id from the web application and enter it in the setup dialog for this plugin. This will configure the correct permissions and settings needed to access the email address and access token.
To get the email:
Debug.Log("Local user's email is " +
((PlayGamesLocalUser)Social.localUser).Email);
To get the access token:
Debug.Log("AccessToken is " +
((PlayGamesLocalUser)Social.localUser).accessToken);
To get the id token:
Debug.Log("IdToken is " +
((PlayGamesLocalUser)Social.localUser).idToken);
NOTE: The email and access tokens are only available on the UI Thread. If you need to get these from the non-UI thread, you can use the helper function RunOnGameThread:
GooglePlayGames.OurUtils.PlayGamesHelperObject.RunOnGameThread(
() => { Debug.Log("Local user's email is " +
((PlayGamesLocalUser)Social.localUser).Email);
// use the email as needed
});

Related

How to interact with html response from http request in Flutter

I have a Flutter app where I am running a Google Apps Script through an http request. The purpose of the script is to create a Form and link the responses to a spreadsheetID that is passed in. The script is configured to only allow Google accounts access it and I've set up the flutter app to use a Service Account to access the script using the format:
getCredentials().then( (AuthClient client){
response = client.get(url, headers{"Authorization": "Bearer ${client.access_token}");
});
Issue: The issue is that the first time that the Service Account makes a request it will get an HTML response saying that it the account needs to give permission to the script to access its data and I'm not sure how to do that.
I'm fairly new to making http requests and using it with the GoogleAPI so I'm stuck. Any advice?
Goal
Create a web page which anyone can use to submit a Google sheet link and for the app to create a form and link the sheet to that.
Authorization
For this users will require a google account and they will be required to go through the OAuth process to authorize your app.
To create the form and link it from client-side JavaScript you would indeed need to call the Apps Script API, though you cannot do this with a service account.
From: https://developers.google.com/apps-script/api/how-tos/execute
Warning: The Apps Script API doesn't work with service accounts.
Luckily, you don't need a service account to do this.
Instructions
Create an Apps Script project with a function something like:
function createForm(ssID){
form = FormApp.create("Your New Form");
form.setDestination(FormApp.DestinationType.SPREADSHEET, ssID);
let formLink = form.getPublishedUrl();
return formLink;
}
Save and take a note of the ID of the script project.
Set up a GCP project (sounds like you already have one).
Make sure the Apps Script API is enabled in your GCP.
Configure the OAuth consent screen and add the scope - https://www.googleapis.com/auth/forms.
Create an API key and a Client ID - add http://localhost:8000 or whatever port you are testing on to the "Authorized JavaScript Origins"
Create OAuth credentials "web browser (JavaScript)".
Link your Apps Script project to the same GCP project - Instructions
Deploy the Apps Script project as an API executable - take not of the deployment ID, although the documentation says that you need the script ID, it is wrong, at least with the new Apps Script IDE.
Write the client-side JavaScript in your app like what is found in the quickstart. Which will enable users to authorize the app. You need to add in the scopes and keys there too. I recommend just following the quick start steps first to get a feel for it. You can use the authorization parts without modification.
Then add in the function that will call your Apps Script, something like this:
function appsScriptCreateForm(ssId) {
var scriptId = "<DEPLOYMENT_ID>";
// Run your Apps Script function
gapi.client.script.scripts
.run({
scriptId: scriptId,
resource: {
function: "createForm",
parameters: [ssId],
},
})
.then(function (resp) {
var result = resp.result;
// ERROR HANDLING
if (result.error && result.error.status) {
appendPre("Error calling API:");
appendPre(JSON.stringify(result, null, 2));
} else if (result.error) {
var error = result.error.details[0];
appendPre("Script error message: " + error.errorMessage);
if (error.scriptStackTraceElements) {
appendPre("Script error stacktrace:");
for (var i = 0; i < error.scriptStackTraceElements.length; i++) {
var trace = error.scriptStackTraceElements[i];
appendPre("\t" + trace.function + ":" + trace.lineNumber);
}
}
// IF SUCCESSFUL
} else {
console.log("success", resp);
}
});
}
Write your HTML with the buttons and inputs necessary.
Add event listeners where appropriate.
Profit!
Please note
This set up is your project running with the authorization of other accounts.
The API requests count against your quota.
You can see details of all the executions in your GCP Project Dashboard.
Users require a Google account and need to authorize the app.
In the Apps Script function above, you just need to pass in the Spreadsheet ID. Not the whole link. You could ask for the whole link and then use Regex to extract the ID if you wanted.
This can be quite tricky and easy to miss a step or make a mistake, so double check your work.
If, after successful authorization, when trying to run the script you get a 404 error, the request has been built wrong, check your IDs. If you get a 500 error, that can mean that the Apps Script function has successfully been called, but, there was an error within Apps Script and failed, check the executions page of the Apps Script editor.
References
Apps Script How to Execute
Apps Script JS Quickstart - Highly recommended you follow these steps first and get that working!
How to link your Apps Script to GCP

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

Facebook access user info if they are not logged in

Ok, so what I am trying to do is a bit odd, so I can't find anything that gives me even a remote idea about how to do this.
I need to access my personal profile posts:
FB.api("/" + myPersonalUserId + "/feed", {limit: 5}, function(data){
console.log(data);
// do stuff with my user info
});
in order to display them on my personal webite, similar to a dynamic blog. But I want it to automatically retrieve these posts without my having to be signed in on each computer that wants to view my site.
Before you get sidetracked on the init, I am using an app and app id that my personal user account has verified access to all permissions.
I know it will require the use of an access token, but how do I get a valid access token without being logged into that computer?
Honestly, I'm starting to question if it is even possible, but if anyone knows how I could accomplish this, that would be awesome!
The best way to achieve this is to just cache the data in your own database and refresh it whenver the user uses your App again.
If that´s not good enough, you have to generate and store an Extended User Token. How to create one is explained in the docs:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
Extended User Tokens are valid for 60 days, there is no User Token that is valid forever. And you should never use Tokens directly on the client, because some user could just copy it from the source. Tokens are meant to be secret, so use it on the server only. You don´t need to use the PHP SDK, a simple CURL call to the Graph API will do it:
https://graph.facebook.com/[your-app-scoped-id]/feed?access_token=[extended-user-token]
Ok, so I found a solution similar to the one above, but offers a permanent access token.
first, build a url:
url = 'https://graph.facebook.com/v2.5/' + {app user Id, not public Id} + '/feed';
url += '?access_token=' + {app Id} + '|' + {app secret};
url += '&fields=id,name,message,full_picture,created_time'; // these scopes should be approved by corresponding user
url += '&limit=5';
then run it by calling a simple ajax request. These variables should be served from the server through ajax, not hardcoded on the client

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 get a user's email address using accounts-facebook in Meteor?

I created a Meteor app that allows users to sign on using Facebook. To do this, I'm using the accounts-ui and accounts-facebook packages. This works fine.
How do I retrieve the user's email address once they've signed on? I understand that this requires special permission, and so I added email as a "User & Friend's Permission" in the app settings on the Facebook developers site. Following the Meteor documentation, I also set up Account.ui.config like this:
Accounts.ui.config({
requestPermissions: {
facebook: ['email'],
},
passwordSignupFields: 'USERNAME_AND_EMAIL'
});
As expected, when a user of my app signs on using Facebook, it correctly asks them to share their email address. But how do I retrieve it? The user document has only the _id and profile.name.
The Facebook user's email address is stored in [userDocument].services.facebook.email, which is not published to the client, but can be accessed from the server or from the client using Meteor.methods and Meteor.call.
this will add the Facebook profile info to the client side user object.
Accounts.onCreateUser (options, user) ->
if options.profile
user.profile = options.profile
# get profile data from Facebook
result = Meteor.http.get "https://graph.facebook.com/me", {
params: access_token: user.services.facebook.accessToken}
if !result.error && result.data
#if successfully obtained facebook profile, save it off
#the user can access the profile object on the client
user.profile.facebook = result.data;
return user
on the server side the facebook.accesstoken can be accessed... so use it to get the full FB info and save it to the client user object..
ping a Meteor.user() in the console now to get the FB info.
dont think this is exactly best practice in terms of having FB info on the client..