天天看點

springboot阿裡雲短信服務內建

添加依賴

<!-- 阿裡雲短信 -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>dysmsapi20170525</artifactId>
            <version>2.0.5</version>
        </dependency>      

在application.yml添加配置

# 阿裡雲短信配置
aliyun:
  # 阿裡雲accessKeyId
  accessKeyId: 
  # 阿裡雲accessKeySecret
  accessKeySecret: 
  # 短信簽名名稱
  signName: 
  # 短信模闆ID
  templateCode: 
  # 模闆中變量
  paramName:      

定義傳回常量

/**
 * 傳回狀态碼
 *
 * 
 */
public class ProcessEnum
{
    /**
     * 手機格式不正确
     */
    public static final String PHONE_FORMAT_ERROR = "手機格式不正确";

    /**
     * 判斷是否已發送
     */
    public static final String SMS_FREQUENTLY = "短信發已發送";

    /**
     * 短信發送成功
     */
    public static final String SUCCESS = "短信發送成功";

    /**
     * 短信發送失敗
     */
    public static final String SMS_FAILED = "短信發送失敗";

}      

編寫請求方法

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.ruoyi.common.constant.ProcessEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 10262
 * @version 1.0
 * @Description TODO
 * @date 2021/9/7 15:19
 */
@Slf4j
@RestController
@RequestMapping("/h5")
public class SmsController
{
    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.signName}")
    private String signName;

    @Value("${aliyun.templateCode}")
    private String templateCode;

    @Value("${aliyun.paramName}")
    private String paramName;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 發送短信.
     * @param mobile 手機号
     * @return String
     */
    @SuppressWarnings("deprecated")
    @GetMapping(value = "/sendSms/{mobile}")
    public String sendSmsNew(@PathVariable("mobile") String mobile) throws Exception
    {
        // 檢驗手機号碼
        boolean isPhone = isPhone(mobile);
        if (!isPhone) {
            return ProcessEnum.PHONE_FORMAT_ERROR;
        }
        // 校驗是否重複發送
        Object code = redisTemplate.opsForValue().get(mobile);
        if (code != null) {
            return ProcessEnum.SMS_FREQUENTLY;
        }
        String kaptcha = this.getKaptcha();
        Map <String, String> map = new HashMap <>(1);
//        map.put(this.paramName, kaptcha);
        map.put("outletName", kaptcha);
        map.put("createTime", kaptcha);
        map.put("reportTypeName", kaptcha);
        String templateParam = JSON.toJSONString(map);
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 通路的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        com.aliyun.dysmsapi20170525.Client client = new com.aliyun.dysmsapi20170525.Client(config);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(mobile)
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setTemplateParam(templateParam);
        // 複制代碼運作請自行列印 API 的傳回值
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        if ( "OK".equals(sendSmsResponse.getBody().getCode()) ){
            // 短信發送成功,将驗證碼存儲到redis,并設定過期時間為5分鐘
            this.redisTemplate.opsForValue().set(mobile, kaptcha);
this.redisTemplate.expire(mobile, 5, TimeUnit.MINUTES);
            // 短信發送成功
            return ProcessEnum.SUCCESS;
        };
        // 短信發送失敗
        return ProcessEnum.SMS_FAILED;
    }

    /**
     * 中國電信号段 133、149、153、173、177、180、181、189、199. 中國聯通号段
     * 130、131、132、145、155、156、166、175、176、185、186. 中國移動号段
     * 134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188、198.
     * 其他号段. 14号段以前為上網卡專屬号段,如中國聯通的是145,中國移動的是147等等. 虛拟營運商. 電信:1700、1701、1702.
     * 移動:1703、1705、1706. 聯通:1704、1707、1708、1709、171. 衛星通信:1349.
     * @param phone phone
     * @return boolean
     */
    public static boolean isPhone(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            return m.matches();
        }
    }

    /**
     * 校驗短信驗證碼.
     * @param mobile mobile
     * @param kaptcha kaptcha
     * @return 校驗結果
     */
    @GetMapping(value = "/checkKaptcha/{mobile}/{kaptcha}")
    public Boolean checkKaptcha(@PathVariable String mobile, @PathVariable String kaptcha) {
        Object s = this.redisTemplate.opsForValue().get(mobile);
        return s != null && s.equals(kaptcha);
    }

    /**
     * 生成短信驗證碼并存儲.
     * @return kaptcha
     */
    private String getKaptcha() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < 6; i++) {
            // 生成一個[0,10)
            int randomInt = random.nextInt(10);
            str.append(randomInt);
        }
        return str.toString();
    }

}      

nnjk