Пример работы с SMS шлюзом на языке Javascript
Отправка смс
Получения статуса отправленной смс
Получение цены отправки
Получение баланса
Отправка смс:
/**
* @param {type} login
* @param {type} password
* @returns {EpochtaApi2}
*/
function EpochtaApiv2(login, password, debug) {
debug = debug || 0;
var self = this;
this.gateway = 'http://api.myatompark.com/members/sms/xml.php';
this.debug = debug ? 1 : 0;
this.login = login;
this.password = password;
this.send_xml = '<?xml version="1.0" encoding="UTF-8"?>\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
';
/**
* Отправка смс
* @param {String} sender
* @param {String} message
* @param {Array} numbers
* ([
* {val: "380933630001", id:"msg1", vars:"var1;var2;var3;"},
* {val: "380933630002", id:"msg2"}
* ])
* @param {String} sentdate (2012-05-01 00:20:00)
* @returns {Boolean}
*/
this.send_sms = function(sender, message, numbers, sentdate, callback, error_callback) {
if (typeof sender === 'undefined'
|| typeof message === 'undefined'
|| typeof numbers === 'undefined'
|| ! numbers.length
|| ! is_function(callback)
|| ! is_function(error_callback))
return false;
self.xml = $.parseXML( self.send_xml );
self.xml = $( self.xml );
self.xml.find( "operation" ).text("SEND");
self.xml.find( "username" ).text(self.login);
self.xml.find( "password" ).text(self.password);
self.xml.find( "sender" ).text(sender);
self.xml.find( "text" ).text(message);
if (typeof sentdate !== 'undefined') {
self.xml.find( "SMS" ).append(''+sentdate+' ');
}
var xml_numbers = self.xml.find( "numbers" ),
node;
for (var i =0; i < numbers.length; i++) {
node = $(''+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.append(node);
}
return this.request('POST', 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} sentdate (2012-05-01 00:20:00)
* @returns {Boolean}
*/
this.get_price = function(sender, message, numbers, sentdate, callback, error_callback) {
if (typeof sender === 'undefined'
|| typeof message === 'undefined'
|| typeof numbers === 'undefined'
|| ! numbers.length
|| ! is_function(callback)
|| ! is_function(error_callback))
return false;
self.xml = $.parseXML( self.send_xml );
self.xml = $( self.xml );
self.xml.find( "operation" ).text("GETPRICE");
self.xml.find( "username" ).text(self.login);
self.xml.find( "password" ).text(self.password);
self.xml.find( "sender" ).text(sender);
self.xml.find( "text" ).text(message);
if (typeof sentdate !== 'undefined') {
self.xml.find( "SMS" ).append(''+sentdate+' ');
}
var xml_numbers = self.xml.find( "numbers" ),
node;
for (var i =0; i < numbers.length; i++) {
node = $(''+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.append(node);
}
return this.request('POST', callback, error_callback);
}
this.status_xml = '<?xml version="1.0" encoding="UTF-8"?>\
\
\
GETSTATUS \
\
\
\
\
\
\
\
';
/**
* Получения статуса отправленной смс
* @param {Array} id_list (['msg1', 'msg2'])
* @returns {Boolean}
*/
this.get_status = function(id_list, callback, error_callback) {
if (typeof id_list === 'undefined'
|| ! id_list.length
|| ! is_function(callback)
|| ! is_function(error_callback))
return false;
self.xml = $.parseXML( self.status_xml );
self.xml = $( self.xml );
self.xml.find( "username" ).text(self.login);
self.xml.find( "password" ).text(self.password);
var statistics = self.xml.find( "statistics" );
for (var i =0; i < id_list.length; i++) {
statistics.append(''+id_list[i].val+' ');
}
return this.request('POST', callback, error_callback);
}
this.balance_xml = '<?xml version="1.0" encoding="UTF-8"?>\
\
\
BALANCE \
\
\
\
\
\
';
/**
* Получение баланса
* @param {Array} id_list (['msg1', 'msg2'])
* @returns {Boolean}
*/
this.get_balance = function(callback, error_callback) {
if ( ! is_function(callback)
|| ! is_function(error_callback))
return false;
self.xml = $.parseXML( self.balance_xml );
self.xml = $( self.xml );
self.xml.find( "username" ).text(self.login);
self.xml.find( "password" ).text(self.password);
return this.request('POST', callback, error_callback);
}
this.credit_price_xml = '<?xml version="1.0" encoding="UTF-8"?>\
\
\
CREDITPRICE \
\
\
\
\
\
';
/**
* Получение стоимости одного кредита
* @param {Array} id_list (['msg1', 'msg2'])
* @returns {Boolean}
*/
this.get_credit_price = function(callback, error_callback) {
if ( ! is_function(callback)
|| ! is_function(error_callback))
return false;
self.xml = $.parseXML( self.credit_price_xml );
self.xml = $( self.xml );
self.xml.find( "username" ).text(self.login);
self.xml.find( "password" ).text(self.password);
return this.request('POST', callback, error_callback);
}
/**
*
* @param {String} type
* @returns {undefined}
*/
this.request = function(type, callback, error_callback) {
var option = {
url: self.gateway,
data: (new XMLSerializer().serializeToString(self.xml[0])),
type: type,
dataType: "text"
};
if (this.debug) {
console.log(option);
return true;
}
var jqxhr = $.ajax(option);
jqxhr.fail(function (xhr, ajaxOptions, thrownError) {
console.log([xhr.status, thrownError]);
});
jqxhr.always(function(xml_result, status, thrownError) {
var doc_result = $(xml_result),
status = doc_result.find('status').text();
if (status >= 0) { // OK
callback(xml_result, doc_result);
} else {
error_callback(xml_result, self.error_handler(status))
}
});
return true;
}
/**
*
*
* @param {type} method
* @param {type} xml
* @returns {undefined}
*/
this.error_handler = function(status) {
var messages = {
'-1': { 'status': '-1', 'code' : 'AUTH_FAILED', 'message': 'Неправильный логин и / или пароль' },
'-2': { 'status': '-2', 'code' : 'XML_ERROR', 'message': 'Неправильный формат XML' },
'-3': { 'status': '-3', 'code' : 'NOT_ENOUGH_CREDITS', 'message': 'Недостаточно денег на аккаунте пользователя' },
'-4': { 'status': '-4', 'code' : 'NO_RECIPIENTS', 'message': 'Нет верных номеров получателей' },
'-7': { 'status': '-7', 'code' : 'BAD_SENDER_NAME', 'message': 'Ошибка в имени отправителя' },
}
if (typeof messages[status] !== 'undefined') {
return messages[status];
}
return {status: status, 'message': 'Unknow error'};
}
}
/**
*
* @param {type} value
* @returns {unresolved}
*/
function gettype(value) {
return Object.prototype.toString.call(value);
}
function is_function(value) {
return (gettype(value) === '[object Function]');
}
/**
* example usage:
*/
var ea2 = new EpochtaApiv2('[email protected]', 'userpassword');
ea2.send_sms('test', 'test msg', [{val:'380933630001'}], '',
function(result){
console.log(result)
},
function(result){
console.log(result)
}
);
Пример использования с формой
По запросу предоставляется необходимое количество дополнительных смс для тестирования сервиса массовых смс-уведомлений ePochta SMS.
Есть вопрос?
- 8 (800) 555-09-63
- Бесплатно по России
Новости:
- 2020-11-27
- Внимание! С 1 декабря 2020 года меняется цена на отправку СМС в сети Билайн
- 2020-11-23
- ePochta объявляет старт Черной Пятницы: Спеццена на рассылку в WhatsApp
- 2020-11-18
- С 1 декабря 2020 года оператор МТС повышает стоимость СМС
- 2020-05-04
- Вебинар: СМС маркетинг. Что писать в тексте СМС рассылок?
- 2020-04-28
- Операторы повышают цены СМС рассылки по прямому каналу в РФ


7 (495) 649-62-48
Украинский
Казахский
English
Italiano
