Flutter教程实现短信验证码发送

在Flutter中实现短信验证码发送功能时,如何集成第三方短信服务商(如阿里云、腾讯云)的SDK?发送验证码前需要做哪些安全校验?有没有完整的代码示例展示从输入手机号到完成验证的流程?如何处理发送频率限制和验证码过期逻辑?测试阶段如何模拟短信接收而不产生实际费用?

3 回复

作为一个屌丝程序员,教你用Flutter实现短信验证码发送。首先集成Firebase,它支持短信认证功能。步骤如下:1. 在Firebase控制台创建项目并启用电话认证;2. 在Flutter项目中添加依赖firebase_auth;3. 编写发送验证码的代码:

Future<void> sendOTP(String phoneNumber) async {
  await FirebaseAuth.instance.verifyPhoneNumber(
    phoneNumber: phoneNumber,
    verificationCompleted: (PhoneAuthCredential credential) {},
    verificationFailed: (FirebaseAuthException e) {},
    codeSent: (String verificationId, int? resendToken) {
      // 保存verificationId以便后续验证
    },
    codeAutoRetrievalTimeout: (String verificationId) {},
  );
}

用户输入验证码后调用:

Future<void> verifyOTP(String verificationId, String userOTP) async {
  PhoneAuthCredential credential = PhoneAuthProvider.credential(
    verificationId: verificationId, 
    smsCode: userOTP,
  );
  await FirebaseAuth.instance.signInWithCredential(credential);
}

记得配置好Android和iOS的权限与证书!

更多关于Flutter教程实现短信验证码发送的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


作为屌丝程序员,我来分享一个简单的实现思路。首先需要后端提供一个接口用于发送短信验证码,比如使用阿里云短信服务。

  1. 后端接口:编写一个接口,接收手机号参数,生成6位随机验证码并存储到Redis中(设置过期时间),然后调用短信服务商API发送验证码。

  2. 前端请求:在Flutter中,使用http库向后端发送GET或POST请求,携带手机号参数。例如:

    Future<void> sendSms(String phone) async {
      final response = await http.post(
        Uri.parse('https://yourserver.com/send-sms'),
        body: {'phone': phone},
      );
      if (response.statusCode == 200) {
        print('短信已发送');
      } else {
        print('发送失败');
      }
    }
    
  3. 验证逻辑:用户输入验证码后,再次调用后端接口验证。后端从Redis取出并对比验证码是否一致。

  4. 依赖管理:记得添加http依赖到pubspec.yaml文件中。

这样就可以完成基本的短信验证码功能啦!虽然简单,但对于屌丝程序员来说足够用了。

Flutter短信验证码发送实现教程

在Flutter中实现短信验证码发送功能通常需要结合后端服务或第三方短信服务API。以下是实现的基本步骤和示例代码:

1. 使用第三方短信服务(如阿里云、腾讯云等)

首先需要注册短信服务提供商并获取API密钥。以下是使用阿里云短信服务的示例:

import 'package:http/http.dart' as http;
import 'dart:convert';

Future<bool> sendSmsVerification(String phoneNumber) async {
  final url = 'https://dysmsapi.aliyuncs.com/';
  
  final params = {
    'AccessKeyId': '你的AccessKey',
    'Action': 'SendSms',
    'PhoneNumbers': phoneNumber,
    'SignName': '你的签名',
    'TemplateCode': '你的模板ID',
    'TemplateParam': '{"code":"123456"}',
    'RegionId': 'cn-hangzhou',
    'Format': 'JSON',
    'SignatureMethod': 'HMAC-SHA1',
    'SignatureVersion': '1.0',
    'Timestamp': DateTime.now().toUtc().toString(),
    'SignatureNonce': '随机数',
  };
  
  try {
    final response = await http.post(Uri.parse(url), body: params);
    final data = json.decode(response.body);
    return data['Code'] == 'OK';
  } catch (e) {
    print('发送短信失败: $e');
    return false;
  }
}

2. 使用Firebase Auth(简单但需要Google服务)

import 'package:firebase_auth/firebase_auth.dart';

Future<void> verifyPhoneNumber(String phoneNumber) async {
  await FirebaseAuth.instance.verifyPhoneNumber(
    phoneNumber: phoneNumber,
    verificationCompleted: (PhoneAuthCredential credential) async {
      await FirebaseAuth.instance.signInWithCredential(credential);
    },
    verificationFailed: (FirebaseAuthException e) {
      print('验证失败: ${e.message}');
    },
    codeSent: (String verificationId, int? resendToken) {
      // 保存verificationId,用于后续验证
    },
    codeAutoRetrievalTimeout: (String verificationId) {},
  );
}

3. 前端验证码倒计时实现

int _countdown = 60;
Timer? _timer;

void startCountdown() {
  _timer = Timer.periodic(Duration(seconds: 1), (timer) {
    if (_countdown > 0) {
      setState(() {
        _countdown--;
      });
    } else {
      _timer?.cancel();
      setState(() {
        _countdown = 60;
      });
    }
  });
}

// 在按钮中使用
ElevatedButton(
  onPressed: _countdown != 60 ? null : () {
    sendSmsVerification('手机号码');
    startCountdown();
  },
  child: Text(_countdown == 60 ? '获取验证码' : '$_countdown秒后重试'),
)

注意事项:

  1. 短信服务通常需要付费
  2. 生产环境需要做好安全验证,防止短信轰炸
  3. 建议添加图形验证码等防护措施
  4. 遵守各平台短信发送频率限制
回到顶部