← 短信API

用 Node.js 发送短信

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

准备工作

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

第 1 步:用 Node.js 发送短信

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

send-sms.mjs
const response = await fetch("https://sms-api.n-soft.pl/v1/sms/send", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.NS_SMS_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    device_id: process.env.NS_SMS_DEVICE_ID,
    to: "+14155550123",
    text: "Your code is 4821",
  }),
});
console.log(response.status, await response.json()); // 202 { id: '...', status: 'accepted' }

第 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
import crypto from "node:crypto";
import express from "express";

const app = express();

app.post("/sms-status", express.raw({ type: "application/json" }), (req, res) => {
  const expected = "sha256=" + crypto
    .createHmac("sha256", process.env.NS_SMS_WEBHOOK_SECRET)
    .update(req.body)
    .digest("hex");
  const given = req.get("X-Signature") ?? "";
  if (given.length !== expected.length ||
      !crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected))) {
    return res.sendStatus(401);
  }
  const event = JSON.parse(req.body);
  console.log(event.sms.id, event.sms.status);
  res.sendStatus(204);
});

app.listen(3000);

第 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