最近做了关于阿里云平台发送短信的功能,记录下代码方便以后查阅:
@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(