一、接收注册短信
1.userService
/**
* 短信注册登录
* @param phone
* @throws ClientException
* @throws JsonProcessingException
*/
@Transactional
public void message(String phone) throws ClientException, JsonProcessingException{
//根据手机号码查询用户信息
List record = this.userMapper.selectByExample(new UserExample(){{
createCriteria().andPhoneEqualTo(phone);
}});
System.out.println("是否存在:"+record.size());
if(record.size() == 0){
//该手机号码未注册,发送登录短信
this.messageService.register(phone);
}else{
//该手机号码已注册,发送注册短信
// this.messageService.register(phone);
throw new SimpleException("该手机号码已注册");
}
}
2.messageService
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import pedicure.exception.SimpleException;
import pedicure.module.Configuration;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public void register(String phone) throws ClientException, JsonProcessingException{
String code = this.generateCode(phone);
String template =Configuration.property(Configuration.ALIYUN_MESSAGE_REGISTER_TEMPLATE_CODE);
this.aliyunSMS(phone,template,new HashMap(){{
this.put("code",code);
}});
}
3.generateCode
public String generateCode(String phone){
if(StringUtils.isBlank(phone)){
throw new SimpleException("未知的手机号码信息~~");
}
ValueOperations operations = this.redisTemplate.opsForValue();
String key = String.format("%s:%s", Configuration.SYSTEM_MESSAGE_NAMESPACE,phone);
//是否在短时间内以发送过验证码
if(operations.get(key) != null){
throw new SimpleException("短信验证码获取频繁~~");
}
//生成短信验证码
String code = String.valueOf(RandomUtils.nextInt(1000,10000));
int active = 120;
operations.set(key,code,active,TimeUnit.SECONDS);
operations.set(key,code);
return code;
}
4.Configuration
public static String property(String key) {
String value = null;
try{
if(PROPERTIES_FACTORY == null){
ClassPathResource properties = new ClassPathResource("config/global.properties");
if(!properties.exists()){
throw new SystemException("configuration [ classpath:config/global.properties ] file cannot be found");
}
PROPERTIES_FACTORY = new PropertiesFactoryBean();
PROPERTIES_FACTORY.setFileEncoding("utf-8");
PROPERTIES_FACTORY.setLocation(properties);
PROPERTIES_FACTORY.afterPropertiesSet();
}
value = PROPERTIES_FACTORY.getObject().getProperty(key);
}catch (IOException io){
LOGGER.error(io.getMessage(),io);
}
if(StringUtils.isBlank(value)){
throw new SystemException("configuration key [ "+key+" ] Non-existent");
}
return value;
}
//public static final String ALIYUN_MESSAGE_REGISTER_TEMPLATE_CODE = "aliyun.message.registerTemplateCode";
//aliyun.message.registerTemplateCode=SMS_***
5.aliyunSMS
private void aliyunSMS(String phone,String template,Map param) throws ClientException,JsonProcessingException{
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",Configuration.property(Configuration.ALIYUN_MESSAGE_ACCESS_KEY_ID), Configuration.property(Configuration.ALIYUN_MESSAGE_SECRET));
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
IAcsClient acsClient = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
request.setPhoneNumbers(phone);
request.setSignName(Configuration.property(Configuration.ALIYUN_MESSAGE_SIGN_NAME));
request.setTemplateCode(template);
request.setTemplateParam(this.mapper.writeValueAsString(param));
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
System.out.println(sendSmsResponse.getCode());
String code = sendSmsResponse.getCode();
switch (code) {
case "OK":
break;
case "isv.MOBILE_NUMBER_ILLEGAL":
throw new SimpleException("非法的手机号码 ~");
case "isv.BUSINESS_LIMIT_CONTROL":
throw new SimpleException("该号码发送频率已达上限,暂时无法服务 ~");
}
}
//public static final String ALIYUN_MESSAGE_ACCESS_KEY_ID = "aliyun.message.accessKeyId";
//aliyun.message.accessKeyId=***
// public static final String ALIYUN_MESSAGE_SECRET = "aliyun.message.secret";
//aliyun.message.secret=***
//public static final String ALIYUN_MESSAGE_SIGN_NAME = "aliyun.message.signName";
//aliyun.message.signName=
二、用户注册(使用redis数据库)
1.userService
@Transactional
public User register(String phone,String code,String password){
if (StringUtils.isBlank(phone)){
throw new SimpleException("请输入手机号码");
}
if (StringUtils.isBlank(password)){
throw new SimpleException("请输入密码");
}
String messageKey = String.format("%s:%s", Configuration.SYSTEM_MESSAGE_NAMESPACE,phone);
String storageCode = (String) this.redisTemplate.opsForValue().get(messageKey);
if (StringUtils.isBlank(code)){
throw new SimpleException("无效的验证码,请重新获取~~");
}
if (!storageCode.equals(code)){
throw new SimpleException("短信验证码不正确~~");
}
User user = new User().setPhone(phone).setNickname("手机用户"+phone).setHead(this.settingMapper.selectUserHead()).setSignature(this.settingMapper.selectUserSignature()).setSex(0).setGrade(1).setDelFlag(false).setCreateTime(new Date()).setUpdateTime(new Date());
this.userMapper.insertSelective(user);
Auth auth = new Auth().setUserId(user.getId()).setType(0).setDelFlag(false).setCreateTime(new Date()).setUpdateTime(new Date()).setCode(this.passwordDigest(user.getId(),password));
this.authMapper.insertSelective(auth);
Accountu accountu = new Accountu().setUserId(user.getId()).setAvaliable(new BigDecimal(0)).setEarning(new BigDecimal(0)).setDelFlag(false).setCreateTime(new Date()).setUpdateTime(new Date());
this.accountuMapper.insertSelective(accountu);
this.redisTemplate.delete(messageKey);//测试的时候建议及时删掉redis中的code,便于多次测试
return user;
}
//public static final String SYSTEM_MESSAGE_NAMESPACE = "pedicure:message";
欢迎大家补充