Intermediate: How to Verify Phone Number and Anonymous Account Login using Huawei Auth Service-AGC in Unity

Search This thread

shikkerimath

Senior Member
Nov 30, 2020
107
25
Introduction

In this article, we will looking that how Huawei Auth Service-AGC provides secure and reliable user authentication system to your application. However building such systems is very difficult process, using Huawei Auth Service SDK only need to access Auth Service capabilities without implementing on the cloud.

Here I am covering sign in anonymously which is anonymous account sign to access your app as guest when you wish to login anonymously, Auth Service provides you unique id to uniquely identify user. And authenticating mobile number by verifying through OTP.

1616493574423.png


Overview

You need to install Unity software and I assume that you have prior

knowledge about the unity and C#.

Hardware Requirements

  • A computer (desktop or laptop) running Windows 10.
  • A Huawei phone (with the USB cable), which is used for debugging.
Software Requirements

  • Java JDK 1.7 or later.
  • Unity software installed.
  • Visual Studio/Code installed.
  • HMS Core (APK) 4.X or later.
Integration Preparations

1. Create a project in AppGallery Connect.

2. Create Unity project.

1616493592324.png


3. Huawei HMS AGC Services to project.

1616493650654.png


4. Download and save the configuration file.

1616493663631.png


Add the agconnect-services.json file following directory Assests > Plugins > Android

1616493674261.png


5. Add the following plugin and dependencies in LaucherTemplate.

Code:
apply plugin: 'com.huawei.agconnect'

6. Add the following dependencies in MainTemplate.

Code:
apply plugin: 'com.huawei.agconnect'


implementation 'com.huawei.agconnect:agconnect-auth:1.4.2.301'
implementation 'com.huawei.hms:base:5.2.0.300'
implementation 'com.huawei.hms:hwid:5.2.0.300'

7. Add dependencies in build script repositories and all project repositories & class path in BaseProjectTemplate.

Code:
maven { url 'https://developer.huawei.com/repo/' }

8. Create Empty Game object rename to GameManager, UI canvas input text fields and buttons and assign onclick events to respective components as shown below.

1616493746926.png


1616493752312.png


MainActivity.java

Code:
package com.huawei.AuthServiceDemo22;
import android.content.Intent;
import android.os.Bundle;
import com.hw.unity.Agc.Auth.ThirdPartyLogin.LoginManager;
import com.unity3d.player.UnityPlayerActivity;
import android.util.Log;
import com.huawei.agconnect.auth.AGConnectAuth;
import com.huawei.agconnect.auth.AGConnectAuthCredential;
import com.huawei.agconnect.auth.AGConnectUser;
import com.huawei.agconnect.auth.PhoneAuthProvider;
import com.huawei.agconnect.auth.SignInResult;
import com.huawei.agconnect.auth.VerifyCodeResult;
import com.huawei.agconnect.auth.VerifyCodeSettings;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hmf.tasks.TaskExecutors;
import java.util.Locale;
public class MainActivity extends UnityPlayerActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       LoginManager.getInstance().initialize(this);
       Log.d("DDDD"," Inside onCreate ");
   }
   public static void AnoniomousLogin(){
    AGConnectAuth.getInstance().signInAnonymously().addOnSuccessListener(new OnSuccessListener<SignInResult>() {
        @Override
        public void onSuccess(SignInResult signInResult) {
            AGConnectUser user = signInResult.getUser();
            String uid = user.getUid();
            Log.d("DDDD"," Login Anonymous UID : "+uid);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            Log.d("DDDD"," Inside ERROR "+e.getMessage());
        }
    });
   }
   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data)
   {
     LoginManager.getInstance().onActivityResult(requestCode, resultCode, data); 
   }
   public static void sendVerifCode(String phone) {
    VerifyCodeSettings settings = VerifyCodeSettings.newBuilder()
            .action(VerifyCodeSettings.ACTION_REGISTER_LOGIN)
            .sendInterval(30) // Shortest sending interval, 30–120s
            .build();
    String countCode = "+91";
    String phoneNumber = phone;
    if (notEmptyString(countCode) && notEmptyString(phoneNumber)) {
        Task<VerifyCodeResult> task = PhoneAuthProvider.requestVerifyCode(countCode, phoneNumber, settings);
        task.addOnSuccessListener(TaskExecutors.uiThread(), new OnSuccessListener<VerifyCodeResult>() {
            @Override
            public void onSuccess(VerifyCodeResult verifyCodeResult) {           
                          Log.d("DDDD"," ==>"+verifyCodeResult);
            }
        }).addOnFailureListener(TaskExecutors.uiThread(), new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Log.d("DDDD"," Inside onFailure");
            }
        });
    }
}
static  boolean notEmptyString(String string) {
    return string != null && !string.isEmpty() && !string.equals("");
}
public static  void linkPhone(String verifyCode1,String phone) {
    Log.d("DDDD", " verifyCode1 "+verifyCode1);
    String phoneNumber = phone;
    String countCode = "+91";
    String verifyCode = verifyCode1;
    Log.e("DDDD", " verifyCode "+verifyCode);
    AGConnectAuthCredential credential = PhoneAuthProvider.credentialWithVerifyCode(
            countCode,
            phoneNumber,
            null, // password, can be null
            verifyCode);
    AGConnectAuth.getInstance().getCurrentUser().link(credential).addOnSuccessListener(new OnSuccessListener<SignInResult>() {
        @Override
        public void onSuccess(SignInResult signInResult) {
            String phoneNumber = signInResult.getUser().getPhone();
            String uid = signInResult.getUser().getUid();
            Log.d("DDDD", "phone number: " + phoneNumber + ", uid: " + uid);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            Log.e("DDDD", "Login error, please try again, error:" + e.getMessage());
        }
    });
}
}

GameManager.cs

Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
    public InputField OtpField,inputFieldPhone;
    string otp=null,phone="";
    // Start is called before the first frame update
    void Start()
    {
        inputFieldPhone.text = "9740424108";
    }
    public void onClickButton(){
        phone = inputFieldPhone.text;
        using (AndroidJavaClass javaClass = new AndroidJavaClass("com.huawei.AuthServiceDemo22.MainActivity"))
        {
            javaClass.CallStatic("sendVerifCode",phone);
        }
    }
    public void LinkPhone(){
        otp = OtpField.text;
        Debug.Log("  OTP "+otp);
         using (AndroidJavaClass javaClass = new AndroidJavaClass("com.huawei.AuthServiceDemo22.MainActivity"))
        {
            javaClass.CallStatic("linkPhone",otp,phone);
        }
    }
    public void AnoniomousLogin(){
         using (AndroidJavaClass javaClass = new AndroidJavaClass("com.huawei.AuthServiceDemo22.MainActivity"))
        {
            javaClass.CallStatic("AnoniomousLogin");
        }
    }
}

10. Click to Build apk, choose File > Build settings > Build, to Build and Run, choose File > Build settings > Build And Run.

1616493865491.png


Result

1616493879900.png


1616493885484.png


1616493890478.png


1616493895992.png


1616493904361.png


1616493912979.png


Tips and Tricks


  • Add agconnect-services.json file without fail.
  • Make sure dependencies added in build files.
  • Make sure that you enabled the Auth Service in AG-Console.
  • Make sure that you enabled the Authentication mode in Auth Service.
Conclusion

We have learnt integration of Huawei Auth Service-AGC anonymous account login and mobile number verification through OTP in Unity Game development. Conclusion is Auth Service provides secure and reliable user authentication system to your application.

Thank you so much for reading article, hope this article helps you.

Reference


Official documentation service introduction

Unity Auth Service Manual

Auth Service CodeLabs

Checkout in forum