← 短信API

用 Go 发送短信

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

准备工作

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

第 1 步:用 Go 发送短信

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

main.go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func main() {
	body, _ := json.Marshal(map[string]string{
		"device_id": os.Getenv("NS_SMS_DEVICE_ID"),
		"to":        "+14155550123",
		"text":      "Your code is 4821",
	})
	req, _ := http.NewRequest("POST", "https://sms-api.n-soft.pl/v1/sms/send", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("NS_SMS_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	var out map[string]any
	json.NewDecoder(res.Body).Decode(&out)
	fmt.Println(res.StatusCode, out)
}

第 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
package webhook

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
)

func ValidSignature(body []byte, header, secret string) bool {
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write(body)
	expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))
	return hmac.Equal([]byte(expected), []byte(header))
}

第 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