@seayoo-io/combo-sdk-node 1.9.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -33,7 +33,7 @@ jsonwebtoken = __toESM(jsonwebtoken);
33
33
  /** SDK 名称 */
34
34
  const SDKName = "combo-sdk-node";
35
35
  /** SDK 版本,在编译前会被动态替换 */
36
- const SDKVersion = "1.9.0";
36
+ const SDKVersion = "1.11.0";
37
37
  /**
38
38
  * 世游支持的服务端点列表
39
39
  */
@@ -413,7 +413,7 @@ async function readBody(req, backup) {
413
413
  backup || console.error({
414
414
  type: "RequestUnReadable",
415
415
  url: req.url,
416
- methe: req.method,
416
+ method: req.method,
417
417
  message: "Cannot read body, stream not readable"
418
418
  });
419
419
  return backup || "";
@@ -464,6 +464,24 @@ function genNonceString() {
464
464
  const r = Math.random() + Math.random();
465
465
  return (0, crypto.createHash)("md5").update(`${ts}${r}`).digest("hex").toLowerCase();
466
466
  }
467
+ /**
468
+ * 检查一个值是否为 Combo ID 的格式。
469
+ *
470
+ * 仅做格式检查,不检查该 ID 是否真实存在。
471
+ */
472
+ function mayBeComboId(id) {
473
+ if (typeof id !== "string") return false;
474
+ const m = id.match(/^9?[15](\d{2})(\d{2})(\d{2})(\d{5})(\d{4})$/);
475
+ if (!m) return false;
476
+ const year = 2e3 + Number(m[1]);
477
+ const month = Number(m[2]);
478
+ const date = Number(m[3]);
479
+ const seconds = Number(m[4]);
480
+ const sn = Number(m[5]);
481
+ if (year <= 2020 || seconds >= 24 * 3600 || sn === 0) return false;
482
+ const d = new Date(Date.UTC(year, month - 1, date));
483
+ return d.getUTCFullYear() === year && d.getUTCMonth() === month - 1 && d.getUTCDate() === date;
484
+ }
467
485
  //#endregion
468
486
  //#region src/request/inc/rule.ts
469
487
  const defaultDataField = "data";
@@ -1710,4 +1728,5 @@ exports.getNotificationHandlerForExpress = getNotificationHandlerForExpress;
1710
1728
  exports.getNotificationHandlerForKoa = getNotificationHandlerForKoa;
1711
1729
  exports.getNotificationMiddlewareForExpress = getNotificationMiddlewareForExpress;
1712
1730
  exports.getNotificationMiddlewareForKoa = getNotificationMiddlewareForKoa;
1731
+ exports.mayBeComboId = mayBeComboId;
1713
1732
  exports.parseAuthorizationHeader = parseAuthorizationHeader;
package/dist/index.d.cts CHANGED
@@ -60,6 +60,12 @@ declare function checkHttpAuthInfo(authString: string, option: SignDataOptionFor
60
60
  //#region src/utils/index.d.ts
61
61
  /** 生成一个 SessionID 以用作用户上下线的上报标记 */
62
62
  declare function genSessionID(comboId: string): string;
63
+ /**
64
+ * 检查一个值是否为 Combo ID 的格式。
65
+ *
66
+ * 仅做格式检查,不检查该 ID 是否真实存在。
67
+ */
68
+ declare function mayBeComboId(id: unknown): id is string;
63
69
  //#endregion
64
70
  //#region src/request/inc/type.d.ts
65
71
  type IBaseRequestBody = URLSearchParams | string;
@@ -443,8 +449,17 @@ interface VoiceModerationRequestOption {
443
449
  server_id: number;
444
450
  /** 提交审核申请的玩家角色 ID。 */
445
451
  requester_role_id: string;
452
+ /** 提交审核申请的玩家的唯一标识,选填。不传表示未提供。 */
453
+ requester_combo_id?: string;
446
454
  /** 被提交语音审核的玩家角色 ID 列表,一次最多提交 32 个。 */
447
455
  target_role_ids: string[];
456
+ /**
457
+ * 提交审核申请的原因列表,选填。
458
+ *
459
+ * 一次最多提交 12 个,单个原因最多 32 个字符,取值参见:审核申请原因维度表。
460
+ * 注意:取值不能包含英文逗号。
461
+ */
462
+ reasons?: string[];
448
463
  }
449
464
  //#endregion
450
465
  //#region src/api/index.d.ts
@@ -895,4 +910,4 @@ declare class RedisIdempotencyStore implements IdempotencyKeyStoreHelper {
895
910
  setXX(key: string, value: string): Promise<void>;
896
911
  }
897
912
  //#endregion
898
- export { type AdPayload, ApiClient, type ApiClientConfig, type CreateOrderOption, type CreateOrderResponse, type DataTag, type DataTagsNotification, type ENotificationPayload, Endpoint, GMError, type GetMiniGameWeixinAccessTokenOption, type GetMiniGameWeixinAccessTokenResponse, IdP, type IdentityPayload, MemoryIdempotencyStore, type NotificationHandler, NotificationType, type OrderMetaData, Platform, RedisIdempotencyStore, type RefundNotification, type SDKBaseConfig, type SendOtpMetaData, type SendOtpOption, type SendOtpResponse, type ShipOrderNotification, type SupportedOtpChannel, TokenVerifier, type VerifyOtpOption, type VerifyOtpResponse, type VoiceModerationRequestOption, calcAuthorizationHeader, checkHttpAuthInfo, genSessionID, getGMCommandHandler, getGMHandlerForExpress, getGMHandlerForKoa, getGMMiddlewareForExpress, getGMMiddlewareForKoa, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, parseAuthorizationHeader };
913
+ export { type AdPayload, ApiClient, type ApiClientConfig, type CreateOrderOption, type CreateOrderResponse, type DataTag, type DataTagsNotification, type ENotificationPayload, Endpoint, GMError, type GetMiniGameWeixinAccessTokenOption, type GetMiniGameWeixinAccessTokenResponse, IdP, type IdentityPayload, MemoryIdempotencyStore, type NotificationHandler, NotificationType, type OrderMetaData, Platform, RedisIdempotencyStore, type RefundNotification, type SDKBaseConfig, type SendOtpMetaData, type SendOtpOption, type SendOtpResponse, type ShipOrderNotification, type SupportedOtpChannel, TokenVerifier, type VerifyOtpOption, type VerifyOtpResponse, type VoiceModerationRequestOption, calcAuthorizationHeader, checkHttpAuthInfo, genSessionID, getGMCommandHandler, getGMHandlerForExpress, getGMHandlerForKoa, getGMMiddlewareForExpress, getGMMiddlewareForKoa, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, mayBeComboId, parseAuthorizationHeader };
package/dist/index.d.ts CHANGED
@@ -60,6 +60,12 @@ declare function checkHttpAuthInfo(authString: string, option: SignDataOptionFor
60
60
  //#region src/utils/index.d.ts
61
61
  /** 生成一个 SessionID 以用作用户上下线的上报标记 */
62
62
  declare function genSessionID(comboId: string): string;
63
+ /**
64
+ * 检查一个值是否为 Combo ID 的格式。
65
+ *
66
+ * 仅做格式检查,不检查该 ID 是否真实存在。
67
+ */
68
+ declare function mayBeComboId(id: unknown): id is string;
63
69
  //#endregion
64
70
  //#region src/request/inc/type.d.ts
65
71
  type IBaseRequestBody = URLSearchParams | string;
@@ -443,8 +449,17 @@ interface VoiceModerationRequestOption {
443
449
  server_id: number;
444
450
  /** 提交审核申请的玩家角色 ID。 */
445
451
  requester_role_id: string;
452
+ /** 提交审核申请的玩家的唯一标识,选填。不传表示未提供。 */
453
+ requester_combo_id?: string;
446
454
  /** 被提交语音审核的玩家角色 ID 列表,一次最多提交 32 个。 */
447
455
  target_role_ids: string[];
456
+ /**
457
+ * 提交审核申请的原因列表,选填。
458
+ *
459
+ * 一次最多提交 12 个,单个原因最多 32 个字符,取值参见:审核申请原因维度表。
460
+ * 注意:取值不能包含英文逗号。
461
+ */
462
+ reasons?: string[];
448
463
  }
449
464
  //#endregion
450
465
  //#region src/api/index.d.ts
@@ -895,4 +910,4 @@ declare class RedisIdempotencyStore implements IdempotencyKeyStoreHelper {
895
910
  setXX(key: string, value: string): Promise<void>;
896
911
  }
897
912
  //#endregion
898
- export { type AdPayload, ApiClient, type ApiClientConfig, type CreateOrderOption, type CreateOrderResponse, type DataTag, type DataTagsNotification, type ENotificationPayload, Endpoint, GMError, type GetMiniGameWeixinAccessTokenOption, type GetMiniGameWeixinAccessTokenResponse, IdP, type IdentityPayload, MemoryIdempotencyStore, type NotificationHandler, NotificationType, type OrderMetaData, Platform, RedisIdempotencyStore, type RefundNotification, type SDKBaseConfig, type SendOtpMetaData, type SendOtpOption, type SendOtpResponse, type ShipOrderNotification, type SupportedOtpChannel, TokenVerifier, type VerifyOtpOption, type VerifyOtpResponse, type VoiceModerationRequestOption, calcAuthorizationHeader, checkHttpAuthInfo, genSessionID, getGMCommandHandler, getGMHandlerForExpress, getGMHandlerForKoa, getGMMiddlewareForExpress, getGMMiddlewareForKoa, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, parseAuthorizationHeader };
913
+ export { type AdPayload, ApiClient, type ApiClientConfig, type CreateOrderOption, type CreateOrderResponse, type DataTag, type DataTagsNotification, type ENotificationPayload, Endpoint, GMError, type GetMiniGameWeixinAccessTokenOption, type GetMiniGameWeixinAccessTokenResponse, IdP, type IdentityPayload, MemoryIdempotencyStore, type NotificationHandler, NotificationType, type OrderMetaData, Platform, RedisIdempotencyStore, type RefundNotification, type SDKBaseConfig, type SendOtpMetaData, type SendOtpOption, type SendOtpResponse, type ShipOrderNotification, type SupportedOtpChannel, TokenVerifier, type VerifyOtpOption, type VerifyOtpResponse, type VoiceModerationRequestOption, calcAuthorizationHeader, checkHttpAuthInfo, genSessionID, getGMCommandHandler, getGMHandlerForExpress, getGMHandlerForKoa, getGMMiddlewareForExpress, getGMMiddlewareForKoa, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, mayBeComboId, parseAuthorizationHeader };
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ import jwt from "jsonwebtoken";
7
7
  /** SDK 名称 */
8
8
  const SDKName = "combo-sdk-node";
9
9
  /** SDK 版本,在编译前会被动态替换 */
10
- const SDKVersion = "1.9.0";
10
+ const SDKVersion = "1.11.0";
11
11
  /**
12
12
  * 世游支持的服务端点列表
13
13
  */
@@ -387,7 +387,7 @@ async function readBody(req, backup) {
387
387
  backup || console.error({
388
388
  type: "RequestUnReadable",
389
389
  url: req.url,
390
- methe: req.method,
390
+ method: req.method,
391
391
  message: "Cannot read body, stream not readable"
392
392
  });
393
393
  return backup || "";
@@ -438,6 +438,24 @@ function genNonceString() {
438
438
  const r = Math.random() + Math.random();
439
439
  return createHash("md5").update(`${ts}${r}`).digest("hex").toLowerCase();
440
440
  }
441
+ /**
442
+ * 检查一个值是否为 Combo ID 的格式。
443
+ *
444
+ * 仅做格式检查,不检查该 ID 是否真实存在。
445
+ */
446
+ function mayBeComboId(id) {
447
+ if (typeof id !== "string") return false;
448
+ const m = id.match(/^9?[15](\d{2})(\d{2})(\d{2})(\d{5})(\d{4})$/);
449
+ if (!m) return false;
450
+ const year = 2e3 + Number(m[1]);
451
+ const month = Number(m[2]);
452
+ const date = Number(m[3]);
453
+ const seconds = Number(m[4]);
454
+ const sn = Number(m[5]);
455
+ if (year <= 2020 || seconds >= 24 * 3600 || sn === 0) return false;
456
+ const d = new Date(Date.UTC(year, month - 1, date));
457
+ return d.getUTCFullYear() === year && d.getUTCMonth() === month - 1 && d.getUTCDate() === date;
458
+ }
441
459
  //#endregion
442
460
  //#region src/request/inc/rule.ts
443
461
  const defaultDataField = "data";
@@ -1662,4 +1680,4 @@ function getGMMiddlewareForKoa(paths, config, handler, storeHelper) {
1662
1680
  };
1663
1681
  }
1664
1682
  //#endregion
1665
- export { ApiClient, Endpoint, GMError, IdP, MemoryIdempotencyStore, NotificationType, Platform, RedisIdempotencyStore, TokenVerifier, calcAuthorizationHeader, checkHttpAuthInfo, genSessionID, getGMCommandHandler, getGMHandlerForExpress, getGMHandlerForKoa, getGMMiddlewareForExpress, getGMMiddlewareForKoa, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, parseAuthorizationHeader };
1683
+ export { ApiClient, Endpoint, GMError, IdP, MemoryIdempotencyStore, NotificationType, Platform, RedisIdempotencyStore, TokenVerifier, calcAuthorizationHeader, checkHttpAuthInfo, genSessionID, getGMCommandHandler, getGMHandlerForExpress, getGMHandlerForKoa, getGMMiddlewareForExpress, getGMMiddlewareForKoa, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, mayBeComboId, parseAuthorizationHeader };
@@ -0,0 +1,224 @@
1
+ > [Combo SDK for Node.js](../README.md) / ApiClient
2
+
3
+ # ApiClient
4
+
5
+ ## 初始化
6
+
7
+ ```js
8
+ import { ApiClient, Endpoint } from "@seayoo-io/combo-sdk-node"
9
+
10
+ const client = new ApiClient({
11
+ game: "<GameId>",
12
+ secret: "<SecretKey>",
13
+ endpoint: Endpoint.China,
14
+ // 以下参数可选
15
+ maxRetry: 1, // 失败后自动重试次数,默认 1
16
+ retryInterval: 1000, // 重试间隔,默认是 1000,单位 ms,可以传递函数动态设置间隔
17
+ logger: function (log) {}, // 请求日志函数,log 类型参见源码类型定义
18
+ timeout: 5000, // 超时等待时长,单位 ms,默认 5000
19
+ })
20
+ ```
21
+
22
+ ## 创建订单 CreateOrder
23
+
24
+ ```js
25
+ // 导入枚举变量
26
+ import { Platform } from "@seayoo-io/combo-sdk-node"
27
+
28
+ // 创建订单
29
+ const createOrderResult = await client.createOrder({
30
+ /** 用于标识创建订单请求的唯一 ID */
31
+ reference_id: "<游戏订单ID>",
32
+ /** 发起购买的用户的唯一标识 */
33
+ combo_id: "<ComboID>",
34
+ /**
35
+ * 要购买的商品 ID
36
+ * 这里指的是在世游发行平台管理的商品 ID,其中重要的两个约定是:
37
+ * - 商品价格是正整数
38
+ * - 商品价格单位为 分 或 美分,即商品币种所支持的最小流通单位
39
+ */
40
+ product_id: "<ProductID>",
41
+ /** 平台,支持类型见源码类型定义 Platform */
42
+ platform: Platform.iOS,
43
+ /**
44
+ * 游戏侧接收发货通知的服务端地址
45
+ * 这个地址对应的服务端应该通过 Notify 模块实现路由处理
46
+ */
47
+ notify_url: "https://<YourSite>/<YourPath>"
48
+ /** 要购买的商品的数量,最小为 1,必须为正整数 */
49
+ quantity: 1,
50
+ /** [可选]订单上下文,在发货通知中透传回游戏 */
51
+ context: "",
52
+ /**
53
+ * 订单的元数据,详细定义参看 OrderMetaData
54
+ *
55
+ * 大部分元数据用于数据分析与查询,游戏侧应当尽量提供
56
+ * 某些元数据在特定的支付场景下是必须的,例如微信小游戏的 iOS 支付场景
57
+ */
58
+ meta: { ... }
59
+ })
60
+
61
+ interface OrderMetaData {
62
+ /** 游戏大区 ID */
63
+ zone_id?: string
64
+ /** 游戏服务器 ID */
65
+ server_id?: string
66
+ /** 游戏角色 ID */
67
+ role_id?: string
68
+ /** 游戏角色名 */
69
+ role_name?: string
70
+ /** 游戏角色的等级 */
71
+ role_level?: number
72
+ }
73
+
74
+ interface CreateOrderResponse {
75
+ /** 世游服务端创建的,标识订单的唯一 ID。 */
76
+ order_id: string
77
+ /** 世游服务端创建的订单 token,用于后续支付流程。 */
78
+ order_token: string
79
+ /** 订单失效时间。Unix timestamp in seconds。 */
80
+ expires_at: number
81
+ }
82
+ ```
83
+
84
+ ## 进入/离开游戏
85
+
86
+ 下述两个接口对应的功能是**中宣部防沉迷系统**的上报功能,这里的 SessionID 是一次游戏会话的标识,也就是每次玩家进入游戏+离开游戏,算一个 Game Session。单次游戏会话的上下线动作必须使用同一个 SessionID 上报。
87
+
88
+ ```js
89
+ // 进入游戏
90
+ await client.enterGame("<ComboID>", "<SessionID>")
91
+
92
+ // 离开游戏
93
+ await client.leaveGame("<ComboID>", "<SessionID>")
94
+ ```
95
+
96
+ > 注意,SessionID 不可重复使用,可以使用 SDK 提供的工具函数生成 SessionID
97
+
98
+ ```js
99
+ import { genSessionID } from "@seayoo-io/combo-sdk-node"
100
+
101
+ // genSessionID 接受唯一参数 comboId 作为输入,返回一个 32 位固定长度的不重复字符串
102
+ const userSessionID = genSessionID("<ComboID>")
103
+ ```
104
+
105
+ ## 发送/验证短信验证码 OTP
106
+
107
+ 用于向用户发送短信验证码 (OTP),以及校验用户输入的验证码,可用于账号绑定、敏感操作二次确认等场景。
108
+
109
+ > 验证码的目标行为 `action` 由世游发行平台创建并管理。同一次验证流程中,`sendOtp` 与 `verifyOtp` 传入的 `action` 和 `channel` 必须保持一致。
110
+
111
+ ```js
112
+ // 1. 发送验证码
113
+ const sendResult = await client.sendOtp({
114
+ /** 要发送验证码的用户的唯一标识 */
115
+ combo_id: "<ComboID>",
116
+ /** [可选] 发送验证码的通道,目前仅支持 "sms",不填写时默认为 "sms" */
117
+ channel: "sms",
118
+ /** 发送验证码的目标行为,由世游发行平台创建并管理 */
119
+ action: "<Action>",
120
+ /**
121
+ * [可选] 发送方元数据,主要用于数据分析,游戏服务端应当尽量提供
122
+ * 字段定义同 OrderMetaData
123
+ */
124
+ meta: { ... },
125
+ })
126
+
127
+ interface SendOtpResponse {
128
+ /** 掩码后的手机号,仅当 channel=sms 时有值。 */
129
+ mobile: string
130
+ /** 验证码有效期,单位秒。 */
131
+ otp_ttl: number
132
+ /** 重新发送验证码的冷却时间,单位秒。 */
133
+ otp_cooldown: number
134
+ }
135
+
136
+ // 2. 验证验证码
137
+ const verifyResult = await client.verifyOtp({
138
+ /** 要验证验证码的用户的唯一标识 */
139
+ combo_id: "<ComboID>",
140
+ /** [可选] 发送验证码的通道,需与发送时一致,不填写时默认为 "sms" */
141
+ channel: "sms",
142
+ /** 发送验证码的目标行为,需与发送时一致 */
143
+ action: "<Action>",
144
+ /** 用户输入的验证码 */
145
+ otp: "<OTP>",
146
+ })
147
+
148
+ if (verifyResult.valid) {
149
+ // 验证通过。验证码立即失效,不可重复使用
150
+ } else {
151
+ // 验证失败:验证码错误或已过期,建议提示用户重新输入
152
+ }
153
+
154
+ interface VerifyOtpResponse {
155
+ /**
156
+ * 是否验证通过。
157
+ * - true 表示验证通过。验证通过后验证码立即失效,不可重复使用。
158
+ * - false 表示验证失败,验证码不匹配或已过期,建议用户重新检查后重试。
159
+ */
160
+ valid: boolean
161
+ }
162
+ ```
163
+
164
+ > ⚠️ 错误处理
165
+ >
166
+ > - `sendOtp` 在请求失败时(如触发发送冷却、参数错误、服务端错误)会**抛出异常**,请使用 try/catch 捕获处理。
167
+ > - `verifyOtp` 仅在请求本身失败时抛出异常。**验证码不正确属于正常业务结果**,此时会返回 `{ valid: false }` 而不会抛出异常,游戏侧需要根据 `valid` 字段判断验证是否通过。
168
+
169
+ ## 获取微信小游戏接口调用凭证 GetMiniGameWeixinAccessToken
170
+
171
+ 获取微信小游戏的接口调用凭证(Access Token),供游戏服务端调用微信服务端 API 使用。接口调用凭证由世游服务端统一维护和刷新,游戏侧无需自行调用微信接口获取。
172
+
173
+ > 此接口仅适用于微信小游戏。
174
+
175
+ ```js
176
+ const result = await client.getMiniGameWeixinAccessToken({
177
+ /** 微信小游戏的 AppID,必须是当前游戏配置的微信小游戏应用 */
178
+ app_id: "<WeixinAppID>",
179
+ })
180
+
181
+ interface GetMiniGameWeixinAccessTokenResponse {
182
+ /** 微信小游戏的 AppID,与请求中的 app_id 一致。 */
183
+ app_id: string
184
+ /** 微信小游戏的接口调用凭证。 */
185
+ access_token: string
186
+ }
187
+ ```
188
+
189
+ > ⚠️ 注意事项
190
+ >
191
+ > - 游戏服务端应当**缓存**接口调用凭证,缓存时间 1 分钟,按照 1 次/分钟 的频率请求该 API 获取并刷新缓存。
192
+ > - `getMiniGameWeixinAccessToken` 在请求失败时会**抛出异常**,请使用 try/catch 捕获处理。
193
+
194
+ ## 申请语音审核 VoiceModerationRequest
195
+
196
+ 玩家认为语音房间内某些玩家存在语音违规行为时,可提交语音审核申请。调用前提是:游戏已经在世游开启语音审核服务。
197
+
198
+ ```js
199
+ const ok = await client.voiceModerationRequest({
200
+ /** 房间实例 ID,唯一标识某个语音房间的一次存续(从开启到关闭) */
201
+ room_instance_id: "<RoomInstanceID>",
202
+ /** 游戏服务器 ID */
203
+ server_id: 1001,
204
+ /** 提交审核申请的玩家角色 ID */
205
+ requester_role_id: "<PlayerRoleID>",
206
+ /** 提交审核申请的玩家的唯一标识,选填 */
207
+ requester_combo_id: "<PlayerComboID>",
208
+ /** 被提交语音审核的玩家角色 ID 列表,一次最多提交 32 个 */
209
+ target_role_ids: ["<TargetRoleID1>", "<TargetRoleID2>"],
210
+ /** 提交审核申请的原因列表,选填,数据来自于 GM 维度表 */
211
+ reasons: ["abuse", "noise"],
212
+ })
213
+
214
+ // ok 为 true 表示提交成功,false 表示提交失败(已自动打印错误日志)
215
+ if (ok) {
216
+ // 提交成功
217
+ }
218
+ ```
219
+
220
+ > ⚠️ 注意事项
221
+ >
222
+ > - `voiceModerationRequest` 不会在失败时抛出异常,而是返回 `false`。游戏侧可根据返回值决定后续处理。
223
+ > - `target_role_ids` 一次最多提交 32 个玩家角色 ID。
224
+ > - `reasons` 选填,一次最多提交 12 个,单个原因最多 32 个字符且不能包含英文逗号,取值参见:审核申请原因维度表。
package/docs/gm.md ADDED
@@ -0,0 +1,153 @@
1
+ > [Combo SDK for Node.js](../README.md) / GM
2
+
3
+ # GM
4
+
5
+ GM 模块使用方式类似于 Notify 模块。
6
+
7
+ ## Step 1 准备
8
+
9
+ ```js
10
+ import { GMError } from "@seayoo-io/combo-sdk-node"
11
+
12
+ // 1.1 定义 GM 处理函数
13
+ function gmCommandHandler(command, args, requestId, idempotencyKey, version, origin) {
14
+ // command 对应的是 GM 协议中定义的方法名,区分大小写,args 为该方法的参数。
15
+ // requestId 本次 GM 请求的唯一 ID。游戏侧可用此值来对请求进行去重。
16
+ // idempotencyKey 本次 GM 请求的 Idempotency Key。如果有非空值则应当执行幂等处理逻辑。
17
+ // SDK 已经内置了 idempotencyKey 的处理工具和配置,详细见下描述
18
+ // version 对应的是世游 GM 服务的版本号,目前固定是 2.0
19
+ // origin 对应的是 GM 请求的来源标记,区分大小写,如 combo/console
20
+ // 详见 https://docs.seayoo.com/combo/server/gm/#gm-request
21
+ switch(command) {
22
+ case "SomeCmdName":
23
+ // 参数 args 由协议定义,在使用前需要做严格的格式和逻辑校验
24
+ // 返回值需要根据协议定义进行响应,通常是一个包含了多个字段的 object
25
+ return await execSomeCommand(args);
26
+ case "OtherCmdName":
27
+ // 抛出自定义错误有三种方式:
28
+ // 1. 返回一个 Error 对象,最终响应以 500(internalServerError)作为 http status
29
+ return new Error("自定义错误信息")
30
+ // 2. 返回一个自定义消息体 (预设的消息类型见下描述),推荐使用此方式
31
+ return { error: GMError.ThrottlingError, message: "请求过于频繁,请稍后再试" }
32
+ // 3. 直接抛出错误,用于处理异常场景,最终响应以 500 作为 http status
33
+ // 相比于方式1,此流程会打印一条错误日志
34
+ throw new Error("some unknown error")
35
+ ...
36
+ default: // 不识别的指令进行返回
37
+ return { error: GMError.InvalidCommand, message: "不识别的指令"+ command }
38
+ }
39
+ }
40
+
41
+ /** GM 预设错误类型枚举 */
42
+ enum GMError {
43
+ /** 请求中的 HTTP method 不正确,没有按照预期使用 POST。*/
44
+ InvalidHttpMethod = "invalid_http_method",
45
+ /** 请求中的 Content-Type 不是 application/json。*/
46
+ InvalidContentType = "invalid_content_type",
47
+ /** 对 HTTP 请求的签名验证不通过。这意味着 HTTP 请求不可信。 */
48
+ InvalidSignature = "invalid_signature",
49
+ /** 请求的结构不正确。例如,缺少必要的字段,或字段类型不正确。 */
50
+ InvalidRequest = "invalid_request",
51
+ /** 游戏侧不认识请求中的 GM 命令。 */
52
+ InvalidCommand = "invalid_command",
53
+ /** GM 命令发送频率过高,被游戏侧限流,命令未被处理。 */
54
+ ThrottlingError = "throttling_error",
55
+ /** 幂等处理重试请求时,idempotency_key 所对应的原始请求尚未处理完毕。*/
56
+ IdempotencyConflict = "idempotency_conflict",
57
+ /** 幂等处理重试请求时,请求内容和 idempotency_key 所对应的原始请求内容不一致。*/
58
+ IdempotencyMismatch = "idempotency_mismatch",
59
+ /** GM 命令的参数不正确。例如,参数缺少必要的字段,或参数的字段类型不正确。 */
60
+ InvalidArgs = "invalid_args",
61
+
62
+ /** 游戏当前处于停服维护状态,无法处理收到的 GM 命令。*/
63
+ MaintenanceError = "maintenance_error",
64
+ /** 网络通信错误。 */
65
+ NetworkError = "network_error",
66
+ /** 数据库操作异常导致 GM 命令执行失败。 */
67
+ DatabaseError = "database_error",
68
+ /** GM 命令处理超时。 */
69
+ TimeoutError = "timeout_error",
70
+ /** 处理 GM 命令时内部出错。可作为兜底的通用错误类型。*/
71
+ InternalError = "internal_error",
72
+ }
73
+
74
+ // 1.2 创建配置,相比于 Notify 模块,此处不需要 endpoint 配置
75
+ const config = {
76
+ game: "<GameId>",
77
+ secret: "<SecretKey>",
78
+ }
79
+ ```
80
+
81
+ ## Step 2 创建 Store Helper 以启用 idempotencyKey 处理逻辑
82
+
83
+ ```js
84
+ // SDK 内置 idempotencyKey 处理逻辑,其需要相关存储来实现,比如 Redis。
85
+ // 创建 Store Helper 用于启用内置的 idempotencyKey 处理逻辑
86
+ // store helper 需要实现以下方法即可:
87
+ interface IdempotencyKeyStoreHelper {
88
+ /**
89
+ * setNX 用于原子性地存储幂等记录并返回旧值。
90
+ * value 仅在 key 不存在时才会被存储 (Only set the key if it does not already exist)。
91
+ * 返回值是 key 存在时的旧值。如果 key 不存在则返回空字符串。
92
+ */
93
+ setNX: (key: string, value: string) => Promise<string>
94
+
95
+ /**
96
+ * setXX 用于原子性地更新已存在的幂等记录。
97
+ * value 仅在 key 存在时才会被存储 (Only set the key if it already exists)。
98
+ */
99
+ setXX: (key: string, value: string) => Promise<void>
100
+ }
101
+
102
+ // SDK 内置实现了两个工具类
103
+ import { MemoryIdempotencyStore, RedisIdempotencyStore } from "@seayoo-io/combo-sdk-node"
104
+
105
+ // MemoryIdempotencyStore 仅仅用于本地调试
106
+ const storeHelper = new MemoryIdempotencyStore()
107
+ // RedisIdempotencyStore 基于 ioredis 实现,需要 Redis 版本大于 7: https://redis.io/docs/latest/commands/set/
108
+ const storeHelper = new RedisIdempotencyStore({
109
+ /** 超时设定,单位秒,推荐不低于24小时 */
110
+ ttl?: number
111
+ /** ioredis 客户端 */
112
+ client: Redis
113
+ /** key 前缀 */
114
+ prefix?: string
115
+ })
116
+
117
+ // 当然可以直接自行实现上述 store helper 方法
118
+ ```
119
+
120
+ ## Step 3 绑定处理函数
121
+
122
+ 绑定方式同 Notify 类似,提供三种不同的方式来对接 http 服务。推荐使用方式 3。
123
+
124
+ ```js
125
+ // 方式 1. 使用 http 模块处理函数
126
+ import { getGMCommandHandler } from "@seayoo-io/combo-sdk-node"
127
+ // storeHelper 类型为 IdempotencyKeyStoreHelper
128
+ // 可不传递,如果不提供则不会启用内置的 idempotencyKey 处理逻辑,下同
129
+ const handler = getGMCommandHandler(config, gmCommandHandler, storeHelper)
130
+ http.createServer(async function (req, res) {
131
+ if (req.path === "<YourNotifyUrl>" && req.method === "POST") {
132
+ await handler(req, res)
133
+ }
134
+ })
135
+
136
+ // 方式 2. 使用 express / koa 的 handler
137
+ import { getGMHandlerForExpress } from "@seayoo-io/combo-sdk-node"
138
+ const expressHandler = getGMHandlerForExpress(config, gmCommandHandler, storeHelper)
139
+ app.post("/path/to/your/gm/url", expressHandler)
140
+
141
+ import { getGMHandlerForKoa } from "@seayoo-io/combo-sdk-node"
142
+ const koaHandler = getGMHandlerForKoa(config, gmCommandHandler, storeHelper)
143
+ app.post("/path/to/your/gm/url", koaHandler)
144
+
145
+ // 方式 3. 使用 express / koa 的中间件,推荐
146
+ import { getGMMiddlewareForExpress } from "@seayoo-io/combo-sdk-node"
147
+ const gmMiddleware = getGMMiddlewareForExpress("/path/to/your/gm/url", config, gmCommandHandler, storeHelper)
148
+ app.use(gmMiddleware)
149
+
150
+ import { getGMMiddlewareForKoa } from "@seayoo-io/combo-sdk-node"
151
+ const gmMiddleware = getGMMiddlewareForKoa("/path/to/your/gm/url", config, gmCommandHandler, storeHelper)
152
+ app.use(gmMiddleware)
153
+ ```