Springboot实现短信验证码功能(阿里云)

最近在写毕业设计,找回密码时用到了短信验证码功能,记录如下,初学者 大神勿喷

通过阿里云实现短信验证功能,一定要申请一个阿里账号

登录阿里云控制台,通过AccessKey 开启子用户,添加一个用户组和用户。

权限管理 –》 添加权限 –》SMS(管理短信服务) –》创建用户(开启编程访问)–》得到一个id和密码(一定要本地保存,以后看不到密码了)

开通阿里云短信服务

控制台搜索短信服务–》开通服务 –》国内消息 填写签名和模版 (申请成功后记住模版的code)等待审核通过

文档地址:https://help.aliyun.com/document_detail/101300.html?spm=a2c4g.11186623.6.610.430856e0Ncmg7L 点击跳转

编写测试代码

1.添加maven依赖

<dependency>
    <groupId>com.aliyungroupId>
    <artifactId>aliyun-java-sdk-coreartifactId>
    <version>4.5.1version>
dependency>

<dependency>
<groupId>com.aliyungroupId>
<artifactId>aliyun-java-sdk-dysmsapiartifactId>
<version>1.1.0version>
dependency>

2.编写测试代码

 @Test
    void contextLoads() {
//        连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "签名", "密码");
        IAcsClient client = new DefaultAcsClient(profile);
//构建请求 setSysDomain  setSysAction  不要改
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
//        自定义参数 (手机号,验证码,签名,模版)
        request.putQueryParameter("PhoneNumbers", "手机号"); //手机号
        request.putQueryParameter("SignName", ""); //签名
        request.putQueryParameter("TemplateCode", ""); //模版

//        构建短信验证码
        HashMap<Object, Object> map = new HashMap<Object, Object>();
        map.put("code",1122);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));//验证码


        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }

accessKeyID Password
Springboot实现短信验证码功能(阿里云)_第1张图片
一般使用子用户创建
Springboot实现短信验证码功能(阿里云)_第2张图片
Password为对应的密码 如图所示 在你创建时给你一定要保存
Springboot实现短信验证码功能(阿里云)_第3张图片

Sign 在这里插入图片描述

TemplateCode
在这里插入图片描述

3.可以封装为一个接口,方便以后的调用

注:

private final static String accessKeyID = “”;
private final static String Password = “”;
private final static String Sign = “”;
private final static String TemplateCode = “”;

一定要填写自己的,这里我都设为null了



public interface sendsms {
    Boolean sendMessage(String phone,HashMap<String,Object> code);
}

/**
 * @author Fluency
 * @creat 2021-01
 */
@Service
public class sendmessage implements sendsms {
  //为了方便写在这里,也可以放在配置文件或者特定的类中 一般放在常量类中
    private  final static String accessKeyID = ""; 
    private  final static String Password = "";
    private  final static String Sign = "";
    private  final static String TemplateCode = "";


    @Override
    public Boolean sendMessage(String phone,  HashMap<String, Object> code) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyID, Password);
        IAcsClient client = new DefaultAcsClient(profile);
//构建请求 setSysDomain  setSysAction  不要改
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
//        自定义参数 (手机号,验证码,签名,模版)
        request.putQueryParameter("PhoneNumbers", phone); //手机号
        request.putQueryParameter("SignName", Sign); //签名
        request.putQueryParameter("TemplateCode", TemplateCode); //模版
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));//验证码


        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return true;
        }catch (ServerException e){
              e.printStackTrace();
        }
        catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

}

注:在类中调用sendSms接口是一定要先注入Service

@Autowired
private sendSms sendSms;

生成验证码的工具类(4位,包含字母)

/**
 * @author Fluency
 * @creat 2021-01
 */
public class GenerateWord {
    public String generateWord() {
        String[] beforeShuffle = new String[] { "0","1","2", "3", "4", "5", "6", "7",
                "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
                "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z" };
        List list = Arrays.asList(beforeShuffle);
        Collections.shuffle(list);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
        }
        String afterShuffle = sb.toString();
        String result = afterShuffle.substring(5, 9);
        return result;
    }
}

我的实际调用代码(一定要@Autowired) 初学者 仅供参考 这里的Result是我自定义的一个返回结果封装类

 @Override
    public Result sendSms(String account, String userPhone) {
        //验证 用户名和手机号是否匹配
        if (userMapper.queryUserByAccount(account).getUserPhone().equals(userPhone) ){
            GenerateWord generateWord = new GenerateWord();
            verCode = generateWord.generateWord();
            HashMap<String, Object> map = new HashMap<>();
            map.put("code",verCode);
          	//放入生成的随机数 和 手机号
            Boolean message = sendSms.sendMessage(userPhone,map);
            if (message){
                return Result.ok("发送验证码成功!");
            }else {
                return Result.fail("发送验证码失败");
            }
        }else {
            return  Result.fail("用户名和手机号不匹配~请核对后重新输入");
        }
    }

你可能感兴趣的:(SpringBoot,阿里云,java)