springboot整合阿里雲短信

轉載請表明出處 https://blog.csdn.net/Amor_Leo/article/details/106843874 謝謝

springboot整合阿里雲短信

pom

        <!--阿里雲短信-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>2.1.0</version>
        </dependency>

YML

# 阿里短信
aliyun:
  sms:
    accessKeyId: xxxx
    accessKeySecret: xxxx
    templateCode: SMS_xxxx
    signName: xxx

業務層

@Override
    public boolean sendValidateCode(String mobile) {
        String code = createRandom(true, 6);
        String mobileKey = GlobalsConstants.MOBILE_KEY + mobile;
        long seconds = 3 * 60;
        //發送驗證碼到手機上
        boolean validateCode = sendMobleCode(code, mobile, mobileKey, seconds);
        if (!validateCode) {
            return false;
        }
        return true;
    }
    
//發送驗證碼到手機
    private boolean sendMobleCode(String code, String mobile, String mobileKey, long seconds) {
        boolean sms = aliyunSmsUtils.sendSms(mobile, code,mobileKey,seconds);
        return sms;
    }

   /**
     * 創建指定數量的隨機字符串
     *
     * @param numberFlag 是否是數字
     * @param length     長度
     * @return String
     */
    private String createRandom(boolean numberFlag, int length) {
        String retStr = "";
        String strTable = numberFlag ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);

        return retStr;
    }

工具類


/**
 * @Auther: LHL
 */
@Slf4j
@Component
public class AliyunSmsUtils {

    /**
     * 阿里雲 accessKeyId(安全信息管理下面)
     */
    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    /**
     * 阿里雲 accessKeySecret(安全信息管理下面)
     */
    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;


    /**
     * 阿里雲 templateCode
     */
    @Value("${aliyun.sms.templateCode}")
    private String templateCode;

    /**
     * 阿里雲 signName
     */
    @Value("${aliyun.sms.signName}")
    private String signName;

    /**
     * 短信API產品名稱(短信產品名固定,無需修改)
     */
    private static final String product = "Dysmsapi";

    /**
     * 短信API產品域名,接口地址固定,無需修改
     */
    private static final String domain = "dysmsapi.aliyuncs.com";


    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    public boolean sendSms(String phone, String code, String mobileKey, long seconds) {

        /* 超時時間,可自主調整 */
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        /* 初始化acsClient,暫不支持region化 */
        IClientProfile profile = DefaultProfile.getProfile("default", accessKeyId, accessKeySecret);
        IAcsClient acsClient = 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", signName);
        /* 必填:短信模板code-可在短信控制檯中找到 */
        request.putQueryParameter("TemplateCode", templateCode);
        /* 可選:模板中的變量替換JSON串,如模板內容爲"親愛的用戶,您的驗證碼爲${code}"時,此處的值爲 */
        String templateParam = "{\"code\":\"" + code + "\"}";
        request.putQueryParameter("TemplateParam", templateParam);
        CommonResponse response = null;
        try {
            response = acsClient.getCommonResponse(request);
        }  catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        if (null != response) {

            Map map = JSON.parseObject(response.getData(), Map.class);
            if (map.get("Code") != null && map.get("Code").equals("OK")) {
                //短信發送成功,驗證碼存入redis,有效期180s(3分鐘)
                redisTemplate.opsForValue().set(mobileKey, code, seconds, TimeUnit.SECONDS);
                log.info("手機號: {}, 短信發送成功!驗證碼:{}", phone, code);
                return true;
            } else {
                log.info("短信發送失敗!");
                return false;
            }
        }
        return false;
    }


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章