SpringBoot 整合 发送阿里云SMS短信验证码

本页目录

SpringBoot 整合 发送阿里云SMS短信验证码_第1张图片

常规Maven依赖


            org.jsoup
            jsoup
            1.12.1
        

        
            cn.hutool
            hutool-all
            5.7.3
        
        
        
            javax.mail
            mail
            1.5.0-b01
        

AliSMSUtils工具类

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.util.Date;

/**
 * 官方 get请求 代码在这里:https://help.aliyun.com/document_detail/101343.htm?spm=a2c4g.11186623.2.4.792731cbursOI1#t83667.html
 * 本工具类需要 Hutool、Lombok的Maven jar依赖
 */
@Slf4j
public class AliSMSUtils {


    public static void main(String[] args) {
        try {
            AliSMSUtils.sendSMS("17356261979", "SMS_218890333", "000000");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param number    手机号
     * @paramregisterTemplateCode 模版CODE 在阿里云短信服务里面查找
     * @param checkCode 验证码
     * @return 返回短信验证码请求阿里SMS接口后返回的内容
     * @throws Exception
     */

    public static Boolean sendSMS(String number, String registerTemplateCode, String checkCode) throws Exception {
        number = "17356261979";
        registerTemplateCode = "SMS_218890333";
        checkCode = "000000";
        String accessKeyId = "LTAI5tK8kiHaum6T59MZSX55";
        String accessSecret = "A9SRz4u0CwBxtqtzCmip46pQ7o2Qvm";
        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));// 这里一定要设置GMT时区
        java.util.Map paras = new java.util.HashMap();
        // 1. 系统参数
        paras.put("SignatureMethod", "HMAC-SHA1");
        paras.put("SignatureNonce", java.util.UUID.randomUUID().toString());
        paras.put("AccessKeyId", accessKeyId);
        paras.put("SignatureVersion", "1.0");
        paras.put("Timestamp", df.format(new Date()));
        paras.put("Format", "XML");
        // 2. 业务API参数
        paras.put("Action", "SendSms");
        paras.put("Version", "2017-05-25");
        paras.put("RegionId", "cn-hangzhou");
        paras.put("PhoneNumbers", number);
        paras.put("SignName", "合肥讯聊科技有限公司");// 签名也是阿里云短信服务里面查找
        paras.put("TemplateParam", "{\"code\":" + " \"" + checkCode + "\"" +"}");
        paras.put("TemplateCode", registerTemplateCode);
        paras.put("OutId", "123");
        // 3. 去除签名关键字Key
        if(paras.containsKey("Signature")){
            paras.remove("Signature");
        }
        System.out.println(paras.get("TemplateParam"));
        // 4. 参数KEY排序
        java.util.TreeMap sortParas = new java.util.TreeMap();
        sortParas.putAll(paras);
        // 5. 构造待签名的字符串
        java.util.Iterator it = sortParas.keySet().iterator();
        StringBuilder sortQueryStringTmp = new StringBuilder();
        while (it.hasNext()) {
            String key = it.next();
            sortQueryStringTmp.append("&").append(specialUrlEncode(key)).append("=").append(specialUrlEncode(paras.get(key)));
        }
        String sortedQueryString = sortQueryStringTmp.substring(1);// 去除第一个多余的&符号
        StringBuilder stringToSign = new StringBuilder();
        stringToSign.append("GET").append("&");
        stringToSign.append(specialUrlEncode("/")).append("&");
        stringToSign.append(specialUrlEncode(sortedQueryString));
        String sign = sign(accessSecret + "&", stringToSign.toString());
        // 6. 签名最后也要做特殊URL编码
        String signature = specialUrlEncode(sign);
        /*
        System.out.println(paras.get("SignatureNonce"));
        System.out.println("\r\n=========\r\n");
        System.out.println(paras.get("Timestamp"));
        System.out.println("\r\n=========\r\n");
        System.out.println(sortedQueryString);
        System.out.println("\r\n=========\r\n");
        System.out.println(stringToSign.toString());
        System.out.println("\r\n=========\r\n");
        System.out.println(sign);
        System.out.println("\r\n=========\r\n");
        System.out.println(signature);
        System.out.println("\r\n=========\r\n");
        */
        String url = "http://dysmsapi.aliyuncs.com/?Signature=" + signature + sortQueryStringTmp;
        // 最终打印出合法GET请求的URL
        //System.out.println(url);
        // 发送请求,并进行解析
        String s = HttpUtil.get(url);
        // Jsoup 包下的 Document 、 Jsoup
        Document parse = Jsoup.parse(s);
        if ("OK".equals(parse.select("Code").get(0).text())) {
            log.info(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + number + "  的短信发送成功");
            return true;
        } else {
            log.error(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + " " + number + " 短信发送失败,原因:" + parse.select("Message").get(0).text());
            return false;
        }
    }


    public static String specialUrlEncode(String value) throws Exception {
        return java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
    }

    public static String sign(String accessSecret, String stringToSign) throws Exception {
        javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
        mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return new sun.misc.BASE64Encoder().encode(signData);
    }
}

完成!

特殊说明: 以上文章,均是我实际操作,写出来的笔记资料,不会盗用别人文章!烦请各位,请勿直接盗用!转载记得标注来源!
收_心
永久会员
打赏 收藏 海报 链接

你可能感兴趣的:(spring,boot,java,spring,tomcat,后端)