Send SMS with Node.js
Node.js 18 or newer has fetch built in, so no dependencies are needed. The helper below works in ES modules and, with require, in CommonJS.
Official client
Prefer a ready-made client? The official package budgetsms-sdk (Node.js 18 or newer, no dependencies, TypeScript types, MIT) wraps every call and rejects with an error that carries the API error code:
npm install budgetsms-sdk
import { BudgetSms } from 'budgetsms-sdk';
const sms = new BudgetSms({ username: 'USERNAME', userid: 'USERID', handle: 'HANDLE' });
const result = await sms.sendSms('31612345678', 'Your verification code is 482913', 'MyCompany');
console.log(result.smsId, result.price, result.credit);
The rest of this page shows how the API works without any library.
The helper
// budgetsms.js
const BASE = 'https://api.budgetsms.net/';
const auth = {
username: process.env.BUDGETSMS_USERNAME,
userid: process.env.BUDGETSMS_USERID,
handle: process.env.BUDGETSMS_HANDLE,
};
export class BudgetSmsError extends Error {
constructor(code) { super(`BudgetSMS error ${code}`); this.code = code; } // code: see the error code list
}
/** Calls sendsms, testsms, checkcredit, np, hlr or checksms; resolves with the words after "OK". */
export async function call(endpoint, params = {}) {
const url = new URL(BASE + endpoint + '/');
for (const [key, value] of Object.entries({ ...auth, ...params })) url.searchParams.set(key, String(value));
const response = await fetch(url, { signal: AbortSignal.timeout(20000) });
if (!response.ok) throw new Error(`BudgetSMS HTTP ${response.status}`);
const [status, ...rest] = (await response.text()).trim().split(' ');
if (status !== 'OK') throw new BudgetSmsError(rest.join(' '));
return rest;
}
/** Your price per SMS part for every operator, keyed by operator id. */
export async function pricing() {
const url = new URL(BASE + 'getpricing/');
for (const [key, value] of Object.entries(auth)) url.searchParams.set(key, value);
return (await fetch(url)).json();
}
Send an SMS
import { call, BudgetSmsError } from './budgetsms.js';
try {
const [smsId] = await call('sendsms', { from: 'BudgetSMS', to: '31612345678', msg: 'Hello from BudgetSMS' });
console.log('sent, message id', smsId); // keep it for the delivery report
} catch (e) {
if (e instanceof BudgetSmsError) console.log('not sent:', e.code); else throw e;
}
Use 'testsms' while developing: same parameters and answer format, but it is a simulator: no SMS is sent and nothing is charged, the message id and price in the answer are random, and about one in five calls returns a random ERR 2xxx so your error handling gets exercised (the destination number is not checked). With price: 1, mccmnc: 1 or credit: 1 the array also contains the price and number of parts, the receiver's network and your remaining credit.
Credit, number lookup and delivery status
const [credit] = await call('checkcredit'); // '123.4550'
const [mcc, mnc, price] = await call('np', { to: '31612345678' }); // '204', '08', '0.0640'
const [status] = await call('checksms', { smsid: 64354593 }); // '1' = delivered; see the DLR status list
const prices = await pricing(); // { '6': { countryname: 'Netherlands', operatorname: 'KPN', price: '0.06400', ... }, ... }
Receive delivery reports (Push DLR) with Express
Enter the URL of this route in the control panel under Push DLR; we call it with GET on every status update.
import express from 'express';
const app = express();
app.get('/dlr', (req, res) => {
const smsId = Number(req.query.id); // message id from the sendsms response
const status = Number(req.query.status); // 1 = delivered, 2 and 3 = failed; full list: DLR status
const date = new Date(Number(req.query.date) * 1000);
// update your own records here
res.send('OK');
});
app.listen(3000);