调用阿里短信接口

/**
 *  阿里云短信服务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("验证码发送成功!");
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值