开发者文档中心

为开发者提供短信、人机验证、SSL等产品的 API 接入指南与多种开发语言 SDK

短信服务 SDK

Ruby SDK 接入指南

Luosimao 官方提供的 Ruby 语言 SDK,适用于 Ruby / Rails 应用,封装了单条发送、批量发送和账户余额查询等功能。

环境要求:Ruby >= 2.7,推荐使用 Bundler 管理依赖。

1. 安装

方式一:直接安装

使用 gem 命令直接安装:

Terminal
gem install luosimao-sms

方式二:Bundler 安装(推荐)

Gemfile 中添加:

Gemfile
gem 'luosimao-sms'

然后执行:

Terminal
bundle install

2. 快速使用

2.1 初始化客户端

init.rb
require 'luosimao-sms'

client = Luosimao::SMS::Client.new(api_key: 'your_api_key')

支持以下配置参数:

  • api_key - 必填,API Key。未带 key- 前缀会自动补全。
  • timeout - 读取超时时间,默认为 30 秒。
  • open_timeout - 连接超时时间,默认为 10 秒。
  • base_url - API 基础地址,默认为 https://sms-api.luosimao.com(可用于测试环境)。

2.2 发送单条短信

send.rb
response = client.send(mobile: '13800138000', message: '验证码:123456【你的公司】')

if response.success?
  puts "发送成功!"
else
  puts "发送失败:#{response.error}"
end

2.3 批量发送短信

批量发送支持向多个手机号发送相同内容,传入 Time 对象还可以实现定时发送。

batch.rb
response = client.send_batch(
  mobiles: ['13800138000', '13800138001'],
  message: '活动通知:全场半价!【你的公司】'
)

if response.success?
  puts "批量发送成功,批次号:#{response.batch_id}"
else
  puts "发送失败:#{response.error}"
end

2.4 查询账户余额

status.rb
status = client.status
puts "当前账户余额:#{status.deposit} 条"

3. 异常处理

SDK 定义了三类异常,通过 rescue 捕获即可获取详细错误信息:

异常类 说明 帮助方法
Luosimao::SMS::APIError API 返回了错误码 auth_failed?, insufficient_balance?, sensitive_words?, ip_not_allowed?
Luosimao::SMS::NetworkError 网络异常(超时、连接拒绝、非法 JSON) -
Luosimao::SMS::ArgumentError 参数错误 -
error_handling.rb
begin
  client.send(mobile: '13800138000', message: '验证码123456【你的公司】')
rescue Luosimao::SMS::APIError => e
  puts "接口错误 [#{e.code}]:#{e.message}"
  puts "余额不足!" if e.insufficient_balance?
rescue Luosimao::SMS::NetworkError => e
  puts "网络异常:#{e.message}"
rescue Luosimao::SMS::ArgumentError => e
  puts "参数错误:#{e.message}"
end

4. 接口说明

方法 说明
client.send(mobile:, message:) 发送单条短信。返回 Luosimao::SMS::Response
client.send_batch(mobiles:, message:, send_at: nil) 批量发送。传入 Time 对象可实现定时发送。
client.status 查询账户余额。返回 Luosimao::SMS::StatusResponse