添加小程序推送信息功能

This commit is contained in:
yangjun 2025-07-23 13:44:54 +08:00
parent cc0d353b8b
commit 8c2602ee58
6 changed files with 267 additions and 0 deletions

View File

@ -0,0 +1,88 @@
package com.nu.modules.weixin.controller;
import cn.hutool.json.JSONObject;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.nu.modules.orgapplyinfo.entity.OrgApplyInfo;
import com.nu.modules.orgapplyinfo.service.IOrgApplyInfoService;
import com.nu.modules.weixin.utils.TemplateMessageSender;
import com.nu.modules.weixin.utils.WechatMiniProgramUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/weixinMini")
@Slf4j
public class WechatMiniController {
@Autowired
private BaseCommonService baseCommonService;
@Autowired
private IOrgApplyInfoService orgApplyInfoService;
@AutoLog(value = "推送机构加盟审核结果通知")
@ApiOperation("推送机构加盟审核结果通知")
@RequestMapping("/sendOrgAuthInfo")
public Result sendOrgAuthInfo(@RequestParam(name="openId",required=true) String openId,@RequestParam(name="id",required=true) String id,HttpServletRequest request, HttpServletResponse response){
try {
if (StringUtils.isNotBlank(openId) && StringUtils.isNotBlank(id)) {
// 1. 获取access token
String accessToken = WechatMiniProgramUtils.getAccessToken();
// 2. 准备模板消息数据
String templateId = "CJ6NDNV4mTTyOdYhbksyA_YjDORVemJRmzEVAUZMBis";
String page = "pages/index/index"; // 点击消息跳转的页面
Map<String, Object> data = new HashMap<>();
data.put("thing5", "详情请咨询客服进行了解"); // 对应模板中的字段
data.put("phrase6", "审核通过");
data.put("date2", DateUtils.now());
// 3. 发送模板消息
String resInfo = TemplateMessageSender.sendTemplateMessage( accessToken, openId, templateId, page, data);
if(StringUtils.equals(resInfo,"error")){
baseCommonService.addLog("机构加盟审核,发送通知失败-发送消息异常56 " +resInfo, CommonConstant.LOG_TYPE_2, 1);
return Result.error("发送消息异常");
}
JSONObject jsonObject = new JSONObject(resInfo);
boolean success = jsonObject.getInt("errcode") == 0;
if (success) {
OrgApplyInfo orgApplyInfo = new OrgApplyInfo();
orgApplyInfo.setId(id);
orgApplyInfo.setBuildStatus("6");
orgApplyInfoService.updateById(orgApplyInfo);
System.out.println("模板消息发送成功");
baseCommonService.addLog("机构加盟审核,发送通知成功 " , CommonConstant.LOG_TYPE_2, 1);
return Result.ok("发送消息成功");
} else {
baseCommonService.addLog("机构加盟审核,发送通知失败-发送消息异常68 " +resInfo , CommonConstant.LOG_TYPE_2, 1);
System.out.println("模板消息发送失败");
return Result.error("发送消息异常");
}
}else{
baseCommonService.addLog("机构加盟审核,发送通知失败-openId为空或id为空 " , CommonConstant.LOG_TYPE_2, 1);
return Result.error("操作失败openId为空或id为空");
}
} catch (Exception e) {
e.printStackTrace();
return Result.error("发送消息异常");
}
}
}

View File

@ -0,0 +1,57 @@
package com.nu.modules.weixin.utils;
import cn.hutool.json.JSONObject;
import okhttp3.*;
import java.io.IOException;
import java.util.Map;
public class TemplateMessageSender {
private static final String SEND_TEMPLATE_MSG_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s";
/**
* 发送小程序订阅消息
* @param accessToken 接口调用凭证
* @param openId 接收者openid
* @param templateId 模板ID
* @param page 点击消息跳转的小程序页面
* @param data 模板内容
* @return 是否发送成功
*/
public static String sendTemplateMessage(String accessToken, String openId,
String templateId, String page, Map<String, Object> data) throws IOException {
String url = String.format(SEND_TEMPLATE_MSG_URL, accessToken);
JSONObject json = new JSONObject();
json.put("touser", openId);
json.put("template_id", templateId);
json.put("page", page);
JSONObject dataJson = new JSONObject();
for (Map.Entry<String, Object> entry : data.entrySet()) {
JSONObject valueJson = new JSONObject();
valueJson.put("value", entry.getValue());
dataJson.put(entry.getKey(), valueJson);
}
json.put("data", dataJson);
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(json.toString(), MediaType.get("application/json"));
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
String responseBody = response.body().string();
System.out.println(responseBody);
return responseBody;
}catch (Exception e){
e.printStackTrace();
return "error";
}
}
}

View File

@ -0,0 +1,33 @@
package com.nu.modules.weixin.utils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class WechatMiniProgramUtils {
private static final String APP_ID = "wx53bc8a44e780d26a";
private static final String APP_SECRET = "7dfcbf80cb4ff379454a3d6b1f8bd61f";
private static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
// 获取access token
public static String getAccessToken() throws IOException {
String url = String.format(GET_TOKEN_URL, APP_ID, APP_SECRET);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
String responseBody = response.body().string();
JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
JsonObject jsonObject = jsonparer.parse(responseBody).getAsJsonObject();
return jsonObject.get("access_token").getAsString();
}
}
}

View File

@ -9,6 +9,8 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nu.modules.orgapplyinfo.entity.OrgApplyInfo;
import com.nu.modules.orgapplyinfo.service.IOrgApplyInfoService;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.model.SysUserSysDepartModel;
@ -104,6 +106,8 @@ public class SysUserController {
@Autowired
private JeecgRedisClient jeecgRedisClient;
@Autowired
private IOrgApplyInfoService orgApplyInfoService;
/**
* 获取租户下用户数据支持租户隔离
@ -1900,4 +1904,57 @@ public class SysUserController {
result.setMessage("发送验证码成功!");
return result;
}
/**
* 申请审批账号初始化
* @param jsonObject
* @return
*/
@RequiresPermissions("system:user:initialization")
@RequestMapping(value = "/initialization", method = RequestMethod.POST)
public Result<SysUser> initialization(@RequestBody JSONObject jsonObject) {
Result<SysUser> result = new Result<SysUser>();
String selectedRoles = "f6817f48af4fb3af11b9e8bf182f618b";
String selectedDeparts = "";
try {
SysUser user = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
SysDepart depart = sysDepartService.getDepartById(user.getOrgCode());
if(depart == null){
return result.error500("未找到当前机构信息");
}
selectedDeparts = depart.getId();
user.setOrgCode(depart.getOrgCode());
user.setWorkNo(depart.getOrgCode()+"01");
user.setPassword("123456");
user.setCreateTime(new Date());//设置创建时间
String salt = oConvertUtils.randomGen(8);
user.setSalt(salt);
String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
user.setPassword(passwordEncode);
user.setStatus(1);
user.setDelFlag(CommonConstant.DEL_FLAG_0);
//用户表字段org_code不能在这里设置他的值
user.setOrgCode(null);
// 保存用户走一个service 保证事务
//获取租户ids
String relTenantIds = jsonObject.getString("relTenantIds");
String dataSourceCode = depart.getOrgCode();
sysUserService.saveUserInitialization(dataSourceCode,user, selectedRoles, selectedDeparts, relTenantIds);
baseCommonService.addLog("添加用户username " +user.getUsername() ,CommonConstant.LOG_TYPE_2, 2);
//修改机构加盟申请信息
OrgApplyInfo orgApplyInfo = new OrgApplyInfo();
orgApplyInfo.setId(depart.getId());
orgApplyInfo.setBuildStatus("5");
orgApplyInfoService.updateById(orgApplyInfo);
result.success("添加成功!");
} catch (Exception e) {
log.error(e.getMessage(), e);
result.error500("操作失败");
}
return result;
}
}

View File

@ -458,4 +458,6 @@ public interface ISysUserService extends IService<SysUser> {
* @param username
*/
void userLogOff(JSONObject jsonObject, String username);
void saveUserInitialization(String dataSourceCode, SysUser user, String selectedRoles, String selectedDeparts, String relTenantIds);
}

View File

@ -5,6 +5,7 @@ import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
@ -2019,6 +2020,35 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
redisUtil.removeAll(CacheConstant.SYS_USERS_CACHE + phone);
}
@Override
@DS("#dataSourceCode")
public void saveUserInitialization(String dataSourceCode, SysUser user, String selectedRoles, String selectedDeparts, String relTenantIds) {
//step.1 保存用户
this.save(user);
//获取用户保存前台传过来的租户id并添加到租户
this.saveUserTenant(user.getId(),relTenantIds);
//step.2 保存角色
if(oConvertUtils.isNotEmpty(selectedRoles)) {
String[] arr = selectedRoles.split(",");
for (String roleId : arr) {
SysUserRole userRole = new SysUserRole(user.getId(), roleId);
sysUserRoleMapper.insert(userRole);
}
}
//step.3 保存所属部门
if(oConvertUtils.isNotEmpty(selectedDeparts)) {
String[] arr = selectedDeparts.split(",");
for (String deaprtId : arr) {
SysUserDepart userDeaprt = new SysUserDepart(user.getId(), deaprtId);
sysUserDepartMapper.insert(userDeaprt);
}
}
//step.4 保存职位
this.saveUserPosition(user.getId(),user.getPost());
}
/**
* 发送短信验证码
* @param phone