发送手机验证码

public R getVerifyCode(String phone) {    if (redisTemplate.hasKey(Constant.PREFIX_VER + phone)) {        return R.error("请不要频繁发送短息");    } else {        // 生成6位验证码        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);        if (nutsMessageUtil.sendVerifyCode(phone, verifyCode)) {            //未使用验证码情况下,60类不能重复发送            redisTemplate.opsForValue().set(Constant.PREFIX_VER + phone, "SEND", 60, TimeUnit.SECONDS);            //验证码5分钟内有效,使用后失效            redisTemplate.opsForValue().set(phone, verifyCode, 5, TimeUnit.MINUTES);            //return R.ok().setMsg("验证码:"+verifyCode);            return R.ok().setMsg("短信发送成功");        } else {            return R.error("获取验证码失败");        }    }}
/** * 发送验证码给收件人 * @param mobile * @param code * @return */public  boolean sendVerifyCode(String mobile, String code) {    JSONObject map = new JSONObject();    map.put("templateCode",NUSTS_MSG_APP_TEMPLATE_VER);    JSONObject json = new JSONObject();    json.put("No", code);    map.put("templateParam", json);    map.put("userId",mobile);    return sendRequest(map);}
/** * @param map 请求参数 * @return */public  Boolean sendRequest(JSONObject map) {    map.put("accessId",NUSTS_MSG_APP_ACCESSID);    map.put("accessToken",NUSTS_MSG_APP_ACCESSTOKEN);    String stringJson = JSON.toJSONString(map);    String body = HttpClientUtil.doPostJson(NUSTS_MSG_API, stringJson);    JSONObject jsonObject = JSONObject.parseObject(body);    if (jsonObject.getBooleanValue("success")){        return true;    }else {        log.info("短信发送失败,失败编码:{},描述信息:{}",jsonObject.get("errorCode"),jsonObject.get("errorMessage"));        return false;    }}
/** * 发post请求 传入xml/json字符串 * @param url * @param json * @return */public static String doPostJson(String url, String json) {    log.info("POST请求地址:{},请求参数内容:{}",url,json);    // 创建Httpclient对象    CloseableHttpClient httpClient = HttpClients.createDefault();    CloseableHttpResponse response = null;    String resultString = "";    try {        // 创建Http Post请求        HttpPost httpPost = new HttpPost(url);        // 创建请求内容        StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);        httpPost.setEntity(entity);        // 执行http请求        response = httpClient.execute(httpPost);        resultString = EntityUtils.toString(response.getEntity(), "utf-8");    } catch (Exception e) {        e.printStackTrace();    } finally {        try {            response.close();        } catch (IOException e) {            e.printStackTrace();        }    }    log.info("POST响应参数:{}",resultString);    return resultString;}

相关推荐