使用阿里云短信发送验证码

    技术2023-04-08  85

    1,目录结构

    2,相关依赖

    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.72</version> </dependency> <!-- 阿里云发送短息相关 aliyun-java-sdk-core --> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.5.2</version> </dependency>

    3,配置类

    定义了连接阿里云的key秘钥等信息

    @Component @PropertySource({"classpath:oss.properties"}) public class OSSConfig implements InitializingBean { // Endpoint以青岛为例,其它Region请按实际情况填写。 @Value("${endpoint}") private String endpoint; @Value("${accessKeyId}") private String accessKeyId; @Value("${accessKeySecret}") private String accessKeySecret; public static String ENDPOINT; public static String ACCESSKEYID; public static String ACCESSKEYSECRET; @Override public void afterPropertiesSet() throws Exception { ENDPOINT=endpoint; ACCESSKEYID=accessKeyId; ACCESSKEYSECRET=accessKeySecret; } }

    4,controller

    发送成功后将验证码存在了redis缓存中,设置过期时间,每次发送前先读取,如果不存在就发送,存在就直接返回

    @Controller @CrossOrigin @RequestMapping("/msm") public class MsmController { @Autowired private MsmService msmService; @Autowired private RedisTemplate<String,String> redisTemplate; @GetMapping("/send/{phone}") @ResponseBody public String sendMsm(@PathVariable("phone") String phone){ //1,从redis中查询验证码 String code = redisTemplate.opsForValue().get(phone); if (!StringUtils.isEmpty(code)){ return "已发送"; } //2,没有就生成 code = RandomUtil.getFourBitRandom(); Map<String,Object> map = new HashMap<>(); map.put("code",code); Boolean success = msmService.sendMsm(map,phone); if (success){ redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES); return "成功"; } return "失败"; } }

    5,service发送短信

    @Service public class MsmServiceImpl implements MsmService { //发送短信 @Override public Boolean sendMsm(Map<String, Object> map, String phone) { if (StringUtils.isEmpty(phone)){ return false; } DefaultProfile profile = DefaultProfile.getProfile("default",OSSConfig.ACCESSKEYID,OSSConfig.ACCESSKEYSECRET); IAcsClient client = new DefaultAcsClient(profile); //设置参数(固定) 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","纵横江湖"); //阿里云申请的签名 request.putQueryParameter("TemplateCode","SMS_195190***");//申请的模板的code request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map)); //发送 try { CommonResponse response = client.getCommonResponse(request); boolean success = response.getHttpResponse().isSuccess(); return success; } catch (ClientException e) { e.printStackTrace(); } return false; } }
    Processed: 0.010, SQL: 9