我正在尝试使用 flutter FirebaseAuth 实例向用户发送验证短信代码,下面是代码的快照
pubspec.yml firebase_auth: ^1.2.0
Future<void> sendPhoneVerificationCode(String phoneNumber) async {
await FirebaseAuth.instance.verifyPhoneNumber(
autoRetrievedSmsCodeForTesting: phoneNumber,
phoneNumber: '+267$phoneNumber',
timeout: Duration(seconds: 60),
verificationCompleted: (phoneAuthCredential) {
this.smsCode = phoneAuthCredential.smsCode;
this.verificationId = phoneAuthCredential.verificationId;
logger.w(
'verification smsCode ${this.smsCode}',
);
},
verificationFailed: (error) {
if (error.code == 'invalid-phone-number') {
errorMessage = 'The provided phone number is not valid.';
} else {
errorMessage = error.message;
}
},
codeSent: (verificationId, [forceResendingToken]) {
this.verificationId = verificationId;
logger.w('verificationId is $verificationId');
},
codeAutoRetrievalTimeout: (String verificationId) {
this.verificationId = verificationId;
},
);
}
我没有从 verifyCompleted 方法获取短信代码,而是获取电话号码, 如何让短信验证码发送给用户?
答案 0 :(得分:0)
这是一个示例存储库:- demo repo sendPhoneVerificationCode 函数:-
Future<void> _submitPhoneNumber() async {
/// NOTE: Either append your phone number country code or add in the code itself
/// Since I'm in India we use "+91 " as prefix `phoneNumber`
String phoneNumber = "+91 " + _phoneNumberController.text.toString().trim();
print(phoneNumber);
/// The below functions are the callbacks, separated so as to make code more readable
void verificationCompleted(AuthCredential phoneAuthCredential) {
print('verificationCompleted');
...
this._phoneAuthCredential = phoneAuthCredential;
print(phoneAuthCredential);
}
void verificationFailed(AuthException error) {
...
print(error);
}
void codeSent(String verificationId, [int code]) {
...
print('codeSent');
}
void codeAutoRetrievalTimeout(String verificationId) {
...
print('codeAutoRetrievalTimeout');
}
await FirebaseAuth.instance.verifyPhoneNumber(
/// Make sure to prefix with your country code
phoneNumber: phoneNumber,
/// `seconds` didn't work. The underlying implementation code only reads in `milliseconds`
timeout: Duration(milliseconds: 10000),
/// If the SIM (with phoneNumber) is in the current device this function is called.
/// This function gives `AuthCredential`. Moreover `login` function can be called from this callback
verificationCompleted: verificationCompleted,
/// Called when the verification is failed
verificationFailed: verificationFailed,
/// This is called after the OTP is sent. Gives a `verificationId` and `code`
codeSent: codeSent,
/// After automatic code retrival `tmeout` this function is called
codeAutoRetrievalTimeout: codeAutoRetrievalTimeout,
); // All the callbacks are above
}