搭建企业级微信公众号管理平台(三)----注册码实现与校验,Redis存储
生活随笔
收集整理的這篇文章主要介紹了
搭建企业级微信公众号管理平台(三)----注册码实现与校验,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 {@Autowiredprivate 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 {@Autowiredprivate RedisUtil redisUtil;@Overridepublic 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("驗證碼比對正確");}}接口校驗
?
?
總結
以上是生活随笔為你收集整理的搭建企业级微信公众号管理平台(三)----注册码实现与校验,Redis存储的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 点图
- 下一篇: Redis五种数据类型及命令(一)