Procházet zdrojové kódy

订阅消息接口优化

tags/v1.0.0^2
chengwang před 1 rokem
rodič
revize
c35aa5f025
3 změnil soubory, kde provedl 170 přidání a 47 odebrání
  1. +5
    -0
      tuoheng-service/tuoheng-miniprogram/src/main/java/com/tuoheng/miniprogram/entity/wx/WxMessageRequest.java
  2. +51
    -0
      tuoheng-service/tuoheng-miniprogram/src/main/java/com/tuoheng/miniprogram/enums/WeiXinRequestEnum.java
  3. +114
    -47
      tuoheng-service/tuoheng-miniprogram/src/main/java/com/tuoheng/miniprogram/service/impl/WxServiceImpl.java

+ 5
- 0
tuoheng-service/tuoheng-miniprogram/src/main/java/com/tuoheng/miniprogram/entity/wx/WxMessageRequest.java Zobrazit soubor

@@ -19,6 +19,11 @@ public class WxMessageRequest {
*/
private String questionId;

/**
* 租户id
*/
private String tenantId;

/**
* 上报时间
*/

+ 51
- 0
tuoheng-service/tuoheng-miniprogram/src/main/java/com/tuoheng/miniprogram/enums/WeiXinRequestEnum.java Zobrazit soubor

@@ -0,0 +1,51 @@
package com.tuoheng.miniprogram.enums;

/**
* 获取子部门列表返回码
* 模块代码:20(部门管理)
* 接口代码:06 (获取子部门列表)
*
* @author wanjing
* @team tuoheng
* @date 2022-11-22
*/
public enum WeiXinRequestEnum {

INSPECTION_ID_IS_NULL(120010, "任务id为空"),
QUESTION_ID_IS_NULL(120011, "问题id为空"),
TENANT_ID_NOT_EXIST(120012, "租户id为空"),
CREATE_TIME_IS_NULL(120013, "上报时间为空"),
INSPECTION_NAME_NOT_EXIST(120014, "问题标题不存在"),
QUESTION_DESC_NOT_EXIST(120015, "问题标题不存在");
/**
* 错误码
*/
private int code;

/**
* 错误信息
*/
private String msg;

WeiXinRequestEnum(int code, String msg){
this.code = code;
this.msg = msg;
}

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

}

+ 114
- 47
tuoheng-service/tuoheng-miniprogram/src/main/java/com/tuoheng/miniprogram/service/impl/WxServiceImpl.java Zobrazit soubor

@@ -1,5 +1,6 @@
package com.tuoheng.miniprogram.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
@@ -27,6 +28,7 @@ import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@@ -110,7 +112,7 @@ public class WxServiceImpl implements IWxService {
*/
public String getAccessToken(){
//判断accessToken是否已经过期,如果国企需要重新获取
// if(accessToken == null || expiresTime <System.currentTimeMillis()){
if(accessToken == null || expiresTime <System.currentTimeMillis()){
RestTemplate restTemplate = new RestTemplate();
Map<String,String> params = new HashMap<>(2);
params.put("APPID",CommonConfig.appId);
@@ -131,7 +133,7 @@ public class WxServiceImpl implements IWxService {
Long expires_in = object.getLong("expires_in");
//失效时间 = 当前时间+有效期(提前一分钟,也可以不提前)
expiresTime = System.currentTimeMillis() + (expires_in - 60) * 1000;
// }
}

return accessToken;
}
@@ -143,59 +145,124 @@ public class WxServiceImpl implements IWxService {
*/
@Override
public JsonResult sendMessage(WxMessageRequest wxMessageRequest) {
//获取当前登录用户id
String userId = CurrentUserUtil.getUserId();
User user = CurrentUserUtil.getUserInfo();
if(user.getAuthorize() == AuthorizeStatusEnum.AUTHORIZE_ON.getCode()
&& user.getSubscribeTimes() == SubscribeTimesEnum.SUBSCRIBE_TIMES_NO_ONE.getCode()){
return JsonResult.success();
JsonResult result = this.check(wxMessageRequest);
if(result.getCode() != 0){
//正常返回,信息提示
return JsonResult.success(result.getCode(),result.getMsg());
}
List<User> userList = (List<User>) result.getData();
boolean isSend =false;
//获取当前登录openId
UserAuthorize userAuthorize = userAuthorizeMapper.selectOne(Wrappers.<UserAuthorize>lambdaQuery()
.eq(UserAuthorize::getUserId, userId)
.eq(UserAuthorize::getMark, MarkEnum.VALID.getCode()));
//对用户进行遍历推送消息
for (User user : userList) {
String userId = user.getId();
if(user.getAuthorize() == AuthorizeStatusEnum.AUTHORIZE_DOWN.getCode()){
//本次结束,进入下次循环
continue;
}
if(user.getAuthorize() == AuthorizeStatusEnum.AUTHORIZE_ON.getCode()
&& user.getSubscribeTimes() == SubscribeTimesEnum.SUBSCRIBE_TIMES_NO_ONE.getCode()){
continue;
}
//获取当前登录openId
UserAuthorize userAuthorize = userAuthorizeMapper.selectOne(Wrappers.<UserAuthorize>lambdaQuery()
.eq(UserAuthorize::getUserId, userId)
.eq(UserAuthorize::getMark, MarkEnum.VALID.getCode()));
//授权数据校验
JsonResult jsonResult = this.getUserAuthorize(userAuthorize);
if(jsonResult.getCode() != 0){
continue;
}
String openId = userAuthorize.getOpenId();
RestTemplate restTemplate = new RestTemplate();
//发送消息订阅
String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
WxSendMessageParam param = new WxSendMessageParam();
param.setPage("/package_question/pages/taskList/taskList");
param.setTouser(openId);
param.setTemplate_id(CommonConfig.templateId);
Map<String, TemplateMinDto> data = new HashMap<>(3);
//消息模板{{time12.DATA}} {{thing4.DATA}} {{thing13.DATA}} 时间格式一定是这样的2022-01-13 02:31:36
ResponseEntity<String> responseEntity = null;
try {
data.put("time12",new TemplateMinDto(wxMessageRequest.getCreateTime()));
data.put("thing4",new TemplateMinDto(wxMessageRequest.getInspectionName()));
data.put("thing13",new TemplateMinDto(wxMessageRequest.getQuestionDesc()));
param.setData(data);

responseEntity = restTemplate.postForEntity(url, param, String.class);
String messageBody = responseEntity.getBody();
Integer errcode = JSONObject.parseObject(messageBody).getInteger("errcode").intValue();
if(errcode != null && errcode == 0){
//修改用户订阅次数
user.setSubscribeTimes(SubscribeTimesEnum.SUBSCRIBE_TIMES_NO_ONE.getCode());
int count = userMapper.updateById(user);
if(count <= 0){
throw new RuntimeException("更新用户订阅次数失败");
}
}else if(errcode != null && errcode != 0){
String errmsg = JSONObject.parseObject(messageBody).getString("errmsg");
log.info("请求accessToken失败,返回码:" + errcode.intValue() + "错误信息:" + errmsg);
//return JsonResult.error(errcode.intValue(),errmsg);
}
JSONObject jsonObject = JSON.parseObject(messageBody);
if(Objects.nonNull(jsonObject)){
log.info("openId:" + openId + "发送消息返回内容:" + jsonObject.toJSONString());
}
isSend = true;
} catch (RestClientException e) {
log.info("openId:"+ openId +"发送消息异常报错:"+e);
e.printStackTrace();
}

}

return JsonResult.success(isSend);

}

/**
* 校验权限数据
* @param userAuthorize
* @return
*/
private JsonResult getUserAuthorize(UserAuthorize userAuthorize) {
if(ObjectUtil.isNull(userAuthorize)){
return JsonResult.error(UserAuthorizeEnum.UNAUTHORIZED.getCode(),UserAuthorizeEnum.UNAUTHORIZED.getMsg());
}
if(StringUtils.isEmpty(userAuthorize.getOpenId())){
return JsonResult.error(UserAuthorizeEnum.OPEN_ID_IS_NULL.getCode(),UserAuthorizeEnum.OPEN_ID_IS_NULL.getMsg());
}
String openId = userAuthorize.getOpenId();
RestTemplate restTemplate = new RestTemplate();
//发送消息订阅
String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
WxSendMessageParam param = new WxSendMessageParam();
param.setPage("/package_question/pages/taskList/taskList");
param.setTouser(openId);
param.setTemplate_id(CommonConfig.templateId);
Map<String, TemplateMinDto> data = new HashMap<>(3);
//消息模板{{time12.DATA}} {{thing4.DATA}} {{thing13.DATA}} 时间格式一定是这样的2022-01-13 02:31:36
ResponseEntity<String> responseEntity = null;
try {
data.put("time12",new TemplateMinDto(wxMessageRequest.getCreateTime()));
data.put("thing4",new TemplateMinDto(wxMessageRequest.getInspectionName()));
data.put("thing13",new TemplateMinDto(wxMessageRequest.getQuestionDesc()));
param.setData(data);

responseEntity = restTemplate.postForEntity(url, param, String.class);
String messageBody = responseEntity.getBody();
Integer errcode = JSONObject.parseObject(messageBody).getInteger("errcode").intValue();
if(errcode != null && errcode != 0){
String errmsg = JSONObject.parseObject(messageBody).getString("errmsg");
log.info("请求accessToken失败,返回码:" + errcode.intValue() + "错误信息:" + errmsg);
return JsonResult.error(errcode.intValue(),errmsg);
}
JSONObject jsonObject = JSON.parseObject(messageBody);
if(Objects.nonNull(jsonObject)){
log.info("openId:" + openId + "发送消息返回内容:" + jsonObject.toJSONString());
}
isSend = true;
} catch (RestClientException e) {
log.info("openId:"+ openId +"发送消息异常报错:"+e);
e.printStackTrace();
}
return JsonResult.success();
}

return JsonResult.success(isSend);
private JsonResult check(WxMessageRequest wxMessageRequest) {
//传参校验
if(StringUtils.isEmpty(wxMessageRequest.getTenantId())){
return JsonResult.error(WeiXinRequestEnum.TENANT_ID_NOT_EXIST.getCode(),WeiXinRequestEnum.TENANT_ID_NOT_EXIST.getMsg());
}
if(StringUtils.isEmpty(wxMessageRequest.getInspectionId())){
return JsonResult.error(WeiXinRequestEnum.INSPECTION_ID_IS_NULL.getCode(),WeiXinRequestEnum.INSPECTION_ID_IS_NULL.getMsg());
}
if(StringUtils.isEmpty(wxMessageRequest.getQuestionId())){
return JsonResult.error(WeiXinRequestEnum.QUESTION_ID_IS_NULL.getCode(),WeiXinRequestEnum.QUESTION_ID_IS_NULL.getMsg());
}
if(StringUtils.isEmpty(wxMessageRequest.getCreateTime())){
return JsonResult.error(WeiXinRequestEnum.CREATE_TIME_IS_NULL.getCode(),WeiXinRequestEnum.CREATE_TIME_IS_NULL.getMsg());
}
if(StringUtils.isEmpty(wxMessageRequest.getInspectionName())){
return JsonResult.error(WeiXinRequestEnum.INSPECTION_NAME_NOT_EXIST.getCode(),WeiXinRequestEnum.INSPECTION_NAME_NOT_EXIST.getMsg());
}
if(StringUtils.isEmpty(wxMessageRequest.getQuestionDesc())){
return JsonResult.error(WeiXinRequestEnum.QUESTION_DESC_NOT_EXIST.getCode(),WeiXinRequestEnum.QUESTION_DESC_NOT_EXIST.getMsg());
}
//根据租户id查询用户列表
List<User> users = userMapper.selectList(Wrappers.<User>lambdaQuery()
.eq(User::getMark, MarkEnum.VALID.getCode())
.eq(User::getTenantId, wxMessageRequest.getTenantId())
.eq(User::getStatus, 1));
if(CollectionUtil.isEmpty(users) || users.size() == 0){
return JsonResult.error("此租户下没有用户");
}
return JsonResult.success(users);
}
}

Načítá se…
Zrušit
Uložit