跳到主要内容

Midasbuy Minigame SDK API 协议

1. 概述

Midasbuy Minigame SDK 是一个统一的小游戏 SDK 加载器和适配器,提供一致的 API 接口用于 Menu、Payment 和 Login 功能模块。

2. SDK 集成

<script src="https://cdn.midasbuy.com/js/minigame.stable.js"></script>

3. API 协议

3.1 初始化 midas.minigame(options)

const minigameApi = midas.minigame({
// 基础配置
appid: '1460000904',
region: 'us',
language: 'en',
sandbox: 1,
shopcode: 'ludoinapp',
reportDevMode: 0,

// Menu 模块配置, 可选
menu: {
isWithPcHeader: true
},

// Payment 模块配置, 可选
payment: {
openid: '1018553529511732',
charac_name: 'Player1',
useIpCountry: true,
},

// Login 模块配置, 可选
login: {
environment: 'sandbox',
debug: true,
timeout: 30000
}
});

参数说明

参数类型必填描述
appidstring应用 ID
regionstring地区代码,2位字符
languagestring语言代码,默认 'en'
sandboxnumber环境:0-生产,1-沙箱,2-测试,默认 0
shopcodestring商店代码
reportDevModenumber上报开发模式:0-关闭,1-开启,默认 0
menuMenuConfigMenu 模块配置
paymentPaymentConfigPayment 模块配置
loginLoginConfigLogin 模块配置
interface MenuConfig {
isWithPcHeader?: boolean; // PC端是否包含顶部header
}

PaymentConfig 类型

interface PaymentConfig {
openid?: string; // 用户 openid
charac_name?: string; // 角色名称
useIpCountry?: boolean; // 是否使用 IP 国家
}

LoginConfig 类型

interface LoginConfig {
environment?: 'production' | 'sandbox'; // 环境配置
debug?: boolean; // 调试模式
timeout?: number; // 请求超时时间(毫秒)
}

3.2 菜单功能

3.2.1 显示菜单 minigameApi.showMenu(options)

// 显示游戏菜单
minigameApi.showMenu({
gradually: true
});
参数说明
参数类型必填描述
graduallyboolean是否渐进式显示,默认 true

3.2.2 隐藏菜单 minigameApi.hideMenu(options)

// 隐藏游戏菜单
minigameApi.hideMenu({
gradually: true
});
参数说明
参数类型必填描述
graduallyboolean是否渐进式隐藏,默认 true

3.3 支付功能

3.3.1 显示支付页面 minigameApi.showPayment(options)

事件监听方式(传统):

// 使用事件监听器显示支付页面
minigameApi.on('payment:success', (data) => {
console.log('支付成功:', data);
});

minigameApi.on('payment:failed', (error) => {
console.log('支付失败:', error);
});

minigameApi.showPayment({
params: {
game_openid: '1018553529511732',
role_id: '1555629938',
product_id: 'coins_01-midasbuy'
},
extra: {
hideResultPage: true
}
});

Promise 方式(推荐):

// 使用 Promise 显示支付页面
minigameApi.showPayment({
params: {
game_openid: '1018553529511732',
role_id: '1555629938',
product_id: 'coins_01-midasbuy',
server_id: 'server_001'
},
extra: {
hideResultPage: true
}
})
.then(data => {
console.log('支付成功:', data);
// data 包含: { order_no, openid, order_no_hash }
})
.catch(error => {
console.log('支付错误:', error);

// 处理不同类型的错误
switch(error.type) {
case 'failed':
console.log('支付失败:', error.data);
break;
case 'hide':
console.log('支付弹窗被关闭');
break;
case 'queryChannelsFailed':
console.log('加载支付渠道失败:', error.data);
break;
}
});

// 使用 async/await
async function handlePayment() {
try {
const result = await minigameApi.showPayment({
params: {
game_openid: '1018553529511732',
role_id: '1555629938',
product_id: 'coins_01-midasbuy',
server_id: 'server_001'
}
});
console.log('支付成功:', result);
} catch (error) {
console.log('支付失败:', error.type, error.message);
}
}
参数说明
参数类型必填描述
paramsPaymentParams支付参数
extraPaymentExtra支付额外参数

PaymentParams 类型

interface PaymentParams {
game_openid: string; // 游戏用户 ID
role_id: string; // 角色 ID
product_id: string; // 商品 ID
server_id?: string; // 游戏分区ID
is_vip_product?: boolean; // 是否VIP商品
}

PaymentExtra 类型

interface PaymentExtra {
hideResultPage?: boolean; // 是否隐藏结果页面
}

PaymentError 类型

interface PaymentError extends Error {
code: string; // 错误代码
type: 'failed' | 'hide' | 'queryChannelsFailed'; // 错误类型
data?: any; // 额外错误数据
timestamp: number; // 错误时间戳
}
错误类型
类型描述发生时机
failed支付交易失败用户支付未成功
hide支付弹窗关闭用户关闭了支付弹窗
queryChannelsFailed加载支付渠道失败网络错误或商品无效

3.3.2 隐藏支付页面 minigameApi.hidePayment()

// 隐藏支付页面
minigameApi.hidePayment();

3.4 登录功能

3.4.1 用户登录 minigameApi.login(options)

回调方式:

// 使用回调函数的用户登录
minigameApi.login({
success: function(result) {
console.log('登录成功:', result);
},
fail: function(error) {
console.log('登录失败:', error);
}
});

Promise 方式:

// 使用 Promise 的用户登录
minigameApi.login()
.then(result => {
console.log('登录成功:', result);
})
.catch(error => {
console.log('登录失败:', error);
});

// 或者使用 async/await
async function handleLogin() {
try {
const result = await minigameApi.login();
console.log('登录成功:', result);
} catch (error) {
console.log('登录失败:', error);
}
}

参数说明:

参数类型必填说明
successFunction登录成功回调函数
failFunction登录失败回调函数

注意: 使用 Promise 方式时,可以省略 successfail 回调函数,改用 .then().catch() 方法。

成功回调参数:

{
code: 0,
message: 'success',
data: {
jwtToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
expiresIn: 3600,
refreshToken: 'rt_xxxxxxxxxxxxxxxx'
}
}

失败回调参数:

{
code: -1,
message: '错误描述',
error: 'ERROR_CODE'
}

3.5 事件监听 minigameApi.on(event, callback)

// 游戏菜单事件
minigameApi.on('menu:show', (data) => {
console.log('游戏菜单显示成功', data);
});

minigameApi.on('menu:hide', () => {
console.log('游戏菜单隐藏');
});

minigameApi.on('menu:error', (error) => {
console.error('游戏菜单错误', error);
});

// 支付事件
minigameApi.on('payment:success', (data) => {
console.log('支付成功', data);
});

minigameApi.on('payment:failed', (error) => {
console.log('支付失败', error);
});

minigameApi.on('payment:hide', () => {
console.log('支付页面隐藏');
});

minigameApi.on('payment:queryChannelsFailed', (error) => {
console.log('查询渠道失败', error);
});

// 登录事件
minigameApi.on('login:success', (data) => {
console.log('登录成功', data);
});

minigameApi.on('login:failed', (error) => {
console.log('登录失败', error);
});

minigameApi.on('login:statusChanged', (status) => {
console.log('登录状态变化', status);
});

minigameApi.on('login:tokenExpired', () => {
console.log('Token已过期');
});

// 通用事件
minigameApi.on('sdk:loaded', (modules) => {
console.log('SDK加载完成', modules);
});

minigameApi.on('sdk:error', (error) => {
console.error('SDK错误', error);
});

事件类型

事件名描述回调参数
menu:show游戏菜单显示成功{ res: string, size?: { width?: string, height?: string } }
menu:hide游戏菜单隐藏
menu:error游戏菜单错误Error
payment:success支付成功{ order_no: string, openid: string, order_no_hash: string }
payment:failed支付失败Error
payment:hide支付页面隐藏
payment:queryChannelsFailed查询渠道失败Error
login:success登录成功{ jwtToken: string, userInfo: object }
login:failed登录失败Error
login:statusChanged登录状态变化'logged_in' | 'logged_out' | 'token_expired'
login:tokenExpiredToken过期
sdk:loadedSDK加载完成string[] (已加载的模块列表)
sdk:errorSDK错误Error

3.6 取消事件监听 minigameApi.off(event, callback?)

// 取消特定回调
minigameApi.off('payment:success', callback);

// 取消所有回调
minigameApi.off('payment:success');

3.7 工具方法

3.7.1 获取模块实例 minigameApi.getModule(module)

获取特定模块实例的直接访问权限,用于高级用法。

// 获取菜单模块实例
const menuModule = minigameApi.getModule('menu');
if (menuModule) {
// 直接访问菜单模块方法
menuModule.show({ gradually: false });
}

// 获取支付模块实例
const paymentModule = minigameApi.getModule('payment');
if (paymentModule) {
// 直接访问支付模块方法
paymentModule.emit('checkout', params);
}

// 获取登录模块实例
const loginModule = minigameApi.getModule('login');
if (loginModule) {
// 直接访问登录模块方法
const isLoggedIn = loginModule.isLoggedIn();
}
参数说明
参数类型必填描述
modulestring模块名称:'menu'、'payment' 或 'login'
返回值

返回对应的模块实例,如果模块未加载或无效则返回 null

3.7.2 隐藏所有模块 minigameApi.hideAll()

// 隐藏所有模块(菜单、支付等)
minigameApi.hideAll();

4. 错误处理

4.1 错误类型

interface MinigameError extends Error {
code: string;
module?: 'menu' | 'payment' | 'core';
details?: any;
}

4.2 错误代码

错误代码描述
INIT_FAILED初始化失败
MODULE_NOT_LOADED模块未加载
INVALID_PARAMS无效参数
SHOW_FAILED显示失败
HIDE_FAILED隐藏失败
PAYMENT_FAILED支付失败
NETWORK_ERROR网络错误

4.3 全局错误处理

minigameApi.setErrorHandler((error) => {
console.error('Minigame SDK Error:', error);
// 自定义错误处理逻辑
});

5. 类型定义

declare namespace midas {
interface MinigameAPI {
showMenu(options?: MenuShowOptions): Promise<ShowResult>;
hideMenu(options?: MenuHideOptions): void;
showPayment(options: PaymentShowOptions): Promise<PaymentResult>;
hidePayment(): void;
hideAll(): void;
login(options: LoginOptions): Promise<LoginResult>;
getLoginStatus(): boolean;
getUserInfo(): UserInfo | null;
logout(): void;
on(event: string, callback: Function): void;
off(event: string, callback?: Function): void;
getModule(module: 'menu' | 'payment' | 'login'): any;
setErrorHandler(handler: (error: MinigameError) => void): void;
}

interface MenuShowOptions {
gradually?: boolean;
}

interface MenuHideOptions {
gradually?: boolean;
}

interface PaymentShowOptions {
params: PaymentParams;
extra?: PaymentExtra;
}

interface ShowResult {
res: string;
size?: {
width?: string;
height?: string;
};
}

interface LoginOptions {
success?: (result: LoginResult) => void;
fail?: (error: LoginError) => void;
}

interface LoginError {
code: number;
message: string;
error: string;
}

interface LoginResult {
code: number;
message: string;
data: {
jwtToken: string;
expiresIn: number;
refreshToken: string;
};
}

interface PaymentResult {
order_no: string; // 订单号
openid: string; // 用户ID
order_no_hash: string; // 订单哈希值
}

interface PaymentError extends Error {
code: string;
type: 'failed' | 'hide' | 'queryChannelsFailed';
data?: any;
timestamp: number;
}

function minigame(options: MinigameOptions): MinigameAPI;
}

6. 使用示例

6.1 完整示例

// 初始化 SDK
const minigameApi = midas.minigame({
appid: '1460000904',
region: 'us',
language: 'en',
sandbox: 1,
shopcode: 'ludoinapp',
reportDevMode: 0,
menu: {
isWithPcHeader: true
},
payment: {
openid: '1018553529511732'
},
login: {
environment: 'sandbox',
debug: true,
timeout: 30000
}
});

// 监听事件
minigameApi.on('sdk:loaded', (modules) => {
console.log('SDK加载完成:', modules);

// 获取模块实例以便直接访问
const menuModule = minigameApi.getModule('menu');
const paymentModule = minigameApi.getModule('payment');
const loginModule = minigameApi.getModule('login');

console.log('菜单模块:', menuModule);
console.log('支付模块:', paymentModule);
console.log('登录模块:', loginModule);
});

minigameApi.on('payment:success', (data) => {
console.log('支付成功:', data);
// 隐藏支付页面
minigameApi.hidePayment();
});

minigameApi.on('login:success', (data) => {
console.log('登录成功:', data);
// 显示游戏菜单
minigameApi.showMenu({
gradually: true
});
});

minigameApi.on('login:statusChanged', (status) => {
console.log('登录状态变化:', status);
});

// 用户登录 - 回调方式
minigameApi.login({
success: function(result) {
console.log('登录成功:', result);
},
fail: function(error) {
console.log('登录失败:', error);
}
});

// 用户登录 - Promise 方式
minigameApi.login()
.then(result => {
console.log('登录成功:', result);
// 登录成功后显示游戏菜单
return minigameApi.showMenu({ gradually: true });
})
.catch(error => {
console.log('登录失败:', error);
});

// 显示游戏菜单
minigameApi.showMenu({
gradually: true
});

// 显示支付页面 - Promise 方式(推荐)
minigameApi.showPayment({
params: {
game_openid: '1018553529511732',
role_id: '1555629938',
product_id: 'coins_01-midasbuy'
},
extra: {
hideResultPage: true
}
})
.then(result => {
console.log('支付成功:', result);
// result 包含: { order_no, openid, order_no_hash }
})
.catch(error => {
console.log('支付错误:', error.type, error.message);

// 处理特定错误类型
if (error.type === 'queryChannelsFailed') {
console.log('请检查网络连接');
} else if (error.type === 'hide') {
console.log('用户取消了支付');
}
});

7. 最佳实践

7.1 错误处理

minigameApi.setErrorHandler((error) => {
// 上报错误到监控系统
reportError(error);

// 用户友好的错误提示
if (error.code === 'PAYMENT_FAILED') {
showToast('支付失败,请稍后重试');
}
});

7.2 基于 Promise 的支付流程

// 现代化的 async/await 支付流程
class PaymentManager {
constructor(minigameApi) {
this.minigameApi = minigameApi;
}

async processPayment(productId, userId, roleId) {
try {
console.log('开始支付流程...');

const result = await this.minigameApi.showPayment({
params: {
game_openid: userId,
role_id: roleId,
product_id: productId,
server_id: 'server_001'
},
extra: {
hideResultPage: true
}
});

// 支付成功
console.log('支付完成:', result);
this.handlePaymentSuccess(result);
return result;

} catch (error) {
console.log('支付出现错误:', error);
this.handlePaymentError(error);
throw error;
}
}

handlePaymentSuccess(result) {
// 更新游戏状态,解锁内容等
console.log(`订单 ${result.order_no} 已完成,用户 ${result.openid}`);

// 显示成功消息
this.showNotification('支付成功!您的购买内容现已可用。');
}

handlePaymentError(error) {
switch (error.type) {
case 'failed':
this.showNotification('支付失败,请重试。');
this.trackEvent('payment_failed', error.data);
break;

case 'hide':
this.showNotification('支付已取消。');
this.trackEvent('payment_cancelled');
break;

case 'queryChannelsFailed':
this.showNotification('无法加载支付选项,请检查网络连接。');
this.trackEvent('payment_channels_failed', error.data);
break;
}
}

showNotification(message) {
// 显示用户友好的通知
console.log(`[通知] ${message}`);
}

trackEvent(eventName, data = null) {
// 记录分析事件
console.log(`[分析] ${eventName}`, data);
}
}

7.3 基于 Promise 的登录流程

// 现代化的 async/await 登录流程
class GameManager {
constructor() {
this.minigameApi = midas.minigame(config);
this.setupEventListeners();
}

async initializeGame() {
try {
// 等待 SDK 加载完成
await this.waitForSDKLoad();

// 尝试登录
const loginResult = await this.minigameApi.login();
console.log('用户已登录:', loginResult.data.jwtToken);

// 登录成功后显示游戏菜单
await this.minigameApi.showMenu({ gradually: true });

} catch (error) {
console.error('游戏初始化失败:', error);
this.handleInitError(error);
}
}

waitForSDKLoad() {
return new Promise((resolve) => {
this.minigameApi.on('sdk:loaded', resolve);
});
}

handleInitError(error) {
// 处理初始化错误
if (error.code === 'MODULE_NOT_LOADED') {
console.error('SDK 模块未正确加载');
}
}
}

7.4 事件管理

// 使用事件委托模式
class GameManager {
constructor() {
this.minigameApi = midas.minigame(config);
this.setupEventListeners();
}

setupEventListeners() {
this.minigameApi.on('payment:success', this.handlePaymentSuccess.bind(this));
this.minigameApi.on('menu:show', this.handleMenuShow.bind(this));
}

handlePaymentSuccess(data) {
// 处理支付成功
this.updateGameState(data);
}

handleMenuShow(data) {
// 处理游戏菜单显示
this.trackEvent('menu_show', data);
}
}