java调用阿里云实现短信验证码

进入阿里云的官网自己申请

要用到
accessKeyId
accessKeySecret
你的短信签名
你的短信模板
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

pom.xml依赖

<!-- 阿里云短信验证码 核心 -->
        <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>3.5.0</version>
        </dependency>
        <!-- 阿里云短信验证码 -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>1.0.0</version>
        </dependency>

html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" id="viewport" name="viewport">
    <title></title>
    <style type="text/css">
        body,div{
            padding: 0;
            margin: 0;
        }
        .wraper{
            padding: 100px;
        }
        .phone{
            width: 220px;
            height: 40px;
            box-sizing: border-box;
            outline: none;
            padding: 0 10px;
        }
        .getverify-code-btn{
            display: inline-block;
            width: 140px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            background-color: blue;
            border: 1px solid #ccc;
            box-sizing: border-box;
            vertical-align: middle;
            cursor: pointer;
            color: #fff;
        }
        .getverify-code-btn.unabled{
            background-color: lightblue;
            color: #eee;
            cursor: default;
        }
    </style>
    <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
<!--    <link rel="shortcut icon" href="#" />-->
    <script type="text/javascript">
        var countdown=60;
        function settime() {
            var obj=document.getElementById("btn");
            if (countdown == 0) {
                obj.removeAttribute("disabled");
                obj.value="免费获取验证码";
                countdown = 60;
                return;
            } else {
                obj.setAttribute("disabled", true);
                obj.value="重新发送(" + countdown + ")";
                countdown--;
            }
            setTimeout(function() {
                    settime(obj) }
                ,1000)
        }
        function sendInfo(){

            var phoneReg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/,
                flag = phoneReg.test($("#phone").val());
            if(!flag){
                alert("电话号码填写不正确!");
                return false;
            }

            settime();//倒计时

            yzm(); //console.log(2);//生成验证码 并存储

        }
        function yzm(){
            // alert(JSON.stringify($("#phone").val()));
            $.ajax({
                url: "/dxyanz1",
                type:'post',
                data:{
                    phone:$("#phone").val(),
                },
                dataType: 'json',
                success:function (result) {
                    alert(result)
                }
            })
        }
    </script>

</head>
<body>
<form action="/dxyanz2" method="post">
    <div class="wraper">
        <h1>获取手机验证码</h1>

        手机号:<input type="text" id="phone" name="phone" class="phone">
        <input type="button" id="btn" class="getverify-code-btn" value="免费获取验证码" onclick="sendInfo()" ><br>
        验证码:<input type="text" class="phone" name="yzm" id="yzm"/><br>
        <input name="sub" type="submit" value="提交">
    </div>
</form>
</body>

</html>

util工具包

package com.jwt.demo.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

/**
 * @Auther: 小宇不吃饭
 * @Date: 2020/12/16 10:49
 * @Description: 短信验证码测试
 */
public class DXutil {
    // 产品名称:API产品,开发者无需替换
    static final String product = "Dysmsapi";
    // 产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = "accessKeyId";           // TODO 改这里
    static final String accessKeySecret = "accessKeySecret"; // TODO 改这里

    public static SendSmsResponse sendSms(String telephone, String code) throws ClientException {
        // 可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        // 初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        // 组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        // 必填:待发送手机号
        request.setPhoneNumbers(telephone);
        // 必填:短信签名-可在短信控制台中找到
        request.setSignName("你的短信签名"); // TODO 改这里 ==你的短信签名
        // 必填:短信模板-可在短信控制台中找到
        request.setTemplateCode("你的短信模板");  // TODO 改这里===你的短信模板
        // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的用户,您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{\"code\":\"" + code + "\"}");

        // 选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        // request.setSmsUpExtendCode("90997");

        // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("yourOutId");

        // hint 此处可能会抛出异常,注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        if(sendSmsResponse.getCode()!= null && sendSmsResponse.getCode().equals("OK")){
            System.out.println("短信发送成功!");
        }else {
            System.out.println("短信发送失败!");
        }
        return sendSmsResponse;
    }

    //以下为测试代码,随机生成验证码
    private static int newcode;
    public static int getNewcode() {
        return newcode;
    }
    public static void setNewcode(){
        newcode = (int)(Math.random()*9999)+100;  //每次调用生成一次四位数的随机数
    }

}

controller层

package com.jwt.demo.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Random;

import static com.jwt.demo.util.DXutil.*;

@Controller
public class Verification {
    public static int Aa;
    public static String Bb;
    @RequestMapping("/dxyanz")
    public String verification(){
        return "yanz";
    }

    @PostMapping("/dxyanz1")
    @ResponseBody
//    public static void main(String[] args) throws Exception {
    public void DXyz(HttpServletRequest request) throws Exception {
        String phone = request.getParameter("phone");
        System.out.println("11111111111111");
        System.out.println(phone);
//        String phone = "15194069931";
        setNewcode();
        //给全局变量赋值
        Aa=getNewcode();
        Bb=phone;
        System.out.println(Aa);
//        System.out.println(Bb);
        String code = Integer.toString(getNewcode());//15762971759
        SendSmsResponse sendSms =sendSms(phone,code);//填写你需要测试的手机号码
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + sendSms.getCode());
        System.out.println("Message=" + sendSms.getMessage());
        System.out.println("RequestId=" + sendSms.getRequestId());
        System.out.println("BizId=" + sendSms.getBizId());
//        return getNewcode();
    }

    @PostMapping("/dxyanz2")
    @ResponseBody
    public String  DXyz2(HttpServletRequest request) throws Exception{
        String phone = request.getParameter("phone");
        String  yzm = request.getParameter("yzm");
        if (phone==""){
            System.out.println("手机号不能为空");
            return "手机号不能为空";
        }
        if (yzm==""){
            System.out.println("验证码不能为空");
            return "验证码不能为空";
        }
        System.out.println(phone);
        System.out.println(Bb);
        System.out.println(yzm);
        System.out.println(Aa);
        //equals用的都是String类型的,所以需要先转换类型
        String AA = ""+Aa;
        if(phone.equals(Bb) && yzm.equals(AA)){
            return "验证码对了,成功";
        }else {
            return "验证码不对,失败";
        }
    }


//    @RequestMapping("/yanz1")
//    @ResponseBody
//    public String testRandom(){
//        String msg="您的注册码为%s,谢谢注册!";
//        System.out.println("Math.random得到小数");
//        System.out.println(Math.round((Math.random()+1) * 1000));
//        System.out.println("Random");
//        System.out.println(new Random().nextInt(9999));
//        System.out.println("字符串前面补0的话就这样String.format");
//        System.out.println(String.format("%04d",new Random().nextInt(9999)));
//        return msg;
//    }

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现短信验证码登录,需要以下步骤: 1. 前端页面中添加手机号码输入框和获取验证码按钮。 2. 用户输入手机号码后,点击获取验证码按钮,前端发送请求到后端获取验证码。 3. 后端接收到请求后,生成随机验证码,并将验证码保存到缓存中,同时调用短信接口将验证码发送给用户。 4. 用户输入收到的验证码后,前端将手机号码和验证码发送到后端进行验证。 5. 后端从缓存中获取对应手机号码的验证码进行比对,如果验证码正确,则返回登录成功的信息。 下面是Java实现短信验证码登录的示例代码: 1. 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.5.0</version> </dependency> ``` 2. 在后端代码中添加以下方法: ```java // 发送短信验证码 public boolean sendSmsCode(String phoneNumber) { // 生成随机验证码 String code = String.valueOf((int)((Math.random()*9+1)*100000)); // 将验证码保存到缓存中,有效期为5分钟 // 这里使用redis作为缓存,需要自行安装redis并添加依赖 redisTemplate.opsForValue().set(phoneNumber, code, 5, TimeUnit.MINUTES); // 调用阿里云短信接口发送验证码 DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "accessKeyId", "accessSecret"); 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("PhoneNumbers", phoneNumber); request.putQueryParameter("SignName", "短信签名"); request.putQueryParameter("TemplateCode", "短信模板ID"); request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}"); try { CommonResponse response = client.getCommonResponse(request); String result = response.getData(); // 判断短信是否发送成功 JSONObject jsonObject = JSON.parseObject(result); if (jsonObject.get("Code").toString().equals("OK")) { return true; } return false; } catch (Exception e) { e.printStackTrace(); return false; } } // 验证短信验证码 public boolean verifySmsCode(String phoneNumber, String code) { // 从缓存中获取对应手机号码的验证码 String smsCode = (String) redisTemplate.opsForValue().get(phoneNumber); // 比对验证码是否正确 if (smsCode != null && smsCode.equals(code)) { return true; } return false; } ``` 3. 在Controller中添加以下接口: ```java // 发送短信验证码 @RequestMapping(value = "/sendSmsCode", method = RequestMethod.POST) public Result sendSmsCode(@RequestParam("phoneNumber") String phoneNumber) { boolean isSuccess = userService.sendSmsCode(phoneNumber); if (isSuccess) { return Result.success("短信验证码发送成功"); } else { return Result.fail("短信验证码发送失败"); } } // 短信验证码登录 @RequestMapping(value = "/loginBySmsCode", method = RequestMethod.POST) public Result loginBySmsCode(@RequestParam("phoneNumber") String phoneNumber, @RequestParam("code") String code) { // 验证短信验证码是否正确 boolean isVerified = userService.verifySmsCode(phoneNumber, code); if (isVerified) { // 验证通过,返回登录成功的信息 return Result.success("登录成功"); } else { // 验证失败,返回登录失败的信息 return Result.fail("验证码错误"); } } ``` 4. 在前端页面中添加以下代码: ```html <!-- 手机号码输入框 --> <input type="text" id="phoneNumber" placeholder="请输入手机号码"> <!-- 获取验证码按钮 --> <button onclick="sendSmsCode()">获取验证码</button> <!-- 短信验证码输入框 --> <input type="text" id="smsCode" placeholder="请输入短信验证码"> <!-- 登录按钮 --> <button onclick="loginBySmsCode()">登录</button> <script> // 发送短信验证码 function sendSmsCode() { var phoneNumber = $("#phoneNumber").val(); $.ajax({ type: "POST", url: "/sendSmsCode", data: { "phoneNumber": phoneNumber }, success: function (result) { alert(result.message); }, error: function () { alert("发送短信验证码失败"); } }); } // 短信验证码登录 function loginBySmsCode() { var phoneNumber = $("#phoneNumber").val(); var smsCode = $("#smsCode").val(); $.ajax({ type: "POST", url: "/loginBySmsCode", data: { "phoneNumber": phoneNumber, "code": smsCode }, success: function (result) { alert(result.message); }, error: function () { alert("短信验证码登录失败"); } }); } </script> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值