我在 Phone 身份验证系统中没有收到来自 firebase 的 Otp

I'm Not recieving an Otp from firebase in the Phone authentication system

我基本上创建了2个Xml。用户输入 phone 号码,然后按下按钮进入 OTP 验证屏幕。但这里的问题是我没有收到来自 Firebase 的任何 OTP,但 5 秒后我收到一条消息,提示验证失败。如果我什至没有收到消息,它怎么会失败。 我还尝试输入另一个数字,以便我可以手动输入代码。但是 Firebase 没有向我发送 OTP。

基本实现---点击忘记密码->询问手机号码->验证OTP->重置密码->登录页面

P.S 我在 Firebase 中启用了 phone 身份验证。

OtpActivity.java

public class VerifyOtp extends AppCompatActivity {

    public String NumberEnteredByUser,verificationCodeBySystem;
    Button VerifyButton;
    PinView phoneEnteredByUser;
    FirebaseAuth auth;
    PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallback;



    

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify_otp);
        getSupportActionBar().hide();

        Intent intent =getIntent();
        NumberEnteredByUser = intent.getStringExtra("phoneNo");



        VerifyButton = findViewById(R.id.btnVerify);
        phoneEnteredByUser = findViewById(R.id.EnterCode);
        auth = FirebaseAuth.getInstance();

        send_code_to_user(NumberEnteredByUser);




        VerifyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkcode();
            }
        });

    }


    private void checkcode() {
        String userEnteredOtp = phoneEnteredByUser.getText().toString();
        if(userEnteredOtp.isEmpty() || userEnteredOtp.length()<6){
            Toast.makeText(this, "Wrong Otp!", Toast.LENGTH_SHORT).show();
            return;
        }
        finishEverything(userEnteredOtp);
    }

    private void finishEverything(String code) {
        phoneEnteredByUser.setText(code);
        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCodeBySystem,code);
        sign_in(credential);
    }

    private void sign_in(PhoneAuthCredential credential) {
        FirebaseAuth auth = FirebaseAuth.getInstance();
        auth.signInWithCredential(credential).addOnCompleteListener(VerifyOtp.this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if(task.isSuccessful())
                {
                    Toast.makeText(VerifyOtp.this, "UserSignedInSuccessfully", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(getApplicationContext(),ResetPassword.class));
                }
                else {
                    Toast.makeText(VerifyOtp.this,task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void send_code_to_user(String NumberEnteredByUser ) {
        PhoneAuthOptions options =
                PhoneAuthOptions.newBuilder(auth)
                        .setPhoneNumber(NumberEnteredByUser)       // Phone number to verify
                        .setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
                        .setActivity(this)                 // Activity (for callback binding)
                        .setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

                            @Override
                            public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
                                Toast.makeText(VerifyOtp.this, "Verification Completed", Toast.LENGTH_SHORT).show();
                                String code = phoneAuthCredential.getSmsCode();
                                if (code != null) {
                                    finishEverything(code);
                                }
                            }

                            @Override
                            public void onVerificationFailed(FirebaseException e) {
                                Toast.makeText(VerifyOtp.this, "Verification Failed", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
                                super.onCodeSent(s, forceResendingToken);
                                verificationCodeBySystem = s;
                                Toast.makeText(VerifyOtp.this, "Code sent", Toast.LENGTH_SHORT).show();
                            }
                        })          // OnVerificationStateChangedCallbacks
                        .build();
        PhoneAuthProvider.verifyPhoneNumber(options);

    }
}

构建Gradle项目

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.2"
        classpath 'com.google.gms:google-services:4.3.8'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

构建Gradle应用程序

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'


}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.mitadt.newui"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation platform('com.google.firebase:firebase-bom:28.0.1')
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.navigation:navigation-fragment:2.2.2'
    implementation 'androidx.navigation:navigation-ui:2.2.2'
    implementation 'com.google.firebase:firebase-firestore:23.0.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation 'com.google.firebase:firebase-database:19.7.0'
    implementation 'com.google.firebase:firebase-auth:19.3.2'
    implementation 'com.android.support:multidex:1.0.3'
    //OTP VIEW DEPENDENCY
    implementation 'com.chaos.view:pinview:1.4.3'
}

请帮帮我。谢谢!!!

在用户 phone 号码前添加国家代码(印度为 +91)。它会起作用。

NumberEnteredByUser = "91"+intent.getStringExtra("phoneNo");   

验证失败,因为您没有启用应用验证。为此,您可以按照以下步骤操作:

  1. 转到 Google Cloud Console,Select 您的项目并启用 Android 设备验证。这里直接link:https://console.cloud.google.com/apis/library/androidcheck.googleapis.com

  2. 在Android工作室中,转到右上角栏,然后按“Gradle”。然后展开(您的项目名称)> app > Tasks > android,然后双击 signingReport。您将在 运行 window 中找到 SHA1 和 SHA-256,如下所示:

  3. 转到您的 firebase 控制台,然后打开应用程序。转到项目设置。向下滚动,您会发现 Add Fingerprint,您需要在其中插入 SHA1 和 SHA-256 密钥。插入后,您需要下载更新的google-services.json。将 android 工作室项目中的旧 google-services.json 替换为新的。

  4. 现在在app级添加浏览器依赖,因为app需要从浏览器打开验证码页面:

     implementation 'androidx.browser:browser:1.3.0' 
    
  5. 然后,在 Android Studio 顶部菜单 Build > Clean ProjectBuild > Rebuild Project

现在,你可以开始了。

注意:您的应用可能会显示验证码验证网页