Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by unity_XY9GfkpHMyaikw · May 22, 2019 at 12:02 PM · errorloginphonenumberauthentication

Phone Number Authentication for Firebase Through Unity (C#)

0

I'm trying to get phone number authentication for Unity up and running but I am getting no SMS response. The documentation online is super unclear about how to do this. I'd much rather have Google Auth for Firebase but apparently it isn't supported yet. Can anyone help me figure out how to get this up and running?

Here is what I have so far...

public class SignIn : MonoBehaviour {

private string phoneNumber; private string secureCode; private uint phoneAuthTimeoutMs; private Firebase.Auth.FirebaseAuth firebaseAuth; private Credential credential; private string verificationId; private string verificationCode;

public Text PhoneNumberInputFieldText; public Text SecureCodeInputFieldText; public Button SendSecureCodeButton; public Button SubmitSecureCodeButton;

// Use this for initialization void Start() { SendSecureCodeButton.GetComponent().onClick.AddListener(() => StartSignIn());

} // Update is called once per frame void Update () {

}

void StartSignIn() { firebaseAuth = Firebase.Auth.FirebaseAuth.DefaultInstance; phoneAuthTimeoutMs = 60000; phoneNumber = PhoneNumberInputFieldText.text; Debug.Log(phoneNumber);

 if (PlayerPrefs.GetString("secureCode") != null)
 {
     verificationId = PlayerPrefs.GetString("secureCode");
 }
 PhoneAuthProvider provider = PhoneAuthProvider.GetInstance(firebaseAuth);
 provider.VerifyPhoneNumber(phoneNumber, phoneAuthTimeoutMs, null,
   verificationCompleted: (credential) =>
   {
       // Auto-sms-retrieval or instant validation has succeeded (Android only).
       // There is no need to input the verification code.
       // `credential` can be used instead of calling GetCredential().
   },
   verificationFailed: (error) =>
   {
       // The verification code was not sent.
       // `error` contains a human readable explanation of the problem.
   },
   codeSent: (id, token) =>
   {
       //Prompt here to type in SecureCode
       PlayerPrefs.SetString("secureCode", id);


       credential = provider.GetCredential(verificationId, verificationCode);

       firebaseAuth.SignInWithCredentialAsync(credential).ContinueWith(task => {
           if (task.IsFaulted)
           {
               Debug.LogError("SignInWithCredentialAsync encountered an error: " +
                               task.Exception);
               return;
           }

           FirebaseUser newUser = task.Result;
           Debug.Log("User signed in successfully");
           // This should display the phone number.
           Debug.Log("Phone number: " + newUser.PhoneNumber);
           // The phone number providerID is 'phone'.
           Debug.Log("Phone provider ID: " + newUser.ProviderId);
       });

       // Verification code was successfully sent via SMS.
       // `id` contains the verification id that will need to passed in with
       // the code from the user when calling GetCredential().
       // `token` can be used if the user requests the code be sent again, to
       // tie the two requests together.
   },
   codeAutoRetrievalTimeOut: (id) =>
   {
       // Called when the auto-sms-retrieval has timed out, based on the given
       // timeout parameter.
       // `id` contains the verification id of the request that timed out.
   });


} }

Thanks in advance!

Here is my Firebase Console:alt text

console.png (21.2 kB)
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by unity_XY9GfkpHMyaikw · May 25, 2019 at 01:56 PM

Update: Since the documentation to use Firebase along with Unity is really unclear I had to find an alternative. I found the solution. I am using TextLocal as a SMS gateway provider. Here's the tutorial I followed on Youtube: https://www.youtube.com/watch?v=d8OrtnpFC3M&feature=player_embedded

The tutorial is in C# but is not meant for Unity. I modified the code to suit Unity and here's my code:

using System; using System.Collections.Generic; using System.Net; using System.Collections.Specialized; using System.IO; using System.Text; using UnityEngine; using System.Collections.Generic; using System.Net; using System.Collections.Specialized; using System.Threading.Tasks; using System.Linq; using Random = System.Random; using UnityEngine.UI;

public class OTPSMS : MonoBehaviour { // public string txtPhone; // public string txtName; string randomNumber; public GameObject MessageBox; public GameObject MessageBox2; public GameObject MessageBox3; public GameObject MessageBox4; public InputField txtPhone; public InputField txtName; public InputField txtVerOTP;

 // Start is called before the first frame update
 void Start()
 {
     MessageBox.SetActive(false);
     MessageBox2.SetActive(false);
     MessageBox3.SetActive(false);
     MessageBox4.SetActive(false);
 }

 // Update is called once per frame
 void Update()
 {

 }

 public void login()
 {

     String result;
     string apiKey = "YOUR API KEY"; //The one which you get on TextLocal after registering . Follow the youtube tutorial
     string numbers = txtPhone.text; // in a comma seperated list
    
     string sender = "TXTLCL";
     string name = txtName.text;
     var rnd = new Random();
     randomNumber = (rnd.Next(100000, 999999)).ToString();
     string message = "Hey " +name+ " Your OTP is " +randomNumber ;

     String url = "https://api.textlocal.in/send/?apikey=" + apiKey + "&numbers=" + numbers + "&message=" + message + "&sender=" + sender;
     //refer to parameters to complete correct url string

     StreamWriter myWriter = null;
     HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);

     objRequest.Method = "POST";
     objRequest.ContentLength = Encoding.UTF8.GetByteCount(url);
     objRequest.ContentType = "application/x-www-form-urlencoded";
     try
     {
         myWriter = new StreamWriter(objRequest.GetRequestStream());
         myWriter.Write(url);
     }
     catch (Exception e)
     {
         MessageBox.SetActive(true);
     }
     finally
     {
         myWriter.Close();
     }

     HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
     using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
     {
         result = sr.ReadToEnd();
         // Close and clean up the StreamReader
         sr.Close();
     }
     MessageBox2.SetActive(true);

 }

 public void Verify()
 {
     if(txtVerOTP.text ==randomNumber)
     {
         MessageBox3.SetActive(true);
     }
     else
     {
         MessageBox4.SetActive(true);
     }
 }

}

And this is what the UI and hierarchy looks like: alt text


otp.png (135.8 kB)
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ChetanaMali · Jun 16, 2021 at 07:43 PM 0
Share

I try this but I didn't get any OTP through Massage also I get error that shown in img. It pause after click on login button. How to resolve this error?

[1]: /storage/temp/182225-null-ref-exception-error1.jpg

null-ref-exception-error1.jpg (16.9 kB)

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

139 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Help with Game Center login. 1 Answer

Sorry, this link is no longer valid 3 Answers

MYSQL for webplayer 0 Answers

Is This Login Algoritm Secure For an MMO? 0 Answers

Can't log in... 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges