flutter: phone Authentication failed -ERROR: Invalid token.. Try again later

Viewed 1497

Firebase Phone Auth is working in simulator and not working in real device.

already i created an apn key in developer.apple.com and add that in firebase and enabled background mode and check fetch, process and background.

This is what the console prints out:

Runner[11345:2633540] GTMSessionFetcher invoking fetch callbacks, data {length = 252, bytes = 0x7b0a2020 22657272 6f72223a 207b0a20 ... 5d0a2020 7d0a7d0a }, error Error Domain=com.google.HTTPStatus Code=400 "(null)" UserInfo={data={length = 252, bytes = 0x7b0a2020 22657272 6f72223a 207b0a20 ... 5d0a2020 7d0a7d0a }, data_content_type=application/json; charset=UTF-8}
2021-10-29 22:07:22.273998+0300 Runner[11345:2633546] flutter: Invalid token.
2021-10-29 22:07:22.523814+0300 Runner[11345:2633540] [connection] nw_resolver_start_query_timer_block_invoke [C3.1] Query fired: did not receive all answers in time for www.googleapis.com:443

My flutter code is like below

      Future<void> verifyPhone() async {
    await _auth.verifyPhoneNumber(
      phoneNumber: _phoneNumber,
      verificationCompleted: (PhoneAuthCredential credential) async {
        await FirebaseAuth.instance.signInWithCredential(credential);
        final snackBar = SnackBar(content: Text("Login Success"));
        ScaffoldMessenger.of(context).showSnackBar(snackBar);
      },
      verificationFailed: (FirebaseAuthException e) {
        print(e.message);
        final snackBar =
            SnackBar(content: Text("verificationFailed ${e.message}"));
        ScaffoldMessenger.of(context).showSnackBar(snackBar);
      },
      codeSent: (String verficationId, int resendToken) {
        setState(() {
          codeSent = true;
          verId = verficationId;
        });
      },
      codeAutoRetrievalTimeout: (String verificationId) {
        setState(() {
          verId = verificationId;
        });
      },
      timeout: Duration(seconds: 60),
    );
  }

AppDelegate.swift

import UIKit
import Flutter
import Firebase

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    FirebaseApp.configure()
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Podfile

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'
platform :ios, '10.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
  end
end

Info.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>$(DEVELOPMENT_LANGUAGE)</string>
    <key>CFBundleDisplayName</key>
    <string>DOTHawala</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleLocalizations</key>
    <array>
        <string>en</string>
        <string>fa</string>
        <string>ar</string>
    </array>
    <key>CFBundleName</key>
    <string>dot_exchange</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>$(FLUTTER_BUILD_NAME)</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>com.googleusercontent.apps.768659512914-kgtssn20sbm0ioj47dnp8ekcgsgou7b8</string>
            </array>
        </dict>
    </array>
    <key>CFBundleVersion</key>
    <string>$(FLUTTER_BUILD_NUMBER)</string>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>https</string>
        <string>http</string>
    </array>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    <key>UIBackgroundModes</key>
    <array>
        <string>fetch</string>
        <string>processing</string>
        <string>remote-notification</string>
    </array>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <false/>
</dict>
</plist>
3 Answers

I've faced the exactly same problem, and fixed up.

  1. First of all, make sure that firebase_messaging is listed in the pubspec.yaml.

  2. If you set an option for Info.plist <key>FirebaseAppDelegateProxyEnabled</key> <false/>, it would be resolved by adding this implement on ios/Runner/AppDelegate.swift. (or possibly just removing <key>FirebaseAppDelegateProxyEnabled</key> <false/> from Info.plist, it will be solved simply.)

import UIKit
import Flutter
import FirebaseMessaging

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
  //  this block
  override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // NOTE: For logging
    // let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    // print("==== didRegisterForRemoteNotificationsWithDeviceToken ====")
    // print(deviceTokenString)
    Messaging.messaging().apnsToken = deviceToken
  }
}

I faced same problem when I want send OTP and get notifications on iphone physical device, so after did all confics and finished coding I created APN key on apple developer console then added it to firebase after that everything got well: enter image description here

Create an apn key in developer.apple.com and add that in firebase. Then in xcode add URL scheme and paste the reverse client id in it. Enable push notification in capabilities, enable background mode and check fetch, process and background.

Edit Add these lines in your info.plist too <key>FirebaseAppDelegateProxyEnabled</key> <false/>

and in the code add

 FirebaseMessaging.instance.getToken().then((token) {
  print('$token');
});

just to check if you are receiving the token as expected.

Related