若依实现手机验证码登入功能及企业微信机器人预警功能

若依框架实现验证码登入
有效期为5分钟,由于阿里电话短信服务有同一appCode给同一用户10分钟最多只能发送3条短信的限制,这里尽可能的提高用户的体验度和系统的可用性!有设置了2分钟不可重复发送的限制。
查询redis对用key所剩时间的代码如下:

Long phoneLong = redisTemplate.opsForValue().getOperations().getExpire(phone);

可以看得到获取得到的数据类型是long,单位是秒。

主要代码如下

//发送短信的方法,短信都是要发送到手机上的,所以会需要手机号
    @PostMapping("send/{phone}")
    public AjaxResult sendMsm(@PathVariable String phone){
        //1.从redis中获取验证码,如果获取到则直接返回
        String code = redisCache.getCacheObject(phone);
        if (!StringUtils.isEmpty(code)){
            //获取redis数据过期时间
            Long phoneLong = redisTemplate.opsForValue().getOperations().getExpire(phone);
            if (phoneLong > 180L){
                return AjaxResult.error("验证发已送达,请不要在两分钟内重复发送");
            }
//            System.out.println("key的过期时间:"+phoneLong);
            redisCache.deleteObject(phone);
//            return AjaxResult.error("验证发已送达,请不要重复发送");
        }
        //2.获取不到的话,那直接生成发送
        //生成随机的值,传递给阿里云进行发送
        String str="0123456789";
        StringBuilder sb=new StringBuilder(4);
        for(int i=0;i<4;i++) {
            char ch = str.charAt(new Random().nextInt(str.length()));
            sb.append(ch);
        }
        code = sb.toString();
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
        //调用service发送短信方法
        boolean isSend = msmService.send(param,phone);
        if (isSend){
            //发送成功,把发送成功的验证码放到redis中去,同时设置有效时间
//            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);//设置了五分钟的有效时长
            // 保存验证码信息
            String uuid = IdUtils.simpleUUID(); //生成一个uuid
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
            redisCache.setCacheObject(verifyKey, code, 5, TimeUnit.MINUTES);
            redisCache.setCacheObject(phone, code, 5, TimeUnit.MINUTES);
//            System.out.println("已经打入redis中");
            return AjaxResult.success();
        }else {
            return AjaxResult.error("短信发送失败");
        }
    }

send方法对应service代码如下

package com.ruoyi.system.service;

import java.util.Map;

public interface MsmService {
    boolean send(Map<String, Object> param, String phone);

    /**
     * v2登录接口(自建应用)
     * @param text
     * @return
     */
    void postXiaoRun(String text);
}

send对应imp代码如下

package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.service.MsmService;
import com.ruoyi.system.utils.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 阿里验证码发送规则:
 * 10分钟只准许给通一个电话发送3条消息
 * 1天只准许给通一个电话号码发送40条
 */
@Service
public class MsmServiceImpl implements MsmService {
    //发送短信的方法
    public boolean send(Map<String, Object> param, String phone) {
        String host = "https://wwsms.market.alicloudapi.com";
        String path = "/send_sms";
        String method = "POST";
        String appcode = "***你自己的appCode值(要注意这里适用的是appCode类型的,ali还提供了另外一种类型,如需要请根据官网调整)";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe9****
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求,定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("content", "code:"+"***你想传入的数据");
        bodys.put("phone_number", phone);
        bodys.put("template_id", "***你自己的样板代码");


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString()+"携带了什么");
            //获取response的body
            String entitys = EntityUtils.toString(response.getEntity());
            System.out.println(entitys+"状态为:*********");
            if (response.toString().indexOf("403") != -1 && entitys.indexOf("Quota Exhausted") != -1){
                postXiaoRun("短信发送失败了原因是次数用完了快去通知Oscar!!!");
                System.out.println("发送验证码没有成功原因是次数用完了");
                return false;
            }else if (response.toString().indexOf("400") != -1){
                postXiaoRun("短信发送失败了原因是请求参数出问题了快去通知Henry!!!");
                System.out.println("短信发送失败了原因是请求参数出问题了快去通知Henry");
                return false;
            }else if (response.toString().indexOf("401") != -1){
                postXiaoRun("短信发送失败了原因是未授权或授权失败快去通知Henry!!!");
                System.out.println("短信发送失败了原因是未授权或授权失败快去通知Henry");
                return false;
            }else if (response.toString().indexOf("403") != -1 && entitys.indexOf("RATE_LIMIT") != -1){
                postXiaoRun("短信发送失败了原因是"+phone+"手机号的调用超出频率的限额(同一用户10分钟内只能发送三次,一个自然日最多发送50次!)快去通知Henry!!!");
                System.out.println("短信发送失败了原因是调用超出频率的限额(同一用户10分钟内只能发送三次,一个自然日最多发送50次!)快去通知Henry");
                return false;
            }else if (response.toString().indexOf("404") != -1){
                postXiaoRun("短信发送失败了原因是请求路径错误快去通知Henry!!!");
                System.out.println("短信发送失败了原因是请求路径错误快去通知Henry");
                return false;
            }else if (response.toString().indexOf("500") != -1){
                postXiaoRun("短信发送失败了原因是服务器错通知谁也没用了!!!");
                System.out.println("短信发送失败了原因是服务器错通知谁也没用了");
                return false;
            }else if (response.toString().indexOf("512") != -1){
                postXiaoRun("短信发送失败了原因是短信通道暂不可用快去通知ali!!!");
                System.out.println("短信发送失败了原因是短信通道暂不可用快去通知ali");
                return false;
            }else if (response.toString().indexOf("403") != -1 && entitys.indexOf("Unauthorized") != -1){
                postXiaoRun("短信发送失败了原因是不能跨商品调用快去通知Henry!!!");
                System.out.println("短信发送失败了原因是不能跨商品调用快去通知Henry");
                return false;
            }else{
                System.out.println(phone+"手机号验证码发送成功");
            }
            return true;
        } catch (Exception e) {
            postXiaoRun("短信发送失败了快去通知Henry!!!");
            e.printStackTrace();
            return false;
        }
        //验证码的过期问题用redis实现
    }

    @Override
    public void postXiaoRun(String text){
        String url = "https://qyapi.weixin.qq.com/cgi-bin/***你企业微信机器人的访问接口";
        //        请求表
        JSONObject paramMap = new JSONObject();
        paramMap.put("msgtype", "text");
        JSONObject textJson = new JSONObject();
        textJson.put("content",text);
        ArrayList<String> mentionedList = new ArrayList<>();
        mentionedList.add("@all");
        textJson.put("mentioned_list",mentionedList);
        paramMap.put("text",textJson);
        //        请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("user-agent", "Mozilla/5.0 WindSnowLi-Blog");
        //        整合请求头和请求参数
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(paramMap, headers);
        //         请求客户端
        RestTemplate client = new RestTemplate();
        //      发起请求
        JSONObject body = client.postForEntity(url, httpEntity, JSONObject.class).getBody();
//        System.out.println("******** POST请求 *********");
        assert body != null;
//        System.out.println(body.toJSONString());
    }

}

从上面不难发现,有很多关于发送状态的提示!考虑到购买短信服务的手机号不在你我手里所以这里添加一个机器人提醒的功能还是很有必要的!如果没有在程序因为条数不够而报错时咱们只能背黑锅了!这里务必要加上!

doPst涉及到的代码如下:

package com.ruoyi.system.utils;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.ruoyi.common.utils.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpUtils {

    /**
     * get
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doGet(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    /**
     * post form
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param bodys
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      Map<String, String> bodys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        return httpClient.execute(request);
    }

    /**
     * Post String
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    /**
     * Post stream
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    /**
     * Put String
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys,
                                     String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    /**
     * Put stream
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys,
                                     byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    /**
     * Delete
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doDelete(String host, String path, String method,
                                        Map<String, String> headers,
                                        Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }

    private static HttpClient wrapClient(String host) {
        HttpClient httpClient = new DefaultHttpClient();
        if (host.startsWith("https://")) {
            sslClient(httpClient);
        }

        return httpClient;
    }

    private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] xcs, String str) {

                }
                public void checkServerTrusted(X509Certificate[] xcs, String str) {

                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }
}

需要阿里的jar引入代码如下

        <!--案例云-电话发送验证码-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.2.1</version>
        </dependency>

基本上就这些了,要是还有什么没有提到的请积极沟通一起进步!

Logo

快速构建 Web 应用程序

更多推荐