阿里大于短信验证码node koa2的实现代码(最新)

时间:2019-04-01
本文章向大家介绍阿里大于短信验证码node koa2的实现代码(最新),主要包括阿里大于短信验证码node koa2的实现代码(最新)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

今天给大家分享一下最新版阿里大于的短信验证码在node koa2的实现,还是有很多坑需要注意。

首先需要在阿里云注册账号,并获取阿里云访问秘钥,在控制台完成模板与签名的申请获得调用接口的必备参数。具体方法参见短信发送api

步骤一:安装npm包

npm install @alicloud/sms-sdk --save 

步骤二:代码实现。常见一个sendmsg.js的controller

/** 
 * 引用sdk 
 */ 
const SMSClient = require('@alicloud/sms-sdk') 
const accessKeyId = ''//你自己在阿里云后台的accessKeyId 
const secretAccessKey = ''//secretAccessKey 
var sendmsg = {}; 
module.exports = sendmsg; 
/** 
 * 发送短信验证码 
 */ 
sendmsg.send = async (ctx, next) =>{ 
  var number=""; 
  for(var i=0;i<6;i++){ 
    number+=Math.floor(Math.random()*10) 
  } 
  //初始化sms_client 
  let smsClient = new SMSClient({accessKeyId, secretAccessKey}) 
  //发送短信 
  var s = await smsClient.sendSMS({ 
    PhoneNumbers: '13888888888',//发送的电话号码 
    SignName: '阿斯蒂芬',//认证签名 
    TemplateCode: 'SMS_11111111',//模板id 
    TemplateParam: '{"number":"'+number+'","product":"阿斯蒂芬"}'//特别注意,这里的参数名 
  }) 
  if(s.Code=="OK"){ 
    ctx.body = {code :1,msg :number} 
  }else{ 
    ctx.body = {code :0} 
  } 
}; 

路由:

const sendmsg = require('../controller/sendmsg'); 
//发送短信 
router.get('/sendmsg',sendmsg.send); 

访问localhost:3000/sendmsg就可以发送短信验证了。

总结

以上所述是小编给大家介绍的阿里大于短信验证码node koa2的实现代码(最新),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!