首页 > 编程语言 > 详细

Spring Boot 发送验证码

时间:2020-09-06 21:31:35      阅读:76      评论:0      收藏:0      [点我收藏+]

前期准备

这里我使用的是阿里云的短信服务来发送短信,因此,需要先开通短信服务。
可以参考我的这篇文章 Java实现发送手机验证码,发送短信

Spring Boot 集成

  • 添加依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- 短信  SDK-->
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.5.1</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
  • 配置
# 如果有中文,在赋值时可能出现中文乱码
sms.accessKeyId=你的accessKeyId
sms.accessKeySecret=你的accessKeySecret
sms.signName=你的signName
sms.templateCode=你的signName
  • SmsBean.java
@JsonIgnoreProperties(ignoreUnknown = true)
public class SmsBean {
    private String code;
    private String message;
    private String requestid;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getRequestid() {
        return requestid;
    }

    public void setRequestid(String requestId) {
        this.requestid = requestId;
    }

    @Override
    public String toString() {
        return "SmsBean{" +
                ", code=‘" + code + ‘\‘‘ +
                ", message=‘" + message + ‘\‘‘ +
                ", requestId=‘" + requestid + ‘\‘‘ +
                ‘}‘;
    }
}
  • SmsTemplate.java
@Component
@ConfigurationProperties(prefix = "sms")
public class SmsTemplate {
    private String accessKeyId;
    private String accessKeySecret;
    // 如果在 signName 出现中文,则通过配置文件读取时可能出现中文乱码
    // 因此,可以在此进行初始化
    private String signName = "";
    private String templateCode;

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    public String getSignName() {
        return signName;
    }

    public void setSignName(String signName) {
        this.signName = signName;
    }

    public String getTemplateCode() {
        return templateCode;
    }

    public void setTemplateCode(String templateCode) {
        this.templateCode = templateCode;
    }

    /**
     * 生成 6 位随机码
     * @return 验证码
     */
    public String getCode() {
        return String.valueOf(new Random().nextInt(899999) + 100000);
    }

    /**
     * 发送验证码
     * @param telphone 接收方
     * @return 发送状态;ok 表示成功
     */
    public String sendSms(String telphone) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, 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("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", telphone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{\"code\":" + getCode() + "}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            ObjectMapper objectMapper = new ObjectMapper();
            SmsBean smsBean = objectMapper.readValue(response.getData().toLowerCase(), SmsBean.class);
            return smsBean.getCode();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

  • SmsController.java
@RestController
@RequestMapping("/sms")
public class SmsController {
    @Autowired
    private SmsTemplate smsTemplate ;

    // 使用正则表达式,将路径变量的值保存在 telphone 中
    // 如请求 /send/123456,则相当于 telphone=123456
    @GetMapping("/send/{telphone:.+}")
    public String sendSms(@PathVariable String telphone) {
        String code = smsTemplate.sendSms(telphone);
        if ("ok".equals(code)) {
            return "{\"code\":" + code + "}";
        }
        return "{\"code\":\"fail\"}";
    }
}

然后运行项目,访问 localhost:8080/sms/send/xxx,其中 xxx 是接收验证码的手机号

Spring Boot 发送验证码

原文:https://www.cnblogs.com/daijf/p/13623431.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!