Java后端阿里云短信平台发送短信

最近做了关于阿里云平台发送短信的功能,记录下代码方便以后查阅:

@Service
public class ALiYunSMSServiceImpl implements ALiYunSMSService {
    @Autowired
    private AliyunSMSProperties aliyunSMSProperties;

    /**
     * 短信发送验证码
     * @param aliyunSMSInfo
     * @return
     */
    @Override
    public AliyunSMSReturnInfo sendSMSToVertifyCode(AliyunSMSInfo aliyunSMSInfo) {

        AliyunSMSReturnInfo aliyunSMSReturnInfo = new AliyunSMSReturnInfo();
        aliyunSMSReturnInfo.setReturnCode(AliyunSMSConstants.RETURN_FAIL);// 默认返回失败

        /**
         * Step 1. 获取主题引用
         */
        CloudAccount account = new CloudAccount(aliyunSMSProperties.getAccessId(), aliyunSMSProperties.getAccessKey(),
                aliyunSMSProperties.getMnsEndpoint());
        MNSClient client = account.getMNSClient();
        CloudTopic topic = client.getTopicRef(aliyunSMSProperties.getTopic());
        /**
         * Step 2. 设置SMS消息体(必须)
         *
         * 注:目前暂时不支持消息内容为空,需要指定消息内容,不为空即可。
         */
        RawTopicMessage msg = new RawTopicMessage();
        msg.setMessageBody(AliyunSMSConstants.MESSAGEBODY_SMS_MESSAGE);
        /**
         * Step 3. 生成SMS消息属性
         */
        MessageAttributes messageAttributes = new MessageAttributes();
        BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();
        // 3.1 设置发送短信的签名(SMSSignName)
        batchSmsAttributes.setFreeSignName(aliyunSMSProperties.getSignName());
        // 3.2 设置发送短信使用的模板(SMSTempateCode)
        batchSmsAttributes.setTemplateCode(aliyunSMSInfo.getSmsTemplateCode());
        // 3.3 设置接收短信的手机号码(在短信模板中定义的)
        BatchSmsAttributes.SmsReceiverParams smsReceiverParams = new BatchSmsAttributes.SmsReceiverParams();
        smsReceiverParams.setParam(AliyunSMSConstants.REGISTER_VERTIFY_TEMPLATE_CODE,
                aliyunSMSInfo.getSmsVertifyCode());// 模板里面{}部分
        smsReceiverParams.setParam(AliyunSMSConstants.REGISTER_VERTIFY_TEMPLATE_PRODUCT,
                AliyunSMSConstants.REGISTER_VERTIFY_TEMPLATE_PRODUCT_NAME);// 模板里面{}部分
        // 3.4 增加接收短信的号码
        batchSmsAttributes.addSmsReceiver(aliyunSMSInfo.getMobile(), smsReceiverParams);
        // batchSmsAttributes.addSmsReceiver("$YourReceiverPhoneNumber2",
        // smsReceiverParams);
        messageAttributes.setBatchSmsAttributes(batchSmsAttributes);
        try {
            /**
             * Step 4. 发布SMS消息
             */
            TopicMessage ret = topic.publishMessage(msg, messageAttributes);
            aliyunSMSReturnInfo.setReturnCode(AliyunSMSConstants.RETURN_SUCCESS);// 返回成功
            aliyunSMSReturnInfo
                    .setReturnMsg("MessageId: " + ret.getMessageId() + " MessageMD5: " + ret.getMessageBodyMD5());
        } catch (ServiceException se) {
            aliyunSMSReturnInfo.setReturnCode(AliyunSMSConstants.RETURN_FAIL);// 返回失败
            aliyunSMSReturnInfo.setReturnMsg("ErrorCode: " + se.getErrorCode() + " RequestId: " + se.getRequestId()
                    + " Message:" + se.getMessage() + " Exception:" + se.toString());
        } catch (Exception e) {
            aliyunSMSReturnInfo.setReturnCode(AliyunSMSConstants.RETURN_FAIL);// 返回失败
            aliyunSMSReturnInfo.setReturnMsg("Exception:" + e.toString());
        } finally {
            client.close();
        }
        return aliyunSMSReturnInfo;
    }
//发送特定消息
    @Override
    public AliyunSMSReturnInfo sendSMSMsg(List mobileList, SmsReceiverParams smsReceiverParams,
            String smsTemplateCode) {

        AliyunSMSReturnInfo aliyunSMSReturnInfo = new AliyunSMSReturnInfo();
        aliyunSMSReturnInfo.setReturnCode(AliyunSMSConstants.RETURN_FAIL);// 默认返回失败

        /**
         * Step 1. 获取主题引用
         */
        CloudAccount account = new CloudAccount(aliyunSMSProperties.getAccessId(), aliyunSMSProperties.getAccessKey(),
                aliyunSMSProperties.getMnsEndpoint());
        MNSClient client = account.getMNSClient();
        CloudTopic topic = client.getTopicRef(aliyunSMSProperties.getTopic());
        /**
         * Step 2. 设置SMS消息体(必须)
         *
         * 注:目前暂时不支持消息内容为空,需要指定消息内容,不为空即可。
         */
        RawTopicMessage msg = new RawTopicMessage();
        msg.setMessageBody(AliyunSMSConstants.MESSAGEBODY_SMS_MESSAGE);
        /**
         * Step 3. 生成SMS消息属性
         */
        MessageAttributes messageAttributes = new MessageAttributes();
        BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();
        // 3.1 设置发送短信的签名(SMSSignName)
        batchSmsAttributes.setFreeSignName(aliyunSMSProperties.getSignName());
        // 3.2 设置发送短信使用的模板(SMSTempateCode)
        batchSmsAttributes.setTemplateCode(smsTemplateCode);
        // 3.3 设置发送短信所使用的模板中参数对应的值(在短信模板中定义的,没有可以不用设置)
        // ...smsReceiverParams
        // 3.4 增加接收短信的号码
        for (String mobile : mobileList) {
            batchSmsAttributes.addSmsReceiver(mobile, smsReceiverParams);
        }
        messageAttributes.setBatchSmsAttributes(batchSmsAttributes);
        try {
            /**
             * Step 4. 发布SMS消息
             */
            TopicMessage ret = topic.publishMessage(msg, messageAttributes);
            aliyunSMSReturnInfo.setReturnCode(AliyunSMSConstants.RETURN_SUCCESS);// 返回成功
            aliyunSMSReturnInfo
                    .setReturnMsg("MessageId: " + ret.getMessageId() + " MessageMD5: " + ret.getMessageBodyMD5());
        } catch (ServiceException se) {
            aliyunSMSReturnInfo.setReturnCode(AliyunSMSConstants.RETURN_FAIL);// 返回失败
            aliyunSMSReturnInfo.setReturnMsg("ErrorCode: " + se.getErrorCode() + " RequestId: " + se.getRequestId()
                    + " Message:" + se.getMessage() + " Exception:" + se.toString());
        } catch (Exception e) {
            aliyunSMSReturnInfo.setReturnCode(AliyunSMSConstants.RETURN_FAIL);// 返回失败
            aliyunSMSReturnInfo.setReturnMsg("Exception:" + e.toString());
        } finally {
            client.close();
        }
        return aliyunSMSReturnInfo;
    }

}
//返回消息
public class AliyunSMSReturnInfo {
    private String returnCode;//返回码 0-失败 1-成功
    private String returnMsg;//返回信息
    public String getReturnCode() {
        return returnCode;
    }
    public void setReturnCode(String returnCode) {
        this.returnCode = returnCode;
    }
    public String getReturnMsg() {
        return returnMsg;
    }
    public void setReturnMsg(String returnMsg) {
        this.returnMsg = returnMsg;
    }
/**
 * 阿里云短信发送验证码信息体
 * @author Administrator
 *
 */
public class AliyunSMSInfo {

    private String smsTemplateCode;// 短信模板CODE
    private String smsVertifyCode;// 验证码
    private String mobile;// 手机号

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getSmsVertifyCode() {
        return smsVertifyCode;
    }

    public void setSmsVertifyCode(String smsVertifyCode) {
        this.smsVertifyCode = smsVertifyCode;
    }

    public String getSmsTemplateCode() {
        return smsTemplateCode;
    }

    public void setSmsTemplateCode(String smsTemplateCode) {
        this.smsTemplateCode = smsTemplateCode;
    }

}
//阿里云短信配置信息
@Configuration
@PropertySource("classpath:aliyunsms.properties")
public class AliyunSMSProperties {
    @Value("${AccessId}")
    private String accessId;//
    @Value("${AccessKey}")
    private String accessKey;//
    @Value("${MNSEndpoint}")
    private String mnsEndpoint;//
    @Value("${Topic}")
    private String topic;// 主题名称
    @Value("${SignName}")
    private String signName;// 短信签名--注意是中文名称

    public String getAccessId() {
        return accessId;
    }

    public void setAccessId(String accessId) {
        this.accessId = accessId;
    }

    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public String getMnsEndpoint() {
        return mnsEndpoint;
    }

    public void setMnsEndpoint(String mnsEndpoint) {
        this.mnsEndpoint = mnsEndpoint;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public String getSignName() {
        return signName;
    }

    public void setSignName(String signName) {
        this.signName = signName;
    }

}
/**
 * 阿里云短信服务通用常量
 */
public class AliyunSMSConstants {

    /**
     * SMS消息体 sms-message
     */
    public static final String MESSAGEBODY_SMS_MESSAGE = "sms-message";

    /**
     * 阿里云-用户注册验证码模板${code} ${product}
     */
    public static final String REGISTER_VERTIFY_TEMPLATE_CODE = "code";
    /**
     * 阿里云-用户注册验证码模板${code} ${product}
     */
    public static final String REGISTER_VERTIFY_TEMPLATE_PRODUCT = "product";
    /**
     * 阿里云-用户注册验证码模板编号
     */
    public static final String REGISTER_SMS_TEMPLATE_CODE = "REGISTER_SMS_TEMPLATE_CODE";
    /**
     * 阿里云-用户忘记密码模板编号
     */
    public static final String FORGET_SMS_TEMPLATE_CODE = "FORGET_SMS_TEMPLATE_CODE ";

    /**
     * 通知用户初始密码
     */
    public static final String SEND_PASSWORD_SMS_TEMPLATE_CODE = "SEND_PASSWORD_SMS_TEMPLATE_CODE ";
    /**
     * 预定发送短信
     */
    public static final String RESERVATION_SMS_TEMPLATE_CODE = "RESERVATION_SMS_TEMPLATE_CODE ";
    /**
     * 阿里云-用户注册验证码模板${product} 名称 
     */
    public static final String REGISTER_VERTIFY_TEMPLATE_PRODUCT_NAME = "编号";

    /**
     * 返回码1-成功
     */
    public static final String RETURN_SUCCESS = "1";
    /**
     * 返回码0-失败
     */
    public static final String RETURN_FAIL = "0";
}

调用代码

 /**
     * 通知用户初始密码 发送特定消息
     * @param phone 手机号
     * @param password 密码
     * @param userName 用户名
     */
    private void sendNewPassWord(String phone, String password, String userName) {
        List mobileList = new ArrayList();
        mobileList.add(phone);
        //加入需要发送的手机号码
        // mobileList.add("180000000000");
        SmsReceiverParams smsReceiverParams = new SmsReceiverParams();
        smsReceiverParams.setParam("name", userName);
        smsReceiverParams.setParam("psw", password);
        aliYunSMSService.sendSMSMsg(mobileList, smsReceiverParams, AliyunSMSConstants.SEND_PASSWORD_SMS_TEMPLATE_CODE);
    }
//验证码调用代码
 String verifyCode = String.valueOf(RandNumberUtil.getRandNum(1, 999999));
            // 发送短信
            AliyunSMSInfo aliyunSMSInfo = new AliyunSMSInfo();
            aliyunSMSInfo.setMobile(mobile);
            if (StringUtils.equals(type, "register")) {
                aliyunSMSInfo.setSmsTemplateCode(AliyunSMSConstants.REGISTER_SMS_TEMPLATE_CODE);
            } else if (StringUtils.equals(type, "forget")) {
                aliyunSMSInfo.setSmsTemplateCode(AliyunSMSConstants.FORGET_SMS_TEMPLATE_CODE);
            }
            aliyunSMSInfo.setSmsVertifyCode(verifyCode);
            AliyunSMSReturnInfo aliyunSMSReturnInfo = aliyunSMSService.sendSMSToVertifyCode(aliyunSMSInfo);

你可能感兴趣的:(Java后端阿里云短信平台发送短信)