← 全部集成

无需插件的 WooCommerce 短信通知

顾客看短信比看邮件快。一段简短的代码挂接到 WooCommerce 订单状态,在订单付款(Processing)和完成时,用你店铺的号码给顾客发短信。无需短信插件,也无需额外订阅。

适合谁

  • 每天发送最多几百条订单短信的 WooCommerce 店铺。
  • 希望顾客看到店铺自己的号码并能直接回复的店主。
  • 宁愿写 60 行代码也不想再装一个插件的开发者。

开始之前

  • 一部 Android 手机(8.0 或更高版本),装有可发送短信的 SIM 卡。
  • 从 Google Play 安装 NS SMS 应用,设为默认短信应用,并在 API 标签页开启“接受 API 请求”。
  • API 标签页中的手机 ID(device_id)和 API 密钥(nss_...)。下文以 YOUR_DEVICE_ID 和 nss_YOUR_API_KEY 表示。
  • 能通过 FTP 或主机文件管理器访问 wp-config.php 和子主题(或你自己的小插件)。请先备份。
  • 结账页面有电话字段。代码使用 billing phone 和 billing country。

无需账号、邮箱或密码。安装应用,开启 API,复制手机 ID 和 API 密钥即可。

分步设置

  1. 第 1 步.把密钥加入 wp-config.php

    在 "That's all, stop editing!" 这一行上方添加两个常量。放在 wp-config.php 中的密钥不会进入数据库,也不会出现在主题文件里。

    wp-config.php
    define('NS_SMS_API_KEY', 'nss_YOUR_API_KEY');
    define('NS_SMS_DEVICE_ID', 'YOUR_DEVICE_ID');
    // Only for the optional status webhook: the signing secret shown in the app.
    define('NS_SMS_WEBHOOK_SECRET', 'YOUR_SIGNING_SECRET');
  2. 第 2 步.把代码加入 functions.php

    把代码粘贴到子主题的 functions.php 中(父主题更新会把它删掉)。woocommerce_order_status_processing 和 woocommerce_order_status_completed 钩子会在订单进入相应状态时运行。代码把 billing phone 转成 E.164 格式,发送短信,并在订单中添加一条记录结果的备注。

    functions.php (child theme)
    <?php
    // NS SMS: text the customer when an order is paid (processing) and when it is completed.
    add_action('woocommerce_order_status_processing', 'ns_sms_order_status', 10, 2);
    add_action('woocommerce_order_status_completed', 'ns_sms_order_status', 10, 2);
    
    function ns_sms_order_status($order_id, $order = null)
    {
        $order = $order instanceof WC_Order ? $order : wc_get_order($order_id);
        if (!$order || !defined('NS_SMS_API_KEY')) {
            return;
        }
    
        $templates = [
            'processing' => 'Thanks for your order #%s at %s. We are preparing it now.',
            'completed'  => 'Good news: your order #%s from %s is on its way.',
        ];
        $status = $order->get_status();
        $to = ns_sms_e164($order->get_billing_phone(), $order->get_billing_country());
        if (!isset($templates[$status]) || $to === '') {
            return;
        }
    
        $response = wp_remote_post('https://sms-api.n-soft.pl/v1/sms/send', [
            'timeout' => 10,
            'headers' => [
                'Authorization'   => 'Bearer ' . NS_SMS_API_KEY,
                'Content-Type'    => 'application/json',
                // The same order and status never sends twice.
                'Idempotency-Key' => 'wc-' . $order->get_id() . '-' . $status,
            ],
            'body' => wp_json_encode([
                'device_id' => NS_SMS_DEVICE_ID,
                'to'        => $to,
                'text'      => sprintf($templates[$status], $order->get_order_number(), get_bloginfo('name')),
            ]),
        ]);
    
        $code = wp_remote_retrieve_response_code($response);
        $order->add_order_note($code === 202
            ? 'SMS sent to ' . $to
            : 'SMS not sent: ' . (is_wp_error($response) ? $response->get_error_message() : wp_remote_retrieve_body($response)));
    }
    
    // "0412 345 678" + "AU" -> "+61412345678". Numbers with + or 00 are kept as they are.
    function ns_sms_e164($phone, $country)
    {
        $phone = preg_replace('/[^\d+]/', '', (string) $phone);
        if ($phone === '') {
            return '';
        }
        if (strpos($phone, '+') === 0) {
            return $phone;
        }
        if (strpos($phone, '00') === 0) {
            return '+' . substr($phone, 2);
        }
        $prefix = WC()->countries->get_country_calling_code($country);
        $prefix = is_array($prefix) ? reset($prefix) : $prefix;
    
        return $prefix ? $prefix . ltrim($phone, '0') : '';
    }
  3. 第 3 步.用自己的订单测试

    用自己的手机号下一个测试订单,然后在 WooCommerce > Orders 中把状态改为 Processing 和 Completed。订单备注会显示 "SMS sent to ..." 或未发送的原因。

  4. 第 4 步.调整文案和状态

    修改 $templates 中的文案。如需其他状态,再添加一行 add_action(例如 woocommerce_order_status_on-hold)和一个同名键(on-hold)的模板。中文短信始终使用 Unicode 编码,一条最多 70 个字符;只含无重音拉丁字母的文本一条最多 160 个字符。

查看状态并接收 Webhook

发送请求会立即返回 202 和消息 ID。之后状态依次变为 received(手机已收到)、sent 和 delivered,或带错误码的 failed。你可以用 GET /v1/sms/{id} 查询,也可以让服务器把每次变化 POST 到你在应用(API 标签页)中设置的 Webhook 地址。所有套餐都支持 Webhook,还会推送 usage.warning、usage.limit_reached、device.offline 和 device.online 事件。

订单备注会告诉你 API 是否接受了短信。如需送达状态,请在同一个 functions.php 中添加一个小型 REST 端点,在应用中把 https://YOUR-SHOP/wp-json/ns-sms/v1/status 设为 Webhook 地址,并把 NS_SMS_WEBHOOK_SECRET(应用中显示的签名密钥)加入 wp-config.php。端点会先校验 X-NS-Signature 请求头,再信任该事件:

functions.php (child theme)
// Webhook address for the app: https://YOUR-SHOP/wp-json/ns-sms/v1/status
add_action('rest_api_init', function () {
    register_rest_route('ns-sms/v1', '/status', [
        'methods'             => 'POST',
        'callback'            => 'ns_sms_webhook',
        'permission_callback' => '__return_true', // the signature is checked below
    ]);
});

function ns_sms_webhook(WP_REST_Request $request)
{
    $body = $request->get_body();
    // X-NS-Signature: t=<unix time>,v1=<hex HMAC-SHA256 of "<t>.<body>">
    parse_str(str_replace(',', '&', (string) $request->get_header('x-ns-signature')), $sig);
    $t = (string) ($sig['t'] ?? '');
    $expected = hash_hmac('sha256', $t . '.' . $body, NS_SMS_WEBHOOK_SECRET);
    if (!hash_equals($expected, (string) ($sig['v1'] ?? '')) || abs(time() - (int) $t) > 300) {
        return new WP_REST_Response(null, 401);
    }

    $event = json_decode($body, true);
    if (($event['event'] ?? '') === 'sms.status' && ($event['sms']['status'] ?? '') === 'failed') {
        error_log('NS SMS failed: ' . $event['sms']['id'] . ' ' . $event['sms']['error_code']);
    }

    return new WP_REST_Response(null, 204);
}

常见问题

  • 完全没有订单备注:钩子没有运行。检查代码是否位于当前启用的主题中,以及常量是否已定义。
  • "SMS not sent" 并带 validation_failed:billing phone 无法转换为 E.164。顾客输入带 + 和国家代码的号码总能成功;对于本地号码,代码会去掉一个开头的 0,这适用于大多数国家,但并非全部(例如意大利会保留它)。
  • 支付网关会自动把已付款订单改为 Processing,因此这条短信无需任何人点击就会发出。Idempotency-Key 确保同一订单的同一状态绝不会重复发送短信。
  • 保存订单时最多会等待 API 10 秒。通常 API 的响应远不到一秒。
  • 401 unauthorized:Authorization 请求头必须是 "Bearer " 加上密钥,且 device_id 必须属于该密钥。
  • 403 api_disabled:打开应用,在 API 标签页开启“接受 API 请求”。
  • 422 validation_failed:号码必须是国际 E.164 格式,带 + 和国家代码(例如 +14155550123),文本最多 1,600 个字符。
  • 429:每分钟超过 30 个请求,或超出套餐的每日或每月上限(Free 每天 50 条,Pro 500 条,Business 1,000 条)。响应会说明是哪一项。

短信API参考 → 短信错误码 → 套餐与每日额度 →

WooCommerce 的使用场景

其他集成