在 Kotlin 中发送短信:用于快速集成的 API 库
在现代 Web 开发中,以编程方式发送短信的能力仍然是一项受欢迎的功能——从双因素身份验证到订单状态通知。如果您在服务器端(Ktor、Spring Boot)或移动应用程序(Android)中使用 Kotlin,您将需要一个可靠的短信服务提供商工具。在本文中,我们将介绍 用于在 Kotlin 中发送短信的 API 库、其功能、集成示例和最佳实践。
什么是用于发送短信的 API 库?
API 库是一组类和函数,它抽象了与短信服务提供商服务器进行 HTTP 请求的工作。您无需手动构建 URL、标头和解析 JSON,只需调用简单的 Kotlin 方法:sendSms(phone, message)。该库负责身份验证、序列化、网络错误时的重试以及响应处理。
库的主要功能
- 简单发送短信 — 指定收件人号码、文本以及可选的发件人名称(字母名称)。
- 批量发送 — 向号码列表发送一条消息。
- 状态检查 — 获取投递信息(已投递、排队中、错误)。
- 支持不同的提供商 — Twilio、Vonage (Nexmo)、SMSC.ru、Smsc.ua 等。
- 异步 — 所有方法返回
suspend函数或Deferred以支持协程。 - 日志记录和错误处理 — 内置调试机制。
安装和配置
该库通过 Maven Central 或 JitPack 分发。在 build.gradle.kts 中添加依赖项:
// build.gradle.kts (适用于 Gradle Kotlin DSL)dependencies { implementation("com.example:sms-api:1.0.0") // 如果您使用 Ktor Client implementation("io.ktor:ktor-client-core:2.3.0") implementation("io.ktor:ktor-client-okhttp:2.3.0")}对于 Android,还需在 AndroidManifest.xml 中添加互联网权限。
发送短信的基本示例
我们来看一个通过 SMSC.ru 提供商发送单条消息的最小示例(其他提供商类似)。
import com.example.smsapi.SmsClientimport com.example.smsapi.model.SmsRequestimport com.example.smsapi.model.SmsResponse
suspend fun sendSingleSms() { // 使用凭据创建客户端 val client = SmsClient.create( login = "your_login", password = "your_password", provider = SmsProvider.SMSC )
// 构建请求 val request = SmsRequest( phone = "+71234567890", message = "您的验证码:1234", sender = "MyApp" // 字母名称,如果支持 )
// 发送并获取响应 val response: SmsResponse = client.send(request)
when (response.status) { SmsStatus.SUCCESS -> println("短信已发送,ID:${response.id}") SmsStatus.ERROR -> println("错误:${response.errorMessage}") else -> println("未知状态") }}批量发送
要向多个号码发送同一条消息,请使用 sendBatch 方法:
val phones = listOf("+71234567890", "+70987654321", "+71112223344")val batchRequest = BatchSmsRequest( phones = phones, message = "尊敬的客户,促销活动已延长至周五!", sender = "ShopBot")
val batchResponse = client.sendBatch(batchRequest)batchResponse.results.forEach { result -> println("电话:${result.phone},状态:${result.status}")}使用协程进行异步处理
该库完全