How to Send SMS through the SMPP API using Javascript/Node.js

The Short Message Peer-to-Peer (SMPP) API is a robust and widely-used protocol for sending and receiving SMS messages between Short Message Service Centers (SMSCs) and External Short Messaging Entities (ESMEs). For developers leveraging JavaScript and Node.js, integrating the SMPP API with tools like Ozeki SMS Gateway enables seamless SMS communication. This guide provides a step-by-step tutorial on setting up an SMPP client, managing connections, sending SMS, and handling delivery reports using JavaScript and Node.js, complete with practical code examples.

Why Use the SMPP API with JavaScript?

The SMPP protocol is a powerful choice for SMS communication due to its reliability, scalability, and support for high-volume messaging. By using JavaScript and Node.js, developers can create efficient, event-driven applications that integrate seamlessly with the SMPP API. The smpp package, available via npm, simplifies low-level protocol interactions, allowing developers to focus on building robust SMS applications.

Setting Up an SMPP API Client in JavaScript (Node.js) for SMS Sending

Before you can send SMS messages using the SMPP API, you need to configure an SMPP user account and connect to an SMPP server, such as the one provided by Ozeki SMS Gateway. This section explains how to set up the environment and establish a connection using JavaScript.

Step 1: Install the SMPP Package

To interact with the SMPP protocol, install the smpp package from npm, which provides a simple interface for SMPP API operations in JavaScript.

npm install smpp

Step 2: Establish a Connection

Below is an example of how to connect to an SMPP server using Node.js and the smpp package. Replace your.ozeki.server, your_username, and your_password with your actual server details and credentials.

const smpp = require('smpp');
const session = smpp.connect({
    host: 'your.ozeki.server',
    port: 2775
});

session.on('connect', () => {
    console.log('Connected to SMPP server');
    
    session.bind_transceiver({
        system_id: 'your_username',
        password: 'your_password'
    }, (pdu) => {
        if (pdu.command_status === 0) {
            console.log('Successfully bound to SMPP server');
        } else {
            console.error('Bind failed:', pdu.command_status);
        }
    });
});

session.on('error', (error) => {
    console.error('SMPP connection error:', error);
});

Ensure your SMPP server is accessible and your credentials are correct to avoid connection issues. The bind_transceiver method establishes a two-way connection for both sending and receiving SMS.

Managing SMPP API Connections in Node.js for SMS Messaging

Maintaining an active SMPP session requires sending periodic keep-alive messages using the enquire_link PDU. This ensures the connection remains open and responsive, especially for long-running applications.

const keepAliveInterval = setInterval(() => {
    session.enquire_link({}, (pdu) => {
        if (pdu.command_status !== 0) {
            console.error('Keep-alive failed:', pdu.command_status);
        }
    });
}, 30000);

session.on('close', () => {
    clearInterval(keepAliveInterval);
    console.log('SMPP connection closed');
});

This code sends an enquire_link every 30 seconds to keep the session active and clears the interval when the connection closes.

Sending SMS with JavaScript via the SMPP API (Node.js Example)

Once connected, you can send SMS messages using the submit_sm PDU. The following JavaScript function demonstrates how to send an SMS with the SMPP API.

function sendSMS(from, to, message) {
    session.submit_sm({
        source_addr: from,
        destination_addr: to,
        short_message: message,
        data_coding: 0, // GSM 7-bit encoding
        source_addr_ton: 1, // International format
        source_addr_npi: 1, // ISDN numbering plan
        dest_addr_ton: 1,  // International format
        dest_addr_npi: 1    // ISDN numbering plan
    }, (pdu) => {
        if (pdu.command_status === 0) {
            console.log(`Message sent successfully, message_id: ${pdu.message_id}`);
        } else {
            console.error('Message submission failed:', pdu.command_status);
        }
    });
}

sendSMS('12345', '+1234567890', 'Hello from Node.js SMPP client!');

The data_coding, source_addr_ton, and dest_addr_ton parameters ensure proper message encoding and phone number formatting. Adjust these based on your requirements.

Handling SMS Delivery Reports in JavaScript Using the SMPP API

The SMPP API supports delivery reports to confirm whether an SMS was delivered. The following code handles incoming deliver_sm PDUs to process delivery notifications.

session.on('pdu', (pdu) => {
    if (pdu.command === 'deliver_sm') {
        const messageId = pdu.receipted_message_id;
        const status = pdu.message_state;
        
        console.log(`Delivery report for ${messageId}: ${status}`);
        
        session.deliver_sm_resp({
            sequence_number: pdu.sequence_number
        });
    }
});

This code logs the delivery status and responds to the server to acknowledge receipt of the report.

Complete SMPP API Client Implementation in JavaScript (Node.js) for SMS Sending

For a production-ready solution, the following JavaScript class encapsulates connection management, message sending, and reconnection logic for the SMPP API.

const smpp = require('smpp');

class SMPPClient {
    constructor(config) {
        this.config = config;
        this.session = null;
        this.keepAliveInterval = null;
        this.connect();
    }

    connect() {
        this.session = smpp.connect(this.config);
        
        this.session.on('connect', () => {
            console.log('Connected to SMPP server');
            this.bind();
        });

        this.session.on('error', (error) => {
            console.error('Connection error:', error);
            this.reconnect();
        });

        this.session.on('close', () => {
            console.log('Connection closed');
            this.cleanup();
            this.reconnect();
        });
    }

    bind() {
        this.session.bind_transceiver({
            system_id: this.config.system_id,
            password: this.config.password
        }, (pdu) => {
            if (pdu.command_status === 0) {
                console.log('Successfully bound to SMPP server');
                this.startKeepAlive();
            } else {
                console.error('Bind failed:', pdu.command_status);
                this.session.close();
            }
        });
    }

    startKeepAlive() {
        this.keepAliveInterval = setInterval(() => {
            this.session.enquire_link({}, (pdu) => {
                if (pdu.command_status !== 0) {
                    console.error('Keep-alive failed:', pdu.command_status);
                }
            });
        }, 30000);
    }

    sendSMS(from, to, message) {
        return new Promise((resolve, reject) => {
            this.session.submit_sm({
                source_addr: from,
                destination_addr: to,
                short_message: message,
                data_coding: 0
            }, (pdu) => {
                if (pdu.command_status === 0) {
                    resolve(pdu.message_id);
                } else {
                    reject(new Error(`SMPP error: ${pdu.command_status}`));
                }
            });
        });
    }

    cleanup() {
        if (this.keepAliveInterval) {
            clearInterval(this.keepAliveInterval);
            this.keepAliveInterval = null;
        }
    }

    reconnect() {
        this.cleanup();
        setTimeout(() => {
            console.log('Attempting to reconnect...');
            this.connect();
        }, 5000);
    }
}

const client = new SMPPClient({
    host: 'your.ozeki.server',
    port: 2775,
    system_id: 'your_username',
    password: 'your_password'
});

client.sendSMS('12345', '+1234567890', 'Hello from complete SMPP client!')
    .then(messageId => console.log('Message ID:', messageId))
    .catch(err => console.error('Error:', err));

This implementation includes error handling, automatic reconnection, and promise-based message sending, making it suitable for production environments.

Best Practices for Using SMPP API with JavaScript

  • Error Handling: Implement robust error handling to manage network issues and server errors.
  • Async/Await: Use promises or async/await for better control flow in asynchronous operations.
  • Message Queuing: For high-volume SMS sending, implement a queue to manage message throughput.
  • Connection Monitoring: Continuously monitor the connection state and implement automatic reconnection logic.
  • Character Encoding: Handle different character encodings (e.g., GSM 7-bit, UCS-2) to support international SMS.

Conclusion

This comprehensive guide has shown how to implement a robust SMPP client using JavaScript and Node.js to interact with the SMPP API and Ozeki SMS Gateway. From setting up the connection to sending SMS and handling delivery reports, the provided examples demonstrate practical applications of the smpp package. For advanced use cases, consider exploring features like message concatenation, advanced encoding schemes, and logging for production-grade applications.

For further details on the SMPP protocol or Ozeki SMS Gateway, visit the official documentation or contact your SMS gateway provider.

More information