如题,本文写的是发送单个短信的代码,用于客户登录发送短信验证码
1.建表,保存购买的短信服务的配置
CREATE TABLE `sms_info` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`app_id` bigint(20) NOT NULL COMMENT 'appId',
`app_key` varchar(64) DEFAULT NULL COMMENT 'appKey',
`template_id` bigint(20) NOT NULL COMMENT '模板Id',
`template_type` varchar(20) NOT NULL COMMENT '模板类型,区分不同的短信类型',
`status` varchar(20) NOT NULL DEFAULT '' COMMENT '状态,active 生效 delete 已失效',
`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='短信模板表';
2.查看购买的短信服务配置
如下图:查看appId和appKey
查看短信的签名:
查看短信模板ID:
3.编写代码
//查看短信的配置
@Resource
private SmsInfoMapper smsInfoMapper;
//短信模板是:{1}为您的登录验证码,请于{2}分钟内填写,如非本人操作,请忽略本短信。
@ApiOperation(value = "发送短信校验码")
@RequestMapping(value = "send-sms-code", method = RequestMethod.POST)
public Result<?> sendSmsCode(@RequestBody PhoneRequest request) throws HuihuaException {
logger.info("sendSmsCode request: {}", request.toString());
String phone = request.getPhone();
VerifyUtils.verifyPhoneNo(phone, true, "phone");
String lockKey = redisValueService.buildKeyString(PREFIX_PHONE_TOKEN, phone);
boolean locked = lockService.tryLockDistribute(lockKey, RedisConstants.LOCK_APP_TOKEN_TIMEOUT_SEC);
if (!locked) {
throw new UserException(ResultCode.LOGIN_MUTEX_LOCK_FAILED,
"send-sms-code function locked ,is processing and phone = {}" + phone);
}
try {
//发送短信频次限制 。x分钟内仅能发一条短信
String key = redisValueService.buildKeyString(RedisConstants.PREFIX_SMS_INTERVAL, phone);
//取短信发送时间频次控制标识
if (userProperties.getSmsSendInterval() > 0) {
String intervalFlag = redisValueService.get(key);
if (StringUtils.isNotBlank(intervalFlag)) {
throw new UserException(ResultCode.SEND_SMS_TOO_FREQ.getCode(),
MessageFormat.format(ResultCode.SEND_SMS_TOO_FREQ.getMsg(),
userProperties.getSmsSendInterval() + "分钟"), "phone=" + phone);
}
redisValueService.set(key, "1", userProperties.getSmsSendInterval(), TimeUnit.MINUTES);
}
StringBuilder smsCodeBuilder = new StringBuilder();
for (int i = 0; i < 4; i++) {
smsCodeBuilder.append(RandomUtils.nextInt(10));
}
String smsCode = smsCodeBuilder.toString();
//查询供应商短信模板配置
SmsInfoDO condition = new SmsInfoDO();
condition.setTemplateType(Constants.LOGIN_SMS_TEMPLATE_TYPE);
condition.setStatus(Constants.SMS_STATUS_ACTIVE);
SmsInfoDO smsInfoDO = smsInfoMapper.querySingleSmsInfo(condition);
if (smsInfoDO == null) {
return ResultUtils.failedResult(ResultCode.SMS_INFO_QUERY_FAIL);
}
//叮铛满满手机号登录短信模板 : {1}为您的登录验证码,请于{2}分钟内填写,如非本人操作,请忽略本短信。
//SmsSender.sendSms(phone, smsCode, smsInfoDO);
String[] params = new String[2];
params[0] = smsCode;
params[1] = "10";
int appId = smsInfoDO.getAppId().intValue();
String appKey = smsInfoDO.getAppKey();
int templateId = smsInfoDO.getTemplateId().intValue();
String smsSign = "啊啊啊啊";//这个就是上面的短信签名,需要官方审核
List<String> phoneList = new ArrayList<>();
phoneList.add(phone);
String[] phoneNumbers = phoneList.toArray(new String[phoneList.size()]);
SmsSingleSender singleSender = new SmsSingleSender(appId, appKey);
SmsSingleSenderResult result = singleSender.sendWithParam("86", phone, templateId, params, smsSign, "", "");
/*SmsMultiSender smsSender = new SmsMultiSender(appId, appKey);
SmsMultiSenderResult result = null;
result = smsSender.sendWithParam("86", phoneNumbers, templateId, params, smsSign, "", "");*/
log.info("推送短信内容:{},号码:{},短信返回:{}", params, phone, result);
// store to redis
redisValueService.set(RedisConstants.SMS_LOGIN + phone, smsCode, 10, TimeUnit.MINUTES);
logger.info("User request send-sms-code.phone:{},smsCode:{}", phone, smsCode);
//return ResultUtils.successResult(null);
} catch (Exception e) {
log.info("send-sms-code fucntion error and e ={}" + e.getMessage());
} finally {
lockService.unlockDistribute(lockKey);
log.info("-----短信任务结束-----");
}
return ResultUtils.successResult(null);
}