技术分享

java阿里云短信发送验证码开发整理

2020-01-08  本文已影响0人  星可码农

废话不多说直接上代码:
验证码生成代码:

String code = KeyGenerater.getRandomNumberKey(6);
        String data = FastJsonUtil.of("code", code, "product", "网").toJSONString();
        if (sendSms(phoneNum, data, codeModel)) {
            redisService.set(cacheKey, code, GlobalCacheManageEnum.PHONE_SMS_KEY.getExpireTime());
            resultVo.setData(total);
            return resultVo;
        }

调用发送消息:
配置:


image.png

远程调用:

 private Boolean sendSms(String phoneNum, String data, String codeModel) {

        if (StringUtils.isBlank(phoneNum) || StringUtils.isBlank(data) || StringUtils.isBlank(codeModel)) {
            throw new OpBusinessException(PublicExceptionCodeEnum.EX_PARAM_NOT_NULL.getCode(), PublicExceptionCodeEnum.EX_PARAM_NOT_NULL.getMsg());
        }
        if (redisService.exists(GlobalCacheManageEnum.PHONE_SMS_KEY.getCacheKey(codeModel, phoneNum))) {
            throw new OpBusinessException(ExceptionCodeEnum.EX_PHONE_CODE_IS_USING.getCode(), ExceptionCodeEnum.EX_PHONE_CODE_IS_USING.getMsg());
        }
        // 1:组装发送信息
        String randomKey = KeyGenerater.getRandomKey(32);
        Map<String, String> param = new HashMap<String, String>();
        param.put("appId", phoneSmsAppId);
        param.put("mobile", phoneNum);
        param.put("data", data);
        param.put("codeModel", codeModel);
        param.put("randomKey", randomKey);
        String sign = MD5Facade.getFormDataParamMD5(param, phoneSmsSecretKey, null);
        param.put("sign", sign);
        // 4:获取验证码
        String result;
        try {
            result = HttpClientUtil.doGet(phoneSmsUrl, param);
        } catch (Exception e) {
            throw new RpcInvokeException("sendSms-------" + phoneSmsUrl, e);
        }
        if (StringUtils.isEmpty(result)) {
            // 短信服务器异常
            throw new OpBusinessException(ExceptionCodeEnum.EX_PHONE_SMS_SERVICE_ERROR.getCode(), ExceptionCodeEnum.EX_PHONE_SMS_SERVICE_ERROR.getMsg());
        }
        // 5:解析结果
        ResultVo<Object> stringResultVo = JSONObject.parseObject(result, new TypeReference<ResultVo<Object>>() {
        });
        if (stringResultVo == null || !PublicExceptionCodeEnum.SUCCESS.getCode().equals(stringResultVo.getCode())) {
            throw new OpBusinessException(ExceptionCodeEnum.EX_PHONE_SMS_SERVICE_ERROR.getCode(), ExceptionCodeEnum.EX_PHONE_SMS_SERVICE_ERROR.getMsg(), FastJsonUtil.of("stringResultVo", stringResultVo));
        }
        return true;
    }

远程代码:

@RequestMapping(value = "/sendSms", method = RequestMethod.GET)
    @ResponseBody
    public ResultVo<Object> sendSms(@RequestParam("appId") String appId, @RequestParam("mobile") String mobile,
                                    @RequestParam("data") String data, @RequestParam("codeModel") String codeModel,
                                    @RequestParam("randomKey") String randomKey, @RequestParam("sign") String sign) {
        if (!RegExUtil.isPhoneLegal(mobile)) {
            throw new SmsBusinessException(SmsExceptionCodeEnum.EX_PHONE_IS_ERROR.getCode());
        }
        Map<String, String> param = new HashMap<String, String>(5);
        param.put("appId", appId);
        param.put("mobile", mobile);
        param.put("data", data);
        param.put("codeModel", codeModel);
        param.put("randomKey", randomKey);
        if (!MD5Facade.validateFormDataParamMD5(param, secretKey, sign)) {
            throw new SmsBusinessException(SmsExceptionCodeEnum.EX_SIGN_ERROR.getCode(), FastJsonUtil.of("param", param));
        }
        return aliSmsService.sendCode(mobile, SmsCodeModelEnum.eval(codeModel), data);
    }

配置文件:


image.png
  @Override
    public ResultVo<Object> sendCode(String phoneNum, SmsCodeModelEnum codeModelEnum, String data) {
        ResultVo<Object> resultVo = ResultFactory.success();
        try {
            if (StringUtils.isBlank(phoneNum) || null == codeModelEnum || StringUtils.isBlank(data)) {
                throw new SmsBusinessException(PublicExceptionCodeEnum.Ex_PARAM_ERROR.getCode());
            }
            //设置超时时间-可自行调整
            System.setProperty("sun.net.client.defaultConnectTimeout", timeOut);
            System.setProperty("sun.net.client.defaultReadTimeout", timeOut);
            //初始化ascClient需要的几个参数

            //初始化ascClient,暂时不支持多region(请勿修改)
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKey,
                    accessSecret);
            try {
                DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            } catch (ClientException e) {
                throw new RpcInvokeException("DefaultProfile.addEndpoint" + FastJsonUtil.of("product", product, "domain", domain), e);
            }
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //组装请求对象
            SendSmsRequest request = new SendSmsRequest();
            //使用post提交
            request.setMethod(MethodType.POST);
            //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为00+国际区号+号码,如“0085200000000”
            request.setPhoneNumbers(phoneNum);
            //修改数据交互方式
            request.setAcceptFormat(FormatType.JSON);
            //必填:短信签名-可在短信控制台中找到
            request.setSignName("资明网");
            //必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
            request.setTemplateCode(codeModelEnum.getCode());
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
            request.setTemplateParam(data);

            //请求失败这里会抛ClientException异常
            SendSmsResponse sendSmsResponse = null;
            try {
                sendSmsResponse = acsClient.getAcsResponse(request);
            } catch (ClientException e) {
                throw new RpcInvokeException("acsClient.getAcsResponse-----" + request, e);
            }
            String responseOk = "OK";
            if (sendSmsResponse.getCode() == null || !responseOk.equals(sendSmsResponse.getCode())) {
            //请求成功
                throw new SmsBusinessException(SmsExceptionCodeEnum.EX_HTTP_INVOKE_ERROR.getCode(), FastJsonUtil.of("sendSmsResponse", sendSmsResponse));
            }
        } catch (BusinessBaseException e) {
            LogUtils.logInfoBusinessErrorService(log, "sendCode", e);
            resultVo = ResultFactory.failure(e.getCode(), e.getMsg());
        }
        return resultVo;
    }

短信模板类:

public enum  SmsCodeModelEnum {
    VERIFICATION_MODEL("SMS_********","********通验证码模版"),
    SERVER_ALARM_MODEL("SMS_********","服务器监控报警模板"),
    BASE_VERIFICATION_MODEL("SMS_********","验证码模版"),
    IDENTITY_MODEL("SMS_1********","身份验证模版"),
    LOGIN_CONFIRMATION("SMS_********","登录确认模版"),
    USER_REGISTER("SMS_********","用户注册模版"),
    ;
    private String code;

    private String description;

    SmsCodeModelEnum(String code, String description) {
        this.code = code;
        this.description = description;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public static SmsCodeModelEnum eval(String code) {
        for (SmsCodeModelEnum type : SmsCodeModelEnum.values()) {
            if (type.getCode().equals(code)) {
                return type;
            }
        }
        return null;
    }

    public static boolean contains(String code) {
        for (SmsCodeModelEnum type : SmsCodeModelEnum.values()) {
            if (type.getCode().equals(code)) {
                return true;
            }
        }
        return false;
    }
}
上一篇下一篇

猜你喜欢

热点阅读