发送短信验证码分析

哈哈 阅读:189 2021-06-15 12:13:44 评论:0
package com.example.demo; 
 
import java.time.LocalDateTime; 
 
public class SmsCode { 
 
    private String code; 
 
    private LocalDateTime expireTime; 
 
    public SmsCode(String code, int expireIn) { 
        this.code = code; 
        this.expireTime = LocalDateTime.now().plusSeconds(expireIn); 
    } 
 
    public SmsCode(String code, LocalDateTime expireTime) { 
        this.code = code; 
        this.expireTime = expireTime; 
    } 
 
    public boolean isExpire(){ 
        return LocalDateTime.now().isAfter(expireTime); 
    } 
 
    public String getCode() { 
        return code; 
    } 
 
    public void setCode(String code) { 
        this.code = code; 
    } 
 
    public LocalDateTime getExpireTime() { 
        return expireTime; 
    } 
 
    public void setExpireTime(LocalDateTime expireTime) { 
        this.expireTime = expireTime; 
    } 
}
import org.springframework.web.context.request.ServletWebRequest; 
 
 
public interface ValidateCodeGenerator { 
 
    ValidateCode generate(ServletWebRequest request); 
     
}
import org.apache.commons.lang.RandomStringUtils; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Component; 
import org.springframework.web.context.request.ServletWebRequest; 
 
import com.imooc.security.core.properties.SecurityProperties; 
import com.imooc.security.core.validate.code.ValidateCode; 
import com.imooc.security.core.validate.code.ValidateCodeGenerator; 
 
@Component("smsValidateCodeGenerator") 
public class SmsCodeGenerator implements ValidateCodeGenerator { 
 
    @Autowired 
    private SecurityProperties securityProperties; 
     
    @Override 
    public ValidateCode generate(ServletWebRequest request) { 
        String code = RandomStringUtils.randomNumeric(securityProperties.getCode().getSms().getLength()); 
        return new ValidateCode(code, securityProperties.getCode().getSms().getExpireIn()); 
    } 
 
    public SecurityProperties getSecurityProperties() { 
        return securityProperties; 
    } 
 
    public void setSecurityProperties(SecurityProperties securityProperties) { 
        this.securityProperties = securityProperties; 
    } 
     
     
 
}
package com.example.controller; 
 
import com.example.valicate.SmsCode; 
import com.example.valicate.ValidateCode; 
import com.example.valicate.ValidateCodeGenerator; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.GetMapping; 
import org.springframework.web.context.request.ServletWebRequest; 
 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import java.io.IOException; 
 
@Controller 
public class ValidateCodeController { 
    @Autowired 
    private ValidateCodeGenerator smsCodeGenerator; 
 
    @GetMapping("/code/sms") 
    private void CreateSmsCode(HttpServletRequest request, HttpServletResponse response) throws IOException{ 
//        SmsCode smsCode = smsCodeGenerator.generate(new ServletWebRequest(request)); 
        ValidateCode smsCode = smsCodeGenerator.generate(new ServletWebRequest(request)); 
    } 
 
}
<dependency> 
  <groupId>com.aliyun</groupId> 
  <artifactId>aliyun-java-sdk-core</artifactId> 
  <version>4.0.6</version> <!-- 注:如提示报错,先升级基础包版,无法解决可联系技术支持 --> 
</dependency> 
 
<dependency> 
<groupId>com.aliyun</groupId> 
<artifactId>aliyun-java-sdk-dysmsapi</artifactId> 
<version>1.1.0</version> 
</dependency>
import com.aliyuncs.DefaultAcsClient; 
import com.aliyuncs.IAcsClient; 
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; 
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; 
import com.aliyuncs.exceptions.ClientException; 
import com.aliyuncs.profile.DefaultProfile; 
import com.aliyuncs.profile.IClientProfile; 
import com.yq.model.SmsCode; 
import com.yq.vo.ErpSystemConfigVO; 
import lombok.extern.slf4j.Slf4j; 
 
/** 
 * @author: wensm 
 * @date: 2021/5/29 0029 
 * @description: TODO 
 **/ 
@Slf4j 
public class SmsUtils { 
    // 产品名称:云通信短信API产品,开发者无需替换 
    static final String product = "Dysmsapi"; 
    // 产品域名,开发者无需替换 
    static final String domain = "dysmsapi.aliyuncs.com"; 
 
    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找) 
//    static final String accessKeyId = "youaccessKeyId";           // TODO 改这里 
    static final String accessKeyId = "LTAI5t61GGJVrtQL9GZ5eZCC";           // TODO 改这里 
//    static final String accessKeySecret = "youaccessKeySecret"; // TODO 改这里 
    static final String accessKeySecret = "ed9InMof5lPuZXD3aN03GcH3mcqpDD"; // TODO 改这里 
 
    public static SendSmsResponse sendSms(String telephone, String code) throws ClientException { 
        // 可自助调整超时时间 
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); 
        System.setProperty("sun.net.client.defaultReadTimeout", "10000"); 
 
        // 初始化acsClient,暂不支持region化 
        IClientProfile profile = DefaultProfile.getProfile("cn-heyuan", accessKeyId, accessKeySecret); 
        DefaultProfile.addEndpoint("cn-heyuan", "cn-heyuan", product, domain); 
        IAcsClient acsClient = new DefaultAcsClient(profile); 
 
        // 组装请求对象-具体描述见控制台-文档部分内容 
        SendSmsRequest request = new SendSmsRequest(); 
        // 必填:待发送手机号 
        request.setPhoneNumbers(telephone); 
        // 必填:短信签名-可在短信控制台中找到 
        request.setSignName("XX信息"); // TODO 改这里 
        // 必填:短信模板-可在短信控制台中找到 
        request.setTemplateCode("SMS_217795888");  // TODO 改这里 
        // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的用户,您的验证码为${code}"时,此处的值为 
        request.setTemplateParam("{\"code\":\"" + code + "\"}"); 
 
        // 选填-上行短信扩展码(无特殊需求用户请忽略此字段) 
        // request.setSmsUpExtendCode("90997"); 
 
        // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 
//        request.setOutId("yourOutId"); 
 
        // hint 此处可能会抛出异常,注意catch 
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); 
        if(sendSmsResponse.getCode()!= null && sendSmsResponse.getCode().equals("OK")){ 
            System.out.println("短信发送成功!"); 
        }else { 
            System.out.println("短信发送失败!"); 
        } 
        return sendSmsResponse; 
    } 
 
    public static SendSmsResponse sendSmsCode(ErpSystemConfigVO erpSystemConfigVO, SmsCode smsCode) throws ClientException  { 
        String regionId = erpSystemConfigVO.getRegionId(); 
        String accessId = erpSystemConfigVO.getAccessId(); 
        String accessKey = erpSystemConfigVO.getAccessKey(); 
        String dysmsapi = erpSystemConfigVO.getDysmsApi(); 
        String endpoint = erpSystemConfigVO.getEndpoint(); 
        String signName = erpSystemConfigVO.getSignName(); 
        String sendSms = erpSystemConfigVO.getSendSms(); 
 
        // 可自助调整超时时间 
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); 
        System.setProperty("sun.net.client.defaultReadTimeout", "10000"); 
 
        // 初始化acsClient,暂不支持region化 
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessId, accessKey); 
        DefaultProfile.addEndpoint(regionId, regionId, dysmsapi, endpoint); 
        IAcsClient acsClient = new DefaultAcsClient(profile); 
 
        // 组装请求对象-具体描述见控制台-文档部分内容 
        SendSmsRequest request = new SendSmsRequest(); 
        // 必填:待发送手机号 
        request.setPhoneNumbers(smsCode.getMobilePhone()); 
        // 必填:短信签名-可在短信控制台中找到 
        request.setSignName(signName); // TODO 改这里 
        // 必填:短信模板-可在短信控制台中找到 
        request.setTemplateCode(sendSms);  // TODO 改这里 
        // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的用户,您的验证码为${code}"时,此处的值为 
//        SMS_217795312 
//        您的验证码${code},该验证码5分钟内有效,请勿泄漏于他人! 
//        SMS_217416123 
//        验证码:${code}您正在找回密码,请不要把验证码泄露给其他人。如非本人操作,可不用理会! 
        request.setTemplateParam("{\"code\":\"" + smsCode.getCode() + "\"}"); 
 
        // 选填-上行短信扩展码(无特殊需求用户请忽略此字段) 
        // request.setSmsUpExtendCode("90997"); 
 
        // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 
//        request.setOutId("yourOutId"); 
 
        // hint 此处可能会抛出异常,注意catch 
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); 
        if(sendSmsResponse.getCode()!= null && sendSmsResponse.getCode().equals("OK")){ 
            log.info("=======短信发送成功!======"); 
//            System.out.println("短信发送成功!"); 
        }else { 
            log.info("=======短信发送失败!======"); 
//            System.out.println("短信发送失败!"); 
        } 
        return sendSmsResponse; 
    } 
 
    public static SendSmsResponse sendPwdSmsCode(ErpSystemConfigVO erpSystemConfigVO, SmsCode smsCode) throws ClientException { 
        String regionId = erpSystemConfigVO.getRegionId(); 
        String accessId = erpSystemConfigVO.getAccessId(); 
        String accessKey = erpSystemConfigVO.getAccessKey(); 
        String dysmsapi = erpSystemConfigVO.getDysmsApi(); 
        String endpoint = erpSystemConfigVO.getEndpoint(); 
        String signName = erpSystemConfigVO.getSignName(); 
        String sendSms = erpSystemConfigVO.getSendSms(); 
 
        // 可自助调整超时时间 
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); 
        System.setProperty("sun.net.client.defaultReadTimeout", "10000"); 
 
        // 初始化acsClient,暂不支持region化 
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessId, accessKey); 
        DefaultProfile.addEndpoint(regionId, regionId, dysmsapi, endpoint); 
        IAcsClient acsClient = new DefaultAcsClient(profile); 
 
        // 组装请求对象-具体描述见控制台-文档部分内容 
        SendSmsRequest request = new SendSmsRequest(); 
        // 必填:待发送手机号 
        request.setPhoneNumbers(smsCode.getMobilePhone()); 
        // 必填:短信签名-可在短信控制台中找到 
        request.setSignName(signName); // TODO 改这里 
        // 必填:短信模板-可在短信控制台中找到 
        request.setTemplateCode(sendSms);  // TODO 改这里 
        // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的用户,您的验证码为${code}"时,此处的值为 
//        request.setTemplateParam("{\"code\":\"" + smsCode.getCode() + "\"}"); 
//        SMS_217436152 
//        您的${phone}账户已注册,初始密码为${password},请尽快登录平台修改您的密码。如非本人操作,可不用理会! 
        request.setTemplateParam("{\"phone\":\"" + smsCode.getMobilePhone() + "\",\"password\":\"" + smsCode.getPassword() + "\"}"); 
 
        // 选填-上行短信扩展码(无特殊需求用户请忽略此字段) 
        // request.setSmsUpExtendCode("90997"); 
 
        // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 
//        request.setOutId("yourOutId"); 
 
        // hint 此处可能会抛出异常,注意catch 
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); 
        if(sendSmsResponse.getCode()!= null && sendSmsResponse.getCode().equals("OK")){ 
            log.info("=======短信发送成功!======"); 
//            System.out.println("短信发送成功!"); 
        }else { 
            log.info("=======短信发送失败!======"); 
//            System.out.println("短信发送失败!"); 
        } 
        return sendSmsResponse; 
    } 
 
    //以下为测试代码,随机生成验证码 
//    private static int newcode; 
//    public static int getNewcode() { 
//        return newcode; 
//    } 
//    public static void setNewcode(){ 
//        newcode = (int)(Math.random()*9999)+100;  //每次调用生成一次四位数的随机数 
//    } 
//    public static void main(String[] args) throws Exception { 
//        setNewcode(); 
//        String code = Integer.toString(getNewcode()); 
//        SendSmsResponse sendSms =sendSms("测试手机号码",code);//填写你需要测试的手机号码 
//        System.out.println("短信接口返回的数据----------------"); 
//        System.out.println("Code=" + sendSms.getCode()); 
//        System.out.println("Message=" + sendSms.getMessage()); 
//        System.out.println("RequestId=" + sendSms.getRequestId()); 
//        System.out.println("BizId=" + sendSms.getBizId()); 
//    } 
}

标签:Spring Boot
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

发表评论
搜索
KIKK导航

KIKK导航

排行榜
关注我们

一个IT知识分享的公众号