/** * 阿里云短信服务KEY ID */ private final static String ACCESSKEYID = "*********************" ; /** * 阿里云短信服务秘钥 */ private final static String ACCESSSECRET = "*********************" ;
public SendMsgDto sendMsg(String phone, String code) throws CustomException { if(StringUtils.isEmpty(phone)){ throw new CustomException(Result.ERROR("手机号码不能为空!")); } if(StringUtils.isEmpty(code)){ throw new CustomException(Result.ERROR("验证码不能为空!")); } StringBuffer template = new StringBuffer(""); template.append("{"); template.append("\"code\""); template.append(":"); template.append(""+code+""); template.append("}"); DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESSKEYID, ACCESSSECRET); IAcsClient client = new DefaultAcsClient(profile); CommonRequest request = new CommonRequest(); request.setMethod(MethodType.POST); request.setDomain("dysmsapi.aliyuncs.com"); request.setVersion("2017-05-25"); request.setAction("SendSms"); request.putQueryParameter("RegionId", "cn-hangzhou"); request.putQueryParameter("SignName", "名称"); request.putQueryParameter("TemplateCode", "SMS_187225468"); request.putQueryParameter("TemplateParam", template.toString()); request.putQueryParameter("PhoneNumbers", phone); try { CommonResponse response = client.getCommonResponse(request); SendMsgDto msgDto = JSON.parseObject(response.getData(),SendMsgDto.class); return msgDto ; } catch (ServerException e) { throw new CustomException(Result.ERROR("发送短信出现异常:"+e.getMessage())); } catch (ClientException e) { throw new CustomException(Result.ERROR("发送短信出现异常:"+e.getMessage())); } }
SendMsg checkSendMsg = sendMsgDao.getSendObj(phone); if(checkSendMsg==null){ SendMsgDto msgDto = sendMsgService.sendMsg(phone,code); if(null==msgDto){ return Result.ERROR("短信发送失败!"); } if(!msgDto.getCode().equalsIgnoreCase("OK")){ return Result.ERROR("短信发送失败["+msgDto.getMessage()+"]"); }else{ //保存数据库对应的短信记录信息 SendMsg sendMsg = new SendMsg(); Date cuurDate = new Date(); sendMsg.setCode(code); sendMsg.setPhone(phone); sendMsg.setSendtime(cuurDate); sendMsg.setExptime(DateUtils.dateAddMinutes(cuurDate,5)); //5分钟有效 sendMsgDao.save(sendMsg); } }else{ return Result.ERROR("验证码已经发送,请留意短信信息!"); } } return Result.SUCCESS("验证码发送成功!");