01 | String.prototype.replaceAll = function (reallyDo, replaceWith, ignoreCase) { |
02 | if (!RegExp.prototype.isPrototypeOf(reallyDo)) { |
03 | return this .replace( new RegExp(reallyDo, (ignoreCase ? "gi" : "g" )), replaceWith); |
04 | } else { |
05 | return this .replace(reallyDo, replaceWith); |
06 | } |
07 | }; |
08 |
09 | var dom = require( 'xmldom' ).DOMParser; |
10 |
11 | var _baseUri = "http://api.106xin.com/utf8/sms.aspx" ; |
12 | var _userAgent = "node-106jiekou" ; |
13 |
14 | /** |
15 | * sms constructure. |
16 | * @param account 用户名 |
17 | * @param password 接口密码 |
18 | */ |
19 | var sms = function (account, password) { |
20 | this .spidex = require( "spidex" ); |
21 | this .spidex.setDefaultUserAgent(_userAgent); |
22 |
23 | this .account = account; |
24 | this .password = password; |
25 | }; |
26 |
27 | /** |
28 | * send an SMS. |
29 | * @param mobile |
30 | * @param content |
31 | * @param callback |
32 | */ |
33 | sms.prototype.send = function (mobile, content, callback) { |
34 | var data = { |
35 | account : this .account, |
36 | password : this .password, |
37 | mobile : mobile, |
38 | content : content |
39 | }; |
40 |
41 | this .spidex.post(_baseUri, function (html, status) { |
42 | if (status !== 200) { |
43 | callback( new Error( "短信发送服务器响应失败。" )); |
44 | return ; |
45 | } |
46 |
47 | html = html.replaceAll( "r" , "" ); |
48 | html = html.replaceAll( "n" , "" ); |
49 | html = html.replaceAll( " xmlns="http://api.106xin.com/"" , "" ); |
50 |
51 | //console.log(html); |
52 | var doc = new dom().parseFromString(html); |
53 | var result = doc.lastChild; |
54 | var json = {}; |
55 | for ( var node = result.firstChild; node !== null ; node = node.nextSibling) { |
56 | json[node.tagName] = node.firstChild.data; |
57 | } |
58 |
59 | //console.log(json); |
60 | if (json.code == "2" ) { |
61 | callback( null , json.smsid); |
62 | } else { |
63 | callback( new Error(json.msg, parseInt(json.code))); |
64 | } |
65 | }, data, "utf8" ).on( "err" , function (e) { |
66 | callback(e); |
67 | }); |
68 | }; |
69 |
70 | module.exports = sms; |