Nodejs實現簡訊驗證碼
阿新 • • 發佈:2019-01-11
使用Nodejs的開發者愈來越多,基於Nodejs的後臺開發也多了起來,像簡訊驗證碼、簡訊群發、國際簡訊這些需求,完全可以採用第三方介面來實現,雲片網就提供了這樣的介面。
Nodejs
// 修改為您的apikey.可在官網(https://www.yunpian.com)登入後獲取
var https = require('https');
var qs = require('querystring');
var apikey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// 修改為您要傳送的手機號碼,多個號碼用逗號隔開
var mobile = 'xxxxxxxxxxx' ;
// 修改為您要傳送的簡訊內容
var text = '【雲片網】您的驗證碼是1234';
// 指定傳送的模板編號
var tpl_id = 1;
// 指定傳送模板的內容
var tpl_value = {'#code#':'1234','#company#':'yunpian'};
// 語音簡訊的內容
var code = '1234';
// 查詢賬戶資訊https地址
var get_user_info_uri = '/v2/user/get.json';
// 智慧匹配模板傳送https地址
var sms_host = 'sms.yunpian.com';
var voice_host = 'voice.yunpian.com' ;
send_sms_uri = '/v2/sms/single_send.json';
// 指定模板傳送介面https地址
send_tpl_sms_uri = '/v2/sms/tpl_single_send.json';
// 傳送語音驗證碼介面https地址
send_voice_uri = '/v2/voice/send.json';
query_user_info(get_user_info_uri,apikey);
send_sms(send_sms_uri,apikey,mobile,text);
send_tpl_sms(send_tpl_sms_uri,apikey,mobile,tpl_id,tpl_value);
send_voice_sms(send_voice_uri,apikey,mobile,code);
function query_user_info(uri,apikey){
var post_data = {
'apikey': apikey,
};//這是需要提交的資料
var content = qs.stringify(post_data);
post(uri,content,sms_host);
}
function send_sms(uri,apikey,mobile,text){
var post_data = {
'apikey': apikey,
'mobile':mobile,
'text':text,
};//這是需要提交的資料
var content = qs.stringify(post_data);
post(uri,content,sms_host);
}
function send_tpl_sms(uri,apikey,mobile,tpl_id,tpl_value){
var post_data = {
'apikey': apikey,
'mobile':mobile,
'tpl_id':tpl_id,
'tpl_value':qs.stringify(tpl_value),
};//這是需要提交的資料
var content = qs.stringify(post_data);
post(uri,content,sms_host);
}
function send_voice_sms(uri,apikey,mobile,code){
var post_data = {
'apikey': apikey,
'mobile':mobile,
'code':code,
};//這是需要提交的資料
var content = qs.stringify(post_data);
console.log(content);
post(uri,content,voice_host);
}
function post(uri,content,host){
var options = {
hostname: host,
port: 443,
path: uri,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
};
var req = https.request(options, function (res) {
// console.log('STATUS: ' + res.statusCode);
// console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
//console.log(content);
req.write(content);
req.end();
}
上面就是雲片的全部介面,在實際使用的過程中,可以根據自己的需求,選擇對應的介面使用,具體的可以看這篇文章如何使用雲片API傳送簡訊驗證碼,裡面講了如何使用單發簡訊API、群發簡訊API、不同簡訊內容批量傳送API,很實用。
另外最重要的是,雲片的服務還不錯,簡訊的到達率比較高,出了問題也有人及時回覆,這點在國內所有SaaS廠家中,算是做得很好的一家。