# 自定义消息传递API使用指南
# 概述
自定义消息传递API为美团小游戏提供了一套完整的消息通信机制,支持不同模块间的数据传递和事件通知。该API兼容微信小游戏接口规范,使用 wx 前缀,在打包过程中会自动替换为 mt 前缀。
# 核心功能
- 发送自定义消息到指定通道
- 监听指定通道的消息
- 取消消息监听
# API 列表
注意:只有美团版本等于或高于指定版本才可使用。 美团APP版本android:12.38.400及以上,iOS:12.38.400及以上
| 分类 | API | 说明 |
|---|---|---|
| 消息发送 | wx.sendCustomMsg | 发送自定义消息到指定通道 |
| 消息接收 | wx.onCustomMsg | 注册自定义消息监听器,监听指定通道的消息 |
| wx.offCustomMsg | 取消自定义消息监听 |
# 详细API说明
# wx.sendCustomMsg(channel, data)
发送自定义消息到指定通道。
参数:
- channel
string- 必需,通道ID,用于标识消息类型 - data
object- 必需,要发送的消息数据对象
示例:
// 发送用户状态更新消息
wx.sendCustomMsg(`${appId}_game_to_plugin`, {
type: "first_charge_coupon"
})
- ${appId} 代表应用ID 可从开放平台查看,若当前游戏与appId不符合会被拦截
- game_to_plugin 代表游戏向插件发送消息
- type为消息类型定义,详见【消息定义】
# wx.onCustomMsg(channel, callback)
注册自定义消息监听器,监听指定通道的消息。 参数:
- channel
string- 必需,通道ID,用于标识消息类型 - data
object- 必需,要发送的消息数据对象
特性:
- 支持同一通道注册多个监听器
- 新注册的监听器会自动接收该通道的历史消息
- 历史消息发送后会被自动清理 示例:
interface CouponContentInfo {
// 券最小使用门槛(分)
minUseThresholdCent?: number | null
// 券面额-可抵扣金额(分)
faceAmountCent?: number | null
}
interface DataType {
// 事件类型:使用首充券
type: "use_first_charge_coupon"
params: {
// 券信息
couponContentList: CouponContentInfo[]
}
}
wx.onCustomMsg(`${appId}_plugin_to_game`, function(data: DataType) {
console.log(data.type); // 事件类型:使用首充券
console.log(data.params.skuContentList); // 券信息
})
- ${appId} 代表应用ID 可从开放平台查看,若当前游戏与appId不符合会被拦截
- plugin_to_game 代表插件向游戏发送消息
- type为消息类型定义,详见【消息定义】
- params为消息补充参数,详见【消息定义】
# wx.offCustomMsg(channel, callback?)
取消自定义消息监听。 参数:
- channel
string- 必需,通道ID,用于标识消息类型 - data
object- 必需,要发送的消息数据对象 示例:
// 移除特定的监听器
interface DataType {
type: "use_first_charge_coupon"
}
wx.onCustomMsg(`${appId}_plugin_to_game`, function(data: DataType) {});
// 移除特定监听器
wx.offCustomMsg(`${appId}_plugin_to_game`, function(data: DataType) {});
// 移除所有监听器
wx.offCustomMsg(`${appId}_plugin_to_game`);
# 消息定义
| channel | type | params | 说明 |
|---|---|---|---|
| ${appId}_plugin_to_game | open_shopping_mall | {minUseThresholdCent: number, faceAmountCent: number} | 事件类型:打开游戏商城 minUseThresholdCent - 券最小使用门槛(分);faceAmountCent - 券面额-可抵扣金额(分) |
| use_first_charge_coupon | {minUseThresholdCent: number, faceAmountCent: number} | 事件类型:使用首充券 minUseThresholdCent - 券最小使用门槛(分);faceAmountCent - 券面额-可抵扣金额(分) | |
| ${appId}_game_to_plugin | first_charge_coupon | 发放首充券 | |
| event_report | {event: number} | 游戏节点上报 1-loading结束 | |
| recharge_cancel | 充值取消-用户进入充值页面,但未进行支付 | ||
| action_code_report | {actionCode: string, reportMode?: "platform" | "cp", actionCount?: number} | 行为任务完成上报。用于可多次上报行为任务悬浮球实时更新 actionCode-在开放平台配置的行为 code reportMode-platform 表示平台代上报;CP 自行上报时可不传或传 cp actionCount-本次行为进度增量,默认为 1 |
# 注意事项
参数验证:API 会自动验证参数类型,确保 channel 为字符串,data 为对象,callback 为函数
历史消息:新注册的监听器会自动接收历史消息,历史消息处理完成后会被清理
错误处理:监听器中的错误会被捕获并记录,不会影响其他监听器的执行
内存管理:及时使用 offCustomMsg清理不需要的监听器,避免内存泄漏
重复注册:同一个回调函数不会被重复注册到同一通道