(短信服务)java SpringBoot 阿里云短信功能实现发送手机验证码

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

一.阿里云准备工作

1.阿里云短信服务-注册账号

阿里云官网: https://www.aliyun.com/

点击官网首页注册按钮。

2.阿里云短信服务-设置短信签名阿里云提供测试的签名暂时可以跳过

注册成功后点击登录按钮进行登录。登录后进入短信服务管理页面选择国内消息菜单:

短信签名是短信发送者的署名表示发送方的身份。

3.阿里云短信服务-设置短信模板阿里云提供测试的模板暂时可以跳过

切换到【模板管理】标签页:

短信模板包含短信发送内容、场景、变量信息。

4.阿里云短信服务-设置AccessKey

光标移动到用户头像上在弹出的窗口中点击【AccessKey管理】∶

二、 代码开发

1.导入maven坐标

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.5.16</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
    <version>1.1.0</version>
</dependency>

2.封装发送短信工具类

public class SMSUtils {

	/**
	 * 发送短信
	 * @param signName 签名
	 * @param templateCode 模板
	 * @param phoneNumbers 手机号
	 * @param param 参数
	 */
	public static void sendMessage(String signName, String templateCode,String phoneNumbers,String param){
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "你的accessKeyId", "你的secret");
		IAcsClient client = new DefaultAcsClient(profile);

		SendSmsRequest request = new SendSmsRequest();
		request.setSysRegionId("cn-hangzhou");
		request.setPhoneNumbers(phoneNumbers);
		request.setSignName(signName);
		request.setTemplateCode(templateCode);
		request.setTemplateParam("{\"code\":\""+param+"\"}");
		try {
			SendSmsResponse response = client.getAcsResponse(request);
			System.out.println("短信发送成功");
		}catch (ClientException e) {
			e.printStackTrace();
		}
	}
}

3.调用发送验证码

/**
	 * 发送短信
	 * @param signName 签名
	 * @param templateCode 模板
	 * @param phoneNumbers 手机号
	 * @param param 参数
	 */
SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", "17303320963", "1234");

注意

因为如果自定义签名或者模板的话需要申请所以阿里云提供了可以测试的签名和模板

 4.到这里验证码已经可以发送了

 三、扩展生成验证码与上面的调用方法配合使用

1.封装随机生成验证码的工具类

public class ValidateCodeUtils {
    /**
     * 随机生成验证码
     * @param length 长度为4位或者6位
     * @return
     */
    public static Integer generateValidateCode(int length){
        Integer code =null;
        if(length == 4){
            code = new Random().nextInt(9999);//生成随机数最大为9999
            if(code < 1000){
                code = code + 1000;//保证随机数为4位数字
            }
        }else if(length == 6){
            code = new Random().nextInt(999999);//生成随机数最大为999999
            if(code < 100000){
                code = code + 100000;//保证随机数为6位数字
            }
        }else{
            throw new RuntimeException("只能生成4位或6位数字验证码");
        }
        return code;
    }

    /**
     * 随机生成指定长度字符串验证码
     * @param length 长度
     * @return
     */
    public static String generateValidateCode4String(int length){
        Random rdm = new Random();
        String hash1 = Integer.toHexString(rdm.nextInt());
        String capstr = hash1.substring(0, length);
        return capstr;
    }
}

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: SpringJava