You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Firebase替代Twilio实现短信授权?求技术方案建议

Hey there! Let's figure out how to swap Twilio for Firebase SMS auth in your Android app without rewriting tons of code. I see you tried the Identity Toolkit API but didn't get any SMS—let's break down why that happened and fix it.

Why Your Initial Firebase API Call Failed

The sendVerificationCode endpoint you used requires a client-generated reCAPTCHA token to prevent abuse. Firebase blocks requests that don't include this token (since it needs to confirm the request comes from a legitimate user, not a bot). Your server-side curl call didn't include a valid token, so the request was rejected, and no SMS was sent.

Below are two practical solutions to get this working, with minimal code changes:


Solution 1: Adjust Client + Server (Keep Using HTTP API)

This keeps your existing server-to-third-party flow intact, just swapping Twilio's API for Firebase's, with a tiny Android tweak to generate the required reCAPTCHA token.

Step 1: Add Firebase Auth to Your Android App (Minimal Changes)

You'll need to generate a reCAPTCHA token on the client and pass it to your server. Here's how:

  1. Add Firebase Auth dependency to your build.gradle (if not already present):
    implementation 'com.google.firebase:firebase-auth:22.3.1'
    
  2. Generate the reCAPTCHA token and send it to your server along with the user's phone number:
    // Initialize reCAPTCHA verifier
    RecaptchaVerifier recaptchaVerifier = new RecaptchaVerifier(
        "recaptcha_container_id", // Use a hidden view ID or create one programmatically
        getApplicationContext(),
        new RecaptchaVerifier.OnRecaptchaTokenListener() {
            @Override
            public void onRecaptchaTokenReceived(String token) {
                // Send this token + user's phone number to your server
                sendTokenToServer(phoneNumber, token);
            }
    
            @Override
            public void onRecaptchaError(FirebaseException error) {
                // Handle reCAPTCHA generation failure
            }
        }
    );
    recaptchaVerifier.verify();
    

Step 2: Update Your Server's Curl Request

Now that your server has a valid reCAPTCHA token, use this curl call to trigger the SMS:

curl -X POST \
'https://www.googleapis.com/identitytoolkit/v3/relyingparty/sendVerificationCode?key=YOUR_FIREBASE_WEB_API_KEY' \
-H 'Content-Type: application/json' \
-d '{
    "phoneNumber": "+99670XXXXXXX",
    "recaptchaToken": "CLIENT_GENERATED_RECAPTCHA_TOKEN"
}'
  • Replace YOUR_FIREBASE_WEB_API_KEY with the API key from your Firebase project (found in Console → Project Settings → Web Apps → API Key).
  • This request returns a sessionInfo string—store this on your server. When the user enters the SMS code, use this curl call to verify it:
    curl -X POST \
    'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPhoneNumber?key=YOUR_FIREBASE_WEB_API_KEY' \
    -H 'Content-Type: application/json' \
    -d '{
        "phoneNumber": "+99670XXXXXXX",
        "sessionInfo": "SESSION_INFO_FROM_SEND_REQUEST",
        "code": "USER_INPUT_SMS_CODE"
    }'
    

A successful response will include an idToken you can use to confirm the user's identity, just like you would with Twilio's verification flow.


Solution 2: Use Firebase Admin SDK (More Stable for Servers)

If your server uses Node.js, Python, Java, or another supported language, the Firebase Admin SDK is a more reliable alternative to raw curl calls.

Step 1: Set Up the Admin SDK

  1. Download your Firebase service account key (Console → Project Settings → Service Accounts → Generate New Private Key).
  2. Install the SDK for your server language (example for Node.js):
    npm install firebase-admin
    
  3. Initialize the SDK:
    const admin = require('firebase-admin');
    const serviceAccount = require('./path-to-your-service-account.json');
    
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount)
    });
    

Step 2: Verify the SMS Code

The Admin SDK can't directly send SMS (since it needs the client's reCAPTCHA), but you can have the client trigger the SMS via Firebase Auth, then pass the verification ID and user's code to your server for validation:

  1. On Android, trigger the SMS with Firebase Auth:
    PhoneAuthProvider.getInstance().verifyPhoneNumber(
        phoneNumber,
        60,
        TimeUnit.SECONDS,
        this,
        new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
            @Override
            public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {
                // Send this verificationId to your server
                sendVerificationIdToServer(verificationId);
            }
    
            // Handle other callbacks as needed
        }
    );
    
  2. On your server, use the Admin SDK to verify the code:
    const verificationId = 'FROM_CLIENT';
    const userInputCode = 'USER_SMS_CODE';
    
    const credential = admin.auth.PhoneAuthProvider.credential(verificationId, userInputCode);
    admin.auth().verifyPhoneNumberCredential(credential)
      .then((userRecord) => {
        // Verification succeeded! Use userRecord.uid to confirm identity
        console.log('User verified:', userRecord.uid);
      })
      .catch((error) => {
        // Handle invalid code or verification failure
        console.error('Verification failed:', error);
      });
    

Key Notes to Remember

  • Firebase Quotas: Free Firebase plans have limited SMS credits—check the pricing page for details on paid tiers if you need higher volume.
  • Region Support: Ensure your target countries are supported by Firebase Phone Auth.
  • API Key vs Service Account: Use your project's Web API Key for HTTP calls, and the service account key only for the Admin SDK.

内容的提问来源于stack exchange,提问作者Tologon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 09:57:31