← 短信API

用 Ruby 发送短信

本教程介绍如何使用 NS SMS API 从 Ruby 发送短信。短信从你自己的 Android 手机和 SIM 卡发出,因此没有按条费用,也无需注册发送方。大约需要五分钟。

准备工作

无需账号、邮箱或密码。手机会自动注册,并在应用中直接显示 API 密钥。

第 1 步:用 Ruby 发送短信

用 POST 提交国际格式的收件人号码(E.164,例如 +14155550123)和短信内容。API 返回 202 Accepted 和消息 ID。

send_sms.rb
require "json"
require "net/http"

uri = URI("https://sms-api.n-soft.pl/v1/sms/send")
request = Net::HTTP::Post.new(uri,
  "Content-Type" => "application/json",
  "Authorization" => "Bearer #{ENV.fetch('NS_SMS_API_KEY')}")
request.body = {
  device_id: ENV.fetch("NS_SMS_DEVICE_ID"),
  to: "+14155550123",
  text: "Your code is 4821"
}.to_json

response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request) }
puts response.code, JSON.parse(response.body)

第 2 步:查询送达状态

GET /v1/sms/{id} 返回当前状态:手机已接收、已发送、已送达,或失败并附错误代码。状态通常在几秒内更新。

GET /v1/sms/{id}
GET https://sms-api.n-soft.pl/v1/sms/01JDX4K8Q2M3N4P5R6S7T8V9W0
Authorization: Bearer $NS_SMS_API_KEY

{"id":"01JDX4K8Q2M3N4P5R6S7T8V9W0","status":"delivered","error_code":null,
 "sent_at":"2026-11-26T10:58:30+00:00","delivered_at":"2026-11-26T10:58:31+00:00", ...}

第 3 步:接收状态 Webhook(可选)

在所有套餐中,服务器都会把每次状态变化 POST 到你的 Webhook。信任请求之前,请先校验签名:

webhook
require "openssl"
require "rack/utils"

def valid_signature?(body, header, secret)
  expected = "sha256=" + OpenSSL::HMAC.hexdigest("SHA256", secret, body)
  Rack::Utils.secure_compare(expected, header.to_s)
end

第 4 步:定时发送短信

在同一请求中添加 send_at 即可在指定时间发送,添加 repeat 即可每天、每周或每月发送:

POST /v1/sms/send
{
  "device_id": "01JDX4K8Q2M3N4P5R6S7T8V9W0",
  "to": "+14155550123",
  "text": "Reminder: your appointment is tomorrow at 10:00",
  "send_at": "2026-12-01T09:00:00+01:00",
  "repeat": { "every": "weekly", "count": 4 }
}

其他语言的同一短信API