admin 管理员组

文章数量: 887007

node.js 实现发送短信功能

基于node.js 实现发送短信功能

1.准备

安装 node.js 下载地址:/
SubMail赛邮:/


目前能找到的门槛极低的第三方服务平台,注册即可免费赠送50条
话不多说先进入服务平台界面控制台

可以看到这里业务还是十分齐全的

接下来创建第一个短信模板

1.点击短信>创建新模板


在创建模板之前需要在平台提供身份证信息进行实名验证
2.将编辑好的短信模板提交审核(审核时间一般会很快在5-10分钟左右)
3.审核成功后

标记的红色文字是该短信模板的唯一表示码
4.创建APPID

5.查看短信余额

新用户注册赠送的50条短信
6.回到首页 找到开发文档
短信API

7.核心代码

封装成4个js文件
confing.js 配置 appid 和appkey

var Config = {mailConfig : {appid: 'your mail appid',appkey: 'your mail appkey',signtype: 'normal'},messageConfig : {appid : 'xxxx', //你的短信appidappkey : 'xxxxx', //app keysigntype : 'normal'}
};module.exports = Config;

message.js 用于发送短信请求

var request = require('request');
var crypto = require('crypto');
var config = require('./config.js');function Message() {this.appid = config.messageConfig.appid;this.signtype = config.messageConfig.signtype;this.appkey = config.messageConfig.appkey;this.send = function(params) {var api = '.json';var requestParams = params;requestParams['appid'] = this.appid;var self = this;request({uri: '.json',method: 'GET'}, function(error, response, body) {var result = JSON.parse(body);requestParams['timestamp'] = result["timestamp"];requestParams['sign_type'] = self.signtype;requestParams['signature'] = self.createSignature(requestParams);request.post({url: api, formData: requestParams}, function optionalCallback(err, httpResponse, body) {if (err) {return console.error('upload failed:', err);}console.log('Upload successful!  Server responded with:', body);});});};this.xsend = function(params) {var api = '.json';var requestParams = params;requestParams['appid'] = this.appid;var self = this;request({uri: '.json',method: 'GET'}, function(error, response, body) {var result = JSON.parse(body);requestParams['timestamp'] = result["timestamp"];requestParams['sign_type'] = self.signtype;requestParams['signature'] = self.createSignature(requestParams);request.post({url: api, formData: requestParams}, function optionalCallback(err, httpResponse, body) {if (err) {return console.error('upload failed:', err);}console.log('Upload successful!  Server responded with:', body);});});};this.subscribe = function(params) {var api = '.json';var requestParams = params;requestParams['appid'] = this.appid;var self = this;request({uri: '.json',method: 'GET'}, function(error, response, body) {var result = JSON.parse(body);requestParams['timestamp'] = result["timestamp"];requestParams['sign_type'] = self.signtype;requestParams['signature'] = self.createSignature(requestParams);request.post({url: api, formData: requestParams}, function optionalCallback(err, httpResponse, body) {if (err) {return console.error('upload failed:', err);}console.log('Upload successful!  Server responded with:', body);});});};this.unsubscribe = function(params) {var api = '.json';var requestParams = params;requestParams['appid'] = this.appid;var self = this;request({uri: '.json',method: 'GET'}, function(error, response, body) {var result = JSON.parse(body);requestParams['timestamp'] = result["timestamp"];requestParams['sign_type'] = self.signtype;requestParams['signature'] = self.createSignature(requestParams);request.post({url: api, formData: requestParams}, function optionalCallback(err, httpResponse, body) {if (err) {return console.error('upload failed:', err);}console.log('Upload successful!  Server responded with:', body);});});};this.createSignature = function(params) {if (this.signtype == 'normal') {return this.appkey;} else {return this.buildSignature(params);}};this.buildSignature = function(params) {var sortedParams = this.sortOnKeys(params);var signStr = "";for(var key in sortedParams) {signStr += key + '=' + sortedParams[key] + '&';}signStr = signStr.substring(0, signStr.length-1);signStr = this.appid + this.appkey + signStr + this.appid + this.appkey;if (this.signtype == 'md5') {var md5sum = crypto.createHash('md5');md5sum.update(signStr);return md5sum.digest('hex');}if (this.signtype == 'sha1') {var sha1sum = crypto.createHash('sha1');sha1sum.update(signStr);return sha1sum.digest('hex');}return '';};this.sortOnKeys = function(dict) {var sorted = [];for(var key in dict) {if (key == 'attachments') {continue;}sorted[sorted.length] = key;}sorted.sort();var tempDict = {};for(var i = 0; i < sorted.length; i++) {tempDict[sorted[i]] = dict[sorted[i]];}return tempDict;};
};module.exports = Message;

messageXSend.js 创建短信发送类

var Message = require('./message.js');function MessageXSend() {this.to = [];this.to_name = [];this.addressbook = [];this.project = '';this.vars = {};// set emailthis.add_to = function(address) {this.to.push(address);};this.add_to_name = function(name) {this.to_name.push(name);};this.add_addressbook = function(addressbook) {this.addressbook.push(addressbook);};this.set_project = function(project) {this.project = project;};this.add_var = function(key, val) {this.vars[key] = val;};this.build_params = function() {var params = {};if (this.to.length > 0) {var toValue = '';for (index in this.to) {var name = ''if (this.to_name[index] != undefined) {name = this.to_name[index];}toValue += name + '<' + this.to[index] + '>,';}params['to'] = toValue.substring(0, toValue.length-1);}if (this.addressbook.length > 0) {var addressbookValue = '';for (index in this.addressbook) {addressbookValue += this.addressbook[index] + ',';}params['addressbook'] = addressbookValue.substring(0, addressbookValue.length-1);}if (this.project != '') {params['project'] = this.project;}if (Object.keys(this.vars).length > 0) {params['vars'] = JSON.stringify(this.vars);}return params;};this.xsend = function() {var message = new Message();message.xsend(this.build_params());}
};module.exports = MessageXSend;

messageXTools.js 发送短信的入口文件

var MessageXSend = require('./messageXSend.js');
var messageXSend = new MessageXSend();function validateSMS(phone) {let number = Math.floor(Math.random() * 9000) + 1000; //每次执行生成随机的4位验证码messageXSend.add_to(15008373616); //发送短信的手机号messageXSend.set_project('yy6LN3'); //短信模板ID 在短信模板中可看到messageXSend.add_var('code', number); //短信验证码messageXSend.xsend();return number;
}

node.js 执行发送

发送成功
sms_credits表示还剩下多少次数
收到的短信

好啦一个基于node.js的短信验证发送就实现了
如果还想进一步实现通过点击登录/注册按钮来实现短信发送只需要将messageXTools.js简单修改一下即可

var MessageXSend = require('./messageXSend.js');
var messageXSend = new MessageXSend();function validateSMS(phone) {let number = Math.floor(Math.random() * 9000) + 1000;messageXSend.add_to(phone);messageXSend.set_project('yy6LN3');messageXSend.add_var('code', number);messageXSend.xsend();return number;
}module.exports = validateSMS

编写一个后台接口 code.js

let express = require('express')
let router = express.Router()
let sendCode = require('../code/messageXTools') //请求短信 发送模块的js//短信 coderouter.post('/code',(req,res)=>{  res.json({msg:"成功",code:sendCode(req.body.tel)//前台请求成功后返回的验证码})})module.exports = router

通过页面点击按钮发送请求 小编这里是用的是(React写的一个项目)fetch请求

   fetch('/create',{method:'post', headers: {"Content-Type":"application/json"},               body:JSON.stringify({users:this.refs.tel.value,password:this.refs.pass.value,money:Math.floor(Math.random()*100)})}).then(req=>req.json()).then(data=>{console.log(data.code) //后台返回的验证码})


点击按钮获取短信验证码

页面输出请求的结果 code 就是发送的验证码
收到的短信

好了一个基本的短信验证功能就实现了

有任何问题欢迎留言哦

本文标签: nodejs 实现发送短信功能