Add Gameize games to your app把 Gameize 游戏接入你的应用
Your app opens our HTML5 games in a webview. Our server runs every round and moves coins in your wallet through two signed callbacks on your server.
你的应用在 webview 中打开我们的 HTML5 游戏。每一局都由我们的服务器运行,并通过你服务器上的两个签名回调接口来增减你钱包里的金币。
Quick start快速开始
- Get your credentials获取凭证We give you an
app_id, anapp_channeland a secretapp_key.我们会提供app_id、app_channel和保密的app_key。 - Build two callbacks on your server在服务器上实现两个回调get_user_info returns the player and balance. change_balance takes bets and pays wins. Send us both URLs.get_user_info 返回玩家信息和余额,change_balance 扣除下注并发放奖金。把两个 URL 发给我们。
- Load your game list获取游戏列表Call GET /api/v1/open/games from your server to get the games switched on for your app.从你的服务器调用 GET /api/v1/open/games,获取为你的应用开启的游戏。
How a game launches游戏启动流程
Four parties take part: your app on the phone, the game inside its webview, the Gameize server, and your server.
共有四方参与:手机上的应用、webview 中的游戏、Gameize 服务器,以及你的服务器。
GET /open/games and caches it.通过 GET /open/games 获取游戏列表并缓存。game_url in a webview.玩家点击游戏,应用在 webview 中打开对应的 game_url。getConfig. The app answers with appId, userId, the player's token as code, and the language.游戏调用 getConfig,应用返回 appId、userId、作为 code 的玩家 token,以及语言。code.游戏携带该 code 连接我们的服务器。get_user_info with ss_token = that code. You check the token and return the player and balance.我们以 ss_token = 该 code 调用你的 get_user_info。你校验 token 并返回玩家信息和余额。change_balance: a negative amount for a bet, a positive amount for a win.游戏过程中我们调用 change_balance:下注为负数,赢得奖金为正数。get_sstoken or update_sstoken endpoints. Your own user token is used directly as ss_token. If the token changes while the game is open, send the new one with serverCodeUpdate.你无需实现 get_sstoken 或 update_sstoken。你自己的用户 token 会直接作为 ss_token 使用。如果游戏打开期间 token 发生变化,请通过 serverCodeUpdate 发送新 token。Your credentials你的凭证
| Name名称 | Example示例 | Where it is used用途 |
|---|---|---|
app_id | 1509585550 | Identifies your app. Sent in X-App-Id, in getConfig.appId, and back to you in X-Gamezi-App-Id.标识你的应用。用于 X-App-Id、getConfig.appId,我们回调时也会放在 X-Gamezi-App-Id 中。 |
app_channel | megchat | Your channel name. Sent in getConfig.appChannel. Can replace X-App-Id as X-App-Channel.你的渠道名,用于 getConfig.appChannel。也可用 X-App-Channel 代替 X-App-Id。 |
app_key | •••••••• | The shared secret for every signature, in both directions.双向所有签名使用的共享密钥。 |
| Callback URLs回调地址 | https://api.yourapp.com/… | Your get_user_info and change_balance URLs. Use HTTPS, and send them to us.你的 get_user_info 和 change_balance 地址,请使用 HTTPS,并发送给我们。 |
app_key on your server only. Never put it in the mobile app, the webview, or the game URL. Anyone holding it can sign balance changes.app_key 只能保存在你的服务器上,绝不能放进手机应用、webview 或游戏链接。任何拿到它的人都能伪造余额变更请求。Request signatures请求签名
Every request between your server and ours is signed with HMAC-SHA256 and your app_key. The signature is the lowercase hex digest. There are two directions, each with its own headers.
你的服务器与我们服务器之间的每个请求都使用 app_key 进行 HMAC-SHA256 签名,签名为小写十六进制摘要。共有两个方向,各自使用不同的请求头。
Calling the Open API调用开放接口
X-App-Id(orX-App-Channel)(或X-App-Channel)X-Timestamp· unix seconds· Unix 秒X-Nonce· random string· 随机字符串X-Signature
Our callbacks to you我们发给你的回调
X-Gamezi-App-IdX-Gamezi-Timestamp· unix seconds· Unix 秒X-Gamezi-Nonce· 32 hex characters· 32 位十六进制X-Gamezi-Signature
The rules规则
METHOD | Upper case: GET, POST.大写:GET、POST。 |
PATH | The URL path without host or query string: /api/v1/open/games.不含域名和查询字符串的路径:/api/v1/open/games。 |
TIMESTAMP | Unix time in seconds, as a string. Must be within 5 minutes of our clock.Unix 时间(秒),字符串形式,与我们服务器时间相差不得超过 5 分钟。 |
NONCE | A new random string for every request.每个请求使用新的随机字符串。 |
BODY | The exact raw bytes of the request body. Empty for GET. Do not parse and re-encode the JSON before hashing.请求体的原始字节,GET 为空。计算前不要解析后再重新编码 JSON。 |
GET/api/v1/open/games17944704009f86d081884c7d659a2feaa0c55ad015各部分直接拼接,中间没有分隔符。游戏列表的待签名字符串示例:GET/api/v1/open/games17944704009f86d081884c7d659a2feaa0c55ad015Verify our callbacks校验我们的回调
The ss_token in a callback is your own user token, and the player's phone holds it too. Without a signature check, a player could call your change_balance and add coins. Check these four things before you touch a balance:
回调中的 ss_token 是你自己的用户 token,玩家手机上也有它。如果不校验签名,玩家可能直接调用你的 change_balance 给自己加金币。修改余额前,请检查以下四点:
X-Gamezi-App-Idequals yourapp_id.等于你的app_id。X-Gamezi-Timestampis within 5 minutes of your clock.与你的服务器时间相差不超过 5 分钟。X-Gamezi-Signatureequalshex(HMAC-SHA256(app_key, timestamp + nonce + raw_body)). Compare in constant time.等于hex(HMAC-SHA256(app_key, timestamp + nonce + raw_body)),请使用常量时间比较。X-Gamezi-Noncewas not used in the last 10 minutes. Store it, for example in Redis with a 10 minute expiry.在最近 10 分钟内未被使用过。可存入 Redis 并设置 10 分钟过期。
If a check fails, answer HTTP 401. We treat it as a failed call.
任何一项校验失败,请返回 HTTP 401,我们会视为调用失败。
const crypto = require('crypto');
const express = require('express');
const APP_ID = process.env.GAMEIZE_APP_ID;
const APP_KEY = process.env.GAMEIZE_APP_KEY;
const app = express();
// Keep the raw bytes: the signature covers the body exactly as sent.
app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } }));
async function verifyGameize(req, res, next) {
const ts = req.get('X-Gamezi-Timestamp') || '';
const nonce = req.get('X-Gamezi-Nonce') || '';
const sig = (req.get('X-Gamezi-Signature') || '').toLowerCase();
const expected = crypto.createHmac('sha256', APP_KEY)
.update(ts).update(nonce).update(req.rawBody || '')
.digest('hex');
const ok =
req.get('X-Gamezi-App-Id') === APP_ID &&
Math.abs(Date.now() / 1000 - Number(ts)) <= 300 &&
sig.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected)) &&
// SET NX with a 10 minute expiry: false when the nonce was seen before
(await redis.set('gameize:nonce:' + nonce, '1', { NX: true, EX: 600 })) === 'OK';
if (!ok) return res.status(401).json({ code: 401, message: 'invalid signature' });
next();
}
app.post('/gameize/get_user_info', verifyGameize, getUserInfo);
app.post('/gameize/change_balance', verifyGameize, changeBalance);
// app/Http/Middleware/VerifyGameize.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class VerifyGameize
{
public function handle(Request $request, Closure $next)
{
$ts = (string) $request->header('X-Gamezi-Timestamp', '');
$nonce = (string) $request->header('X-Gamezi-Nonce', '');
$sig = strtolower((string) $request->header('X-Gamezi-Signature', ''));
// getContent() is the raw body, before any JSON decoding
$expected = hash_hmac('sha256', $ts . $nonce . $request->getContent(), config('gameize.app_key'));
$ok = $request->header('X-Gamezi-App-Id') === config('gameize.app_id')
&& abs(time() - (int) $ts) <= 300
&& hash_equals($expected, $sig)
&& Cache::add('gameize_nonce_' . $nonce, 1, 600); // false if seen before
if (! $ok) {
return response()->json(['code' => 401, 'message' => 'invalid signature'], 401);
}
return $next($request);
}
}
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"net/http"
"strconv"
"strings"
"time"
)
// body is the raw request body you read before decoding the JSON.
func verifyGameize(r *http.Request, body []byte, appID, appKey string) bool {
ts := r.Header.Get("X-Gamezi-Timestamp")
nonce := r.Header.Get("X-Gamezi-Nonce")
sig := strings.ToLower(r.Header.Get("X-Gamezi-Signature"))
if r.Header.Get("X-Gamezi-App-Id") != appID {
return false
}
t, err := strconv.ParseInt(ts, 10, 64)
if err != nil {
return false
}
if d := time.Since(time.Unix(t, 0)); d > 5*time.Minute || d < -5*time.Minute {
return false
}
mac := hmac.New(sha256.New, []byte(appKey))
mac.Write([]byte(ts))
mac.Write([]byte(nonce))
mac.Write(body)
if !hmac.Equal([]byte(hex.EncodeToString(mac.Sum(nil))), []byte(sig)) {
return false
}
return rememberNonce(nonce, 10*time.Minute) // false if the nonce was seen before
}
Signature tester签名测试工具
Fill in your values and compare the result with what your code produces. Everything runs in your browser, so nothing you type here leaves this page. The example below gives cb42d485….
填写参数,并与你代码生成的结果进行对比。全部计算都在你的浏览器中完成,输入内容不会离开本页面。下方示例的结果为 cb42d485…。
Test vectors测试向量
All three use app_key test_app_key_123, timestamp 1794470400 and nonce 9f86d081884c7d659a2feaa0c55ad015.
三个示例均使用 app_key test_app_key_123、时间戳 1794470400 和 nonce 9f86d081884c7d659a2feaa0c55ad015。
| Request请求 | Expected signature预期签名 |
|---|---|
| get_user_info | cb42d4855ef0f25a17e531b2b92cc1ae74a9d1f623cc7a2b414928985496e7f2 |
| change_balance (body) | ff9ff8406f01bb084ab441c2b2a123af10e5405fed3e26bcd5f527f1c82b64dd |
| GET /api/v1/open/games | 69b280b5f2232ab5db4f4a74cc6861507ecaaf0e3ee99b906036504e5bdf2a37 |
Get your game list获取游戏列表
Returns the games that are switched on for your app, with everything you need to show and open them. Call it from your server, cache the result for 5 to 10 minutes, and serve your app from the cache.
返回为你的应用开启的游戏,以及展示和打开游戏所需的全部信息。请在你的服务器上调用,将结果缓存 5 到 10 分钟,再由缓存提供给你的应用。
const crypto = require('crypto');
async function listGames() {
const method = 'GET';
const path = '/api/v1/open/games';
const ts = Math.floor(Date.now() / 1000).toString(); // seconds
const nonce = crypto.randomBytes(16).toString('hex');
const signature = crypto.createHmac('sha256', process.env.GAMEIZE_APP_KEY)
.update(method + path + ts + nonce) // GET has no body
.digest('hex');
const res = await fetch('https://system.gameize.net' + path, {
headers: {
'X-App-Id': process.env.GAMEIZE_APP_ID,
'X-Timestamp': ts,
'X-Nonce': nonce,
'X-Signature': signature,
},
});
const json = await res.json();
if (json.code !== 0) throw new Error(json.message);
return json.data.games;
}
use Illuminate\Support\Facades\Http;
$path = '/api/v1/open/games';
$ts = (string) time(); // seconds
$nonce = bin2hex(random_bytes(16));
$sig = hash_hmac('sha256', 'GET' . $path . $ts . $nonce, config('gameize.app_key'));
$json = Http::withHeaders([
'X-App-Id' => config('gameize.app_id'),
'X-Timestamp' => $ts,
'X-Nonce' => $nonce,
'X-Signature' => $sig,
])->get('https://system.gameize.net' . $path)->json();
if (($json['code'] ?? -1) !== 0) {
throw new \RuntimeException($json['message'] ?? 'Gameize error');
}
$games = $json['data']['games'];
func listGames(appID, appKey string) (*http.Response, error) {
path := "/api/v1/open/games"
ts := strconv.FormatInt(time.Now().Unix(), 10)
nb := make([]byte, 16)
rand.Read(nb)
nonce := hex.EncodeToString(nb)
mac := hmac.New(sha256.New, []byte(appKey))
mac.Write([]byte("GET" + path + ts + nonce))
req, _ := http.NewRequest("GET", "https://system.gameize.net"+path, nil)
req.Header.Set("X-App-Id", appID)
req.Header.Set("X-Timestamp", ts)
req.Header.Set("X-Nonce", nonce)
req.Header.Set("X-Signature", hex.EncodeToString(mac.Sum(nil)))
return http.DefaultClient.Do(req)
}
APP_ID="your_app_id"
APP_KEY="your_app_key"
P="/api/v1/open/games"
TS=$(date +%s)
NONCE=$(openssl rand -hex 16)
SIG=$(printf '%s' "GET$P$TS$NONCE" | openssl dgst -sha256 -hmac "$APP_KEY" | sed 's/^.* //')
curl -s "https://system.gameize.net$P" \
-H "X-App-Id: $APP_ID" \
-H "X-Timestamp: $TS" \
-H "X-Nonce: $NONCE" \
-H "X-Signature: $SIG"
{
"code": 0,
"message": "",
"data": {
"app_id": "1509585550",
"total": 1,
"games": [
{
"game_id": "1166",
"game_name": "Greedy Cat King",
"game_type": "multiplier",
"image": "https://system.gameize.net/uploads/games/1166.png",
"version": "1.0.0",
"game_url": "https://cdn.gameize.net/bet/greedy_cat_king/",
"package_url": "",
"ui_config": {},
"updated_at": 1794412800,
"currency_icon": "https://system.gameize.net/uploads/coin_icons/1509585550.png"
}
]
}
}
| Field字段 | Type类型 | What to do with it用途 |
|---|---|---|
game_id | string | Our id for the game. Keep it as a string.游戏 ID,请按字符串保存。 |
game_name | string | Name to show in your game list.在游戏列表中显示的名称。 |
game_type | string | Kind of game, for grouping, e.g. multiplier for room wheels.游戏类型,可用于分组,例如房间转盘为 multiplier。 |
image | string | Full URL of the game icon. May be empty.游戏图标完整地址,可能为空。 |
game_url | string | Open this URL in the webview to start the game.在 webview 中打开此地址启动游戏。 |
package_url | string | Optional ZIP of the game for preloading. Empty when there is none.可选的游戏 ZIP 包,用于预加载,没有时为空。 |
version, updated_at | string, int | Change when we update a game. Refresh your cache or preloaded package when they change. updated_at is unix seconds.游戏更新时会变化,变化时请刷新缓存或预加载包。updated_at 为 Unix 秒。 |
ui_config | object | Extra display settings for the game. Usually {}.额外的显示设置,通常为 {}。 |
currency_icon | string | Your coin icon for this game, or empty. Pass it to the game as gameConfig.currencyIcon in getConfig.该游戏使用的你的金币图标,或为空。请在 getConfig 中作为 gameConfig.currencyIcon 传给游戏。 |
get_user_info
Called when a player opens a game. Check the token, then return the player and the current balance.
玩家打开游戏时调用。校验 token 后,返回玩家信息和当前余额。
POST /gameize/get_user_info HTTP/1.1
Content-Type: application/json
X-Gamezi-App-Id: 1509585550
X-Gamezi-Timestamp: 1794470400
X-Gamezi-Nonce: 9f86d081884c7d659a2feaa0c55ad015
X-Gamezi-Signature: cb42d4855ef0f25a17e531b2b92cc1ae74a9d1f623cc7a2b414928985496e7f2
{"ss_token":"eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIzNDkyIn0.sig"}
| Body field请求字段 | Type类型 | Meaning说明 |
|---|---|---|
ss_token | string | The code your app gave the game in getConfig. Check it as you check your own session tokens.应用在 getConfig 中传给游戏的 code。请按校验你自己会话 token 的方式进行校验。 |
{
"code": 0,
"message": "",
"unique_id": "req_5f2a91",
"data": {
"user_id": "3492",
"user_name": "Lina",
"user_avatar": "https://cdn.yourapp.com/avatars/3492.png",
"balance": 5000
}
}
| Field字段 | Meaning说明 | |
|---|---|---|
code | REQ | 0 for success. Any other number means the token is not valid, and the player cannot join.0 表示成功。其他数值表示 token 无效,玩家无法进入。 |
message | OPT | Error text when code is not 0. We log it.code 不为 0 时的错误信息,我们会记录。 |
unique_id | OPT | Your own id for this reply, for your logs.你为本次响应生成的 ID,便于日志排查。 |
data.user_id | REQ | The player's id as a string. Must be the same id you send as userId in getConfig.玩家 ID(字符串),必须与 getConfig 中的 userId 一致。 |
data.user_name | REQ | Name shown to other players.展示给其他玩家的昵称。 |
data.user_avatar | OPT | Full URL of the picture. Empty shows our default avatar.头像完整地址,为空时显示默认头像。 |
data.balance | REQ | Current coins, as a number.当前金币数量(数字)。 |
change_balance
Called for every coin movement. A negative currency_diff takes coins (a bet). A positive one adds coins (a win or a refund).
每次金币变动时调用。currency_diff 为负数表示扣除金币(下注),为正数表示增加金币(赢得奖金或退款)。
POST /gameize/change_balance HTTP/1.1
Content-Type: application/json
X-Gamezi-App-Id: 1509585550
X-Gamezi-Timestamp: 1794470400
X-Gamezi-Nonce: 9f86d081884c7d659a2feaa0c55ad015
X-Gamezi-Signature: ff9ff8406f01bb084ab441c2b2a123af10e5405fed3e26bcd5f527f1c82b64dd
{"currency_diff":-100,"diff_msg":"bet:FRUIT-1166-20261112-0214","game_id":1166,"ss_token":"eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIzNDkyIn0.sig","transaction_id":"gz_3f9c1e7a5b2d4c6e8f0a1b2c3d4e5f60","user_id":"3492"}
| Body field请求字段 | Type类型 | Meaning说明 |
|---|---|---|
ss_token | string | The player's token, as in get_user_info.玩家 token,与 get_user_info 中相同。 |
user_id | string | The player whose balance changes.余额发生变动的玩家。 |
game_id | number | The game, as a number (1166).游戏 ID(数字,如 1166)。 |
currency_diff | number | Coins to add (positive) or take (negative).增加(正数)或扣除(负数)的金币。 |
diff_msg | string | What the change is for. Save it with the transaction. See the table below.变动原因,请与交易记录一起保存,见下表。 |
transaction_id NEW | string | A unique id for this change, up to 64 characters (gz_ + 32 hex). A retry of the same change sends the same id. Apply each id once. See how.本次变动的唯一 ID,最长 64 个字符(gz_ + 32 位十六进制)。同一变动重试时 ID 不变。每个 ID 只处理一次。查看方法。 |
diff_msg valuesdiff_msg 取值
| Looks like格式 | Meaning含义 |
|---|---|
bet:<round_id> | Bets in a round. Always negative. A player who bets several times in one round sends several calls with this same value.某一局的下注,总为负数。玩家在同一局多次下注时,会发送多个相同取值的请求。 |
result:<round_id>… | Winnings from a round. Always positive.某一局的奖金,总为正数。 |
jackpot:<round_id> | A jackpot prize. Positive.大奖奖金,正数。 |
refund:… | Coins returned from a cancelled game or round. Positive.游戏或回合取消后退回的金币,正数。 |
…:stake:… | Coins a fast game (for example Pirate Fishing) holds while the player plays, then gives back when they leave.快节奏游戏(如海盗捕鱼)在游戏期间暂扣的金币,离开时退回。 |
…:shop:…, …:gift:…, …:reroll:… | Purchases inside a game. Negative.游戏内购买,负数。 |
{
"code": 0,
"message": "",
"unique_id": "tx_88123",
"data": {
"currency_balance": 4900
}
}
data.currency_balance is the balance after the change. To refuse a bet, for example when coins are too few, answer HTTP 200 with a non-zero code:
data.currency_balance 为变动之后的余额。如需拒绝下注(例如金币不足),请返回 HTTP 200 和非 0 的 code:
{ "code": 1004, "message": "insufficient balance", "data": { "currency_balance": 40 } }diff_msg to find repeats. It names the round, not the call: three bets of 500 in one round arrive as three calls with the same diff_msg and three different transaction_id values. Treating them as repeats would refuse real bets. Use transaction_id only.不要用 diff_msg 判断重复请求。它标识的是回合而不是单次请求:同一局的三次 500 下注会以三个请求到达,diff_msg 相同,transaction_id 各不相同。若把它们当作重复,会拒绝真实的下注。请只使用 transaction_id。Apply each transaction_id once每个 transaction_id 只处理一次
transaction_id. If your reply was lost after you added the coins, the retry arrives for a credit you already made. When an id you already applied comes again, answer code: 0 with the current balance and do not add the coins again.
奖金会重试。如果正数变动失败(超时、HTTP 错误或 code 不为 0),我们会保存该请求,并每分钟重新发送一次,最多 50 次,transaction_id 保持不变。如果你已加币但响应丢失,重试会针对一笔已经入账的奖金。当已处理过的 ID 再次到达时,请返回 code: 0 和当前余额,不要重复加币。
The fast way: a table with a unique index on transaction_id, written in the same database transaction as the balance change. A repeat fails on the unique key, so you need no extra lookup, and it adds about one millisecond.
推荐做法:建一张在 transaction_id 上有唯一索引的表,并与余额变更放在同一个数据库事务中写入。重复请求会因唯一键冲突而失败,无需额外查询,耗时约 1 毫秒。
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
try {
$balance = DB::transaction(function () use ($userId, $diff, $txId) {
// Throws on a repeated transaction_id (unique key)
DB::table('gameize_transactions')->insert(['transaction_id' => $txId, 'user_id' => $userId, 'amount' => $diff]);
$user = User::whereKey($userId)->lockForUpdate()->first();
if ($diff < 0 && $user->coins < -$diff) {
throw new \DomainException('insufficient balance');
}
$user->increment('coins', $diff);
return $user->coins;
});
} catch (QueryException $e) {
if (($e->errorInfo[1] ?? 0) !== 1062) throw $e; // not a duplicate
$balance = User::find($userId)->coins; // already applied
}
return ['code' => 0, 'message' => '', 'data' => ['currency_balance' => $balance]];
// Redis: SET NX keeps the id for 7 days; false means it was applied before.
const first = await redis.set('gameize:tx:' + body.transaction_id, '1', { NX: true, EX: 7 * 86400 });
if (first !== 'OK') {
return res.json({ code: 0, message: '', data: { currency_balance: await getBalance(body.user_id) } });
}
try {
const balance = await changeBalance(body.user_id, body.currency_diff);
res.json({ code: 0, message: '', data: { currency_balance: balance } });
} catch (err) {
await redis.del('gameize:tx:' + body.transaction_id); // not applied: allow the retry
res.json({ code: 1004, message: err.message });
}
CREATE TABLE gameize_transactions (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
transaction_id VARCHAR(64) NOT NULL,
user_id VARCHAR(64) NOT NULL,
amount DECIMAL(20,4) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uq_transaction (transaction_id)
);
transaction_id, process it the old way.该字段为新增字段。忽略它的服务器仍可照常工作,只是没有这层保护。若请求中没有 transaction_id,请按原方式处理。Game bridge (getConfig)游戏桥接 (getConfig)
Inside the webview, the game talks to your app through a small JavaScript bridge. The game sends a JSON string. That JSON has a jsCallback field with the name of a global function. Your app answers by calling that function with a JSON string.
在 webview 中,游戏通过一个简单的 JavaScript 桥与应用通信。游戏发送一个 JSON 字符串,其中的 jsCallback 字段是一个全局函数名。应用通过调用该函数并传入 JSON 字符串来回复。
| Platform平台 | The game calls游戏调用 | You answer with你的回复方式 |
|---|---|---|
| Android | window.NativeBridge.getConfig(json) | A @JavascriptInterface object named NativeBridge, then evaluateJavascript("window[cb]('…')")注册名为 NativeBridge 的 @JavascriptInterface 对象,再执行 evaluateJavascript("window[cb]('…')") |
| iOS | webkit.messageHandlers.getConfig.postMessage(json) | A WKScriptMessageHandler per method name, then evaluateJavaScript为每个方法名注册 WKScriptMessageHandler,再执行 evaluateJavaScript |
| Web (iframe)网页 (iframe) | parent.postMessage(json, "*") | iframe.contentWindow.postMessage({ jsMethods: cb, jsData: "…" }, "*") |
{
"appChannel": "megchat",
"appId": 1509585550,
"userId": "3492",
"code": "eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIzNDkyIn0.sig",
"roomId": "88231",
"gameMode": "3",
"language": "2",
"gsp": 101,
"role": 0,
"gameConfig": {
"sceneMode": 0,
"currencyIcon": "https://system.gameize.net/uploads/coin_icons/1509585550.png"
}
}
| Field字段 | Meaning说明 |
|---|---|
appChannel, appId | Your credentials from us.我们提供给你的凭证。 |
userId | The player's id as a string. Same as user_id in get_user_info.玩家 ID,必须为字符串,与 get_user_info 中的 user_id 一致。 |
code | The player's token. We send it back to you as ss_token. If it is a JWT, put the user id in the uid or sub claim.玩家 token,我们会作为 ss_token 回传给你。如果是 JWT,请把用户 ID 放在 uid 或 sub 声明中。 |
roomId | Your voice room id, for games played in a room.你的语音房 ID,用于房间内游戏。 |
gameMode | "3" in a voice room, "1" for a normal game.语音房内为 "3",普通游戏为 "1"。 |
language | "2" English, "7" Arabic, "0" Chinese."2" 英语、"7" 阿拉伯语、"0" 中文。 |
gsp | Always 101.固定为 101。 |
role | 2 for the room host or an admin, otherwise 0.房主或管理员为 2,其他为 0。 |
gameConfig.sceneMode | Send 0 unless we agree on another value.除非另有约定,请发送 0。 |
gameConfig.currencyIcon | The game's currency_icon from the games list. Send an empty string when it is empty, and the game keeps its own coin.游戏列表中该游戏的 currency_icon。为空时请发送空字符串,游戏将使用自带金币图标。 |
Other calls from the game游戏发起的其他调用
gameLoaded | The game finished loading. Hide your loading screen.游戏加载完成,可隐藏加载界面。 |
gameRecharge | The player needs coins. Open your top-up page.玩家需要金币,请打开充值页面。 |
destroy | The player closed the game. Close the webview.玩家关闭了游戏,请关闭 webview。 |
Events you send to the game你发送给游戏的事件
window.walletUpdate("{}") | Call after the player tops up, so the game reloads the balance.玩家充值后调用,游戏会刷新余额。 |
window.serverCodeUpdate('{"code":"…"}') | Call when the player's token changes. The game uses the new token from then on.玩家 token 变化时调用,游戏之后将使用新 token。 |
appId, code and currencyIcon. Answer every call within 5 seconds.这是标准的 Mesh H5 桥接协议。如果你的应用已接入过 Mesh H5 游戏,则已具备该桥接,只需传入正确的 appId、code 和 currencyIcon。每个调用请在 5 秒内回复。Errors and retries错误与重试
Open API errors开放接口错误
| HTTP | message | Fix解决方法 |
|---|---|---|
| 401 | Missing required authentication headers | Send X-App-Id, X-Timestamp and X-Signature.请携带 X-App-Id、X-Timestamp 和 X-Signature。 |
| 401 | Invalid X-Timestamp | Use whole seconds, not milliseconds.请使用整数秒,而不是毫秒。 |
| 401 | X-Timestamp expired | Your clock is more than 5 minutes off. Turn on NTP.服务器时间误差超过 5 分钟,请开启 NTP。 |
| 401 | Invalid app | Check X-App-Id or X-App-Channel.请检查 X-App-Id 或 X-App-Channel。 |
| 401 | Invalid HMAC Signature | Compare your string to sign with the tester. The usual causes are a query string in the path, or the wrong key.请用测试工具对比待签名字符串。常见原因是路径包含查询字符串或密钥错误。 |
| 403 | App is disabled | Your app is switched off. Contact us.你的应用已被停用,请联系我们。 |
| 500 | Failed to fetch games | Try again later, and keep serving your cached list.请稍后重试,并继续使用缓存的列表。 |
When your callback fails回调失败时
| Callback回调 | What happens结果 |
|---|---|
| get_user_info | The player cannot enter the game.玩家无法进入游戏。 |
| change_balance (bet)change_balance(下注) | The bet is cancelled. Nothing is retried.下注取消,不会重试。 |
| change_balance (win)change_balance(奖金) | Saved and retried every minute, up to 50 times.保存后每分钟重试一次,最多 50 次。 |
A call fails when it takes longer than 5 seconds, returns a status other than 200, returns invalid JSON, or returns a code other than 0.
以下情况视为调用失败:超过 5 秒、HTTP 状态不是 200、返回无效 JSON,或 code 不为 0。
Go-live checklist上线检查清单
- Signatures are checked on both callbacks两个回调都校验签名A request with a wrong signature gets 401 and changes nothing.签名错误的请求返回 401,且不产生任何变动。
- Repeated nonces are rejected重复的 nonce 会被拒绝Sending the same signed request twice fails the second time.同一签名请求发送两次,第二次失败。
- Retried wins are not paid twice重试的奖金不会重复发放A
transaction_idyou already applied getscode: 0and no second credit.已处理过的transaction_id返回code: 0,不会再次入账。 - Low balance refuses the bet余额不足时拒绝下注You answer a non-zero code and the balance stays the same.返回非 0 的 code,余额保持不变。
app_keylives only on your serverapp_key只保存在服务器上It is not in the app build, the webview or any URL.不出现在应用安装包、webview 或任何链接中。- The game list comes from the Open API游戏列表来自开放接口Game links and coin icons are not hard-coded in the app.游戏链接和金币图标没有写死在应用中。
Changelog更新记录
transaction_id in change_balance. Retries of a win send the same id, so you can apply it once.change_balance 新增字段 transaction_id。奖金重试时 ID 不变,便于只处理一次。X-Gamezi-*, the Open API GET /open/games with currency_icon, the signature tester and test vectors.文档重写。新增:回调签名请求头 X-Gamezi-*、含 currency_icon 的开放接口 GET /open/games、签名测试工具和测试向量。sign field. Our servers do not use that method. Use the header signatures described above.旧文档描述的参数排序签名及 sign 字段并未被我们的服务器使用,请使用上文所述的请求头签名。