Firebase Auth Phone OTP无法在Android中自动阅读

lx0bsm1f  于 2023-05-12  发布在  Android
关注(0)|答案(1)|浏览(135)

我正在使用最新的firebase sdk进行身份验证,但otp自动填充不工作。OTP短信成功接收,当我手动输入它是没有任何问题的工作.但我需要在没有用户参与的情况下自动获取OTP。
我的代码:

mAuth = FirebaseAuth.getInstance();
    editText = findViewById(R.id.sixdigit);
    mTextViewCountDown = findViewById(R.id.text_view_countdown);

    progress = new ProgressDialog(GVerifyotpActivity.this);
    progress.setMessage("Waiting....");
    progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);

    String phonenumber = getIntent().getStringExtra("phonenumber");
    sendVerificationCode(phonenumber);

    findViewById(R.id.pnext).setOnClickListener(v -> {
        String code = editText.getText().toString().trim();
        if (code.isEmpty() || code.length() < 6) {
            editText.setError("Enter code...");
            editText.requestFocus();
            return;
        }
        verifyCode(code);
    });

    mButtonStartPause = findViewById(R.id.button_start_pause);
    mButtonStartPause.setOnClickListener(view -> {
        resetTimer();
        startTimer();
        resendVerificationCode(phonenumber, mResendToken);
    });
}

private void verifyCode(String code) {
    PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
    signInWithCredential(credential);
    if(progress!=null && !progress.isShowing()) {
        progress.show();
    }
}

private void signInWithCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                     //Success!
                    }).addOnFailureListener(unused-> Toast.makeText(this, R.string.try_1, Toast.LENGTH_SHORT).show());
                } else {
                    Toast.makeText(GVerifyotpActivity.this, Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_LONG).show();
                }
            });
}

private void sendVerificationCode(String number) {
    PhoneAuthOptions options =
            PhoneAuthOptions.newBuilder(mAuth)
                    .setPhoneNumber(number)       // Phone number to verify
                    .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
                    .setActivity(this)                 // Activity (for callback binding)
                    .setCallbacks(mCallbacks)          // OnVerificationStateChangedCallbacks
                    .build();
    PhoneAuthProvider.verifyPhoneNumber(options);

}

private void startTimer() {
    new CountDownTimer(mTimeLeftInMillis, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            mTimeLeftInMillis = millisUntilFinished;
            updateCountDownText();
        }

        @Override
        public void onFinish() {
            mButtonStartPause.setEnabled(true);
        }
    }.start();
}

private void resetTimer() {
    mTimeLeftInMillis = START_TIME_IN_MILLIS;
    updateCountDownText();
    mButtonStartPause.setEnabled(false);
}

private void resendVerificationCode(String phoneNumber,
                                    PhoneAuthProvider.ForceResendingToken token) {
    PhoneAuthOptions options =
            PhoneAuthOptions.newBuilder(mAuth)
                    .setPhoneNumber(phoneNumber)       // Phone number to verify
                    .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
                    .setActivity(this)                 // Activity (for callback binding)
                    .setCallbacks(mCallbacks)          // OnVerificationStateChangedCallbacks
                    .setForceResendingToken(token)     // ForceResendingToken from callbacks
                    .build();
    PhoneAuthProvider.verifyPhoneNumber(options);
}

private void updateCountDownText() {
    int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
    int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
    String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
    mTextViewCountDown.setText(timeLeftFormatted);
}

public void testPhoneAutoRetrieve() {
    // [START auth_test_phone_auto]
    // The test phone number and code should be whitelisted in the console.
    String phoneNumber = "+9471268xxxxx";
    String smsCode = "123456";

    FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
    FirebaseAuthSettings firebaseAuthSettings = firebaseAuth.getFirebaseAuthSettings();

    // Configure faking the auto-retrieval with the whitelisted numbers.
    firebaseAuthSettings.setAutoRetrievedSmsCodeForPhoneNumber(phoneNumber, smsCode);

    PhoneAuthOptions options = PhoneAuthOptions.newBuilder(firebaseAuth)
            .setPhoneNumber(phoneNumber)
            .setTimeout(120L, TimeUnit.SECONDS)
            .setActivity(this)
            .setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
                @Override
                public void onVerificationCompleted(PhoneAuthCredential credential) {
                    // Instant verification is applied and a credential is directly returned.
                    // ...
                    Log.d("TAGRR", "onVerificationCompleted: "+credential);
                }

                // [START_EXCLUDE]
                @Override
                public void onVerificationFailed(FirebaseException e) {
                    Log.d("TAGRR", "onVerificationFailed: "+e);
                }
                // [END_EXCLUDE]
            })
            .build();
    PhoneAuthProvider.verifyPhoneNumber(options);
    // [END auth_test_phone_auto]
}

private PhoneAuthProvider.OnVerificationStateChangedCallbacks
        mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

    @Override
    public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
        super.onCodeSent(s, forceResendingToken);
        verificationId = s;
        mResendToken = forceResendingToken;
    }

    @Override
    public void onVerificationCompleted(@NonNull PhoneAuthCredential credential) {
        // This callback will be invoked in two situations:
        // 1 - Instant verification. In some cases the phone number can be instantly
        //     verified without needing to send or enter a verification code.
        // 2 - Auto-retrieval. On some devices Google Play services can automatically
        //     detect the incoming verification SMS and perform verification without
        //     user action.
        Log.d("TAGP", "onVerificationCompleted:" + credential);

        String code = credential.getSmsCode();
        if (code != null) {
            editText.setText(code);
        }
        signInWithCredential(credential);
        if(progress!=null && !progress.isShowing()) {
            progress.show();
        }
    }

    @Override
    public void onVerificationFailed(FirebaseException e) {
        Toast.makeText(GVerifyotpActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
};

依赖关系

implementation 'com.google.firebase:firebase-auth:21.0.1'
implementation 'com.google.android.gms:play-services-auth-api-phone:17.5.1'
implementation 'com.google.android.gms:play-services-auth:19.2.0'

Android DeviceCheck API添加成功,Firebase设置中插入SHA-256密钥!安全网已启动!

classpath 'com.android.tools.build:gradle:4.2.2'
classpath 'com.google.gms:google-services:4.3.8'

一切都已根据Firebase文档[https://firebase.google.com/docs/auth/android/phone-auth]完成
我测试了testPhoneAutoRetrieve()方法,它的作品,但与真实的的SIM卡它不工作!凭据不是从收到的短信!
找到的日志

Ignoring header X-Firebase-Locale because its value was null.

FirebaseAuth: [SmsRetrieverHelper] Timed out waiting for SMS. 
PhoneAuthProvider: Sms auto retrieval timed-out.

有什么我忘了的吗?应用名称字符限制有问题吗?示例应用程序名称- MyApp:Abc,Xyz(国家)
1.列表项

kg7wmglp

kg7wmglp1#

我也遇到了同样的问题,我的问题是由于应用程序名称太长,无法包含哈希代码。下面是一些工作:
1.您需要确保收到的消息包含您的应用程序的哈希值。下面是正确的格式:
123456是%APP_NAME%的验证码。
abc_hascode_xyz
1.如果您的短信末尾不包含hashCode,则可能需要将应用名称缩短至不超过15个字符。
1.如果您的应用已在Google Play上发布,则SMS中的名称将与Google Play商店中的名称相同。
1.如果您将名称更改为15个字符,但错误仍然存在,则可能需要等待至少24小时,才能在firebase上反映更改。
1.如果经过上述所有步骤仍然无法解决,请检查您的接收器是否在代码中配置良好。
查看GooglePlay关于应用名称的新政策:常见应用程序名称违规示例

相关问题