📜 ⬆️ ⬇️

Unity3d / Android: check user on Node.JS own server

To implement user verification of your android application created in unity3d on your node.js server, you will need:

- Application in GooglePlay (published even in alpha testing mode)
- Plugin GooglePlayGames for Unity3D
- Access to Google Cloud console
- Your Node.JS server
- GoogleApis module for node.js: npm install googleapis --save

If your application is still in alpha / beta mode on GooglePlay - do not forget to add to the list of testers account with which you are going to test. Also, your application must be connected to the Game Services.

image
')

Customer


Unpacking the unity3d plugin GooglePlayForUnity3d. Open Window / GooglePlayGames / Setup / Android Setup.

The first two fields can be left unchanged. For information on Resources Definition, go to the GooglePlay console , in the Gaming Services section, Achievements. Enter at least 5 achievements (if not) and find the link “Get resources”. Click, open the Android section and copy everything into Unity3d in the Resources Definition field.

image

Turn on GooglePlus API. In the Web App Client Id field, enter the type identifier .apps.googleusercontent.com, you can get it in the GoogleCloud console (described below).

image

Click Setup. If you are prompted to change file versions from 10.0.1 to 10.2.0, it is better to refuse and select “Keep”.

A small digression - if you have sdk (* .aar) files above 10.0.1 in the Plugins / Android folder - replace them with version 10.0.1 - you can find them in the sdk you have installed (sdk \ extras \ google \ m2repository \ com \ google \ android \ gms \) is a temporary step - only with this version.

Next, add in the client GoogleAuth.cs which will receive the server token.

GoogleAuth.cs
 using System; using System.Collections; using GooglePlayGames; using GooglePlayGames.BasicApi; using UnityEngine; public class GoogleAuth:MonoBehaviour { /// <summary> ///        /// </summary> /// <param name="callback"></param> public void Auth(Action<string> callback) { InitAuth(() => { GetServerToken(callback); }); } private void InitAuth(Action callback) { var config = new PlayGamesClientConfiguration.Builder() .AddOauthScope("profile") .AddOauthScope("email") .Build(); PlayGamesPlatform.InitializeInstance(config); PlayGamesPlatform.Activate(); Social.localUser.Authenticate((success, str) => { if (success) callback(); else Debug.Log("Error on Social Authenticate: " + str); }); } private void GetServerToken(Action<string> callback) { StartCoroutine(ReadToken((serverToken,empty) => { callback(serverToken); })); } private IEnumerator ReadToken(Action<string, string> callback) { yield return null; if (!PlayGamesPlatform.Instance.IsAuthenticated()) //   { PlayGamesPlatform.Instance.Authenticate((result, msg) => //     { if (!result) { PlayGamesPlatform.Instance.Authenticate( (result2, msg2) => //    googleplay  { if (!result2) { PlayGamesPlatform.Instance.GetIdToken( val => //  IdToken    { StartCoroutine(ReadToken(callback)); }); } }, false); } }, true); } else { PlayGamesPlatform.Instance.GetServerAuthCode( (status, code) => //       { if (status != CommonStatusCodes.Success || string.IsNullOrEmpty(code)) StartCoroutine(ReadToken(callback)); else callback(code, null); }); } } } 


Attach it on stage to any GameObject.

To get a server token, you must call the Auth method with a callback in which will be the server token. You can see the places of occurrence of errors in the GoogleAuth class - you can either display messages to users, or send statistics, etc.

In AndroidManifest.xml add:

 <uses-permission android:name="android.permission.GET_ACCOUNTS"/> <uses-permission android:name="android.permission.USE_CREDENTIALS"/> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 

Server


You need a file containing the identity of your server for GooglePlay. Open the Google Cloud console (https://console.cloud.google.com/apis/credentials?project=id_your_project).

Find in the OAuth 2.0 Client Identifiers section an identifier of the “Web Application” type. Open the ID and download the client-secret (file that ends with apps.googleusercontent.com.json):

image

We save in a folder with server application. The client identifier specified in the same window is copied and pasted into the client part (Unity3d) in the GooglePlayGames - Android configuration window in the “Web App Client id” field, which was previously left blank.

How you will deliver the necessary data from your application to your server is not so important, here is your choice (including express, websocket, socket.io, etc.).

Create a class that will check the token received from the application:

GooglePlayAuth.js
 "use strict"; const fs = require('fs'); const https = require("https"); const google = require('googleapis'); /** *       GoogleCloud */ const _clientSecret = "client_secret.apps.googleusercontent.com.json"; const _userInfoUrl = "https://www.googleapis.com/games/v1/players/me"; let oauth2Client; /** * */ class GooglePlayAuth { /** *   * @param callback */ static Init(callback) { fs.readFile(_clientSecret, function (err, content) { if (err) { callback(err); return; } const credentials = JSON.parse(content); oauth2Client = new google.auth.OAuth2(credentials.web.client_id, credentials.web.client_secret, credentials.web.redirect_uris[0]); callback(null); }); } /** *   * @param serverToken * @param callback */ static Verify(serverToken,callback) { oauth2Client.getToken(serverToken, function (err, token) { if (err) { callback(`Error while retrieve access token: ${err}`); return; } oauth2Client.credentials = token; //    require("https").get(`${_userInfoUrl}?access_token=${token.access_token}`, function (res) { res.on("data", function (d) { let userData = {}; try { userData = JSON.parse(d); } catch (er) { callback(`Error parse user data ${er}`); return; } if (userData.playerId == null) { callback(`Error read playerId: ${userData}`); return; } //   -       callback(null, userData); }); }).on("error", function (err) { callback(`Fail request: ${err}`); }); }); } } module.exports = GooglePlayAuth; 


When starting the server, do not forget to call GooglePlayAuth.Init.

The server token received from the client application is sent to GooglePlayAuth.Verify, which will return either an error in the callback or user data received from the Google service.

Thanks for attention!

Source: https://habr.com/ru/post/325900/


All Articles