fix(服务号通知):微信开放平台unionId获取服务号openId逻辑
This commit is contained in:
+2
-5
@@ -194,11 +194,6 @@ public class OrderController {
|
|||||||
order.setUserId(user.getId());
|
order.setUserId(user.getId());
|
||||||
order.setTenantId(TenantContextHolder.getTenant());
|
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());
|
List<Order> userOrderList = orderService.getOrderCountByStatusAndUser(user.getId(),OrderStatus.PAID.getId());
|
||||||
if (!userOrderList.isEmpty()){
|
if (!userOrderList.isEmpty()){
|
||||||
return Result.succeed("已存在订单");
|
return Result.succeed("已存在订单");
|
||||||
@@ -212,6 +207,8 @@ public class OrderController {
|
|||||||
order.setTourismId(qrCode.getTourismId());
|
order.setTourismId(qrCode.getTourismId());
|
||||||
order.setDeviceSn(qrCode.getDeviceSn());
|
order.setDeviceSn(qrCode.getDeviceSn());
|
||||||
order.setOrderAmount(qrCode.getPrice());
|
order.setOrderAmount(qrCode.getPrice());
|
||||||
|
}else {
|
||||||
|
Assert.notNull(qrCode,"二维码不存在");
|
||||||
}
|
}
|
||||||
boolean result = orderService.createOrder(order);
|
boolean result = orderService.createOrder(order);
|
||||||
if (result) {
|
if (result) {
|
||||||
|
|||||||
+8
@@ -10,6 +10,14 @@ import org.springframework.web.bind.annotation.RestController;
|
|||||||
import java.security.MessageDigest;
|
import java.security.MessageDigest;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* 服务号调用API
|
||||||
|
* @author lsl
|
||||||
|
* @date 2025-04-24
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/token/callback")
|
@RequestMapping("/token/callback")
|
||||||
|
|||||||
+3
-6
@@ -1,8 +1,6 @@
|
|||||||
package com.central.order.listener;
|
package com.central.order.listener;
|
||||||
|
|
||||||
import com.alibaba.fastjson.JSON;
|
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.common.model.SysUser;
|
||||||
import com.central.order.enums.MessageTemplateEnum;
|
import com.central.order.enums.MessageTemplateEnum;
|
||||||
import com.central.order.enums.OrderStatus;
|
import com.central.order.enums.OrderStatus;
|
||||||
@@ -145,13 +143,12 @@ public class OrderStatusChangeListener {
|
|||||||
try {
|
try {
|
||||||
// 1. 发送微信通知
|
// 1. 发送微信通知
|
||||||
|
|
||||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
SysUser sysUser = userCenterService.findUserById(order.getUserId());
|
||||||
SysUser sysUser = userCenterService.findUserById(user.getId());
|
|
||||||
// 2. 查询订单排队信息
|
// 2. 查询订单排队信息
|
||||||
Integer queue = orderService.getOrderRankingByOrderId(order.getId(),tourism.getId());
|
Integer queue = orderService.getOrderRankingByOrderId(order.getId(),tourism.getId());
|
||||||
if (sysUser.getOpenId() != null) {
|
if (sysUser.getUnionId() != null) {
|
||||||
wxTemplateMessageService.sendPaymentSuccessNotice(
|
wxTemplateMessageService.sendPaymentSuccessNotice(
|
||||||
sysUser.getOpenId(),
|
sysUser.getUnionId(),
|
||||||
order.getOrderNo(),
|
order.getOrderNo(),
|
||||||
tourism.getTourismName(),
|
tourism.getTourismName(),
|
||||||
queue
|
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);
|
||||||
|
}
|
||||||
+5
-2
@@ -7,6 +7,7 @@ import lombok.extern.slf4j.Slf4j;
|
|||||||
import me.chanjar.weixin.common.error.WxErrorException;
|
import me.chanjar.weixin.common.error.WxErrorException;
|
||||||
import me.chanjar.weixin.mp.api.WxMpService;
|
import me.chanjar.weixin.mp.api.WxMpService;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||||
import org.springframework.retry.annotation.Backoff;
|
import org.springframework.retry.annotation.Backoff;
|
||||||
import org.springframework.retry.annotation.Recover;
|
import org.springframework.retry.annotation.Recover;
|
||||||
@@ -22,8 +23,10 @@ import java.util.concurrent.TimeUnit;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class WxAccessTokenServiceImpl implements IWxAccessTokenService {
|
public class WxAccessTokenServiceImpl implements IWxAccessTokenService {
|
||||||
|
|
||||||
private final WxMpService wxMpService;
|
@Autowired
|
||||||
private final StringRedisTemplate redisTemplate;
|
private WxMpService wxMpService;
|
||||||
|
@Autowired
|
||||||
|
private StringRedisTemplate redisTemplate;
|
||||||
private static final String ACCESS_TOKEN_KEY = "wx:access_token";
|
private static final String ACCESS_TOKEN_KEY = "wx:access_token";
|
||||||
private static final String ACCESS_TOKEN_LOCK_KEY = "wx:access_token:lock";
|
private static final String ACCESS_TOKEN_LOCK_KEY = "wx:access_token:lock";
|
||||||
|
|
||||||
|
|||||||
+16
-11
@@ -3,7 +3,7 @@ package com.central.order.service.impl;
|
|||||||
import com.central.common.exception.BusinessException;
|
import com.central.common.exception.BusinessException;
|
||||||
import com.central.order.config.WxMpProperties;
|
import com.central.order.config.WxMpProperties;
|
||||||
import com.central.order.service.IWxTemplateMessageService;
|
import com.central.order.service.IWxTemplateMessageService;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.central.order.service.IWxUserService;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import me.chanjar.weixin.common.error.WxErrorException;
|
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.WxMpTemplateData;
|
||||||
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
|
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.retry.annotation.Backoff;
|
import org.springframework.retry.annotation.Backoff;
|
||||||
import org.springframework.retry.annotation.Recover;
|
import org.springframework.retry.annotation.Recover;
|
||||||
import org.springframework.retry.annotation.Retryable;
|
import org.springframework.retry.annotation.Retryable;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.web.client.RestTemplate;
|
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.math.RoundingMode;
|
import java.math.RoundingMode;
|
||||||
@@ -28,24 +28,29 @@ import java.util.Arrays;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
|
public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
|
||||||
|
|
||||||
private final WxMpService wxMpService;
|
@Autowired
|
||||||
private final WxMpProperties wxMpProperties;
|
private WxMpService wxMpService;
|
||||||
private final RestTemplate restTemplate;
|
@Autowired
|
||||||
private final ObjectMapper objectMapper;
|
private WxMpProperties wxMpProperties;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private IWxUserService wxUserService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Retryable(value = WxErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2))
|
@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) {
|
Integer rank) {
|
||||||
log.info("准备发送支付成功通知: openId={}, orderNo={}, serviceName={}, amount={}, tourTime={}",
|
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("参数不能为空");
|
throw new BusinessException("参数不能为空");
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
String openId = wxUserService.getMpOpenIdByUnionId(unionId);
|
||||||
|
log.info("获取到服务号openId={}", openId);
|
||||||
// 构建模板消息
|
// 构建模板消息
|
||||||
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
|
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
|
||||||
.toUser(openId)
|
.toUser(openId)
|
||||||
@@ -68,8 +73,8 @@ public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService {
|
|||||||
saveMessageRecord(openId, orderNo, msgId, templateMessage);
|
saveMessageRecord(openId, orderNo, msgId, templateMessage);
|
||||||
|
|
||||||
} catch (WxErrorException e) {
|
} catch (WxErrorException e) {
|
||||||
log.error("发送模板消息失败: openId={}, orderNo={}, errorCode={}, errorMsg={}",
|
log.error("发送模板消息失败: unionId={}, orderNo={}, errorCode={}, errorMsg={}",
|
||||||
openId, orderNo, e.getError().getErrorCode(), e.getError().getErrorMsg());
|
unionId, orderNo, e.getError().getErrorCode(), e.getError().getErrorMsg());
|
||||||
throw new BusinessException("发送失败:" + e.getError().getErrorMsg());
|
throw new BusinessException("发送失败:" + e.getError().getErrorMsg());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+87
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+7
-2
@@ -85,8 +85,13 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
|||||||
sysUser.setEnabled(Boolean.TRUE);
|
sysUser.setEnabled(Boolean.TRUE);
|
||||||
sysUser.setMobile(mobile);
|
sysUser.setMobile(mobile);
|
||||||
sysUser.setUnionId(unionId);
|
sysUser.setUnionId(unionId);
|
||||||
}else if (ObjectUtils.isEmpty(sysUser.getMobile()) && StringUtils.isNotEmpty(mobile)) {
|
}else {
|
||||||
sysUser.setMobile(mobile);
|
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();
|
String username = sysUser.getUsername();
|
||||||
boolean result = super.saveOrUpdateIdempotency(sysUser, lock
|
boolean result = super.saveOrUpdateIdempotency(sysUser, lock
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ server:
|
|||||||
spring:
|
spring:
|
||||||
application:
|
application:
|
||||||
name: user-center
|
name: user-center
|
||||||
# cloud:
|
cloud:
|
||||||
# nacos:
|
nacos:
|
||||||
# discovery:
|
discovery:
|
||||||
# ip: 124.222.128.40
|
ip: 124.222.128.40
|
||||||
# cloud:
|
# cloud:
|
||||||
# nacos:
|
# nacos:
|
||||||
# discovery:
|
# discovery:
|
||||||
|
|||||||
+1
@@ -78,6 +78,7 @@ public class TencentAuthenticationProvider extends BaseAuthenticationProvider {
|
|||||||
try {
|
try {
|
||||||
String openId = wxLoginResult.get("openid").toString();
|
String openId = wxLoginResult.get("openid").toString();
|
||||||
String sessionKey = wxLoginResult.get("session_key").toString();
|
String sessionKey = wxLoginResult.get("session_key").toString();
|
||||||
|
log.info("openId:{},sessionKey:{},res:{}", openId, sessionKey,wxLoginResult);
|
||||||
String unionId = wxLoginResult.get("unionid").toString();
|
String unionId = wxLoginResult.get("unionid").toString();
|
||||||
String mobile = decryptPhoneNumber(encryptedData,sessionKey,iv);
|
String mobile = decryptPhoneNumber(encryptedData,sessionKey,iv);
|
||||||
userDetails = userDetailsServiceFactory.getService(authToken).loadUserByWxOpenId(openId,mobile, unionId);
|
userDetails = userDetailsServiceFactory.getService(authToken).loadUserByWxOpenId(openId,mobile, unionId);
|
||||||
|
|||||||
@@ -8,10 +8,10 @@ server:
|
|||||||
spring:
|
spring:
|
||||||
application:
|
application:
|
||||||
name: uaa-server
|
name: uaa-server
|
||||||
# cloud:
|
cloud:
|
||||||
# nacos:
|
nacos:
|
||||||
# discovery:
|
discovery:
|
||||||
# ip: 124.222.128.40
|
ip: 124.222.128.40
|
||||||
|
|
||||||
encrypt:
|
encrypt:
|
||||||
key-store:
|
key-store:
|
||||||
|
|||||||
Reference in New Issue
Block a user