阿里云短信服务 从发送到验证简单demo

------------恢复内容开始------------

短信服务是很多项目在登录注册时使用的接口,本博客记录我在项目中简单实现的短信验证.

 一.注册阿里云短信服务https://helpcdn.aliyun.com/product/44282.html

 1.这一步官方教程很详细,按照快速学习逐步完成就可;值得注意的是AccessKey ID 和 AccessKeySecretz在创建用户时会显示.注意保存调用接口时需要.

 2.申请模板和签名,使用阿里云提供例子的模板签名可以更快通过审核,大概1小时就可以.

 二.demo实现

1,官方的demo案例,发送成功证明接口成功调用;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
/*
添加依赖
pom.xml
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.0.3</version>
</dependency>
*/
public class SendSms {
    public static void main(String[] args) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "添加你的accessKeyId", "添加你的accessSecret");
        IAcsClient client = new DefaultAcsClient(profile);
       String scode = String.valueOf(new Random().nextInt(899999) + 100000);//生成验证码
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", "15866668888");//发送到的手机号
        request.putQueryParameter("SignName", "寻趣网");//申请的模板
        request.putQueryParameter("TemplateCode", "SMS_175584853");//申请的模板
  request.putQueryParameter("TemplateParam", "{\"scode\":\""+scode+"[有效期5分钟]"+"\"}");
try { CommonResponse response = client.getCommonResponse(request); System.out.println(response.getData()); } catch (ServerException e) { e.printStackTrace(); } catch (ClientException e) { e.printStackTrace(); } } }

 2.自己写的从发送到验证简单demo

1.controller  (pom依赖就是上面注释部分)

 /*获取验证码controller*/
    @PostMapping("/getcode")
    @ResponseBody
    public String getcode(String phone) {
        if (chackphone.chackphone(phone)) {
            String scode = String.valueOf(new Random().nextInt(899999) + 100000);
        String smsId="SMS_175584853";
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4FodsafasdfVpCiXfasdfwsBZ", "Y7QdsfaXZoKle2zasdfaTCzVS2Vpa");
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("SignName", "寻趣网");
        request.putQueryParameter("PhoneNumbers", ""+phone+"");
        request.putQueryParameter("TemplateCode", ""+smsId+"");
        request.putQueryParameter("TemplateParam", "{\"scode\":\""+scode+"[有效期5分钟]"+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }*/
            System.out.println(phone);
            System.out.println(scode);
            return scode;

        } else {
            return "0";
        }
    }

}

2.手机号验证util

/**
 * @author kpzc
 * 三大运营商号码均可验证(不含卫星通信1349)
 */
public class chackphone {

    public static boolean chackphone(String phone) {
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            if (isMatch) {
                return true;
            } else {
                return false;
            }
        }

    }






}

3.登录页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>登录</title>
    <meta name="Keywords" content="寻趣">
    <meta name="Description" content="寻趣这里更懂你">
    <link th:href="@{/css/base.css}" rel="stylesheet">
    <link th:href="@{/css/iconfont.css}" rel="stylesheet">
    <link th:href="@{/css/reg.css}" rel="stylesheet">

    <script th:inline="javascript">
        var base = [[${#request.getContextPath()}]];
    </script>

</head>
<body>

<div id="ajax-hook">
</div>
<div class="wrap" style="background-image:url(img/background.jpg);" >
    <div class="wpn">
        <div class="form-data pos">
            <a ><img th:src="@{img/logo.png}" class="head-logo"></a>
            <div class="change-login">
                <p class="account_number on">
                    账号登录
                </p>
                <p class="message">
                    短信登录
                </p>
            </div>
            <div class="form1">
                <p class="p-input pos">
                    <label for="username" style="">手机号/用户名/UID/邮箱</label>
                    <input type="text" id="username">
                    <span class="tel-warn num-err hide"><em>账号或密码错误,请重新输入</em><i class="icon-warn"></i></span>
                </p>
                <p class="p-input pos">
                    <label for="password" style="">请输入密码</label>
                    <input type="password" style="display:none">
                    <input type="password" id="password" autocomplete="new-password">
                    <span class="tel-warn pass-err hide"><em>账号或密码错误,请重新输入</em><i class="icon-warn"></i></span>
                </p>
                <!-- <p class="p-input pos code hide">
                     <label for="veri">请输入验证码</label>
                     <input type="text" id="veri">
                     <img src="index.html">
                     <span class="tel-warn img-err hide"><em>账号或密码错误,请重新输入</em><i class="icon-warn"></i></span>
                     &lt;!&ndash; <a href="javascript:;">换一换</a> &ndash;&gt;
                 </p>-->
                <button id="loginButton1" type="button" class="lang-btn off log-btn" onclick="loginButton1()">登录1
                </button>
            </div>
            <div class="form2 hide">

                <p class="p-input pos">
                    <label for="num2">手机号</label>
                    <input type="number" id="num2" >
                    <span class="tel-warn num2-err hide"><em>账号或密码错误</em><i class="icon-warn"></i></span>
                </p>
                <p class="p-input pos">
                    <label for="veri-code">输入验证码</label>
                    <!-- 发送验证码-->
                    <input type="number" id="veri-code">
                    <a href="javascript:;" id="getcode" class="send">发送验证码</a>

                    <span class="time hide"><em>120</em>s</span>
                    <span class="tel-warn error hide">验证码错误</span>
                </p>
                <button id="loginButton2" type="button" class="lang-btn off log-btn" onclick="loginButton2()">登录2
                </button>
            </div>
            <div class="r-forget cl">
                <a onclick="reg()" href="javascript:;" class="z">账号注册</a>

                <a onclick="getpass()" href="javascript:;" class="y">忘记密码</a>
            </div>
            </br>

            <div class="third-party">

                <a href="javascript:;" class="log-qq icon-qq-round"></a>
                <a href="javascript:;" class="log-qq icon-weixin"></a>
                <a href="javascript:;" class="log-qq icon-sina1"></a>
            </div>
            <p class="right">
                Powered by © 2019 寻趣网
            </p>
        </div>
    </div>
</div>


<script th:src="@{/js/jquery.js}"></script>
<script th:src="@{/js/agree.js}"></script>
<script th:src="@{/js/login.js}"></script>
<script th:src="@{/js/yzm.js}"></script>
</body>
</html>

4.js

$(function () {
    /*验证码发送*/
    $("#getcode").click(function () {
        var pNum = $("#num2").val();
        $.ajax({
            url: base + "/getcode",
            type: "post",
            data: {'phone': pNum},
            dataType: "json",
            success: function (data) {
                if (data==0){
                    alert("请检查手机号!")
                    return;
                }else {
                    alert(data)
                    sessionStorage.setItem("scode", data);
                }

            }
        })
    });



});

function loginButton1() {
    alert("登录按钮1")
    var usm = $("#username").val()
    var pass = $("#password").val()
    $.ajax({
        url: base + "/login1",
        type: "post",
        data: {'username': usm, 'password': pass},
        dataType: "json",
        success: function (data) {
            alert(data)
            if (data == 0) {
                alert("登录成功")
                //$("#errorMsg1").text("成功");
                // sessionStorage.setItem("userId", data.userId);
                //主页名字
                location.href = base + "/index";
            } else {
                $("#errorMsg1").text("密码错误!");
            }
        }

    })
};

function loginButton2() {
    alert("登录按钮2")
    var a = sessionStorage.getItem("scode");
    var pcode = $("#veri-code").val();
    alert(a);

    if (pcode == a) {
        alert("验证码正确");
        location.href = base + "/index";
    } else {
        alert("验证码有误");
    }
};

function regButton() {

    alert("注册按钮")
    var nnm = $("#nickname").val();
    var tel = $("#num2").val();
    var pass = $("#password").val();
    var pcode = $("#veri-code").val();
    var b = sessionStorage.getItem("scode");
    $.ajax({
        url: base + "/reg",
        type: "post",
        data: {'nickname': nnm, 'phone': tel, 'passsword': pass},
        dataType: "json",
        success: function (data) {

            if (pcode == b) {
                alert("验证成功");
                if(data==0){
                    alert("注册成功!页面跳转中...");
                    location.href = base + "/index";
                }
                else alert("注册失败")
            } else {
                alert("验证码有误");
            }
        }
    })
};


function getpass() {
    location.href = base + "/getpass";
};

function reg() {
    location.href = base + "/reg";
};

function gologin() {
    location.href = base + "/login";
};

 以上就是短信验证的一个简单使用

ps:可能会因为缺失css有些问题 ,后续我会更新( o=^•ェ•)o ┏━┓

猜你喜欢

转载自www.cnblogs.com/whiskyT/p/11855979.html