這篇文章將為大家詳細講解有關Nodejs怎么實現短信驗證碼功能,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
使用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廠家中,算是做得很好的一家。
關于“Nodejs怎么實現短信驗證碼功能”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。