阿里云获取短信验证码案列
1,集成的springboot框架,以用户注册为列
@ApiOperation(value = "用户注册", notes = "用户注册")
@PostMapping("/register")
@Transactional(rollbackFor = Exception.class)
public ReturnInfo register(@ApiParam(name = "userRegister",value = "用户注册信息",required = true)
@RequestBody UserRegister userRegister,
HttpServletRequest request) {
String phone = userRegister.getPhone();
String smsCode = userRegister.getSmsCode();
String deviceNo = userRegister.getDeviceNo();
logger.info("用户注册:手机号【"+phone+"】,验证码【"+smsCode+"】");
if(!StringUtil.hasValue(phone)){
return ReturnInfo.getInstance().setResult(ErrorCodeEnum.PHONE_NULL);
}
if(!ValidateUtils.isPhone(phone)){
return ReturnInfo.getInstance().setResult(ErrorCodeEnum.PHONE_ERROR);
}
//判断手机号是否已注册
UserInfo regUserInfo = userInfoService.getUserInfoByPhone(phone);
if(regUserInfo != null){
return ReturnInfo.getInstance().setResult(ErrorCodeEnum.PHONE_REG);
}
if(!StringUtil.hasValue(smsCode)){
return ReturnInfo.getInstance().setResult(ErrorCodeEnum.SMS_CODE_NULL);
}
if(smsCode.length() != 4){
return ReturnInfo.getInstance().setResult(ErrorCodeEnum.SMS_CODE_ERROR);
}
//校验验证码
String redisCode = RedisService.getRedisService().get(RedisKeyConstants.SMSCODE_CACHE+phone);
if(!smsCode.equals(redisCode)){
return ReturnInfo.getInstance().setResult(ErrorCodeEnum.SMS_CODE_INVALID);
}
UserInfo userInfo = new UserInfo();
userInfo.setPhone(phone);
userInfo.setDeviceNo(deviceNo);
String host = IpUtil.getIpFromRequest(WebUtils.toHttp(request));
String tokenKey = RedisService.getRedisService().get(RedisKeyConstants.TOKEN_KEY_CACHE+host.toUpperCase()+"_"+userRegister.getUserKey());
String password = AESUtil.aesDecode(userRegister.getPassword(),tokenKey);
userInfo.setPassword(password);
//随机昵称
String nickName = StringUtil.randomNumStr(8);
userInfo.setNickName(nickName);
userInfo.setUpdateTime(new Date());
//设置用户类型为普通用户
userInfo.setUserType("1");
//初始化账户信息
UserAccount userAccount = new UserAccount();
userAccount.setAmount(new Double(0));
//通过设备号获取用户信息
UserInfo userInfoResult = userInfoService.getUserInfoByDeviceNo(deviceNo);
if(userInfoResult != null){
String userId = userInfoResult.getUserId();
userInfo.setUserId(userId);
userAccount.setUserId(userId);
userInfoService.modUserInfo(userInfo);
}else{
String userId = StringUtil.UUID();
userInfo.setUserId(userId);
userAccount.setUserId(userId);
userInfoService.addUserInfo(userInfo);
}
//初始化账户
accountService.addUserAccount(userAccount);
//修改用户注册信息
LoginInfo loginInfo = loginInfoService.getLoginInfoById(userInfo.getUserId());
if(loginInfo == null){
loginInfo = new LoginInfo();
}
Date loginTime = new Date();
String regIp = IpUtil.getIpFromRequest(WebUtils.toHttp(request));
loginInfo.setUserId(userInfo.getUserId());
loginInfo.setRegTime(loginTime);
loginInfo.setRegIp(regIp);
loginInfo.setDeviceNo(deviceNo);
loginInfoService.addOrModLoginInfo(loginInfo);
return ReturnInfo.getInstance().setResult(ErrorCodeEnum.SUCCESS).setData(null);
}
二.获取短信验证码
@ApiOperation(value = "获取短信验证码", notes="获取短信验证码")
@GetMapping("/getSmsCode/{phone}")
public ReturnInfo<String> getSmsCode(@ApiParam(name = "phone", value = "手机号码", required = true) @PathVariable String phone){
if(!StringUtil.hasValue(phone)){
return ReturnInfo.getInstance().setResult(ErrorCodeEnum.PHONE_NULL);
}
if(!ValidateUtils.isPhone(phone)){
return ReturnInfo.getInstance().setResult(ErrorCodeEnum.PHONE_ERROR);
}
String cacheCode = RedisService.getRedisService().get(RedisKeyConstants.SMSCODE_CACHE+phone);
if(StringUtil.hasValue(cacheCode)){
return ReturnInfo.getInstance().setResult(ErrorCodeEnum.SMS_OFTEN_CODE).setData(null);
}
return SmsUtil.sendSmsCode(phone);
}
三.发送短信验证码
/**
* 发送短信验证码
*
* @param phone
* @return
*/
public static ReturnInfo<String> sendSmsCode(String phone) {
boolean sendFlag = false;
//短信验证码长度
/* int codeLength = 4;
String code = StringUtil.randomNumber(codeLength);*/
String code = "8888";
//获取短信运营商列表
byte[] smsOperatorByte = RedisService.getRedisService().getByte(RedisKeyConstants.SMS_OPERATOR);
List<Map<String,Object>> smsOperatorList = FstSerializer.getInstance().deserialize(smsOperatorByte,Map.class);
if(smsOperatorList != null && smsOperatorList.size()>0){
int randomFlag = new Random().nextInt(smsOperatorList.size());
//随机获取一个运营商
Map<String,Object> smsOperatorMap = smsOperatorList.get(randomFlag);
String smsOperatorStr = smsOperatorMap.get("operatorCode").toString();
//阿里云
if("aliyun".equals(smsOperatorStr)){
smsOperatorMap.put("phone", phone);
smsOperatorMap.put("code", code);
sendFlag = aliyunSendSms(smsOperatorMap);
}
}
// 短信发送成功
if(sendFlag){
//将手机号和验证码存入redis
RedisService redisService = RedisService.getRedisService();
redisService.setex(RedisKeyConstants.SMSCODE_CACHE + phone, code, RedisKeyConstants.SMSCODE_TTL);
return ReturnInfo.getInstance().setResult(ErrorCodeEnum.SUCCESS).setData(null);
}
return ReturnInfo.getInstance().setResult(ErrorCodeEnum.SMS_CODE_FAIL).setData(null);
}
/**
* 阿里云短信发送
* @param smsOperatorMap
* @return
*/
private static boolean aliyunSendSms(Map<String, Object> smsOperatorMap){
Map<String, String> map = new HashMap<>();
List<Map<String, String>> smsParamList = (List<Map<String, String>>) smsOperatorMap.get("smsParamList");
smsParamList.stream().forEach((smsParamMap) -> {
map.put(smsParamMap.get("paramCode"),smsParamMap.get("paramValue"));
});
List<Map<String, String>> msgMouldList = ( List<Map<String, String>>) smsOperatorMap.get("msgMouldList");
msgMouldList.stream().forEach((msgMouldMap) -> {
String msgType = msgMouldMap.get("msgType");
if("1".equals(msgType)){
map.put("templateCode",msgMouldMap.get("code"));
String content = msgMouldMap.get("content");
//解析模板内容中的变量
Map<String, String> templateParam = new HashMap<>();
Set<String> result = StringUtil.getStrContainData(content, "{", "}", true);
String[] array = result.toArray(new String[0]);
templateParam.put(array[0],smsOperatorMap.get("code").toString());
map.put("templateParam",JsonUtil.objectToString(templateParam));
}
});
DefaultProfile profile = DefaultProfile.getProfile(map.get("regionId"),map.get("accessKeyId"),map.get("secret"));
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
//request.setProtocol(ProtocolType.HTTPS);
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25"); //api版本号
request.setAction("SendSms");
request.putQueryParameter("RegionId", map.get("regionId"));
request.putQueryParameter("PhoneNumbers", smsOperatorMap.get("phone").toString());
request.putQueryParameter("SignName", map.get("signName"));
request.putQueryParameter("TemplateCode", map.get("templateCode"));
request.putQueryParameter("TemplateParam", map.get("templateParam"));
try {
CommonResponse response = client.getCommonResponse(request);
String resultStr = response.getData();
if(StringUtil.hasValue(resultStr)){
Map<String, String> resMap = JsonUtil.strToObject(response.getData(),HashMap.class);
if("OK".equals(resMap.get("Code"))){
return true;
}
}
} catch (ServerException e) {
logger.error("阿里云发送短信失败:"+e.getMessage(),e);
} catch (ClientException e) {
logger.error("阿里云发送短信失败:"+e.getMessage(),e);
}
return false;
}
四.可以用在用户注册上进行手机号码的校验