SpringBoot中发送短信验证码

短信验证码在今天已经普遍用于各类软件中,主要用户身份验证,注册、登录等,那今天就来学习一下如何在 SpringBoot 中发送短信验证码,这里我使用的是 榛子云

  • 1、首先,我们需要注册 榛子云 平台的开发账号,获取应用信息
注册地址:http://sms_developer.zhenzikj.com/zhenzisms_user/register.html

这里用于测试,我注册了个人开发账户
应用信息
点开详情,我们可以对其应用进行设置
应用详情

<!-- 榛子云短信平台 -->
<dependency>
	<groupId>com.zhenzikj</groupId>
	<artifactId>zhenzisms</artifactId>
	<version>1.0.4</version>
</dependency>
<!-- alibaba的fastjson -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.51</version>
</dependency>

zhenzisms 是榛子云 所需要的依赖包,fastjson 是用来转换 json 对象的,其他的请自行添加

  • 4、将应用信息放置 SpringBoot 的配置信息中
# 榛子云短信平台
sms:
  verific:
    # 请求地址
    apiurl: https://sms_developer.zhenzikj.com
    # appid
    appid: xxxxxx
    # appsecret
    appsecret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  • 5、Controller 代码
/**
 * 手机验证码登录
 */
@RequestMapping("/sendSmsLogin")
private String sendSmsLogin(String phone) {
    try {
        return service.sendCode(phone.trim());
    } catch (Exception e) {
        JSONObject res = new JSONObject();
        res.put("code", 0);
        res.put("msg", "短信验证码接口异常");
        return res.toJSONString();
    }
}
  • 6、Service 代码
/**
 * 平台中提供的 appid 和 appsecret
 */
@Value("${sms.verific.appid}")
public String APPID;
@Value("${sms.verific.appsecret}")
public String APPKEY;
@Value("${sms.verific.apiurl}")
public String URL;

/**
 * 发送四位随机数字验证码
 *  * @param phone
 * @throws Exception
 */
public String sendCode(String phone) throws Exception {
	JSONObject res = new JSONObject();
    if (StringUtils.isEmpty(phone)) {
        res.put("code", 0);
        res.put("msg", "手机号码不能为空");
        return res.toJSONString();
    }
    if (!PhoneUtil.isMobileNumber(phone)) {
        res.put("code", 0);
        res.put("msg", "请输入有效的手机号码");
        return res.toJSONString();
    }
    // 创建发送短信对象
    ZhenziSmsClient client = new ZhenziSmsClient(URL, APPID, APPKEY);
    String code = RandomUtils.number(4);
    // 创建map存放请求参数
    Map<String, String> params = new HashMap<>();
    params.put("message", "您的验证码:" + code + ",验证码在5分钟内有效。");
    params.put("number", phone);
    // 发送验证码,获取响应信息,0--成功,其他--失败
    String response = client.send(params);
    // 将响应信息转为json对象
    JSONObject respJson = JSONObject.parseObject(response);
    // 如果发送成功,就将电话号码和验证码保存至session
    if ("0".equals(respJson.getString("code"))) {
        session.setAttribute("code", code);
        session.setAttribute("phone", phone);
    }
    // 组装返回信息
    res.put("code", "0".equals(respJson.getString("code")) ? 1 : respJson.getString("code"));
    res.put("msg", respJson.getString("data"));
    return res.toJSONString();
}
  • 7、检验手机号码的合法性 PhoneUtil.java
/**
 * 验证手机号是否合法
 *  * @return
 */
public static boolean isMobileNumber(String number) {
    if (StringUtils.isEmpty(number)) {
        return false;
    }
    if (11 != number.length()) {
        return false;
    }
    /**
     * 移动号段正则表达式
     */
    String pat1 = "^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    /**
     * 联通号段正则表达式
     */
    String pat2 = "^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    /**
     * 电信号段正则表达式
     */
    String pat3 = "^((133)|(153)|(177)|(18[0,1,9])|(149))\\d{8}$";
    /**
     * 虚拟运营商正则表达式
     */
    String pat4 = "^((170))\\d{8}|(1718)|(1719)\\d{7}$";

    Pattern pattern1 = Pattern.compile(pat1);
    Matcher match1 = pattern1.matcher(number);
    boolean isMatch1 = match1.matches();
    if (isMatch1) {
        return true;
    }
    Pattern pattern2 = Pattern.compile(pat2);
    Matcher match2 = pattern2.matcher(number);
    boolean isMatch2 = match2.matches();
    if (isMatch2) {
        return true;
    }
    Pattern pattern3 = Pattern.compile(pat3);
    Matcher match3 = pattern3.matcher(number);
    boolean isMatch3 = match3.matches();
    if (isMatch3) {
        return true;
    }
    Pattern pattern4 = Pattern.compile(pat4);
    Matcher match4 = pattern4.matcher(number);
    boolean isMatch4 = match4.matches();
    if (isMatch4) {
        return true;
    }
    return false;
}
  • 8、生成随机验证码工具 RandomUtils.java
/**
 * 用于随机选的数字
 */
public static final String NUMBERCHAR = "0123456789";

/**
 * 返回固定长度的随机数字
 * @param length 长度
 * @return 随机数
 */
public static String number(int length) {
	StringBuilder sb = new StringBuilder();
	Random random = new Random();
	for (int i = 0; i < length; i++) {
		sb.append(NUMBERCHAR.charAt(random.nextInt(NUMBERCHAR.length())));
	}
	return sb.toString();
}
  • 9、开发文档
http://smsow.zhenzikj.com/doc/java_sdk_doc.html
  • 10、错误代码表

错误代码表
如您在阅读中发现不足,欢迎留言!!!

发布了71 篇原创文章 · 获赞 127 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40065776/article/details/104951834