fix(服务号通知):微信开放平台unionId获取服务号openId逻辑

This commit is contained in:
2025-04-28 10:49:53 +08:00
parent 29ed66e0e3
commit 812cc5b4e3
11 changed files with 148 additions and 34 deletions
@@ -194,11 +194,6 @@ public class OrderController {
order.setUserId(user.getId());
order.setTenantId(TenantContextHolder.getTenant());
//景区唯一二维码codeId,该二维码中包含价格信息
if (order.getCodeId() == null){
order.setCodeId("f83be3a9-2888-4000-8cf9-e6acdb3a22cd");
}
List<Order> userOrderList = orderService.getOrderCountByStatusAndUser(user.getId(),OrderStatus.PAID.getId());
if (!userOrderList.isEmpty()){
return Result.succeed("已存在订单");
@@ -212,6 +207,8 @@ public class OrderController {
order.setTourismId(qrCode.getTourismId());
order.setDeviceSn(qrCode.getDeviceSn());
order.setOrderAmount(qrCode.getPrice());
}else {
Assert.notNull(qrCode,"二维码不存在");
}
boolean result = orderService.createOrder(order);
if (result) {
@@ -10,6 +10,14 @@ import org.springframework.web.bind.annotation.RestController;
import java.security.MessageDigest;
import java.util.Arrays;
/**
*
* 服务号调用API
* @author lsl
* @date 2025-04-24
*
*/
@Slf4j
@RestController
@RequestMapping("/token/callback")
@@ -1,8 +1,6 @@
package com.central.order.listener;
import com.alibaba.fastjson.JSON;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysUser;
import com.central.order.enums.MessageTemplateEnum;
import com.central.order.enums.OrderStatus;
@@ -145,13 +143,12 @@ public class OrderStatusChangeListener {
try {
// 1. 发送微信通知
LoginAppUser user = LoginUserContextHolder.getUser();
SysUser sysUser = userCenterService.findUserById(user.getId());
SysUser sysUser = userCenterService.findUserById(order.getUserId());
// 2. 查询订单排队信息
Integer queue = orderService.getOrderRankingByOrderId(order.getId(),tourism.getId());
if (sysUser.getOpenId() != null) {
if (sysUser.getUnionId() != null) {
wxTemplateMessageService.sendPaymentSuccessNotice(
sysUser.getOpenId(),
sysUser.getUnionId(),
order.getOrderNo(),
tourism.getTourismName(),
queue
@@ -0,0 +1,11 @@
package com.central.order.service;
public interface IWxUserService {
/**
* 通过 unionId 获取服务号的 openId
*
* @param targetUnionId 目标用户的 unionId
* @return 服务号的 openId,如果未找到则返回 null
*/
String getMpOpenIdByUnionId(String targetUnionId);
}
@@ -7,6 +7,7 @@ import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
@@ -22,8 +23,10 @@ import java.util.concurrent.TimeUnit;
@RequiredArgsConstructor
public class WxAccessTokenServiceImpl implements IWxAccessTokenService {
private final WxMpService wxMpService;
private final StringRedisTemplate redisTemplate;
@Autowired
private WxMpService wxMpService;
@Autowired
private StringRedisTemplate redisTemplate;
private static final String ACCESS_TOKEN_KEY = "wx:access_token";
private static final String ACCESS_TOKEN_LOCK_KEY = "wx:access_token:lock";
@@ -3,7 +3,7 @@ package com.central.order.service.impl;
import com.central.common.exception.BusinessException;
import com.central.order.config.WxMpProperties;
import com.central.order.service.IWxTemplateMessageService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.central.order.service.IWxUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
@@ -11,11 +11,11 @@ import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal;
import java.math.RoundingMode;
@@ -28,24 +28,29 @@ import java.util.Arrays;
@RequiredArgsConstructor
public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
private final WxMpService wxMpService;
private final WxMpProperties wxMpProperties;
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;
@Autowired
private WxMpService wxMpService;
@Autowired
private WxMpProperties wxMpProperties;
@Autowired
private IWxUserService wxUserService;
@Override
@Retryable(value = WxErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2))
public void sendPaymentSuccessNotice(String openId, String orderNo, String tourismName,
public void sendPaymentSuccessNotice(String unionId, String orderNo, String tourismName,
Integer rank) {
log.info("准备发送支付成功通知: openId={}, orderNo={}, serviceName={}, amount={}, tourTime={}",
openId, orderNo, tourismName, rank);
unionId, orderNo, tourismName, rank);
// 参数验证
if (StringUtils.isAnyBlank(openId, orderNo, tourismName)) {
if (StringUtils.isAnyBlank(unionId, orderNo, tourismName)) {
throw new BusinessException("参数不能为空");
}
try {
String openId = wxUserService.getMpOpenIdByUnionId(unionId);
log.info("获取到服务号openId={}", openId);
// 构建模板消息
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser(openId)
@@ -68,8 +73,8 @@ public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
saveMessageRecord(openId, orderNo, msgId, templateMessage);
} catch (WxErrorException e) {
log.error("发送模板消息失败: openId={}, orderNo={}, errorCode={}, errorMsg={}",
openId, orderNo, e.getError().getErrorCode(), e.getError().getErrorMsg());
log.error("发送模板消息失败: unionId={}, orderNo={}, errorCode={}, errorMsg={}",
unionId, orderNo, e.getError().getErrorCode(), e.getError().getErrorMsg());
throw new BusinessException("发送失败:" + e.getError().getErrorMsg());
}
}
@@ -0,0 +1,87 @@
package com.central.order.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.central.order.service.IWxUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Slf4j
@Service
public class WxUserServiceImpl implements IWxUserService {
@Autowired
private WxMpService wxMpService;
@Autowired
private RestTemplate restTemplate;
@Override
@Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000))
public String getMpOpenIdByUnionId(String targetUnionId) {
try {
String accessToken = wxMpService.getAccessToken();
// 1. 获取服务号所有关注者 openid 列表
String nextOpenId = null;
do {
String userListUrl = String.format("https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=%s",
accessToken, nextOpenId == null ? "" : nextOpenId);
ResponseEntity<String> response = restTemplate.getForEntity(userListUrl, String.class);
JSONObject userList = JSON.parseObject(response.getBody());
if (userList.getJSONObject("data") == null) {
log.warn("No users found in the official account");
break;
}
JSONArray openids = userList.getJSONObject("data").getJSONArray("openid");
// 2. 批量获取用户信息(每次最多100个)
for (int i = 0; i < openids.size(); i += 100) {
int endIndex = Math.min(i + 100, openids.size());
JSONArray batch = new JSONArray();
for (int j = i; j < endIndex; j++) {
JSONObject user = new JSONObject();
user.put("openid", openids.getString(j));
user.put("lang", "zh_CN");
batch.add(user);
}
JSONObject postData = new JSONObject();
postData.put("user_list", batch);
String batchUrl = String.format("https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=%s", accessToken);
ResponseEntity<String> batchResponse = restTemplate.postForEntity(batchUrl, postData, String.class);
JSONObject batchResult = JSON.parseObject(batchResponse.getBody());
JSONArray userInfoList = batchResult.getJSONArray("user_info_list");
for (int j = 0; j < userInfoList.size(); j++) {
JSONObject userInfo = userInfoList.getJSONObject(j);
if (targetUnionId.equals(userInfo.getString("unionid"))) {
log.info("Found matching openid for unionid {}: {}", targetUnionId, userInfo.getString("openid"));
return userInfo.getString("openid");
}
}
}
nextOpenId = userList.getString("next_openid");
} while (nextOpenId != null && !nextOpenId.isEmpty());
log.warn("No matching openid found for unionid: {}", targetUnionId);
return null;
} catch (Exception e) {
log.error("Error getting MP openid for unionid {}: {}", targetUnionId, e.getMessage(), e);
throw new RuntimeException("Failed to get MP openid", e);
}
}
}
@@ -85,8 +85,13 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
sysUser.setEnabled(Boolean.TRUE);
sysUser.setMobile(mobile);
sysUser.setUnionId(unionId);
}else if (ObjectUtils.isEmpty(sysUser.getMobile()) && StringUtils.isNotEmpty(mobile)) {
sysUser.setMobile(mobile);
}else {
if (ObjectUtils.isEmpty(sysUser.getMobile()) && StringUtils.isNotEmpty(mobile)) {
sysUser.setMobile(mobile);
}
if (ObjectUtils.isEmpty(sysUser.getUnionId()) && StringUtils.isNotEmpty(unionId)) {
sysUser.setUnionId(unionId);
}
}
String username = sysUser.getUsername();
boolean result = super.saveOrUpdateIdempotency(sysUser, lock
@@ -4,10 +4,10 @@ server:
spring:
application:
name: user-center
# cloud:
# nacos:
# discovery:
# ip: 124.222.128.40
cloud:
nacos:
discovery:
ip: 124.222.128.40
# cloud:
# nacos:
# discovery:
@@ -78,6 +78,7 @@ public class TencentAuthenticationProvider extends BaseAuthenticationProvider {
try {
String openId = wxLoginResult.get("openid").toString();
String sessionKey = wxLoginResult.get("session_key").toString();
log.info("openId:{},sessionKey:{},res:{}", openId, sessionKey,wxLoginResult);
String unionId = wxLoginResult.get("unionid").toString();
String mobile = decryptPhoneNumber(encryptedData,sessionKey,iv);
userDetails = userDetailsServiceFactory.getService(authToken).loadUserByWxOpenId(openId,mobile, unionId);
+4 -4
View File
@@ -8,10 +8,10 @@ server:
spring:
application:
name: uaa-server
# cloud:
# nacos:
# discovery:
# ip: 124.222.128.40
cloud:
nacos:
discovery:
ip: 124.222.128.40
encrypt:
key-store: