【问题标题】:How to resend SMS verification in Firebase Phone Authentication Android?如何在 Firebase Phone Authentication Android 中重新发送短信验证?
【发布时间】:2017-06-22 01:41:37
【问题描述】:

根据 Firebase 文档 (https://firebase.google.com/docs/auth/android/phone-auth#send-a-verification-code-to-the-users-phone),有 callback 用于处理电话号码身份验证。

mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

    @Override
    public void onVerificationCompleted(PhoneAuthCredential credential) {

        Log.d(TAG, "onVerificationCompleted:" + credential);
        signInWithPhoneAuthCredential(credential);
    }

    @Override
    public void onVerificationFailed(FirebaseException e) {

        Log.w(TAG, "onVerificationFailed", e);
    }

    @Override
    public void onCodeSent(String verificationId,
                           PhoneAuthProvider.ForceResendingToken token) {

        Log.d(TAG, "onCodeSent:" + verificationId);

        // Save verification ID and resending token so we can use them later
        mVerificationId = verificationId;
        mResendToken = token;
    }
};

我的问题是关于onCodeSent 方法。它在这里的文档上说(https://firebase.google.com/docs/reference/android/com/google/firebase/auth/PhoneAuthProvider.ForceResendingToken

token 可用于强制重新发送短信验证码。但是,在对文档进行了一些研究之后,我仍然不知道如何。

请问如何使用这个token重新发送短信验证?

【问题讨论】:

  • 当然感谢您的帮助。 :)

标签: android firebase firebase-authentication sms-verification


【解决方案1】:

来源:Firebase Quickstarts for Android

这是用于重新发送短信验证的方法。

private void resendVerificationCode(String phoneNumber,
                                    PhoneAuthProvider.ForceResendingToken token) {
    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            phoneNumber,        // Phone number to verify
            60,                 // Timeout duration
            TimeUnit.SECONDS,   // Unit of timeout
            this,               // Activity (for callback binding)
            mCallbacks,         // OnVerificationStateChangedCallbacks
            token);             // ForceResendingToken from callbacks
}

【讨论】:

  • 谢谢。你救了我。
  • 直接使用 PhoneAuthProvider.verifyPhoneNumber() 而不是 getInstance。并使用上述所有参数传递 PhoneAuthOptions.newBuilder()。
【解决方案2】:

更新代码

fun resendOTP(activity: Activity,mobileNo: String){
    val options = PhoneAuthOptions.newBuilder(auth)
        .setPhoneNumber(mobileNo) // Phone number to verify
        .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
        .setActivity(activity) // Activity (for callback binding)
        .setCallbacks(callback) // OnVerificationStateChangedCallbacks
        .setForceResendingToken(resendToken!!) // ForceResendingToken from callbacks
        .build()
    PhoneAuthProvider.verifyPhoneNumber(options)
}

对于java,请参阅Github

感谢GGWP 提供链接。

【讨论】:

    【解决方案3】:

    您可以使用 Firebase 方法重新发送验证码,例如 PERSISTENCE 并拦截短信代码以自动签入,例如在运行进度对话框时,对用户透明,简单来说

    // [START resend_verification]
    public void resendVerificationCode(String phoneNumber,
                                       PhoneAuthProvider.ForceResendingToken token) {
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                phoneNumber,        // Phone number to verify
                60,                 // Timeout duration
                TimeUnit.SECONDS,   // Unit of timeout
                activity,           //a reference to an activity if this method is in a custom service
                mCallbacks,
                token);        // resending with token got at previous call's `callbacks` method `onCodeSent` 
        // [END start_phone_auth]
    }
    

    使用片段中的广播接收器检查短信

    private BroadcastReceiver smsBroadcastReceiver;
    IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
    public static final String SMS_BUNDLE = "pdus";
    
     @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    
        smsBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.e("smsBroadcastReceiver", "onReceive");
                Bundle pudsBundle = intent.getExtras();
                Object[] pdus = (Object[]) pudsBundle.get(SMS_BUNDLE);
                SmsMessage messages = SmsMessage.createFromPdu((byte[]) pdus[0]);
                Log.i(TAG,  messages.getMessageBody());
    
                firebaseVerificationCode = messages.getMessageBody().trim().split(" ")[0];//only a number code 
                Toast.makeText(getContext(), firebaseVerificationCode,Toast.LENGTH_SHORT).show();
                String token = firebaseAutenticationService.getVerificationCode();//your service
            firebaseAutenticationService.verifyPhoneNumberWithCode(token,verificationCode);
            }
        };
    }
    

    【讨论】:

      【解决方案4】:

      最终 FirebaseAuth _auth = FirebaseAuth.instance;

        void resendVerificationCode(String phoneNumber) async {
          print(widget.forceResendingToken);
          EasyLoading.show();
          await _auth.verifyPhoneNumber(
              phoneNumber: "+91" + phoneNumber,
              forceResendingToken: widget.forceResendingToken,
              timeout: const Duration(seconds: 120),
              verificationCompleted: (PhoneAuthCredential phoneAuthCredential) async {
                await _auth.signInWithCredential(phoneAuthCredential);
                EasyLoading.dismiss();
                showSnackbar(
                    "Phone number automatically verified and user signed in: ${_auth.currentUser.uid}");
              },
              verificationFailed: (FirebaseAuthException authException) {
                EasyLoading.dismiss();
                showSnackbar(
                    'Phone number verification failed. Code: ${authException.code}. Message: ${authException.message}');
              },
              codeSent: (String verificationId, [int forceResendingToken]) async {
                print("TESTED 1.D");
                EasyLoading.dismiss();
                showSnackbar('Please check your phone for the verification code.');
                widget._verificationId = verificationId;
              },
              codeAutoRetrievalTimeout: (String verificationId) {
                EasyLoading.dismiss();
                showSnackbar("verification code: " + verificationId);
                widget._verificationId = verificationId;
              });
        }
      

      您将在第一次发送 SMS 时获得 forceResendToken。只需将其保存到变量并下次传递该变量即可。

      // forceResendingToken: widget.forceResendingToken

      【讨论】:

        猜你喜欢
        • 2020-12-23
        • 1970-01-01
        • 2020-05-11
        • 2019-01-13
        • 2020-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多