阿里雲--發送短信或短信驗證碼

導入的jar包
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudTopic;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.model.BatchSmsAttributes;
import com.aliyun.mns.model.MessageAttributes;
import com.aliyun.mns.model.RawTopicMessage;


驗證碼所需的4位數字

public String random(){
        int radomInt = new Random().nextInt(9999);
        return String.valueOf(radomInt);
    }


聲明reids類,將驗證碼存入redis內
@Resource
private StringRedisTemplate stringRedisTemplate;



本文,沒有接收阿里的返回值,直接自動判斷是否發送,正常應該接收阿里雲的返回值,因爲發送的短信成功率是 99%,但在此就忽略了,直接上代碼:

 public Result<Object> send(String phone, HttpServletRequest request) {
        Result<Object> re = new Result<Object>();
        /**
         * Step 1. 獲取主題引用
         * CloudAccount(accessId,accessKey,accountEndpoint)
         */
        CloudAccount account = new CloudAccount("afdffa", "er3erefe", "https://1595604544082734.mns.cn-hangzhou.aliyuncs.com/");
        MNSClient client = account.getMNSClient();
        CloudTopic topic = client.getTopicRef("sms.topic-cn-hangzhou");
        /**
         * Step 2. 設置SMS消息體(必須)
         *
         * 注:目前暫時不支持消息內容爲空,需要指定消息內容,不爲空即可。
         */
        RawTopicMessage msg = new RawTopicMessage();
        /**
         * Step 3. 生成SMS消息屬性
         */
        MessageAttributes messageAttributes = new MessageAttributes();
        BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();
        msg.setMessageBody("sms-message");
        // 3.1 設置發送短信的簽名(SMSSignName)
        batchSmsAttributes.setFreeSignName("佰事達旅遊");
        // 3.2 設置發送短信使用的模板(SMSTempateCode)
        batchSmsAttributes.setTemplateCode("SMS_74646445");
        // 3.3 設置發送短信所使用的模板中參數對應的值(在短信模板中定義的,沒有可以不用設置)
        BatchSmsAttributes.SmsReceiverParams smsReceiverParams = new BatchSmsAttributes.SmsReceiverParams();
        //驗證碼
        String ver = random();
        //將驗證碼放入到redis內,驗證時使用驗證
        stringRedisTemplate.opsForValue().set(phone + "phonever", ver, 5,TimeUnit.MINUTES);
        smsReceiverParams.setParam("ver", ver);
        //短信發送功能
        // 3.4 增加接收短信的號碼
        batchSmsAttributes.addSmsReceiver(phone, smsReceiverParams);
        messageAttributes.setBatchSmsAttributes(batchSmsAttributes);
        try {
            /**
             * Step 4. 發佈SMS消息
             */
            // TopicMessage ret = topic.publishMessage(msg, messageAttributes);
            re.setIsTrue(true);
            re.setData(ver);
            topic.publishMessage(msg, messageAttributes);
        } catch (ServiceException se) {
            log.debug("", se);
            re.setMessage("驗證碼錯誤或已失效");
        } catch (Exception e) {
            log.debug("", e);
            re.setMessage("驗證碼錯誤或已失效");
        }
        client.close();
        return re;
    }

以上是本人整理筆記,隨時學習

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