← 短信API

用 PHP 发送短信

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

准备工作

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

第 1 步:用 PHP 发送短信

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

send-sms.php
<?php
$ch = curl_init('https://sms-api.n-soft.pl/v1/sms/send');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('NS_SMS_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'device_id' => getenv('NS_SMS_DEVICE_ID'),
        'to' => '+14155550123',
        'text' => 'Your code is 4821',
    ]),
]);
$response = json_decode(curl_exec($ch), true);
echo $response['id'], ' ', $response['status'], PHP_EOL; // ... 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
<?php
$body = file_get_contents('php://input');
$expected = 'sha256=' . hash_hmac('sha256', $body, getenv('NS_SMS_WEBHOOK_SECRET'));
if (!hash_equals($expected, $_SERVER['HTTP_X_SIGNATURE'] ?? '')) {
    http_response_code(401);
    exit;
}
$event = json_decode($body, true);
error_log($event['sms']['id'] . ' ' . $event['sms']['status']);
http_response_code(204);

第 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