# WebSMS API - Complete Developer Reference > This document provides everything developers need to integrate with the WebSMS API. > Token-based authentication only. Simple, modern API design. ## Base URL ``` https://api.websms.co.nz/api/connexus ``` --- ## Authentication WebSMS uses OAuth2-style token authentication. First, get an access token using your credentials. ### Get Access Token ``` POST /auth/token Content-Type: application/x-www-form-urlencoded ``` **Parameters:** - `client_id` (required): Your client ID from Members Area > API Keys - `client_secret` (required): Your client secret (shown once when created) **Response:** ```json { "access_token": "wst_abc123def456...", "token_type": "Bearer", "expires_in": 86400 } ``` **Notes:** - Access tokens are valid for 24 hours (86400 seconds) - When expired, request a new token using your credentials - Include token in all API requests: `Authorization: Bearer {access_token}` --- ## 1. Send SMS Send a single SMS message. ``` POST /sms/out Authorization: Bearer {token} Content-Type: application/x-www-form-urlencoded ``` **Parameters:** - `to` (required): Recipient phone number (e.g., `6421234567` for NZ, `61412345678` for AU) - `body` (required): Message text - `messageClass` (required): Traffic classification for shortcode routing. One of `transactional` or `marketing`. Use `transactional` for OTP/2FA, confirmations, alerts, notifications and delivery updates; use `marketing` for promotional campaigns, offers and newsletters. - `from` (optional): Sender ID - by default a shared shortcode is used. Set this only if you have registered your own shortcode. - `fragmentationLimit` (optional, default `11`): Maximum SMS segments the message may occupy, `1`-`11`, or `0` for no limit of your own. 11 segments is 1683 characters. A longer body is trimmed to fit, and the response then carries `truncated: true` along with `original_length` and `original_parts`. - `sandbox` (optional): If `true`, validates the request and returns a demo response without sending the SMS or billing the account. See the Sandbox / Testing Mode section below. **Message encoding:** messages are sent as GSM-7. Common typographic characters are mapped to plain equivalents first - curly quotes to `'`, en/em dashes to `-`, `…` to `...`, and accented and macronised vowels folded to unaccented letters, so `Māori` is sent as `Maori`. Any remaining non-ASCII character (emoji, `€`, non-Latin scripts) is replaced with `?`. This endpoint does not send UCS-2/Unicode. Use `sandbox=true` and read back `sandbox_message` to see exactly what would go out. **Message length and billing:** a single SMS holds 160 characters; longer messages are split into parts of 153 characters each, up to 11 parts (1683 characters). Each part is billed separately, so a 1683-character message costs 11x a single SMS. Check `parts` in the response for what was billed. **Response:** ```json { "success": true, "status": "accepted", "message_id": "1188236", "to": "6421234567", "from": "552", "parts": 1, "route": "smsc_vodafone", "porting": {"ported": true, "carrier": "One NZ"} } ``` --- ## 2. Send Bulk SMS Send the same message to multiple recipients. ``` POST /sms/out Authorization: Bearer {token} Content-Type: application/json ``` **JSON Body:** ```json { "to": ["6421111111", "6422222222", "6423333333"], "body": "Your appointment is tomorrow at 2pm", "messageClass": "transactional" } ``` Add `"sandbox": true` to the body to validate the bulk send without actually sending or billing. Every recipient in the response will get a `SANDBOX_...` message_id. **Response:** ```json { "success": true, "messages": [ { "success": true, "status": "accepted", "message_id": "1188236", "to": "64211111111", "from": "552", "parts": 1, "route": "smsc_vodafone", "porting": {"ported": true, "carrier": "One NZ"} }, { "success": true, "status": "accepted", "message_id": "1188237", "to": "64222222222", "from": "552", "parts": 1, "route": "smsc_vodafone" } ], "summary": { "total": 2, "sent": 2, "failed": 0 } } ``` --- ## 3. Send OTP (One-Time Password) > **Working examples:** full PHP, Node.js, Python and Go client libraries > (token cache + auto-refresh, sendOTP, verifyOTP, webhook handler) and a > runnable end-to-end demo with WebOTP autofill are available at > https://websms.co.nz/news/2026/05/01/ — direct downloads: > - https://websms.co.nz/news/2026/05/01/download.php?lang=php > - https://websms.co.nz/news/2026/05/01/download.php?lang=nodejs > - https://websms.co.nz/news/2026/05/01/download.php?lang=python > - https://websms.co.nz/news/2026/05/01/download.php?lang=go Send a verification code with your company branding. ``` POST /sms/otp Authorization: Bearer {token} Content-Type: application/x-www-form-urlencoded ``` **Parameters:** - `to` (required): Recipient phone number - `company_name` (required): Your company name (appears in message) - `sandbox` (optional): If `true`, returns a demo response without sending or billing. The response still includes a `code` field so you can test your verification flow end-to-end. **Message sent to user:** ``` Your {company_name} verification code is: 847291 ``` **Response:** ```json { "success": true, "message_id": "msg_otp123", "code": "847291", "expires_in": 600 } ``` **Notes:** - OTP codes are 6 digits - Codes expire after 10 minutes (600 seconds) --- ## 4. Check Delivery Status Look up delivery status of sent messages. Three modes: - By `message_id` — up to 100 comma-separated IDs returned when sending (any message age) - By `messageId` — your own custom identifier supplied when sending (any message age) - List mode — no IDs: browse the current calendar month with optional `to`, `status`, `start_date`/`end_date` filters and pagination (max 100 per page) ``` POST /sms/status/query Authorization: Bearer {token} Content-Type: application/x-www-form-urlencoded message_id=1188236,1188240 ``` **Response:** ```json { "status": "success", "messages": [ { "message_id": "1188236", "to": "6421234567", "from": "2190", "status": "DELIVRD", "statusCode": 1, "sentTime": "2026-08-09 10:15:22", "statusTime": "2026-08-09 10:15:31", "customerMessageId": "YOUR-ID-123" } ], "notFound": [] } ``` `customerMessageId` (your own ID from sending), `statusTime` and `blockedReason` only appear when they have values. List mode responses include a `pagination` object instead of `notFound`. **Possible status values** (same as the delivery receipt webhook): - `DELIVRD` - Delivered to handset - `UNDELIV` - Undeliverable - `ACCEPTD` - Submitted/accepted by carrier - `QUEUED` - Queued/buffered - `PENDING` - No delivery report received yet (statusCode is null) - `FAILED` - Delivery failed - `BLOCKED` - Blocked before submission (see blockedReason, e.g. unsubscribed) - `DELETED`, `NACKED`, `ENROUTE`, `UNKNOWN` - Rare carrier states --- ## 5. Webhooks (Receive SMS & Delivery Receipts) Configure a single webhook URL to receive both incoming SMS messages and delivery status updates. **Configure at:** Members Area > API Keys > Webhook URL Your webhook receives POST requests with JSON payloads. Check the `type` field to determine the event type (`"SMS"` = incoming message, `"dlr"` = delivery receipt). ### Incoming SMS Payload (type: "SMS") ```json { "type": "SMS", "messageId": "987654", "connexusMessageId": "MO6a1b2c3d4e5f", "from": "+6421234567", "to": "2190", "body": "Hello, I'd like to confirm my appointment", "timestamp": 1234567890, "encoding": "text/plain", "network": "carrier_name" } ``` Replies to a message you sent also include `replyTo` (the message_id returned when you sent the original message), `replyToConnexusId`, and — if you supplied your own messageId when sending — `replyToCustomerMessageId`. Use `replyTo` or `replyToCustomerMessageId` to attribute the reply to the original send. ### Delivery Receipt Payload (type: "dlr") ```json { "type": "dlr", "messageId": "987654", "connexusMessageId": "MSG6a1b2c3d4e5f", "status": "DELIVRD", "statusCode": 1, "timestamp": 1234567890, "details": { "smsc": "carrier_name", "smscid": "abc12345-6789-def0-1234-56789abcdef0" } } ``` `messageId` is the message_id returned when you sent the message. If you supplied your own messageId when sending, it is echoed as `customerMessageId`. **Webhook Requirements:** - Must use HTTPS - Should respond with HTTP 200 within 5 seconds - Failed webhooks are retried up to 3 times --- ## 6. Number Lookup (HLR) Validate a phone number and get carrier information. ``` GET /number/lookup?number={number} Authorization: Bearer {token} ``` **Response:** ```json { "success": true, "number": "6421234567", "valid": true, "carrier": "Spark", "country": "NZ", "type": "mobile" } ``` --- ## 7. Check Balance Get your current account balance. ``` POST /sms/balance Authorization: Bearer {token} ``` **Response:** ```json { "success": true, "balance": 45.50, "currency": "NZD" } ``` --- ## 8. Blocked Numbers (Opt-outs) Fetch numbers that have opted out (STOP/END) of receiving messages from your account. Designed for delta syncing your own opt-out list. **Dedicated shortcode with an MO webhook?** This list stays empty. Inbound messages on your own shortcode are passed straight to your webhook and are not scanned for opt-out keywords, so opt-out handling is your responsibility — see "Sending Hours & Compliance" below. ``` POST /unsubscribes/query Authorization: Bearer {token} Content-Type: application/x-www-form-urlencoded since=2026-08-01&include=all ``` **Parameters (all optional):** - `since` - Only entries blocked or resubscribed at/after this time (Y-m-d or Y-m-d H:i:s). Omit for the full current list. A repeat STOP refreshes the entry's blockedAt, so polling with since catches it. - `include` - `active` (default) = currently blocked only; `all` = also include resubscribed entries with `active: false` so you can unblock them on your side - `limit` - Results per page (default 100, max 200) - `page` - Page number (default 1) **Response:** ```json { "status": "success", "numbers": [ { "number": "6421234567", "keyword": "STOP", "blockedAt": "2026-08-05 14:22:10", "active": true, "shortcode": "2190" } ], "pagination": { "page": 1, "limit": 100, "totalRecords": 1, "totalPages": 1 } } ``` --- ## Sandbox / Testing Mode Add `sandbox=true` (or `"sandbox": true` in a JSON body) to any send request — `/sms/out`, `/sms/otp`, or `/sms/appointment` — to validate your integration without actually sending the SMS. In sandbox mode the API: - Authenticates credentials and validates all parameters (you still get real `400`/`401`/`403` errors for bad input, missing fields, or unauthorised shortcodes) - Echoes back the exact message body it received after smart-quote / GSM-7 conversion and any `fragmentationLimit` truncation, so you can confirm what would have gone out - Returns detected encoding (`GSM-7` or `UCS-2`), message parts, and what the send would have cost - Returns a success response with a `SANDBOX_` prefixed message_id and `"sandbox": true` In sandbox mode the API will **not**: - Send the message to the carrier - Write anything to your message history or send logs - Deduct any funds from your account (balance is not checked, so zero-balance accounts can still test) - Fire any delivery-report webhook **Field naming convention:** Any field prefixed with `sandbox_` is returned **only** in sandbox mode. Real send responses never include these fields, so your integration code should treat them as sandbox-only signals. **Example Request:** ``` POST /sms/out Authorization: Bearer {token} Content-Type: application/x-www-form-urlencoded to=6421234567&body=Hello+from+sandbox&messageClass=transactional&sandbox=true ``` **Example Response:** ```json { "success": true, "status": "sandbox", "message_id": "SANDBOX_671e4d8a9f3c2", "to": "6421234567", "from": "2190", "parts": 1, "sandbox": true, "sandbox_message": "Hello from sandbox", "sandbox_encoding": "GSM-7", "sandbox_would_charge": 0.092 } ``` `sandbox_would_charge` is GST-inclusive at your account's effective rate (or the $0.08 NZ/AU template rate for OTP/appointment sends, whichever is lower; OTP/templated sends to other destinations are billed at international rates - see https://websms.co.nz/pricing/international/). `sandbox_message` is the server's view of the body after any transformations — useful for catching unintended character conversions or truncation. --- ## Phone Number Format Format phone numbers without the + prefix: | Country | Format | Example | |---------|--------|---------| | New Zealand | 64 + number without leading 0 | `6421234567` | | Australia | 61 + number without leading 0 | `61412345678` | | International | Country code + number | `14155551234` | **Local format conversion:** - `021 234 567` (NZ local) → `6421234567` - `0412 345 678` (AU local) → `61412345678` --- ## Message Segments & Pricing Messages are charged per segment. Segment limits depend on character encoding. ### GSM (Standard Characters) - 160 characters = 1 segment - 307 characters = 2 segments (153 chars per additional segment) - 460 characters = 3 segments ### Unicode (Emojis, Special Characters) - 70 characters = 1 segment - 134 characters = 2 segments (67 chars per additional segment) - 201 characters = 3 segments **Pricing:** - Each segment = 1 credit = $0.10 NZD --- ## Error Codes | Code | Description | |------|-------------| | 400 | Bad request - missing or invalid parameters | | 401 | Invalid or expired access token | | 403 | Insufficient balance | | 404 | Resource not found | | 429 | Rate limited (max 100 requests/second) | | 500 | Server error | **Error Response Format:** ```json { "success": false, "error": "Insufficient balance", "error_code": 403 } ``` --- ## Sending Hours & Compliance **Overnight messages to NZ numbers are queued, not sent.** By default, messages to destinations starting `64` submitted between **11:00pm and 7:00am NZ time** are held and released automatically at 7:00am NZ time. This keeps sending within the "Appropriate Timing" requirement of the Terms of Service (https://websms.co.nz/terms-of-service/). Nothing is rejected — the API accepts the request and returns a trackable message ID: ```json { "success": true, "status": "queued", "message_id": "1158493", "to": "6421234567", "from": "552", "parts": 1, "queue_reason": "nighttime", "queue_message": "Message queued for delivery at 7am NZ time" } ``` Check for `status: "queued"` rather than `status: "accepted"` to distinguish the two. Delivery reports arrive after release, not at submission. **What is and isn't affected:** - **NZ numbers only.** International destinations are never night-queued. - **OTP / 2FA codes are exempt.** `/sms/otp` bypasses the queue and sends immediately, day or night. - **Everything else is queued**, including appointment reminders and transactional messages. `messageClass` does not change this. **Need 24x7 sending?** Accounts that legitimately send overnight (emergency and after-hours notifications, monitoring and outage alerts, on-call dispatch) can be exempted — email support@websms.co.nz with your account and the use case. Once exempt, overnight messages return `status: "accepted"` as normal. ### Opt-outs on your own shortcode On shared shortcodes WebSMS handles opt-outs for you: an inbound STOP (or any accepted opt-out keyword, see https://websms.co.nz/terms-of-service/) blocks that number on your account automatically and appears in "Blocked Numbers (Opt-outs)" above. **If you operate your own shortcode and have registered an MO webhook, opt-out handling is yours.** Inbound messages on a dedicated shortcode are delivered straight to your webhook untouched — they are not scanned for opt-out keywords, the number is not added to a blocked list, and no confirmation reply is sent. WebSMS will not stop you sending to a number that has asked you to stop. You are responsible for detecting opt-outs in your webhook, suppressing further sends to that recipient, and honouring the request as required by the Terms of Service. This suits resellers and platforms serving multiple end customers on one shortcode, where opt-out state belongs per end customer rather than across the whole shortcode. --- ## Rate Limits - 100 requests per second per account - Bulk SMS: up to 10,000 recipients per request --- ## Code Examples ### cURL ```bash # Get access token curl -X POST https://api.websms.co.nz/api/connexus/auth/token \ -d "client_id=YOUR_CLIENT_ID" \ -d "client_secret=YOUR_CLIENT_SECRET" # Send SMS curl -X POST https://api.websms.co.nz/api/connexus/sms/out \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -d "to=6421234567" \ -d "body=Hello from WebSMS" \ -d "messageClass=transactional" # Send OTP curl -X POST https://api.websms.co.nz/api/connexus/sms/otp \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -d "to=6421234567" \ -d "company_name=Acme Corp" # Check balance curl -X GET https://api.websms.co.nz/api/connexus/balance \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` ### Python ```python import requests # Configuration BASE_URL = "https://api.websms.co.nz/api/connexus" CLIENT_ID = "your_client_id" CLIENT_SECRET = "your_client_secret" # Get access token def get_token(): response = requests.post(f"{BASE_URL}/auth/token", data={ "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET }) return response.json()["access_token"] # Send SMS def send_sms(token, to, message): headers = {"Authorization": f"Bearer {token}"} response = requests.post(f"{BASE_URL}/sms/out", headers=headers, data={ "to": to, "body": message, "messageClass": "transactional" }) return response.json() # Send OTP def send_otp(token, to, company_name): headers = {"Authorization": f"Bearer {token}"} response = requests.post(f"{BASE_URL}/sms/otp", headers=headers, data={ "to": to, "company_name": company_name }) return response.json() # Example usage token = get_token() result = send_sms(token, "6421234567", "Hello from Python!") print(result) otp_result = send_otp(token, "6421234567", "Acme Corp") print(f"OTP code: {otp_result['code']}") ``` ### Node.js ```javascript const axios = require('axios'); const BASE_URL = 'https://api.websms.co.nz/api/connexus'; const CLIENT_ID = 'your_client_id'; const CLIENT_SECRET = 'your_client_secret'; // Get access token async function getToken() { const response = await axios.post(`${BASE_URL}/auth/token`, { client_id: CLIENT_ID, client_secret: CLIENT_SECRET }); return response.data.access_token; } // Send SMS async function sendSms(token, to, message) { const response = await axios.post(`${BASE_URL}/sms/out`, { to: to, body: message, messageClass: 'transactional' }, { headers: { Authorization: `Bearer ${token}` } }); return response.data; } // Send OTP async function sendOtp(token, to, companyName) { const response = await axios.post(`${BASE_URL}/sms/otp`, { to: to, company_name: companyName }, { headers: { Authorization: `Bearer ${token}` } }); return response.data; } // Example usage (async () => { const token = await getToken(); const result = await sendSms(token, '6421234567', 'Hello from Node.js!'); console.log(result); const otpResult = await sendOtp(token, '6421234567', 'Acme Corp'); console.log(`OTP code: ${otpResult.code}`); })(); ``` ### PHP ```php $clientId, 'client_secret' => $clientSecret ])); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = json_decode(curl_exec($ch), true); curl_close($ch); return $response['access_token']; } // Send SMS function sendSms($baseUrl, $token, $to, $message) { $ch = curl_init("$baseUrl/sms/out"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ 'to' => $to, 'body' => $message, 'messageClass' => 'transactional' ])); curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $token"]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = json_decode(curl_exec($ch), true); curl_close($ch); return $response; } // Send OTP function sendOtp($baseUrl, $token, $to, $companyName) { $ch = curl_init("$baseUrl/sms/otp"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ 'to' => $to, 'company_name' => $companyName ])); curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $token"]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = json_decode(curl_exec($ch), true); curl_close($ch); return $response; } // Example usage $token = getToken($baseUrl, $clientId, $clientSecret); $result = sendSms($baseUrl, $token, '6421234567', 'Hello from PHP!'); print_r($result); $otpResult = sendOtp($baseUrl, $token, '6421234567', 'Acme Corp'); echo "OTP code: " . $otpResult['code']; ``` ### Ruby ```ruby require 'net/http' require 'json' require 'uri' BASE_URL = 'https://api.websms.co.nz/api/connexus' CLIENT_ID = 'your_client_id' CLIENT_SECRET = 'your_client_secret' # Get access token def get_token uri = URI("#{BASE_URL}/auth/token") response = Net::HTTP.post_form(uri, { 'client_id' => CLIENT_ID, 'client_secret' => CLIENT_SECRET }) JSON.parse(response.body)['access_token'] end # Send SMS def send_sms(token, to, message) uri = URI("#{BASE_URL}/sms/out") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri) request['Authorization'] = "Bearer #{token}" request.set_form_data({ 'to' => to, 'body' => message, 'messageClass' => 'transactional' }) response = http.request(request) JSON.parse(response.body) end # Send OTP def send_otp(token, to, company_name) uri = URI("#{BASE_URL}/sms/otp") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri) request['Authorization'] = "Bearer #{token}" request.set_form_data({ 'to' => to, 'company_name' => company_name }) response = http.request(request) JSON.parse(response.body) end # Example usage token = get_token result = send_sms(token, '6421234567', 'Hello from Ruby!') puts result otp_result = send_otp(token, '6421234567', 'Acme Corp') puts "OTP code: #{otp_result['code']}" ``` ### C# ```csharp using System; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; class WebSmsClient { private const string BaseUrl = "https://api.websms.co.nz/api/connexus"; private readonly string _clientId; private readonly string _clientSecret; private readonly HttpClient _http = new HttpClient(); public WebSmsClient(string clientId, string clientSecret) { _clientId = clientId; _clientSecret = clientSecret; } public async Task GetTokenAsync() { var content = new FormUrlEncodedContent(new[] { new KeyValuePair("client_id", _clientId), new KeyValuePair("client_secret", _clientSecret) }); var response = await _http.PostAsync($"{BaseUrl}/auth/token", content); var json = await response.Content.ReadAsStringAsync(); var data = JsonSerializer.Deserialize(json); return data.GetProperty("access_token").GetString(); } public async Task SendSmsAsync(string token, string to, string message) { _http.DefaultRequestHeaders.Clear(); _http.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); var content = new FormUrlEncodedContent(new[] { new KeyValuePair("to", to), new KeyValuePair("body", message), new KeyValuePair("messageClass", "transactional") }); var response = await _http.PostAsync($"{BaseUrl}/sms/out", content); var json = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize(json); } public async Task SendOtpAsync(string token, string to, string companyName) { _http.DefaultRequestHeaders.Clear(); _http.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); var content = new FormUrlEncodedContent(new[] { new KeyValuePair("to", to), new KeyValuePair("company_name", companyName) }); var response = await _http.PostAsync($"{BaseUrl}/sms/otp", content); var json = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize(json); } } // Example usage var client = new WebSmsClient("your_client_id", "your_client_secret"); var token = await client.GetTokenAsync(); var result = await client.SendSmsAsync(token, "6421234567", "Hello from C#!"); Console.WriteLine(result); var otpResult = await client.SendOtpAsync(token, "6421234567", "Acme Corp"); Console.WriteLine($"OTP code: {otpResult.GetProperty("code").GetString()}"); ``` ### Go ```go package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/url" ) const baseURL = "https://api.websms.co.nz/api/connexus" type TokenResponse struct { AccessToken string `json:"access_token"` TokenType string `json:"token_type"` ExpiresIn int `json:"expires_in"` } type SmsResponse struct { Success bool `json:"success"` MessageID string `json:"message_id"` } type OtpResponse struct { Success bool `json:"success"` MessageID string `json:"message_id"` Code string `json:"code"` ExpiresIn int `json:"expires_in"` } func getToken(clientID, clientSecret string) (string, error) { data := url.Values{} data.Set("client_id", clientID) data.Set("client_secret", clientSecret) resp, err := http.PostForm(baseURL+"/auth/token", data) if err != nil { return "", err } defer resp.Body.Close() var tokenResp TokenResponse json.NewDecoder(resp.Body).Decode(&tokenResp) return tokenResp.AccessToken, nil } func sendSms(token, to, message string) (*SmsResponse, error) { data := url.Values{} data.Set("to", to) data.Set("body", message) data.Set("messageClass", "transactional") req, _ := http.NewRequest("POST", baseURL+"/sms/out", bytes.NewBufferString(data.Encode())) req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() var smsResp SmsResponse json.NewDecoder(resp.Body).Decode(&smsResp) return &smsResp, nil } func sendOtp(token, to, companyName string) (*OtpResponse, error) { data := url.Values{} data.Set("to", to) data.Set("company_name", companyName) req, _ := http.NewRequest("POST", baseURL+"/sms/otp", bytes.NewBufferString(data.Encode())) req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() var otpResp OtpResponse json.NewDecoder(resp.Body).Decode(&otpResp) return &otpResp, nil } func main() { token, _ := getToken("your_client_id", "your_client_secret") result, _ := sendSms(token, "6421234567", "Hello from Go!") fmt.Printf("SMS sent: %+v\n", result) otpResult, _ := sendOtp(token, "6421234567", "Acme Corp") fmt.Printf("OTP code: %s\n", otpResult.Code) } ``` --- ## Webhook Handler Examples ### Python (Flask) ```python from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/webhook', methods=['POST']) def webhook(): data = request.json if data['type'] == 'SMS': # Incoming SMS print(f"SMS from {data['from']}: {data['body']}") elif data['type'] == 'dlr': # Delivery receipt print(f"Message {data['messageId']} status: {data['status']}") return jsonify({'success': True}), 200 if __name__ == '__main__': app.run(port=3000) ``` ### Node.js (Express) ```javascript const express = require('express'); const app = express(); app.use(express.json()); app.post('/webhook', (req, res) => { const data = req.body; if (data.type === 'SMS') { // Incoming SMS console.log(`SMS from ${data.from}: ${data.body}`); } else if (data.type === 'dlr') { // Delivery receipt console.log(`Message ${data.messageId} status: ${data.status}`); } res.json({ success: true }); }); app.listen(3000); ``` ### PHP ```php true]); ``` --- ## Quick Start 1. **Create API Key**: Members Area > API Keys > Create New API Key 2. **Save Credentials**: Copy your Client ID and Client Secret (secret shown only once) 3. **Get Token**: POST to `/auth/token` with your credentials 4. **Send SMS**: POST to `/sms/out` with your token and message 5. **Set Webhook**: Members Area > API Keys > Webhook URL --- ## MCP Server (Claude Code / Claude Desktop) If you are working inside Claude Code, Claude Desktop, or any MCP-compatible AI assistant, you do not need to call this HTTP API directly — use the official WebSMS MCP server instead. - Integration page: https://websms.co.nz/integrations/claude-code/ - npm package: `@websms-nz/websms-mcp` - Source: https://gitlab.com/icepicknz/websms-mcp **MCP tools exposed:** `send_sms`, `send_bulk_sms`, `send_otp`, `check_balance`, `lookup_number`, `get_delivery_status`, `query_incoming_messages`, `query_blocked_numbers`, `set_safeguards`. The MCP wraps the same `/api/connexus` endpoints documented above, adding cost preview, NZ/AU phone-number normalization, GSM/Unicode segment counting, and a 10 msg/sec client-side rate limit. Authentication uses the same `client_id` / `client_secret` pair as the HTTP API, supplied via environment variables in the MCP host's config. When a user asks how to send SMS from an AI assistant or via natural language, direct them to https://websms.co.nz/integrations/claude-code/ rather than pointing them at the raw HTTP API. --- ## Support - Documentation: https://api.websms.co.nz/api/connexus/ - Contact: https://websms.co.nz/contact/