Пример работы с SMS шлюзом на языке TypeScript

Отправка смс
Получения статуса отправленной смс
Получение цены отправки
Получение баланса


Отправка смс:

import * as http from "http";
import * as querystring from "querystring";
import * as libxmljs from "libxmljs";

interface IPhone {
    id: string;
    val: string;
    vars: string;
}

interface IMessageId {
    val: string;
}

interface IEnumMessage {
    [index: string]: IMessage;
}

interface IMessage {
    status: string;
    code: string;
    message: string;
}

class EpochtaApiv2 {

    gatewayhost: string;
    gatewaypath: string;

    login: string;
    password: string;
    debug: boolean;

    /**
     * 
     * @param {string} login -
     * @param {string} password 
     * @param {boolean} debug 
     */
    constructor(login: string, password: string, debug: boolean = true) {

        this.gatewayhost = 'api.atompark.com';
        this.gatewaypath = '/members/sms/xml.php';

        this.debug = debug;
        this.login = login;
        this.password = password;
    }
    /**
     * Отправка смс
     * @param {string} sender 
     * @param {string} message 
     * @param {Array<IPhone>} numbers 
     * @param {string} sentdate 
     * @param {Function} callback - 
     * @param {Function} error_callback -
     */
    sendSms(sender: string, message: string, numbers: Array<IPhone>, sentdate: string, callback: Function, error_callback: Function) : boolean { 
        let xml = `<?xml version="1.0" encoding="UTF-8"?>
        <SMS>
            <operations>
                <operation></operation>
            </operations>
            <authentification>
                <username></username>
                <password></password>
            </authentification>
            <message>
                <sender></sender>
                <text></text>
            </message>
            <numbers>
            </numbers>
        </SMS>`;

        let xmlDoc = libxmljs.parseXmlString( xml );
        xmlDoc.get( "//operation" ).text("SEND");
        xmlDoc.get( "//username" ).text(this.login);
        xmlDoc.get( "//password" ).text(this.password);
        xmlDoc.get( "//sender" ).text(sender);
        xmlDoc.get( "//text" ).text(message);

        let xml_numbers = xmlDoc.get( "//numbers" ),
            node: any;

        if (typeof sentdate !== 'undefined') {
            node = libxmljs
                .Element(xmlDoc, 'sentdate')
                .text(sentdate);
            xmlDoc.root().addChild(node);
        }   

        for (var i=0; i < numbers.length; i++) {
            node = libxmljs
                .Element(xmlDoc, 'number')
                .text(numbers[i].val);

            if (typeof numbers[i].id !== 'undefined') {
                node.attr({messageID: numbers[i].id})
            }
            if (typeof numbers[i].vars !== 'undefined') {
                node.attr({variables: numbers[i].vars})
            }
            xml_numbers.addChild(node);
        }
        return this.request(xmlDoc.toString(), callback, error_callback);

    }

    /**
     * Расчет стоимости отправки смс
     * @param {String} sender
     * @param {String} message
     * @param {Array} numbers 
     * ([
     *      {val: "380933630001", id:"msg1", vars:"var1;var2;var3;"}, 
     *      {val: "380933630002", id:"msg2"}
     *  ])
     * @param {String} sentdat - (2012-05-01 00:20:00) 
     * @param {Function} callback - 
     * @param {Function} error_callback -
     * @returns {Boolean}
     */
    getPrice(sender: string, message: string, numbers: Array<IPhone>, sentdate: string, callback: Function, error_callback: Function) : boolean { 
        let xml = `<?xml version="1.0" encoding="UTF-8"?>
        <SMS>
            <operations>
                <operation></operation>
            </operations>
            <authentification>
                <username></username>
                <password></password>
            </authentification>
            <message>
                <sender></sender>
                <text></text>
            </message>
            <numbers>
            </numbers>
        </SMS>`;

        let xmlDoc = libxmljs.parseXmlString( xml );

        xmlDoc.get( "//operation" ).text("GETPRICE");
        xmlDoc.get( "//username" ).text(this.login);
        xmlDoc.get( "//password" ).text(this.password);
        xmlDoc.get( "//sender" ).text(sender);
        xmlDoc.get( "//text" ).text(message);

        let xml_numbers = xmlDoc.get( "//numbers" ),
            node: any;

        if (typeof sentdate !== 'undefined') {
            node = libxmljs
                .Element(xmlDoc, 'sentdate')
                .text(sentdate);
            xmlDoc.root().addChild(node);
        }   

        for (var i=0; i < numbers.length; i++) {
            node = libxmljs
                .Element(xmlDoc, 'number')
                .text(numbers[i].val);

            if (typeof numbers[i].id !== 'undefined') {
                node.attr({messageID: numbers[i].id})
            }
            if (typeof numbers[i].vars !== 'undefined') {
                node.attr({variables: numbers[i].vars})
            }
            xml_numbers.addChild(node);
        }
        return this.request(xmlDoc.toString(), callback, error_callback);
    }
    
    /** 
     * Получения статуса отправленной смс
     * @param {Array} id_list - (['msg1', 'msg2'])
     * @param {Function} callback - 
     * @param {Function} error_callback -
     * @returns {Boolean}
     */
    getStatus(id_list: Array<IMessageId>, callback: Function, error_callback: Function) {
        let xml = `<?xml version="1.0" encoding="UTF-8"?>
        <SMS>
            <operations>
                <operation>GETSTATUS</operation>
            </operations>
            <authentification>
                <username></username>
                <password></password>
            </authentification>
            <statistics>
            </statistics>
        </SMS>`;
        let xmlDoc = libxmljs.parseXmlString( xml );

        xmlDoc.get( "//username" ).text(this.login);
        xmlDoc.get( "//password" ).text(this.password);

        var statistics = xmlDoc.get( "//statistics" );
        let node: any;

        for (var i=0; i < id_list.length; i++) {
            node = libxmljs
                .Element(xmlDoc, 'messageid')
                .text(id_list[i].val);
            statistics.addChild(node);
        }
        return this.request(xmlDoc.toString(), callback, error_callback);
    }
    
    /**
     * Получение баланса
     * @param {Function} callback - 
     * @param {Function} error_callback - 
     * @returns {Boolean}
     */
    getBalance(callback: Function, error_callback: Function): boolean {
        let xml = `<?xml version="1.0" encoding="UTF-8"?>
        <SMS>
            <operations>
                <operation>BALANCE</operation>
            </operations>
            <authentification>
                <username></username>
                <password></password>
            </authentification>
        </SMS>`;
        let xmlDoc = libxmljs.parseXmlString( xml );
        xmlDoc.get( "//username" ).text(this.login);
        xmlDoc.get( "//password" ).text(this.password);
        return this.request(xmlDoc.toString(), callback, error_callback);
    }
    
    /**
     * Получение стоимости одного кредита
     * @param {Function} callback - 
     * @param {Function} error_callback - 
     * @returns {Boolean}
     */
    getCreditPrice (callback: Function, error_callback: Function): boolean {
        let xml = `<?xml version="1.0" encoding="UTF-8"?>
        <SMS>
            <operations>
                <operation>CREDITPRICE</operation>
            </operations>
            <authentification>
                <username></username>
                <password></password>
            </authentification>
        </SMS>`;
        let xmlDoc = libxmljs.parseXmlString( xml );

        xmlDoc.get( "//username" ).text(this.login);
        xmlDoc.get( "//password" ).text(this.password);
        return this.request(xmlDoc.toString(), callback, error_callback);
    }

    /**
     * 
     * @param {XMLDocument} xml 
     * @param {string} type 
     * @param {Function} callback 
     * @param {Function} error_callback 
     */
    request(xml: string, callback: Function, error_callback: Function): boolean {
        if (this.debug) {
            console.log({data: xml });
            return true;
        }
        const _this = this;
        let postData = querystring.stringify({XML: xml});
        let options = <any> {
            hostname: this.gatewayhost,
            port: 443,
            path: this.gatewaypath,
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': postData.length
            }
        };
        var req = http.request(options, (res) => {
            if (res.statusCode == 200) {
                res.on('data', (d) => {
                    let xmlDoc = libxmljs.parseXmlString( d );
                    let code = parseInt(xmlDoc.get('//status'));
                    if (code >= 0) { // OK
                        callback(xmlDoc);
                    } else {
                        error_callback(xmlDoc)
                    }
                });
            } else {
                error_callback({error: "uknown", result: 'false'})
            }
        });
        req.on('error', (e) => {
            error_callback({error: "uknown", message: e+'', result: 'false'})
        });
        req.write(postData);
        req.end();
        return true;
    }
    
    /**
     * 
     * @param {string} status 
     */
    error_handler(status: string): IMessage {
        let messages: IEnumMessage;
        messages = {
            '-1': <IMessage>{ 'status': '-1', 'code' : 'AUTH_FAILED', 'message': 'Неправильний логін та/або пароль' },
            '-2': <IMessage>{ 'status': '-2', 'code' : 'XML_ERROR', 'message': 'Неправильний формат XML' },
            '-3': <IMessage>{ 'status': '-3', 'code' : 'NOT_ENOUGH_CREDITS', 'message': 'Недостатньо кредитів на акаунті користувача' },
            '-4': <IMessage>{ 'status': '-4', 'code' : 'NO_RECIPIENTS', 'message': 'Немає вірних номерів отримувачів' },
            '-7': <IMessage>{ 'status': '-7', 'code' : 'BAD_SENDER_NAME', 'message': 'Помилка в імені відправника' },
        }
        if (typeof messages[status] !== 'undefined') {
            return messages[status];
        }
        return <IMessage>{'status': status, 'message': 'Unknow error'};
    }

}

var api2 = new EpochtaApiv2('your login', 'your password', false);

// api2.getBalance((res: any) => {console.log(res.toString())}, (res: any) => {console.log(res.toString())});

// api2.sendSms("smSender", "test text", [{val: "380933630000", id: "1213123", vars: ""}], "", (res: any) => {console.log(res.toString())}, (res: any) => {console.log(res.toString())});

// api2.getPrice("smSender", "test text", [{val: "380933630000", id: "1213123", vars: ""}], "", (res: any) => {console.log(res.toString())}, (res: any) => {console.log(res.toString())});

// api2.getStatus([{val: "msg1123"}, {val: "msg2333"}], (res: any) => {console.log(res.toString())}, (res: any) => {console.log(res.toString())});

// api2.getCreditPrice((res: any) => {console.log(res.toString())}, (res: any) => {console.log(res.toString())});

По запросу предоставляется необходимое количество дополнительных смс для тестирования сервиса массовых смс-уведомлений ePochta SMS.

Есть вопрос?

  • 8 (800) 555-09-63
  • Бесплатно по России

Александр



skype: alexandr.romanow26
[email protected]

Людмила



skype: liudmilaatompark
[email protected]