1.引言2.开发前准备
2.1 注册码功能开发思路2.2 Redis服务器搭建2.3.开发前项目结构整理 3.注册功能开发
3.3.注册功能开发
3.3.1.Redis封装3.3.2 正则表达式工具类3.3.3 MsgHandler验证码处理 3.2 验证注册码 4.测试
4.1 获取注册码4.2 校验注册码 5.总结
1.引言上一节《果然新鲜电商项目(18)- 项目整合WxJava》,主要讲解如何把WxJava框架整合到我们的电商项目,并完成了“鹦鹉学舌”的功能。
本文主要实现「注册码功能」。在公众号里输入手机号码获取注册码的功能,验证注册码的功能。
2.开发前准备 2.1 注册码功能开发思路本文的开发流程主要如下:
Redis的安装教程,本文不再具体详述.
目前项目结构是这样的:
其实项目结构还可以优化的,有两点:
- 将服务接口层的实体类抽出到一个模块,专门用来管理实体类。统一规定微服务接口状态码
整理后的结构如下:
baseResponse代码如下:
package com.guoranxinxian.entity; import lombok.Data; @Data public class baseResponse{ private Integer code; private String msg; private T data; // 分页 public baseResponse() { } public baseResponse(Integer code, String msg, T data) { super(); this.code = code; this.msg = msg; this.data = data; } }
baseApiService代码如下:
package com.guoranxinxian.entity; import com.guoranxinxian.api.baseResponse; import com.guoranxinxian.constants.Constants; import lombok.Data; import org.springframework.stereotype.Component; @Data @Component public class baseApiService{ public baseResponse setResultError(Integer code, String msg) { return setResult(code, msg, null); } // 返回错误,可以传msg public baseResponse setResultError(String msg) { return setResult(Constants.HTTP_RES_CODE_500, msg, null); } // 返回成功,可以传data值 public baseResponse setResultSuccess(Object data) { return setResult(Constants.HTTP_RES_CODE_200, Constants.HTTP_RES_CODE_200_VALUE, data); } // 返回成功,沒有data值 public baseResponse setResultSuccess() { return setResult(Constants.HTTP_RES_CODE_200, Constants.HTTP_RES_CODE_200_VALUE, null); } // 返回成功,沒有data值 public baseResponse setResultSuccess(String msg) { return setResult(Constants.HTTP_RES_CODE_200, msg, null); } // 通用封装 public baseResponse setResult(Integer code, String msg, Object data) { return new baseResponse(code, msg, data); } }
Constants代码如下:
package com.guoranxinxian.constants;
public interface Constants {
// 响应请求成功
String HTTP_RES_CODE_200_VALUE = "success";
// 系统错误
String HTTP_RES_CODE_500_VALUE = "fial";
// 响应请求成功code
Integer HTTP_RES_CODE_200 = 200;
// 系统错误
Integer HTTP_RES_CODE_500 = 500;
// 未关联QQ账号
Integer HTTP_RES_CODE_201 = 201;
// 发送邮件
String MSG_EMAIL = "email";
// 会员token
String TOKEN_MEMBER = "TOKEN_MEMBER";
// 用户有效期 90天
Long TOKEN_MEMBER_TIME = (long) (60 * 60 * 24 * 90);
int cookie_TOKEN_MEMBER_TIME = (60 * 60 * 24 * 90);
// cookie 会员 totoken 名称
String cookie_MEMBER_TOKEN = "cookie_member_token";
// 微信code
String WEIXINCODE_KEY = "weixin.code";
// 微信注册码有效期3分钟
Long WEIXINCODE_TIMEOUT = 180l;
// 用户信息不存在
Integer HTTP_RES_CODE_EXISTMOBILE_203 = 203;
// token
String MEMBER_TOKEN_KEYPREFIX = "guoranxinxian.member.login";
// 安卓的登陆类型
String MEMBER_LOGIN_TYPE_ANDROID = "Android";
// IOS的登陆类型
String MEMBER_LOGIN_TYPE_IOS = "IOS";
// PC的登陆类型
String MEMBER_LOGIN_TYPE_PC = "PC";
// 登陆超时时间 有效期 90天
Long MEMBRE_LOGIN_TOKEN_TIME = 77776000L;
}
3.注册功能开发
在上一节已经WxJava框架整合到我们的电商项目,并在MsgHandler类里面处理收到的信息,完成了“鹦鹉学舌”的功能,下面开始讲解如何实现注册码功能。
3.3.注册功能开发 3.3.1.Redis封装- 添加maven依赖(guoranxinxian-shop-common-core模块里添加):
org.springframework.boot spring-boot-starter-data-redis
- 在业务模块(guoranxinxian-shop-service-weixin)配置redis(也可以配置到Apollo配置中心):
###服务名称(服务注册到eureka名称)
spring:
application:
name: guoranxinxian-shop-service-weixin
redis:
host: 127.0.0.1
port: 6379
jedis:
pool:
max-idle: 100
min-idle: 1
max-active: 1000
max-wait: -1
### 公众号默认回复消息
guoranxinian:
weixin:
registration:
code:
###微信注册码消息
message: 您的注册码为:%s,欢迎您注册我们的系统!
###默认提示消息
default:
registration:
code:
message: 我们已经收到您的消息,将有客服会及时回复您的!
- 定义RedisUtil工具类(guoranxinxian-shop-common-core模块里添加):
package com.guoranxinxian.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public Boolean setNx(String key, String value, Long timeout) {
Boolean setIfAbsent = stringRedisTemplate.opsForValue().setIfAbsent(key, value);
if (timeout != null) {
stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
return setIfAbsent;
}
public void setString(String key, String data, Long timeout) {
try {
stringRedisTemplate.opsForValue().set(key, data);
if (timeout != null) {
stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
} catch (Exception e) {
}
}
public void begin() {
// 开启Redis 事务权限
stringRedisTemplate.setEnableTransactionSupport(true);
// 开启事务
stringRedisTemplate.multi();
}
public void exec() {
// 成功提交事务
stringRedisTemplate.exec();
}
public void discard() {
stringRedisTemplate.discard();
}
public void setString(String key, String data) {
setString(key, data, null);
}
public String getString(String key) {
String value = stringRedisTemplate.opsForValue().get(key);
return value;
}
public Boolean delKey(String key) {
return stringRedisTemplate.delete(key);
}
public void setList(String key, List listToken) {
stringRedisTemplate.opsForList().leftPushAll(key, listToken);
}
public StringRedisTemplate getStringRedisTemplate() {
return stringRedisTemplate;
}
}
3.3.2 正则表达式工具类
package com.guoranxinxian.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexUtils {
public static boolean checkEmail(String email) {
String regex = "\w+@\w+\.[a-z]+(\.[a-z]+)?";
return Pattern.matches(regex, email);
}
public static boolean checkIdCard(String idCard) {
String regex = "[1-9]\d{13,16}[a-zA-Z0-9]{1}";
return Pattern.matches(regex, idCard);
}
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);
}
public static boolean checkPhone(String phone) {
String regex = "(\+\d+)?(\d{3,4}\-?)?\d{7,8}$";
return Pattern.matches(regex, phone);
}
public static boolean checkDigit(String digit) {
String regex = "\-?[1-9]\d+";
return Pattern.matches(regex, digit);
}
public static boolean checkDecimals(String decimals) {
String regex = "\-?[1-9]\d+(\.\d+)?";
return Pattern.matches(regex, decimals);
}
public static boolean checkBlankSpace(String blankSpace) {
String regex = "\s+";
return Pattern.matches(regex, blankSpace);
}
public static boolean checkChinese(String chinese) {
String regex = "^[u4E00-u9FA5]+$";
return Pattern.matches(regex, chinese);
}
public static boolean checkBirthday(String birthday) {
String regex = "[1-9]{4}([-./])\d{1,2}\1\d{1,2}";
return Pattern.matches(regex, birthday);
}
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);
}
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();
}
public static boolean checkPostcode(String postcode) {
String regex = "[1-9]\d{5}";
return Pattern.matches(regex, postcode);
}
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.3.3 MsgHandler验证码处理
1.在服务模块(guoranxinxian-shop-service)添加Maven依赖:
com.guoranxinxian guoranxinxian-shop-common-core 1.0-SNAPSHOT
2.MsgHandler生成验证码,并把验证码保存到Redis服务器,完整代码如下:
package com.guoranxinxian.mp.handler;
import com.guoranxinxian.constants.Constants;
import com.guoranxinxian.mp.builder.TextBuilder;
import com.guoranxinxian.util.RedisUtil;
import com.guoranxinxian.util.RegexUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import java.util.Map;
import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;
@Component
public class MsgHandler extends AbstractHandler {
@Value("${guoranxinian.weixin.registration.code.message}")
private String registrationCodeMessage;
@Value("${guoranxinian.weixin.default.registration.code.message}")
private String defaultRegistrationCodeMessage;
@Autowired
private RedisUtil redisUtil;
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
Map context, WxMpService weixinService,
WxSessionManager sessionManager) {
if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
// TODO 可以选择将消息保存到本地
}
// 当用户输入关键词如“你好”,“客服”等,并且有客服在线时,把消息转发给在线客服
try {
if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
&& weixinService.getKefuService().kfOnlineList().getKfOnlineList().size() > 0) {
return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE().fromUser(wxMessage.getToUser())
.toUser(wxMessage.getFromUser()).build();
}
} catch (WxErrorException e) {
e.printStackTrace();
}
// 1.获取客户端发送的消息
String fromContent = wxMessage.getContent();
// 2.如果客户端发送消息为手机号码,则发送验证码
if (RegexUtils.checkMobile(fromContent)) {
// 3.生成随机四位注册码
int registCode = registCode();
String content = String.format(registrationCodeMessage, registCode);
// 4.将验证码存放在Redis中
redisUtil.setString(Constants.WEIXINCODE_KEY + fromContent, registCode + "", Constants.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;
}
}
3.2 验证注册码
1.定义验证接口(微信服务接口层guoranxinxian-shop-service-api-weixin):
package com.guoranxinxian.service;
import com.alibaba.fastjson.JSONObject;
import com.guoranxinxian.api.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;
@Api(tags = "微信注册码验证码接口")
public interface VerificaCodeService {
@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 = "微信注册码") })
baseResponse verificaWeixinCode(String phone, String weixinCode);
}
2.实现接口(微信业务层guoranxinxian-shop-service-weixin):
package com.guoranxinxian.impl; import com.alibaba.fastjson.JSONObject; import com.guoranxinxian.api.baseResponse; import com.guoranxinxian.constants.Constants; import com.guoranxinxian.entity.baseApiService; import com.guoranxinxian.service.VerificaCodeService; import com.guoranxinxian.util.RedisUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RestController; @RestController public class VerificaCodeServiceImpl extends baseApiService4.测试implements VerificaCodeService { @Autowired private RedisUtil redisUtil; @Override public baseResponse verificaWeixinCode(String phone, String weixinCode) { if (StringUtils.isEmpty(phone)) { return setResultError("手机号码不能为空!"); } if (StringUtils.isEmpty(weixinCode)) { return setResultError("注册码不能为空!"); } String code = redisUtil.getString(Constants.WEIXINCODE_KEY + phone); if (StringUtils.isEmpty(code)) { return setResultError("注册码已经过期,请重新发送验证码"); } if (!code.equals(weixinCode)) { return setResultError("注册码不正确"); } return setResultSuccess("注册码验证码正确"); } }
启动微信服务:AppWeiXin
4.1 获取注册码注意:代码里设置微信注册码超时时间为3分钟!
首先发送手机号,可以看到:
我们在Redis可视化窗口里也可以看到:



