导入的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;
}
以上是本人整理笔记,随时学习