搭建企业级微信公众号管理平台(三)----注册码实现与校验,Redis存储

1.统一接口返回结果集格式

接口应用

     /**
     * 功能说明: 获取微信服务接口
     */
    @ApiOperation(value = "微信应用服务接口")
    @GetMapping("/getApp")
    public BaseResponse<AppEntity> getApp();


@RestController
public class WeiXinAppServiceImpl extends BaseApiService<AppEntity> implements WeiXinService{

    public BaseResponse<AppEntity> getApp() {
//        return setResultSuccess(new AppEntity("860074898", "请叫我大又土"));
        return setResultError("系统错误");
    }
   
}

2.正则表达式工具类-验证数据类型

package com.tx.core.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/***
 * @Author Sunny
 * @Description //TODO  正则表达式工具类
 * @Date 11:14 2019/9/17
 * @Param
 * @return
 */
public class RegexUtils {

    /**
     * 验证Email
     *
     * @param email email地址,格式:zhangsan@zuidaima.com,zhangsan@xxx.com.cn,
     *              xxx代表邮件服务商
     * @return 验证成功返回true,验证失败返回false
     */
    public static boolean checkEmail(String email) {
        String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?";
        return Pattern.matches(regex, email);
    }

    /**
     * 验证身份证号码
     *
     * @param idCard 居民身份证号码15位或18位,最后一位可能是数字或字母
     * @return 验证成功返回true,验证失败返回false
     */
    public static boolean checkIdCard(String idCard) {
        String regex = "[1-9]\\d{13,16}[a-zA-Z0-9]{1}";
        return Pattern.matches(regex, idCard);
    }

    /**
     * 验证手机号码(支持国际格式,+86135xxxx...(中国内地),+00852137xxxx...(中国香港))
     *
     * @param mobile 移动、联通、电信运营商的号码段
     *               <p>
     *               移动的号段:134(0-8)、135、136、137、138、139、147(预计用于TD上网卡)
     *               、150、151、152、157(TD专用)、158、159、187(未启用)、188(TD专用) 177 170 166
     *               开头
     *               </p>
     *               <p>
     *               联通的号段:130、131、132、155、156(世界风专用)、185(未启用)、186(3g)
     *               </p>
     *               <p>
     *               电信的号段:133、153、180(未启用)、189
     *               </p>
     * @return 验证成功返回true,验证失败返回false
     */
    public static boolean checkMobile(String mobile) {
        String regex = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
        return Pattern.matches(regex, mobile);
    }

    /**
     * 验证固定电话号码
     *
     * @param phone 电话号码,格式:国家(地区)电话代码 + 区号(城市代码) + 电话号码,如:+8602085588447
     *              <p>
     *              <b>国家(地区) 代码 :</b>标识电话号码的国家(地区)的标准国家(地区)代码。它包含从 0 到 9
     *              的一位或多位数字, 数字之后是空格分隔的国家(地区)代码。
     *              </p>
     *              <p>
     *              <b>区号(城市代码):</b>这可能包含一个或多个从 0 到 9 的数字,地区或城市代码放在圆括号——
     *              对不使用地区或城市代码的国家(地区),则省略该组件。
     *              </p>
     *              <p>
     *              <b>电话号码:</b>这包含从 0 到 9 的一个或多个数字
     *              </p>
     * @return 验证成功返回true,验证失败返回false
     */
    public static boolean checkPhone(String phone) {
        String regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$";
        return Pattern.matches(regex, phone);
    }

    /**
     * 验证整数(正整数和负整数)
     *
     * @param digit 一位或多位0-9之间的整数
     * @return 验证成功返回true,验证失败返回false
     */
    public static boolean checkDigit(String digit) {
        String regex = "\\-?[1-9]\\d+";
        return Pattern.matches(regex, digit);
    }

    /**
     * 验证整数和浮点数(正负整数和正负浮点数)
     *
     * @param decimals 一位或多位0-9之间的浮点数,如:1.23,233.30
     * @return 验证成功返回true,验证失败返回false
     */
    public static boolean checkDecimals(String decimals) {
        String regex = "\\-?[1-9]\\d+(\\.\\d+)?";
        return Pattern.matches(regex, decimals);
    }

    /**
     * 验证空白字符
     *
     * @param blankSpace 空白字符,包括:空格、\t、\n、\r、\f、\x0B
     * @return 验证成功返回true,验证失败返回false
     */
    public static boolean checkBlankSpace(String blankSpace) {
        String regex = "\\s+";
        return Pattern.matches(regex, blankSpace);
    }

    /**
     * 验证中文
     *
     * @param chinese 中文字符
     * @return 验证成功返回true,验证失败返回false
     */
    public static boolean checkChinese(String chinese) {
        String regex = "^[\u4E00-\u9FA5]+$";
        return Pattern.matches(regex, chinese);
    }

    /**
     * 验证日期(年月日)
     *
     * @param birthday 日期,格式:1992-09-03,或1992.09.03
     * @return 验证成功返回true,验证失败返回false
     */
    public static boolean checkBirthday(String birthday) {
        String regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}";
        return Pattern.matches(regex, birthday);
    }

    /**
     * 验证URL地址
     *
     * @param url 格式:http://blog.csdn.net:80/xyang81/article/details/7705960? 或
     *            http://www.csdn.net:80
     * @return 验证成功返回true,验证失败返回false
     */
    public static boolean checkURL(String url) {
        String regex = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=.*)?)?";
        return Pattern.matches(regex, url);
    }

    /**
     * <pre>
     * 获取网址 URL 的一级域
     * </pre>
     *
     * @param url
     * @return
     */
    public static String getDomain(String url) {
        Pattern p = Pattern.compile("(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)",
                Pattern.CASE_INSENSITIVE);
        // 获取完整的域名
        // Pattern
        // p=Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)",
        // Pattern.CASE_INSENSITIVE);
        Matcher matcher = p.matcher(url);
        matcher.find();
        return matcher.group();
    }

    /**
     * 匹配中国邮政编码
     *
     * @param postcode 邮政编码
     * @return 验证成功返回true,验证失败返回false
     */
    public static boolean checkPostcode(String postcode) {
        String regex = "[1-9]\\d{5}";
        return Pattern.matches(regex, postcode);
    }

    /**
     * 匹配IP地址(简单匹配,格式,如:192.168.1.1,127.0.0.1,没有匹配IP段的大小)
     *
     * @param ipAddress IPv4标准地址
     * @return 验证成功返回true,验证失败返回false
     */
    public static boolean checkIpAddress(String ipAddress) {
        String regex = "[1-9](\\d{1,2})?\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))";
        return Pattern.matches(regex, ipAddress);
    }
}

 

3.Redis存储

工具类

package com.tx.serviceweixin.mp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/***
 * @Author Sunny
 * @Description //TODO  Redis工具类
 * @Date 11:14 2019/9/17 * @Param
 * @return
 */
@Component
public class RedisUtil {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 存放string类型
     *
     * @param key     key
     * @param data    数据
     * @param timeout 超时间
     */
    public void setString(String key, String data, Long timeout) {
        stringRedisTemplate.opsForValue().set(key, data);
        if (timeout != null) {
            stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
        }
    }

    /**
     * 存放string类型
     *
     * @param key  key
     * @param data 数据
     */
    public void setString(String key, String data) {
        setString(key, data, null);
    }

    /**
     * 根据key查询string类型
     *
     * @param key
     * @return
     */
    public String getString(String key) {
        String value = stringRedisTemplate.opsForValue().get(key);
        return value;
    }

    /**
     * 根据对应的key删除key
     *
     * @param key
     */
    public void delKey(String key) {
        stringRedisTemplate.delete(key);
    }
}

Maven依赖

  <!-- 集成redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

 

配置文件

spring.redis.host = 39.98.138.14
spring.redis.port = 6379
spring.redis.pool.max-idle = 100
spring.redis.pool.min-idle = 1
spring.redis.pool.max-active = 1000
spring.redis.pool.max-wait = -1
spring.redis.password = 123456
spring.redis.database = 0

 Redis界面

4.注册码生成

// 1. 获取微信客户端发送的消息
        String fromContent = wxMessage.getContent();
        // 2.使用正则表达式验证消息是否为手机号码格式
        if (RegexUtils.checkMobile(fromContent)) {
            // 3.如果是手机号码格式的话,随机生产4位数字注册码
            int registCode = registCode();
            // 将配置文件中的您的注册码为:%s中的%s替换为注册码
            String content = registrationCodeMessage.format(registrationCodeMessage, registCode);
            // 将注册码存入在redis中 key为手机号码
            redisUtil.setString(Constant.WEIXINCODE_KEY + fromContent, registCode + "", Constant.WEIXINCODE_TIMEOUT);
            return new TextBuilder().build(content, wxMessage, weixinService);
        }
        // 否则情况下返回默认消息 调用第三方机器人接口
        return new TextBuilder().build(defaultRegistrationCodeMessage, wxMessage, weixinService);





 // 生成注册码
    private int registCode() {
        int registCode = (int) (Math.random() * 9000 + 1000);
        return registCode;
    }

 

5.注册码校验

接口定义

package com.tx.apiweixin.service;

import com.alibaba.fastjson.JSONObject;
import com.tx.core.base.BaseResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;

/***
 * @Author Sunny
 * @Description //TODO  微信服务注册码验证接口
 * @Date 11:14 2019/9/17
 * @Param
 * @return
 */
@Api(tags = "微信注册码验证码接口")
public interface VerificaCodeService {

	/**
	 * 功能说明:根据手机号码验证码token是否正确
	 * 
	 * @return
	 */
	@ApiOperation(value = "根据手机号码验证码token是否正确")
	@GetMapping("/verificaWeixinCode")
	@ApiImplicitParams({
			// @ApiImplicitParam(paramType="header",name="name",dataType="String",required=true,value="用户的姓名",defaultValue="zhaojigang"),
			@ApiImplicitParam(paramType = "query", name = "phone", dataType = "String", required = true, value = "用户手机号码"),
			@ApiImplicitParam(paramType = "query", name = "weixinCode", dataType = "String", required = true, value = "微信注册码") })
	public BaseResponse<JSONObject> verificaWeixinCode(String phone, String weixinCode);
}

接口实现 

package com.tx.serviceweixin.impl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

//import com.ctc.wstx.util.StringUtil;
import com.tx.core.base.BaseApiService;
import com.tx.core.base.BaseResponse;
import com.tx.core.constants.Constant;
import com.tx.serviceweixin.mp.utils.RedisUtil;
import com.tx.apiweixin.service.VerificaCodeService;

@RestController
public class VerificaCodeServiceImpl extends BaseApiService<JSONObject> implements VerificaCodeService {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public BaseResponse<JSONObject> verificaWeixinCode(String phone, String weixinCode) {
        // 1.验证码参数是否为空
        if (StringUtils.isEmpty(phone)) {
            return setResultError("手机号码不能为空!");
        }
        if (StringUtils.isEmpty(weixinCode)) {
            return setResultError("注册码不能为空!");
        }
        // 2.根据手机号码查询redis返回对应的注册码
        String weixinCodeKey = Constant.WEIXINCODE_KEY + phone;
        String redisCode = redisUtil.getString(weixinCodeKey);
        if (StringUtils.isEmpty(redisCode)) {
            return setResultError("注册码可能已经过期!!");
        }
        // 3.redis中的注册码与传递参数的weixinCode进行比对
        if (!redisCode.equals(weixinCode)) {
            return setResultError("注册码不正确");
        }
        // 移出对应验证码
        redisUtil.delKey(weixinCodeKey);
        return setResultSuccess("验证码比对正确");
    }

}

接口校验

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值