美文网首页
调用阿里云短信服务

调用阿里云短信服务

作者: 老祝读书 | 来源:发表于2021-06-17 16:00 被阅读0次

    AliShortMessage.java 发短信工具

    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package com.shortmessage.util;
    
    import com.aliyun.dysmsapi20170525.Client;
    import com.aliyun.dysmsapi20170525.models.*;
    import com.aliyun.teaopenapi.models.*;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.stream.Collectors;
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    /**
     *
     * @author Robbie
     */
    public class AliShortMessage {
    
        private String accessKeyId;
        private String accessKeySecret;
        private String DEFAULT_SIGNNAME;
    
        private static final AliShortMessage instance = new AliShortMessage();
    
        public static void init(String accessKeyId, String accessKeySecret, String defaultSignName) {
            instance.accessKeyId = accessKeyId;
            instance.accessKeySecret = accessKeySecret;
            instance.DEFAULT_SIGNNAME = defaultSignName;
        }
    
        public static AliShortMessage getInstance() throws RuntimeException {
            if (instance.accessKeyId == null || instance.accessKeySecret ==null || instance.DEFAULT_SIGNNAME == null) {
                throw new RuntimeException("未初始化请先初始化");
            }
            
            return instance;
        }
    //    
    
        private Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
            Config config = new Config()
                    // 您的AccessKey ID
                    .setAccessKeyId(accessKeyId)
                    // 您的AccessKey Secret
                    .setAccessKeySecret(accessKeySecret);
            // 访问的域名
            config.endpoint = "dysmsapi.aliyuncs.com";
            return new com.aliyun.dysmsapi20170525.Client(config);
        }
    
        public void sendMessage(String phoneNumber, String templateCode, Map<String, String> param) throws Exception {
            sendMessage(phoneNumber, templateCode, param, DEFAULT_SIGNNAME);
        }
    
        public void sendMessage(String phoneNumber, String templateCode, Map<String, String> param, String signName) throws Exception {
            Client client = createClient(accessKeyId, accessKeySecret);
    
            JSONObject jSONObject = new JSONObject(param);
        
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            sendSmsRequest.setPhoneNumbers(phoneNumber);
            sendSmsRequest.setTemplateCode(templateCode);
            sendSmsRequest.setTemplateParam(jSONObject.toString());
            sendSmsRequest.setSignName(signName);
    
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            if (!Objects.equals(sendSmsResponse.getBody().code, "OK")) {
                throw new RuntimeException(sendSmsResponse.getBody().message);
            }
        }
    
        public void sendBatchMessages(List<String> phoneNumberList, String templateCode, List<Map<String, String>> param) throws Exception {
    
            if (phoneNumberList.size() > 100) {
                throw new RuntimeException("最多100个号码");
            }
            List<String> signNameList = phoneNumberList.parallelStream().map((p) -> DEFAULT_SIGNNAME).collect(Collectors.toList());
            sendBatchMessages(phoneNumberList, templateCode, param, signNameList);
        }
    
        public void sendBatchMessages(List<String> phoneNumberList, String templateCode, List<Map<String, String>> paramList, List<String> signNameList) throws Exception {
            if (phoneNumberList.size() > 100) {
                throw new RuntimeException("最多100个号码");
            }
    
            Client client = createClient(accessKeyId, accessKeySecret);
            JSONArray paramJSONObject = new JSONArray(paramList);
            JSONArray phoneNumberJSONObject = new JSONArray(phoneNumberList);
            JSONArray signNameJSONObject = new JSONArray(signNameList);
    
            SendBatchSmsRequest sendSmsRequest = new SendBatchSmsRequest();
            sendSmsRequest.setPhoneNumberJson(phoneNumberJSONObject.toString());
    
            sendSmsRequest.setTemplateCode(templateCode);
            sendSmsRequest.setTemplateParamJson(paramJSONObject.toString());
            sendSmsRequest.setSignNameJson(signNameJSONObject.toString());
    
            SendBatchSmsResponse sendBatchSmsResponse = client.sendBatchSms(sendSmsRequest);
           
            if (!Objects.equals(sendBatchSmsResponse.getBody().code, "OK")) {
                throw new RuntimeException(sendBatchSmsResponse.getBody().message);
            }
        }
    }
    
    

    测试短信发送

     @Override
        public void initialize(URL location, ResourceBundle resources) {
            AliShortMessage.init("accessKeyId", "accessKeySecret", "defaultSignName");
        }
    
        /**
         * 测试发送短信
         *
         * @param event
         */
        @FXML
        public void send(ActionEvent event) {
            String phoneNumber = "18600000000";
            String templateCode = "SMS_218172077";
            Map<String, String> param = new HashMap<String, String>();
            param.put("name", "张三");
            param.put("address", "南二区");
            param.put("time", "2021-06-10 17:00:00");
            param.put("remark", "CPU过热");
            param.put("code", "FX0001");
            
            try {
                
                AliShortMessage.getInstance().sendMessage(phoneNumber, templateCode, param);
            } catch (Exception ex) {
                Logger.getLogger(ShortMessageController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    
        /**
         * 测试批量发送短信,最多100个号码
         *
         * @param event
         */
        @FXML
        public void sendBatch(ActionEvent event) {
            
            List<String> phoneNumberList = new ArrayList<String>();
            List< Map<String, String>> paramList = new ArrayList<>();
            phoneNumberList.add("18600000000");
            phoneNumberList.add("18600000001");
            
            String templateCode = "SMS_218172077";
            Map<String, String> param = new HashMap<String, String>();
            param.put("name", "张三");
            param.put("address", "南二区");
            param.put("time", "2021-06-10 17:00:00");
            param.put("remark", "CPU过热");
            param.put("code", "FX0001");
            
            paramList.add(param);
            
            param = new HashMap<String, String>();
            param.put("name", "马工");
            param.put("address", "南二区");
            param.put("time", "2021-06-10 17:00:00");
            param.put("remark", "CPU过热");
            param.put("code", "FX0001");
            paramList.add(param);
            try {
                
                AliShortMessage.getInstance().sendBatchMessages(phoneNumberList, templateCode, paramList);
            } catch (Exception ex) {
                Logger.getLogger(ShortMessageController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    

    相关文章

      网友评论

          本文标题:调用阿里云短信服务

          本文链接:https://www.haomeiwen.com/subject/ijpcyltx.html