Files
gofly-platform-services/zlt-doc/alipay/支付宝小程序订阅消息通知实现文档.md

20 KiB
Raw Permalink Blame History

支付宝小程序订阅消息通知 — 实现文档

作者: duzhichao 日期: 2026-06-24 关联文件: OrderStatusChangeListener.java


1. 背景与目标

当前 OrderStatusChangeListener 中的用户通知仅支持微信小程序订阅消息(通过 WxMiniSubscribeService)。需要新增支付宝小程序订阅消息能力,使得通过支付宝小程序下单的用户也能在订单状态变更时收到消息通知。

支付类型枚举(PayTypeEnum)

payType 枚举 说明
1 WECHAT_PAY 微信支付
2 COUPON_PAY 优惠券支付
3 FEIPAI_VERIFY 第三方渠道核销
4 ALIPAY_PAY 支付宝支付

通知路由策略

核心原则:根据订单的 payType 决定通知渠道,而非两个平台都发。

payType 通知渠道 说明
1(微信支付) 微信小程序订阅消息 走 WxMiniSubscribeService
4(支付宝支付) 支付宝小程序订阅消息 走 AlipayMiniSubscribeService
2/3(优惠券/核销) 不发送小程序通知 无需平台通知

当前微信通知覆盖的场景

场景 调用方法 调用位置
支付成功 wxMiniSubscribeService.sendServiceProcessMsg handlePaymentSuccess()
退款中 wxMiniSubscribeService.sendServiceProcessMsg sendMessageForRefunding()
退款完成 wxMiniSubscribeService.sendServiceProcessMsg sendMessageForRefunded()
素材上传完成 wxMiniSubscribeService.sendServiceProcessMsg sendMessageForResouresUploaded()
通知下一位排队用户 wxMiniSubscribeService.sendServiceProcessMsg sendMessageToNextOrderUser()

设计原则

  1. 按 payType 路由:payType=1 走微信,payType=4 走支付宝,互斥非并行
  2. 用户标识隔离:微信使用 SysUser.openId,支付宝通过 UserService.getAlipayOpenIdByUserId(userId, appId) 查询
  3. 租户维度取配置:支付宝小程序配置必须按 order.tenantId + type=MINI 查询,不能全局取第一条配置
  4. 调用语义统一:AlipayMiniSubscribeService 与 WxMiniSubscribeService 都封装“服务进度通知”,但入参按平台差异隔离

2. 现有基础设施分析

项目已具备完整的支付宝集成基础,无需新增 SDK 依赖:

组件 模块 说明
AlipayClientFactory zlt-alipay-spring-boot-starter 多租户 AlipayClient 缓存工厂
AlipayConfig zlt-alipay-common-core 支付宝配置实体(含 type=MINI/PAY)
AlipayAutoConfiguration zlt-alipay-spring-boot-starter 自动配置,条件为 zlt.alipay.enabled=true
UserService.getAlipayOpenIdByUserId() zlt-common-core Feign 接口,通过 userId + appId 反查支付宝用户标识
SysUserThirdOpenid user-center 第三方 openId 映射表(provider=ALIPAY)
alipay-sdk-java:4.40.816.ALL Maven 依赖 已引入;实现前需确认该版本包含目标订阅消息 API 的 Request/Response 类

用户标识获取方式对比

平台 存储位置 获取方式
微信 SysUser.openId userCenterService.findUserById(userId).getOpenId()
支付宝 sys_user_third_openid 表 先按 order.tenantId 查询 type=MINI 配置,再用 config.appId 调 userService.getAlipayOpenIdByUserId(userId, appId)

参考:WxMiniSubscribeService 接口定义

public interface WxMiniSubscribeService {
    void sendPaySuccessMsg(String openId, String orderName, String orderNo, String tip, String amount, String orderTime);
    void sendActivityStartMsg(String openId, String place, String activityName, String remark, String activityNo);
    void sendVideoEditCompleteMsg(String openId, String taskName, String orderNo, String result);
    void sendServiceProcessMsg(String openId, String taskName, String processDesc, String orderNo, String orderTime, String result, String pageUrl);
}

3. 支付宝订阅消息 API

3.1 接口选择

支付宝小程序订阅消息应使用小程序订阅消息专用能力。服务端接口优先核对支付宝开放平台的 alipay.open.app.message.subscription.send(小程序发送订阅消息)及当前 SDK 对应的 Request/Response 类。

⚠️ 不建议直接使用 alipay.open.public.template.message.send 作为本需求的默认接口。该接口偏生活号/公共模板消息语义,容易与“小程序订阅消息”混淆。实现前必须以支付宝开放平台当前文档和本项目锁定的 alipay-sdk-java:4.40.816.ALL 中实际存在的类名为准。

前端需要在支付宝小程序内调用订阅授权 API(如 my.requestSubscribeMessage)让用户授权对应模板,服务端只能给已授权的用户发送订阅消息。

3.2 SDK 调用示例

import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayOpenAppMessageSubscriptionSendRequest;
import com.alipay.api.response.AlipayOpenAppMessageSubscriptionSendResponse;

AlipayClient client = alipayClientFactory.createAlipayClient(config);

AlipayOpenAppMessageSubscriptionSendRequest request =
    new AlipayOpenAppMessageSubscriptionSendRequest();

// 构建订阅消息参数,字段名以支付宝开放平台对应接口文档为准
JSONObject bizContent = new JSONObject();
bizContent.put("to_user_id", alipayUserId);     // 支付宝 userId
bizContent.put("template_id", templateId);       // 订阅消息模板 ID
bizContent.put("page", pageUrl);                 // 跳转小程序页面(可选)

JSONObject data = new JSONObject();
data.put("taskName",   new JSONObject().put("value", tourismName));
data.put("orderNo",    new JSONObject().put("value", orderNo));
data.put("processDesc", new JSONObject().put("value", tip));
data.put("orderTime",  new JSONObject().put("value", payTime));
bizContent.put("data", data);
request.setBizContent(bizContent.toJSONString());

AlipayOpenAppMessageSubscriptionSendResponse response = client.execute(request);
if (!response.isSuccess()) {
    log.error("subCode={}, subMsg={}", response.getSubCode(), response.getSubMsg());
}

4. 详细实现方案

4.1 新增接口 AlipayMiniSubscribeService

文件: zlt-business/order-center/src/main/java/com/central/order/service/AlipayMiniSubscribeService.java

package com.central.order.service;

/**
 * 支付宝小程序订阅消息服务
 * <p>
 * 对标 WxMiniSubscribeService,封装支付宝模板消息发送能力。
 * 支持通过系统 userId + 租户ID 自动查询支付宝 userId 并发送消息。
 *
 * @author duzhichao
 * @date 2026-06-24
 */
public interface AlipayMiniSubscribeService {

    /**
     * 发送服务进度通知(支付成功/退款中/退款完成/排队通知等)
     *
     * @param userId      系统用户ID
     * @param tenantId    租户ID,用于查询 type=MINI 的支付宝小程序配置
     * @param taskName    服务名称(如景区名称)
     * @param processDesc 服务阶段描述(如"支付成功,当前排第2位")
     * @param orderNo     订单编号
     * @param orderTime   下单时间
     * @param pageUrl     跳转小程序页面路径
     */
    void sendServiceProcessMsg(Long userId, String tenantId,
                               String taskName, String processDesc,
                               String orderNo, String orderTime,
                               String pageUrl);
}

4.2 实现类 AlipayMiniSubscribeServiceImpl

文件: zlt-business/order-center/src/main/java/com/central/order/service/impl/AlipayMiniSubscribeServiceImpl.java

package com.central.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayOpenAppMessageSubscriptionSendRequest;
import com.alipay.api.response.AlipayOpenAppMessageSubscriptionSendResponse;
import com.central.alipay.config.AlipayClientFactory;
import com.central.alipay.entity.AlipayConfig;
import com.central.alipay.feign.AlipayConfigService;
import com.central.common.feign.UserService;
import com.central.order.service.AlipayMiniSubscribeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 支付宝小程序订阅消息服务实现
 *
 * @author duzhichao
 * @date 2026-06-24
 */
@Slf4j
@Service
public class AlipayMiniSubscribeServiceImpl implements AlipayMiniSubscribeService {

    @Value("${alipay.mini.template.service-process}")
    private String serviceProcessTemplateId;

    @Autowired
    private AlipayClientFactory alipayClientFactory;

    @Autowired
    private AlipayConfigService alipayConfigService;

    @Autowired
    private UserService userService;

    @Override
    public void sendServiceProcessMsg(Long userId, String tenantId,
                                      String taskName, String processDesc,
                                      String orderNo, String orderTime,
                                      String pageUrl) {
        try {
            // 1. 按租户获取支付宝小程序配置
            AlipayConfig config = alipayConfigService.getConfig("MINI", tenantId);
            if (config == null) {
                log.warn("支付宝小程序配置不存在,跳过通知: tenantId={}", tenantId);
                return;
            }
            String appId = config.getAppId();
            if (appId == null || appId.isEmpty()) {
                log.warn("支付宝小程序 appId 为空,跳过通知: tenantId={}", tenantId);
                return;
            }

            // 2. 通过 userId + appId 反查支付宝 userId
            String alipayUserId = userService.getAlipayOpenIdByUserId(userId, appId);
            if (alipayUserId == null || alipayUserId.isEmpty()) {
                log.warn("用户无支付宝 userId,跳过通知: userId={}, appId={}", userId, appId);
                return;
            }

            // 3. 获取支付宝客户端(MINI 类型配置)
            AlipayClient client = alipayClientFactory.createAlipayClient(config);

            // 4. 构建请求
            AlipayOpenAppMessageSubscriptionSendRequest request =
                new AlipayOpenAppMessageSubscriptionSendRequest();

            // 5. 构建订阅消息参数(字段名需与支付宝开放平台申请的模板变量一致)
            JSONObject data = new JSONObject();
            data.put("taskName",    new JSONObject().put("value", taskName));
            data.put("processDesc", new JSONObject().put("value", processDesc));
            data.put("orderNo",     new JSONObject().put("value", orderNo));
            data.put("orderTime",   new JSONObject().put("value", orderTime));

            JSONObject bizContent = new JSONObject();
            bizContent.put("to_user_id", alipayUserId);
            bizContent.put("template_id", serviceProcessTemplateId);
            bizContent.put("page", pageUrl);
            bizContent.put("data", data);
            request.setBizContent(bizContent.toJSONString());

            // 6. 发送
            AlipayOpenAppMessageSubscriptionSendResponse response = client.execute(request);

            if (response.isSuccess()) {
                log.info("支付宝小程序订阅消息发送成功: userId={}, orderNo={}", userId, orderNo);
            } else {
                log.error("支付宝小程序订阅消息发送失败: userId={}, orderNo={}, subCode={}, subMsg={}",
                    userId, orderNo, response.getSubCode(), response.getSubMsg());
            }

        } catch (Exception e) {
            log.error("支付宝小程序订阅消息发送异常: userId={}, orderNo={}", userId, orderNo, e);
        }
    }
}

5. 配置项

5.1 application.yml 新增

alipay:
  mini:
    template:
      # 支付宝开放平台 → 小程序订阅消息 → 模板ID
      service-process: YOUR_ALIPAY_TEMPLATE_ID

5.2 AlipayConfig 表数据

确保 alipay_config 表中存在 type=MINI 的配置记录:

字段 值
tenant_id 租户ID
type MINI
app_id 支付宝小程序 AppId
app_private_key 应用私钥
alipay_public_key 支付宝公钥
sign_type RSA2
status 1

6. 改造 OrderStatusChangeListener

6.1 新增注入

@Autowired
private AlipayMiniSubscribeService alipayMiniSubscribeService;

6.2 新增辅助方法

/**
 * 根据订单支付类型发送小程序订阅消息
 * payType=1 → 微信通知
 * payType=4 → 支付宝通知
 * 其他 → 不发送
 */
private void sendSubscribeMsgByPayType(Order order, String taskName, String processDesc,
                                        String orderNo, String orderTime, String pageUrl) {
    Integer payType = order.getPayType();

    if (PayTypeEnum.WECHAT_PAY.getCode().equals(payType)) {
        // 微信通知
        SysUser sysUser = userCenterService.findUserById(order.getUserId());
        if (sysUser != null && sysUser.getOpenId() != null) {
            wxMiniSubscribeService.sendServiceProcessMsg(
                sysUser.getOpenId(), taskName, processDesc,
                orderNo, orderTime, "", pageUrl);
        }
    } else if (PayTypeEnum.ALIPAY_PAY.getCode().equals(payType)) {
        // 支付宝通知:服务内部按 tenantId 查询 MINI 配置并获取 appId
        if (order.getTenantId() != null && !order.getTenantId().isEmpty()) {
            alipayMiniSubscribeService.sendServiceProcessMsg(
                order.getUserId(), order.getTenantId(), taskName, processDesc,
                orderNo, orderTime, pageUrl);
        } else {
            log.warn("订单 tenantId 为空,跳过支付宝订阅消息: orderNo={}", orderNo);
        }
    }
    // payType=2(优惠券) / 3(核销) 不发送小程序通知
}


6.3 各场景改造

所有场景统一使用 sendSubscribeMsgByPayType() 方法,根据 payType 自动路由到对应平台。

支付成功 handlePaymentSuccess()

private void handlePaymentSuccess(Order order, Tourism tourism) {
    try {
        Integer queue = orderService.getOrderRankingByOrderIdAndDevice(order.getId(), order.getDeviceSn());
        String orderName = tourism.getTourismName();
        String pageUrl = "pages/task/task";
        String tip = "支付成功,当前排第" + queue + "位";
        String orderTime = DateUtils.sdf.format(order.getPayTime());

        // 根据 payType 发送小程序通知(微信 or 支付宝)
        sendSubscribeMsgByPayType(order, orderName, tip, order.getOrderNo(), orderTime, pageUrl);

        log.info("订单支付成功: orderNo={}, amount={}, tourismName={}",
            order.getOrderNo(), order.getOrderAmount(), tourism.getTourismName());

    } catch (Exception e) {
        log.error("处理支付成功通知失败: orderNo={}", order.getOrderNo(), e);
    }
}

退款中 sendMessageForRefunding()

private void sendMessageForRefunding(Order order, Tourism tourism) {
    String orderName = tourism.getTourismName();
    String pageUrl = "pages/task/task";
    String orderTime = DateUtils.sdf.format(order.getPayTime());

    // 根据 payType 发送小程序通知
    sendSubscribeMsgByPayType(order, orderName, "您的订单正在退款中",
        order.getOrderNo(), orderTime, pageUrl);
}

退款完成 sendMessageForRefunded()

private void sendMessageForRefunded(Order order, Tourism tourism) {
    String orderName = tourism.getTourismName();
    String pageUrl = "pages/task/task";
    String orderTime = DateUtils.sdf.format(order.getPayTime());

    // 根据 payType 发送小程序通知
    sendSubscribeMsgByPayType(order, orderName, "您的订单退款已完成",
        order.getOrderNo(), orderTime, pageUrl);
}

素材上传完成 sendMessageForResouresUploaded()

private void sendMessageForResouresUploaded(Order order, Tourism tourism) {
    String orderName = tourism.getTourismName();
    String pageUrl = "pages/album/album";
    String orderTime = DateUtils.sdf.format(order.getPayTime());

    // 根据 payType 发送小程序通知
    sendSubscribeMsgByPayType(order, orderName, "素材上传完成",
        order.getOrderNo(), orderTime, pageUrl);
}

通知下一位排队用户 sendMessageToNextOrderUser()

private void sendMessageToNextOrderUser(Order order, Tourism tourism) {
    Order nextOrder = orderService.getNextQueueOrder(order.getTourismId(), order.getId());
    if (nextOrder != null) {
        SysUser nextUser = userCenterService.findUserById(nextOrder.getUserId());
        if (nextUser != null && tourism != null) {
            String activityName = tourism.getTourismName();
            String remark = "即将为您进行拍摄服务";
            String activityNo = nextOrder.getOrderNo();
            String pageUrl = "pages/album/album";
            String orderTime = DateUtils.sdf.format(nextOrder.getPayTime());

            // 根据下一笔订单的 payType 发送通知(注意:不是当前订单的 payType)
            sendSubscribeMsgByPayType(nextOrder, activityName, remark,
                activityNo, orderTime, pageUrl);
            log.info("已通知下一个排队用户: userId={}, orderNo={}", nextUser.getId(), activityNo);
        }
    }
}

6.4 改造前后对比

场景 改造前 改造后
支付成功 只走微信,手动检查 openId != null sendSubscribeMsgByPayType() 按 payType 路由
退款中 只走微信 sendSubscribeMsgByPayType() 按 payType 路由
退款完成 只走微信 sendSubscribeMsgByPayType() 按 payType 路由
素材上传完成 只走微信 sendSubscribeMsgByPayType() 按 payType 路由
通知下一位排队 只走微信 sendSubscribeMsgByPayType(nextOrder, ...) 按下一笔订单的 payType 路由

7. 支付宝端前置配置清单

步骤 操作路径 说明
① 开启能力 开放平台 → 应用详情 → 添加能力 → 小程序订阅消息 开通小程序订阅消息能力
② 申请模板 小程序订阅消息 → 模板库 选择或自定义模板,记录模板ID
③ 配置模板变量 模板详情 → 变量定义 确保与代码 data 中的 key 一致
④ 用户订阅授权 小程序前端调用 my.requestSubscribeMessage 用户需主动授权对应模板后才能收到消息
⑤ 填写后端配置 数据库 alipay_config 表 type=MINI 的记录需配置正确的 appId、私钥等

用户授权流程(前端)

// 支付宝小程序端 - 引导用户授权订阅消息
my.requestSubscribeMessage({
  entityIds: ['YOUR_ALIPAY_TEMPLATE_ID'],
  success(res) {
    console.log('订阅消息授权结果', res);
  },
  fail(err) {
    console.error('订阅消息授权失败', err);
  }
});

8. 文件变更清单

操作 文件路径
新增 zlt-business/order-center/src/main/java/com/central/order/service/AlipayMiniSubscribeService.java
新增 zlt-business/order-center/src/main/java/com/central/order/service/impl/AlipayMiniSubscribeServiceImpl.java
修改 zlt-business/order-center/src/main/java/com/central/order/listener/OrderStatusChangeListener.java
修改 对应环境 application.yml 新增 alipay.mini.template.service-process 配置

9. 风险与注意事项

风险点 说明 应对措施
支付宝 userId 获取失败 用户未通过支付宝登录或第三方表无映射 代码中已做 null 检查,静默跳过
模板字段不匹配 代码中的 key 与平台申请的模板变量不一致 上线前严格对照模板变量表
用户未授权订阅 支付宝要求用户主动授权才能发消息 前端引导授权;未授权时 API 返回错误码,不影响主流程
配置缺失 alipay_config 表无当前订单 tenantId + type=MINI 记录 AlipayMiniSubscribeService 按租户查询失败时跳过,日志告警
接口限流 支付宝 API 有调用频率限制 try-catch 不影响主业务流程
排队通知的 payType sendMessageToNextOrderUser 应使用下一笔订单的 payType,而非当前订单 sendSubscribeMsgByPayType(nextOrder, ...) 传入 nextOrder