Commit c12f57c3 authored by kongfm's avatar kongfm

微信后台服务搭建 及 微信公众号openid 及 手机号绑定

parent 9134c415
......@@ -64,7 +64,7 @@ public class ControllerAop {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 不需要添加请求头的接口
String[] url = new String[]{"/api/user/selectInfo", "/api/user/save/curCompany", "/jcs/command/lookHtmlText", "/jcs/common/duty-person/findByDutyAreaId"};
String[] url = new String[]{"/api/user/selectInfo", "/api/user/save/curCompany", "/jcs/command/lookHtmlText", "/jcs/common/duty-person/findByDutyAreaId", "/tzs/wechatBack"};
// 获取请求路径
for(String uri : url) {
if(request.getRequestURI().indexOf(uri) != -1) {
......
......@@ -30,6 +30,8 @@ public class RedisKey {
public static final String TZS_ALERTCALLED_ID="tzs_alertcalled_id_";
/**联通CTI token */
public static final String CTI_TOKEN = "cti_token";
/**微信公众平台 token */
public static final String WECHAT_TOKEN = "wechat_token";
/** 驼峰转下划线(简单写法,效率低于 ) */
public static String humpToLine(String str) {
......
package com.yeejoin.amos.boot.module.tzs.api.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* 微信验证DTO
*/
@Data
@Accessors(chain = true)
@ApiModel(value = "WechatDto", description = "WechatDto")
public class WechatDto {
@ApiModelProperty(value = "微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数")
private String signature;
@ApiModelProperty(value = "时间戳")
private String timestamp;
@ApiModelProperty(value = "随机数")
private String nonce;
@ApiModelProperty(value = "随机字符串")
private String echostr;
}
package com.yeejoin.amos.boot.module.tzs.api.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import com.yeejoin.amos.boot.biz.common.dto.BaseDto;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* 微信公众号openid与电话号对应关系表
*
* @author system_generator
* @date 2021-09-22
*/
@Data
@ApiModel(value="WechatRelationDto", description="微信公众号openid与电话号对应关系表")
public class WechatRelationDto {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "微信公众号openid")
private String openId;
@ApiModelProperty(value = "系统注册账户电话号")
private String phone;
@ApiModelProperty(value = "验证码")
private String code;
}
package com.yeejoin.amos.boot.module.tzs.api.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.util.Date;
/**
* 微信公众号openid与电话号对应关系表
*
* @author system_generator
* @date 2021-09-22
*/
@Data
@Accessors(chain = true)
@TableName("tz_wechat_relation")
public class WechatRelation {
private static final long serialVersionUID = 1L;
@TableId(value = "sequence_nbr", type = IdType.ID_WORKER)
protected Long sequenceNbr;
/**
* 微信公众号openid
*/
@TableField("open_id")
private String openId;
/**
* 系统注册账户电话号
*/
@TableField("phone")
private String phone;
}
package com.yeejoin.amos.boot.module.tzs.api.mapper;
import com.yeejoin.amos.boot.module.tzs.api.entity.WechatRelation;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* 微信公众号openid与电话号对应关系表 Mapper 接口
*
* @author system_generator
* @date 2021-09-22
*/
public interface WechatRelationMapper extends BaseMapper<WechatRelation> {
}
package com.yeejoin.amos.boot.module.tzs.api.service;
/**
* 微信公众号openid与电话号对应关系表接口类
*
* @author system_generator
* @date 2021-09-22
*/
public interface IWechatRelationService {
}
package com.yeejoin.amos.boot.module.tzs.api.service;
/**
* 微信公众号服务类
*/
public interface IWechatService {
/**
* 获取token
* @return
*/
String getAccessToken();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yeejoin.amos.boot.module.tzs.api.mapper.WechatRelationMapper">
</mapper>
package com.yeejoin.amos.boot.module.tzs.biz.controller;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.tzs.api.service.IWechatService;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.SmsRecordModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* 微信公众号controller
*/
@RestController
@Api(tags = "微信公众号Api")
@RequestMapping(value = "/wechatBack")
public class WechatController extends BaseController {
private long time = 600l;
private final String token = "yeejoin_2021";
@Autowired
RedisUtils redisUtils;
@Autowired
private IWechatService wechatService;
/**
* 获取微信回调信息返回验证是否通过
* @param signature
* @param timestamp
* @param nonce
* @param echostr
* @return
*/
@TycloudOperation(ApiLevel = UserType.ANONYMOUS , needAuth = false)
@GetMapping(value = "/getInfo")
@ApiOperation(httpMethod = "GET", value = "获取微信传回的get信息", notes = "获取微信传回的get信息")
public String getWechatInfo(@RequestParam String signature,@RequestParam String timestamp,@RequestParam String nonce,@RequestParam String echostr) {
List<String> params = new ArrayList<String>();
params.add(token);
params.add(timestamp);
params.add(nonce);
Collections.sort(params);
String tokenStr = StringUtils.join(params,"");
tokenStr = DigestUtils.sha1Hex(tokenStr);
if(tokenStr.equals(signature)) {
return echostr;
} else {
return "";
}
}
/**
* 获取微信推送的操作通知
* @param xml
* @param resp
* @return
*/
@TycloudOperation(ApiLevel = UserType.ANONYMOUS , needAuth = false)
@PostMapping(value = "/getInfo")
@ApiOperation(httpMethod = "POST", value = "获取微信传回的post信息", notes = "获取微信传回的post信息")
public String getWechatInfoPost(@RequestBody String xml, HttpServletResponse resp) {
Map<String, String> requtstMap = xmlToMap(xml);
return "1";
}
/**
* XML格式字符串转换为Map
*
* @param xml XML字符串
* @return XML数据转换后的Map
* @throws Exception
*/
public static Map<String, String> xmlToMap(String xml) {
try {
Map<String, String> data = new HashMap<>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
org.w3c.dom.Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int idx = 0; idx < nodeList.getLength(); ++idx) {
Node node = nodeList.item(idx);
if (node.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element element = (org.w3c.dom.Element) node;
data.put(element.getNodeName(), element.getTextContent());
}
}
stream.close();
return data;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取wechatToken信息
*
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@GetMapping(value = "/getAccessToken")
@ApiOperation(httpMethod = "GET", value = "获取token信息", notes = "获取token信息")
public ResponseModel<String> getAccessToken() {
String token = wechatService.getAccessToken();
return ResponseHelper.buildResponse(token);
}
/**
* 根据手机号发送短信验证码
* @param tel
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@GetMapping(value = "/sendSms/{tel}")
@ApiOperation(httpMethod = "GET", value = "根据手机号发送短信验证码", notes = "根据手机号发送短信验证码")
public ResponseModel<Boolean> sendSmsCode(@PathVariable String tel) {
Boolean flag = false;
String code = getrandom();
HashMap<String, String> params = new HashMap<>();
params.put("smsCode","SMS_TZS_0001");
params.put("mobile",tel);
params.put("code",code);
FeignClientResult<SmsRecordModel> result = Systemctl.smsClient.sendCommonSms(params);
if(result.getStatus() == 200) {
flag = true;
// code 保存在redis中 设置10分钟过期时间
redisUtils.set("tel_code_" + tel, code,time);
}
return ResponseHelper.buildResponse(flag);
}
public static String getrandom(){
String code = "";
Random random = new Random();
for (int i = 0; i < 6; i++) {
int r = random.nextInt(10); //每次随机出一个数字(0-9)
code = code + r; //把每次随机出的数字拼在一起
}
return code;
}
}
package com.yeejoin.amos.boot.module.tzs.biz.controller;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RestController;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import java.util.List;
import com.yeejoin.amos.boot.module.tzs.biz.service.impl.WechatRelationServiceImpl;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.tzs.api.dto.WechatRelationDto;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
/**
* 微信公众号openid与电话号对应关系表
*
* @author system_generator
* @date 2021-09-22
*/
@RestController
@Api(tags = "微信公众号openid与电话号对应关系表Api")
@RequestMapping(value = "/wechat-relation")
public class WechatRelationController extends BaseController {
@Autowired
WechatRelationServiceImpl wechatRelationServiceImpl;
@Autowired
RedisUtils redisUtils;
/**
* 新增微信公众号openid与电话号对应关系表
*
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@PostMapping(value = "/save")
@ApiOperation(httpMethod = "POST", value = "新增微信公众号openid与电话号对应关系表", notes = "新增微信公众号openid与电话号对应关系表")
public ResponseModel<WechatRelationDto> save(@RequestBody WechatRelationDto model) {
if (ValidationUtil.isEmpty(model.getOpenId())
|| ValidationUtil.isEmpty(model.getPhone())
|| ValidationUtil.isEmpty(model.getCode()))
throw new BadRequest("参数校验失败.");
if(!model.getCode().equals(redisUtils.get("tel_code_" + model.getPhone()))) {
throw new BadRequest("验证码验证失败!");
}
model = wechatRelationServiceImpl.createWithModel(model);
return ResponseHelper.buildResponse(model);
}
}
package com.yeejoin.amos.boot.module.tzs.biz.service.impl;
import com.yeejoin.amos.boot.module.tzs.api.entity.WechatRelation;
import com.yeejoin.amos.boot.module.tzs.api.mapper.WechatRelationMapper;
import com.yeejoin.amos.boot.module.tzs.api.service.IWechatRelationService;
import com.yeejoin.amos.boot.module.tzs.api.dto.WechatRelationDto;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;
/**
* 微信公众号openid与电话号对应关系表服务实现类
*
* @author system_generator
* @date 2021-09-22
*/
@Service
public class WechatRelationServiceImpl extends BaseService<WechatRelationDto,WechatRelation,WechatRelationMapper> implements IWechatRelationService {
/**
* 分页查询
*/
public Page<WechatRelationDto> queryForWechatRelationPage(Page<WechatRelationDto> page) {
return this.queryForPage(page, null, false);
}
/**
* 列表查询 示例
*/
public List<WechatRelationDto> queryForWechatRelationList() {
return this.queryForList("" , false);
}
}
\ No newline at end of file
package com.yeejoin.amos.boot.module.tzs.biz.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.tzs.api.service.IWechatService;
import com.yeejoin.amos.boot.module.tzs.biz.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import java.util.HashMap;
import java.util.Map;
/**
* 微信公众号服务实现类
*/
@Service
public class WechatServiceImpl implements IWechatService {
@Autowired
RedisUtils redisUtils;
/**
* token 过期时间,wechat 系统为7200 ,tzs 系统小于7200 防止获取到无效token
*/
private long time = 6000l;
@Value("${tzs.wechat.appid}")
private String APP_ID;
@Value("${tzs.wechat.secret}")
private String SECRET_KEY;
@Value("${tzs.wechat.url}")
private String wechatUrl;
@Override
public String getAccessToken() {
if(redisUtils.hasKey(RedisKey.WECHAT_TOKEN)){
Object obj= redisUtils.get(RedisKey.WECHAT_TOKEN);
return obj.toString();
} else {
String tokenAccessUrl = wechatUrl+ "/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + SECRET_KEY;
String responseStr = HttpUtils.doGet(tokenAccessUrl);
JSONObject response = null;
try {
response = JSONObject.parseObject(responseStr);
} catch (Exception e) {
throw new BadRequest("获取token 出错:" + e.getMessage());
}
if(response.get("access_token") != null) { // 获取token 成功
try {
String token = response.getString("access_token");
redisUtils.set(RedisKey.WECHAT_TOKEN, token,time);
return token;
} catch (Exception e) {
throw new BadRequest("获取token 出错:" + e.getMessage());
}
} else {
throw new BadRequest("获取token 出错:" + response);
}
}
}
}
\ No newline at end of file
......@@ -40,3 +40,9 @@ emqx.password=a123456
tzs.cti.appkey=4e805006-3fef-ae43-3915-a153731007c4
tzs.cti.secretkey=7bd29115-99ee-4f7d-1fb1-7c4719d5f43a
tzs.cti.url=http://36.46.151.113:8000
tzs.wechat.url=https://api.weixin.qq.com/cgi-bin
##wechatAPPID
tzs.wechat.appid=wx8918c1aaad956617
##wechatSECRET
tzs.wechat.secret=337c3d8f3e749140d4f9aedc8311033b
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment