SpringBoot实现短信验证码登录

一、要找一个提供短信接口的第三方平台,这里我使用的是榛子云
二、在注册后,就可以使用了
三、首先是在pom.xml中添加依赖

<!-- fastjosn -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.4</version>
</dependency>
<dependency>
    <groupId>com.zhenzikj</groupId>
    <artifactId>zhenzisms</artifactId>
    <version>1.0.2</version>
</dependency>

1.验证码发送的controller

package com.foreknow.controller;
import com.alibaba.fastjson.JSONObject;
import com.foreknow.model.Member;
import com.foreknow.service.MemberService;
import com.zhenzi.sms.ZhenziSmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.util.Random;

@Controller
public class CodeController {
private static final long serialVersionUID = 1L;
//短信平台相关参数
//这个不用改
private String apiUrl = "https://sms_developer.zhenzikj.com";
//榛子云系统上获取
private String appId = "100862";
private String appSecret = "62358d10-bc0e-4152-a52c-578a8debc9b9";

@ResponseBody
@GetMapping("/fitness/code")
public boolean getCode(@RequestParam("memPhone") String memPhone, HttpSession httpSession){
    Member member = memberService.selectByPhone(memPhone);
    if (member!=null){
        try {
        JSONObject json = null;
        //随机生成验证码
        String code = String.valueOf(new Random().nextInt(999999));
        //将验证码通过榛子云接口发送至手机
        ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
        String result = client.send(memPhone, "您的验证码为:" + code + ",该码有效期为5分钟,该码只能使用一次!");
        
        json = JSONObject.parseObject(result);
        if (json.getIntValue("code")!=0){//发送短信失败
            return  false;
        }
        //将验证码存到session中,同时存入创建时间
        //以json存放,这里使用的是阿里的fastjson
        json = new JSONObject();
        json.put("memPhone",memPhone);
        json.put("code",code);
        json.put("createTime",System.currentTimeMillis());
        // 将认证码存入SESSION
        httpSession.setAttribute("code",json);
        return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
        return false;
}
}

其中的局部变量是在榛子云的个人中心获取:
在这里插入图片描述
登录时从session中获取刚刚发送到手机的验证码对象:

JSONObject userCode = (JSONObject)session.getAttribute("code");
//验证码
userCode .get("code");
//手机号
userCode.get("memPhone");

前端限制60秒只能获取一次验证码的效果实现:
在这里插入图片描述

<div id="model2">
    <div class="layui-form-item input-item">
        <label for="userName">手机号</label>
        <input type="text" placeholder="请输入手机号" autocomplete="off" id="memPhone" name="memPhone" class="layui-input">
    </div>
    <div class="layui-form-item input-item">
        <label for="userName">验证码</label>
        <input type="text" placeholder="请输入验证码" autocomplete="off" id="code" name="code" maxlength="6" class="layui-input" style="width: 50%;display: inline">
        <input type="button" class="layui-btn layui-btn-primary" value="获取验证码" id="sendBtn" style="width:41%;margin-left: 18px;border-color:#1e9fff !important;" onclick="sendCode(this)"></input>
    </div>
</div>

 function sendCode(){
       var memPhone = $("#memPhone").val();
       console.log(memPhone.length);
       if(memPhone == '' || memPhone.length != 11){
           layer.msg("请输入正确的手机号!");
           return;
       }else{
           $.ajax({
               type: 'GET',
               url: '[[${basePath}]]/fitness/code',
               data: {
                   memPhone : memPhone
               },
               dataType: 'json',
               success: function(data) {
                  if(data){
                      timer();
                  }else{
                      layer.msg("获取验证码失败");
                  }
               },
               error: function(data) {
                   layer.msg('连接超时!');
               },
           });
       }
   }
   
   var wait = 60;
   //倒计时
   function timer() {
       if(wait == 0){
           $("#sendBtn").val("获取验证码");
           $("#sendBtn").removeAttr("disabled");
           $("#sendBtn").css("border-color","1e9fff").css("background", "#ffffff").css("cursor", "pointer");
           wait = 60;
       }else{
           $("#sendBtn").attr("disabled","true");
           $("#sendBtn").css("border-color","fbfbfb").css("background", "#ccc").css("cursor", "not-allowed");
           $("#sendBtn").val(wait + "秒后重发");
           wait--;
           setTimeout(function() {timer()}, 1000);
       }
   }

猜你喜欢

转载自blog.csdn.net/qq_35500685/article/details/92796831