Integration guide
Patterns for a production integration. Start with the Quickstart if you haven't made your first call yet. Examples use gl, the example JavaScript client from the developer kit; each method maps to one API call.
Integration patterns#
Backend to backend (recommended)#
Your app sends the action to your backend, and your backend calls the GameLayer API. The Account API key never reaches the user's device, and because you decide when events fire, you can check them and limit them first.
Never ship the key in an app#
Don't call the GameLayer API from a web page or a mobile app. The key would ship inside the app, and anyone who extracts it can call every GameLayer API operation for your account: complete events and claim prizes for any player, delete players and teams, and set leaderboard scores. (It doesn't give access to the Admin API.)
Instead, give your app a small endpoint on your own backend. Your backend knows who the signed-in user is, decides which events they may send, and adds the key:
// Your backend (Node.js with Express). The app calls POST /api/lesson-complete.
app.post("/api/lesson-complete", requireSignedIn, async (req, res) => {
const result = await fetch(`${BASE_URL}/events/complete-lesson/complete`, {
method: "POST",
headers: {
"api-key": process.env.GL_API_KEY, // stays on the server
"Content-Type": "application/json",
"Idempotency-Key": req.get("Idempotency-Key"), // the app generates one per action
},
body: JSON.stringify({ account: process.env.GL_ACCOUNT, player: req.user.id, count: 1 }),
});
res.status(result.status).json(await result.json());
});- The player ID comes from your sign-in session, never from the request, so a user can't act for someone else.
- Expose only the actions your app needs, one endpoint each. Don't forward any path the app asks for.
- Return only what the app shows, such as
progress, if you'd rather not pass on the whole response.
Player lifecycle#
Create players#
Create a player when a user first signs up or logs in, using your own user ID as the player ID.
const player = await gl.createPlayer(user.id, user.displayName, {
tags: ["new-user"],
category: user.plan, // e.g. "free", "premium"
});If the player already exists, the API answers 409 Conflict with error code 21. Treat it as done:
try {
await gl.createPlayer(user.id, user.displayName);
} catch (err) {
if (err.errorCode !== 21) throw err; // 21 = player exists
}Update players#
Use PATCH /players/{player} when their details change in your system. This is also how a player joins a team:
await gl.updatePlayer(user.id, { name: user.newDisplayName });
await gl.updatePlayer(user.id, { category: "premium", tags: ["premium", "early-adopter"] });
await gl.updatePlayer(user.id, { team: "team-alpha" });Categories and tags drive requirements: a mission can require the tag premium, so only premium players see it.
Set the player's refresh offset the same way, so their missions reset at their own midnight:
await gl.updatePlayer(user.id, { refreshOffset: "UTC+02:00" });Adjust points and credits#
The same call corrects a player's balance. By default, points and credits are added to the current values, so a negative number lowers them. With mode: "set", they replace the current values.
// Take back 50 points awarded by mistake
await gl.updatePlayer(user.id, { points: -50 });
// Set the balances outright
await gl.updatePlayer(user.id, { points: 1200, credits: 0, mode: "set" });- There's no floor: a balance can go below zero.
- An amount added or taken away also counts toward the player's team totals.
mode: "set"leaves team totals unchanged.
Event tracking#
Call POST /events/{id}/complete whenever a user does something meaningful. Pass an idempotencyKey: a new UUID for each player action, kept for retries of that action:
import { randomUUID } from "node:crypto";
await gl.completeEvent("complete-lesson", user.id, 1, {}, { idempotencyKey: randomUUID() });
await gl.completeEvent("make-purchase", user.id, purchaseAmount, {}, { idempotencyKey: order.id }); // count = the amount
await gl.completeEvent("daily-login", user.id, 1, { tags: ["mobile"] }, { idempotencyKey: randomUUID() });Retrying safely#
A request can reach GameLayer and count while its response is lost, such as on a timeout or a dropped mobile connection. Without a key, a retry counts the event again, with its rewards.
- Make the key once per action, before the first attempt, and send the same key and identical body on every retry. An ID you already have for the action, such as an order ID, works well.
- A retry of a request that succeeded gets the same response, with
X-Idempotent-Replay: true, and counts nothing again. - A retry while the first request is still running gets
429with error code24. Wait forRetry-After, then retry. - The same key with a different body, event or player gets
422with error code111. A new action needs a new key. - Keys are kept 24 hours. Retry for up to 23 hours; after that, drop the event, since it may already have counted.
Claims and quiz and survey completions take no key. See When to retry.
The kit's example clients do this for you: completeEventReliably in JavaScript, complete_event_reliably in Python and CompleteEventReliablyAsync in C# make the key, retry with it and tell you whether the answer was a replay.
Counts#
count registers several completions in one call. If a user walks 5,000 steps, one call with count: 5000 moves a "walk 10,000 steps" mission halfway.
Show what happened#
The response's progress object lists everything the event set off. Use it for instant feedback:
const { progress } = await gl.completeEvent("complete-lesson", user.id);
if (progress.points.earned > 0) showToast(`+${progress.points.earned} points`);
for (const m of progress.missions) showModal(`Mission complete: ${m.name}`);
for (const l of progress.levels.completed) showCelebration(`Level up: ${l.name}`);
for (const a of progress.achievements) showBadge(a.name, a.imgUrl);
for (const s of progress.activeStreaks) showStreak(`${s.name}: ${s.streakCount} in a row`);Languages#
Pass language (an ISO 639-1 code such as fr) on player-facing GET requests to get element names and descriptions in that language. It works on lists and single elements for events, missions, achievements, levels, streaks, prizes, leaderboards, mystery boxes, raffles, quizzes and surveys. Where there's no translation, you get the default text, except for leaderboards, which answer 404 with error code 100. See Leaderboards. See Languages for the codes.
Showing progress#
GameLayer has no webhooks: it never calls your system. Progress is only available in the response of the call that caused it, and through the GET endpoints. Most integrations use both:
- The event response, for toasts and pop-ups straight after an action.
- The player's progress lists, for progress pages and dashboards:
GET /players/{player}/missions,/achievements,/levels,/streaksand others.
Each list is split into started and completed:
const { missions } = await gl.getPlayerMissions(user.id, { completion: "all" });
// missions.started: [{ id, name, objectives, ... }]
// missions.completed: [{ id, name, reward, actions: { completedOn }, ... }]
const { levels } = await gl.getPlayerLevels(user.id);
// levels.started: { id, name, ordinal, ... } the current level (one object)
// levels.completed: [{ id, name, ordinal, ... }]A mission's objectives holds exactly one of events, missions, quizzId or surveyId. The missions form is a mission made of other missions.
For progress bars, get one mission's progress per objective:
const { progress } = await gl.getPlayerMissionProgress(user.id, "weekly-lessons");
// progress.totalAverage = 0.6 (60% complete)
// progress.events = [{ id: "complete-lesson", count: 5, currentCount: 3, average: 0.6 }]Pagination#
Lists return 50 items unless you pass limit, and skip with skip. The response headers say where you are:
| Header | Meaning |
|---|---|
X-Total-Count | Total matching items |
X-Limit-Count | Items per page |
X-Skip-Count | Items skipped |
let skip = 0;
const limit = 20;
const players = [];
while (true) {
const res = await fetch(`${BASE_URL}/players?account=${ACCOUNT}&limit=${limit}&skip=${skip}`, {
headers: { "api-key": API_KEY },
});
players.push(...(await res.json()));
skip += limit;
if (skip >= Number(res.headers.get("X-Total-Count"))) break;
}Location-aware elements#
Missions, prizes, mystery boxes and raffles can be tied to a place, with an inner actionable zone and an outer viewable zone. See Concepts.
Pass the player's coordinates when you list, complete events and claim:
// Missions the player can act on (the default)
await fetch(`${BASE_URL}/missions?account=${ACCOUNT}&player=${user.id}&lat=${lat}&lon=${lon}`, { headers });
// Missions the player can see, for a map
await fetch(`${BASE_URL}/missions?account=${ACCOUNT}&player=${user.id}&lat=${lat}&lon=${lon}&locationFilter=viewable`, { headers });
// Completing an event near a location-aware mission
await gl.completeEvent("check-in", user.id, 1, { lat, lon });- With coordinates, only missions whose actionable zone the player is in progress.
- Without coordinates, location-aware elements are left out of lists and event progress. Everything else works as normal.
- A claim from outside the actionable zone, or without coordinates, answers with code
7.
Prize store#
List and claim#
Pass player to list only prizes the player is eligible for:
const prizes = await gl.listPrizes({ player: user.id });
for (const prize of prizes) {
renderPrizeCard({
name: prize.name,
cost: prize.credits,
inStock: prize.stock.available > 0,
canAfford: playerCredits >= prize.credits,
});
}A claim always answers with a code. Handle each one:
const claim = await gl.claimPrize("cup-coffee", user.id);
switch (claim.code) {
case 1: showSuccess(`You claimed ${claim.prize.name}`); updateCredits(claim.player.credits); break;
case 2: showError("Not enough credits"); break;
case 3: showError("Out of stock"); break;
case 5: showError("You've claimed this the maximum number of times"); break;
case 7: showError("You're too far away to claim this"); break;
}All codes are in Claim result codes.
Voucher codes#
A prize can have voucher codes, for QR codes, email campaigns or partner rewards. Claiming with a valid code waives the credit cost; stock, claim limits and location checks still apply.
const claim = await gl.claimPrize("cup-coffee", user.id, { voucherCode: "PROMO-001" });
// 1 = redeemed, no credits deducted; 8 = invalid or used code; 10 = this prize needs a code- Single-use codes work once. Multi-use codes can be shared by many players. For example, a code
PIZZAfor the first 100 players, one each: a multi-use code on a prize with stock 100 and a claim limit of 1. - If any other check fails, the code isn't used up and the player can try again.
- When a prize has
useVoucherson, every claim needs a code; without one the answer is code10. Filter with?useVouchers=trueorfalse. - Codes for expired prizes are removed after 30 days.
- Voucher codes are managed in the dashboard. The Account API key can't list or manage them, so a key in an app doesn't expose them.
Mystery boxes and raffles#
const box = await gl.claimMysteryBox("daily-box", user.id);
if (box.code === 1) showReveal(`You won ${box.prize.name}`);
const ticket = await gl.buyRaffleTicket("weekly-draw", user.id);
if (ticket.code === 1) showSuccess(`Ticket bought. Draw on ${new Date(ticket.raffle.drawTime).toLocaleDateString()}`);Leaderboards#
const { leaderboard, scores } = await gl.getLeaderboard("hall-of-fame", { limit: "10" });
for (const entry of scores.data) console.log(`#${entry.rank} ${entry.name}: ${entry.scores}`);- Team leaderboards rank teams:
scores.dataholds{ team, name, scores, rank }. - Players in one team: pass
team: "team-alpha". - Fair team comparison: pass
rankBy: "average"to rank teams by average score per member instead of total. - Languages: unlike other elements, a leaderboard with no translation in the requested
languageanswers404with error code100, not the default text. Request it withoutlanguage, or fall back to that yourself. - Players join teams through their
teamfield: see Update players.
Quizzes and surveys#
Quizzes#
A quiz goes start, answer, complete:
const started = await gl.startQuiz("product-quiz", user.id);
const answers = started.questions.map((q) => ({ questionId: q.id, answerIds: [chosen[q.id]] }));
const result = await gl.completeQuiz("product-quiz", user.id, answers);
if (result.actions.passed) showSuccess(`Passed: ${result.actions.lastScore}/${started.quiz.maxScore}`);
else showError(`Score ${result.actions.lastScore}. Needed ${started.quiz.requiredPassRate}%`);- Points per question: with
isQuestionScoringEnabled, each fully correct answer awards itspoints, pass or fail. The response givesquestionPointsAwardedand the totalpointsAwarded. - Timed quizzes: if
quiz.timing.maxSecondsToCompleteis set, show a countdown. A late submission answers with error code53.
Surveys#
Surveys have no right answers and always reward:
const survey = await gl.getSurvey("feedback-survey");
const answers = survey.questions.map((q) => ({ questionId: q.id, answerIds: [chosen[q.id]] }));
const result = await gl.completeSurvey("feedback-survey", user.id, answers);
const summary = await gl.getSurveyResult("feedback-survey"); // results per choice, in percentTesting#
Use a separate trial account, so test players never mix with live data. Request one through the trial form. See Environments and testing.
To start a player again, delete and recreate them:
await gl.deletePlayer("test-user", true); // true = remove all their data
await gl.createPlayer("test-user", "Test User");A good end-to-end test:
- Create a test player.
- Complete the events that should complete a mission.
- Check the mission is in
GET /players/{player}/missions. - Check achievement steps went up.
- Check the points and credits balances.
- Claim a prize.
- Delete the test player.
Errors and retries: see Error codes.