Flutter短信发送插件infobip_sms的使用

发布于 1周前 作者 yibo5220 来自 Flutter

Flutter短信发送插件infobip_sms的使用

Infobip SMS Plugin 是一个帮助你集成 Infobip 的短信服务以实现快速有效的电话号码验证的 Flutter 插件。

功能

  • 电话号码验证:直接通过短信发送一次性验证码(OTP)。
  • 消息发送:自定义并发送消息到任何电话号码。
  • 状态跟踪:检查消息状态(已送达、失败等)。
  • 简单集成:快速安装和简单的配置。

安装

pubspec.yaml 文件中添加插件:

dependencies:
  infobip_sms: <最新版本>

然后运行:

flutter pub get

配置

创建一个 Infobip 账户并从 Infobip Dashboard 获取 API 密钥。

使用

首先,在 AndroidManifest.xml 文件中添加所需的权限:

<manifest>
  <uses-permission android:name="android.permission.INTERNET" />
</manifest>

接下来,在你的 Flutter 应用程序中初始化 Infobip SMS 插件,并编写发送和验证 OTP 的方法:

import 'package:flutter/material.dart';
import 'package:infobip_sms/infobip_sms.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  void initState() {
    super.initState();
    InfoBipSms.init(
        baseUrl: 'https://api.infobip.com', // 基础 URL
        apiKey: 'your_api_key_here', // 你的 API 密钥
        onError: (e) {
          // 错误处理
        });
  }

  sendOTP() async {
    try {
      // 发送 OTP 码到指定电话号码
      await InfoBipSms.sendPinCode(recipientPhone: '+840987654321');
    } catch (e) {
      // 错误处理
    }
  }

  verifyOTP() async {
    try {
      // 验证 OTP 码
      await InfoBipSms.verifyPin(pinCode: '1234');
    } catch (e) {
      // 错误处理
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Column(
          children: [
            // 发送 OTP 按钮
            ElevatedButton(onPressed: sendOTP, child: const Text('发送 OTP')),
            // 验证 OTP 按钮
            ElevatedButton(
              onPressed: verifyOTP,
              child: const Text('验证 OTP'),
            ),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter短信发送插件infobip_sms的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter短信发送插件infobip_sms的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用infobip_sms插件发送短信的示例代码。这个插件允许你通过Infobip的SMS API发送短信。

首先,你需要在你的pubspec.yaml文件中添加infobip_sms依赖:

dependencies:
  flutter:
    sdk: flutter
  infobip_sms: ^最新版本号  # 请替换为实际的最新版本号

然后运行flutter pub get来获取依赖。

接下来,你需要在你的Flutter应用中配置Infobip的API密钥和账户信息。这通常涉及到在项目的某个配置文件中存储这些敏感信息,但为了简化示例,这里直接在代码中硬编码(注意:在实际应用中,应避免在代码中硬编码敏感信息,应使用环境变量或安全的密钥管理服务)。

以下是一个完整的示例,展示如何使用infobip_sms插件发送短信:

import 'package:flutter/material.dart';
import 'package:infobip_sms/infobip_sms.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String result = "";

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Infobip SMS Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'Send SMS using Infobip',
                style: TextStyle(fontSize: 24),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  // 配置Infobip API密钥和账户信息
                  final infobipSms = InfobipSms(
                    baseUrl: 'https://api.infobip.com', // Infobip API的基础URL
                    apiKey: 'your-api-key-here',        // 替换为你的Infobip API密钥
                  );

                  // 发送短信的请求体
                  final messageRequest = MessageRequest(
                    from: 'YourSenderID',               // 发送者ID或电话号码
                    to: ['+1234567890'],               // 接收者电话号码列表
                    text: 'Hello, this is a test message!', // 短信内容
                  );

                  try {
                    // 发送短信并处理响应
                    final response = await infobipSms.sendMessage(messageRequest);
                    setState(() {
                      result = 'Message sent successfully: ${response.toJson()}';
                    });
                  } catch (e) {
                    setState(() {
                      result = 'Error sending message: ${e.message}';
                    });
                  }
                },
                child: Text('Send SMS'),
              ),
              SizedBox(height: 20),
              Text(result),
            ],
          ),
        ),
      ),
    );
  }
}

// 假设infobip_sms插件提供了以下数据结构(实际数据结构请参考插件文档)
class MessageRequest {
  String from;
  List<String> to;
  String text;

  MessageRequest({required this.from, required this.to, required this.text});
}

class InfobipSms {
  String baseUrl;
  String apiKey;

  InfobipSms({required this.baseUrl, required this.apiKey});

  Future<Map<String, dynamic>> sendMessage(MessageRequest request) async {
    // 实际的发送逻辑会涉及到HTTP请求,这里仅展示一个假设的返回结果
    // 在实际使用中,你需要根据Infobip API文档构建正确的HTTP请求
    // 并处理API的响应
    return {
      'messages': [
        {
          'status': {
            'groupId': 1,
            'groupName': 'PENDING',
            'id': 1,
            'name': 'DELIVRD',
            'description': 'Message delivered to recipient'
          },
          // 其他响应字段...
        }
      ]
    };
  }
}

注意

  1. 上面的InfobipSms类和sendMessage方法中的实现是假设的,因为实际的infobip_sms插件会有自己的API封装。你需要参考插件的官方文档来正确实现这部分。
  2. MessageRequest类也是基于假设的数据结构,实际使用时需要根据插件提供的类和方法进行调整。
  3. 替换your-api-key-here为你的实际Infobip API密钥。
  4. 确保你的电话号码格式正确,符合国际格式(例如:+1234567890)。

这个示例提供了一个基本的框架,展示了如何在Flutter应用中集成和使用infobip_sms插件来发送短信。实际使用中,你需要根据插件的文档和API规范进行进一步的调整和错误处理。

回到顶部