天天看點

node短信接口開發

最近上新項目,要用到一個短信驗證的功能,之前也沒接觸過這類東西,也搞了半天

基本的流程大概是這樣:

前台頁面做好輸入框使用者填寫手機号 -> 背景生成驗證用的數字code -> 調用短信接口下發code ->  使用者填寫code送出 -> 校驗是否通過

前面兩步也沒什麼好說的,做一個表單。 然後生成一段6位code

var code = Math.floor((Math.random()*999999)+111111);
           

接下來調用短信接口

公司這邊給的是Luosimao的短信接口

文檔位址luosimao.com/docs/api

自己先封裝了一個簡易版的module,後續考慮優化一下。

var https = require('https');
var querystring = require('querystring');

function luosimaosms(option){
    this.protocol = 'https';
    this.url = 'sms-api.luosimao.com';
    this.path = '/v1/send.json';
    this.username = 'api';
    this.key = ‘key-231123132123123123123';
}

luosimaosms.prototype.sendMessage = function(mobile,code,callback){

    var postData = {
        mobile: mobile,
        message:'您的驗證碼是:' + code
    };

    var content = querystring.stringify(postData);

    var req = https.request({
        host:this.url,
        path:this.path,
        method:'POST',
        auth:  this.username + ':' + this.key,
        agent:false,
        rejectUnauthorized : false,
        headers:{
            'Content-Type' : 'application/x-www-form-urlencoded',
            'Content-Length' : content.length
        }
    }, function(res){
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            callback(JSON.parse(chunk));
        });
    });

    req.write(content);
    req.end();

};

module.exports = luosimaosms;
           

調用

var luosimaosms = require('luosimao-sms-node');
var client = new luosimaosms();
client.sendMessage(‘13700000000',’1234’,function(data){
    console.log(data);
});
           

這家用的是basic auth 的驗證方式,之前沒接觸過,搞了好久。。。索性短信速度還可以,就大功告成了。

最後就是校驗一下使用者送出的code是否符合生成值,存資料庫。

這裡記錄一下此類接口的調用方式,後面再優化一下。

繼續閱讀