java集成阿里云短信

252 阅读2分钟

阿里云短信验证码

前置

  1. 开通阿里云短信服务(直接在产品里搜索短信)
  2. 获取Accesskey
  3. 创建accessKey 注意保存好id和 secret信息
  4. 打开控制台设置手机号
  5. 点击测试,收到信息即成功

代码实战

步骤

  1. 引入sdk
  2. 初始化配置对象 com.aliyun.teaopenapi.models.Config 。
  3. 设置请求的签名模板
  4. 发送请求

代码

sdk

<dependency>
			<groupId>com.aliyun</groupId>
			<artifactId>dysmsapi20170525</artifactId>
			<version>2.0.24</version>
		</dependency>

工具类,用于初始化

/**
 * 短信发送工具类
 */
public class SMSUtils {
    public static final String ALIBABA_CLOUD_ACCESS_KEY_ID = "xxxxx";
    public static final String ALIBABA_CLOUD_ACCESS_KEY_SECRET = "xxxxx";

    /**
     * 使用AK&SK初始化Client
     * 使用客户端去发送短信
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return
     * @throws Exception
     */
    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 必填,您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填,您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名 固定写法
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 向指定手机号发送短信
     *
     * @param signName     签名
     * @param templateCode 模板
     * @param phoneNumbers 手机号
     * @param param        参数 ---验证码
     */
    public static void sendMessage(String signName, String templateCode, String phoneNumbers, String param) throws Exception {
        // 获取客户端对象
        Client client = createClient(ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET);
        // 获取发送短信对象 设置发送短信的 签名,模板,手机号,验证码
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        request.setPhoneNumbers(phoneNumbers);
        request.setTemplateParam("{"code":"" + param + ""}");
        // 运行时行为  例如最大尝试次数,超时时间等等
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 根据信息发送短信
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(request, runtime);
            System.out.println(new Gson().toJson(sendSmsResponse.body));
        } catch (TeaException error) {
            // 如有需要,请打印 error
            System.out.println(error);
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要,请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }


    /**
     * 随机数
     */
    public static String randomNum() {
        // 获得四位的随机整数
        return RandomUtil.randomNumbers(4);
    }

    public static void main(String[] args) {
        System.out.println(randomNum());
    }
}

请求

@RestController
@Slf4j
public class MSMController {
    @PostMapping("/sendMsg")
    public String sendMsg(@RequestBody String phone) throws Exception {
        // 获取手机号
        if (StringUtils.isNotEmpty(phone)) {
            // 生成随机的4位验证码
            String code = SMSUtils.randomNum();
            log.info("code={}", code);
            log.info("开始发送");
            // 调用阿里云提供的短信服务API完成发送短信
            SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", phone, code);
            log.info("发送完成");
            // 将生成的验证码缓存到Redis中,并且设置有效期为5分钟
            // redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return "手机验证码发送成功";
        }
        return "验证码发送失败";
    }

    // 为了方便直接本地测试
    public static void main(String[] args) throws Exception {
        MSMController msmController = new MSMController();
        msmController.sendMsg("测试手机号,注意如果使用的是SMS_154950909测试的模板,只能使用设置了测试校验的手机号");
    }
}

失败

成功

业务中,登录或者其他,根据redis中或者数据库中的验证码 和用户输入的进行校验。