Realize the function of receiving mobile phone verification code based on SpringBoot+Tencent Cloud SMS service

  1. Configure the required services in Tencent Cloud
  2. Apply for signature and SMS templates
  3. create application
  4. Configure related parameters in project application.yml
  5. Install the dependency package of Tencent Cloud SMS service in the project
    <!--腾讯云-->
            <dependency>
                <groupId>com.github.qcloudsms</groupId>
                <artifactId>qcloudsms</artifactId>
                <version>1.0.6</version>
            </dependency>

  6. Create a SmsConstantUtil tool class to get the parameters in the configuration file
    
    
    import org.springframework.beans.factory.InitializingBean;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.stereotype.Component;
    
    
    /*
    *腾讯云短信服务 */
    @Component
    @PropertySource("classpath:application.yml")
    public class SmsConstantUtil implements InitializingBean {
    
      @Value("${tencent.appid}")
      private Integer APPID;
    
      @Value("${tencent.appkey}")
      private String APPKEY;
    
      @Value("${tencent.templateId}")
      private Integer TEMPLATEID;
    
      @Value("${tencent.signname}")
      private String SIGNNAME;
    
      public static Integer APP_ID;
      public static String APP_KEY;
      public static Integer TEMPLATE_ID;
      public static String SIGN_NAME;
    
    
    
      @Override
      public void afterPropertiesSet() throws Exception {
        APP_ID = APPID;
        APP_KEY = APPKEY;
        TEMPLATE_ID = TEMPLATEID;
        SIGN_NAME = SIGNNAME;
      }
    }
    

  7. Create a service and implementation class to implement the corresponding function
    ps: here the required parameters are encapsulated
    @Data
    @Component
    public class SmsCodeVo {
      private String phone;
      private String code;
    }

    SmsService:

    public interface SmsService {
    
      Result sendCode(SmsCodeVo smsCodeVo);
    }

    SmsServiceImpl:

    @Service
    public class SmsServiceImpl implements SmsService {
      @Autowired
      SmsCodeVo smsCodeVo;
    
      @Autowired
      RedisTemplate<String, String> redisTemplate;
    
    
      @Override
      public Result sendCode(SmsCodeVo smsCodeVo) {
    //    获取配置信息
        Integer appId = SmsConstantUtil.APP_ID;
        String appKey = SmsConstantUtil.APP_KEY;
        Integer templateId = SmsConstantUtil.TEMPLATE_ID;
        String signName = SmsConstantUtil.SIGN_NAME;
    
        if (StringUtils.isBlank(smsCodeVo.getPhone())){
          return Result.error(ErrorCode.PARAMS_NULL.getCode(),ErrorCode.PARAMS_NULL.getMsg());
        }
    //    获取手机号
         String phone = smsCodeVo.getPhone();
    //    生成验证码
        String verifyCode = vcode();
        smsCodeVo.setCode(verifyCode);
    //    存入redis
        redisTemplate.opsForValue().set(phone,verifyCode.replaceAll("[[\\s-:punct:]]", ""), 300, TimeUnit.SECONDS);
        try{
          String[] params = {smsCodeVo.getCode()}; //短信中的参数
          SmsSingleSender ssender = new SmsSingleSender(appId, appKey);
          SmsSingleSenderResult result = ssender.sendWithParam("86", smsCodeVo.getPhone(), templateId,
                  params, signName, "", "");
    //      打印返回结果
          System.out.println(result);
          if (result.result == 0){
            return  Result.success(200,"发送成功");
          }
          if (result.result == 1025){
            return Result.error(1025,"验证码已经发上限制!!!,请稍后再试");
          }
        } catch (HTTPException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
    
        return Result.error(400,"发送失败");
      }
    
      /**
      * 生成6位随机短信验证码
      */
      public static String vcode(){
        String vcode = "";
        for (int i = 0;i <6;i++){
          vcode = vcode + (int) (Math.random()*9);
        }
        return vcode;
      }
    
    }

  8. Implement the call function in the controller controller
    @RestController
    @Controller
    @Api(tags = "短信模块")
    @CrossOrigin
    public class SmsController {
    
      @Autowired
      SmsService smsService;
    
      @PostMapping("/sendCode")
      @ApiOperation(value = "发送短信验证码")
      public Result sendCode(@RequestBody SmsCodeVo smsCodeVo){
        return smsService.sendCode(smsCodeVo);
      }
    
    
    
    }
    

  9. Start the project, test the function
  10. The mobile phone receives as follows:

 

Guess you like

Origin blog.csdn.net/weixin_44030860/article/details/122631439