zoukankan      html  css  js  c++  java
  • Node 接入阿里云实现短信验证码

    本文介绍在案例云开通短信服务的流程以及在Node项目中使用的方法。

    一、开通阿里云短信服务

    登陆阿里云,然后进入 https://dysms.console.aliyun.com/dysms.htm 。

    选择国内消息,在“签名管理”里添加签名,获取 SignName;在“模板管理”里添加模板,获得 TemplateCode 。

     

    二、获取 AccessKey

    要调用短信服务,需要通过 AccessKey 鉴权。登陆阿里云,进入 https://usercenter.console.aliyun.com/ ,创建 AccessKey,得到 accessKeyId 和 accessKeySecret 。

    三、费用支付

    短信服务是收费的,可以按发送次数计费,也可以购买套餐。跟手机用户向联通移动付费的方式相似,会在月底出账单,欠费的话会停掉短信服务。

    为避免欠费,可以在阿里云帐户内存入一定余额。进入 https://usercenter2.aliyun.com/home 查看:

     

    四、Node调用

    @alicloud/pop-core 是阿里提供的核心库,需要在项目中引入:

    npm install @alicloud/pop-core -S

    下面是 sms.js 示例代码,其中 SignName / TemplateCode / accessKeyId / accessKeySecret 都要从阿里云获取,请替换为实际值。

    /**
     * sms.send(手机号) 发送短信验证码
     * sms.verify(手机号,验证码) 校验验证码是否正确
     **/
    
    const Core = require('@alicloud/pop-core');
    const _ = require('lodash');
    
    // 阿里云控制台 - 短信服务 - 国内消息
    const SignName = "东方网络";
    const TemplateCode = "SMS_123456";
    
    // https://usercenter.console.aliyun.com/
    const accessKeyId = "ljksdhfjklJKGKGKJHK";
    const accessKeySecret = "HKAJSHDIU90800980jkahsd";
    
    var client = new Core({
        accessKeyId,
        accessKeySecret,
        endpoint: 'https://dysmsapi.aliyuncs.com',
        apiVersion: '2017-05-25'
    });
    
    // 保存手机号和验证码的对应关系
    // phone_code_list = {'18855551234':['1024']}
    var phone_code_list = {};
    
    exports.send = function(phone) {
        // 生成验证码
        var code = "" + _.random(9) + _.random(9) + _.random(9) + _.random(9);
        return new Promise((resolve, reject) => {
            try {
                client.request('SendSms', {
                    RegionId: "cn-hangzhou",
                    PhoneNumbers: phone,
                    SignName,
                    TemplateCode,
                    TemplateParam: "{code:" + code + "}"
                }, {
                    method: 'POST'
                }).then((result) => {
                    if (result.Message && result.Message == "OK" && result.Code && result.Code == "OK") { // 短信发送成功
                        // 保存验证码
                        if (phone_code_list[phone]) {
                            phone_code_list[phone].push(code);
                        } else {
                            phone_code_list[phone] = [code];
                        }
                        // 三分钟后删除验证码
                        setTimeout(() => {
                            _.pull(phone_code_list[phone], code);
                            if (phone_code_list[phone] && phone_code_list[phone].length == 0) {
                                delete phone_code_list[phone];
                            }
                        }, 3 * 60 * 1000)
                        resolve(result)
                    } else {
                        reject(result)
                    }
                }, (ex) => {
                    reject(ex)
                })
            } catch (error) {
                reject(error)
            }
        })
    }
    
    exports.verify = function(phone, code) {
        return (phone_code_list[phone].indexOf(code) > -1)
    }

    调用方式参考:

    const sms = require("./util/sms.js")
    
    // 发送验证码
    sms.send("18855551234").then((result) => {
        console.log("短信发送成功")
        console.log(result)
    }, (ex) => {
        console.log("短信发送失败")
        console.log(ex)
    });
    
    // 校验用户提交的验证码
    var isCodeRight = sms.verify("18855551234","0000"); // 返回true/false
    

      

  • 相关阅读:
    Django对静态文件的处理——部署阶段
    使用Django来处理对于静态文件的请求
    Django1.7如何配置静态资源访问
    Spring WebSocket中403错误解决
    FastJSON JSONObject 字段排序 Feature.OrderedField
    国际化(i18n) 各国语言缩写
    【转】java.io.Closeable接口
    【转】spring bean 卸载
    This content should also be served over HTTPS
    Failed to close the ServletOutputStream connection cleanly, Broken pipe
  • 原文地址:https://www.cnblogs.com/yangshifu/p/12810538.html
Copyright © 2011-2022 走看看