QuestEngine SDK for Unity
The official Unity client for QuestEngine, a backend for game features: player accounts, wallets and items, a store with App Store and Google Play receipt checks, levels, missions, live events, leaderboards, friends, an inbox, cloud saves and remote config.
- Unity 2021.3 or later, every platform including WebGL.
- Asynchronous,
Task-based API with typed results. - Depends on
com.unity.nuget.newtonsoft-json3.2.1, which the Package Manager installs for you.
Install
From the tarball (recommended)
- Download questengine-unity.tgz.
- In Unity, open Window → Package Manager, click + and choose Add package from tarball….
- Pick the downloaded file.
Unity saves the tarball's path in Packages/manifest.json. Keep the file inside your project
folder (for example next to manifest.json) so the path is relative and works for your team and
your build machines. To update, download the new tarball and add it the same way.
From Git (needs access to the repository)
If you have access to the QuestEngine repository and Git is installed, choose Add package from git URL… and enter:
https://github.com/alvarlaigna/questengine-backend.git?path=sdk/unity
Add #<branch or tag> at the end of the URL to pin a version.
Sample
In the Package Manager, select QuestEngine, open Samples and import Quickstart. Add the
QuestEngineQuickstart component to a GameObject, paste your client key and press Play.
Quickstart
using QuestEngine;
var qe = new QuestEngineClient("https://questengine.eu/api/v1", "qe_pk_…");
await qe.Auth.LoginWithDeviceAsync(); // token is kept in PlayerPrefs
var wallet = await qe.Economy.GetWalletAsync();
var attempt = await qe.Levels.StartAsync(1);
var result = await qe.Levels.FinishAsync(attempt.Id, LevelResult.Won, score: 1200, stars: 3);
await qe.Leaderboards.SubmitScoreAsync("high_scores", 1200);
The client key (qe_pk_…) is on the console's API & SDKs page. It is public and ships in
your build. In a MonoBehaviour, the same code goes into an async method:
using QuestEngine;
using UnityEngine;
public class Backend : MonoBehaviour
{
public static QuestEngineClient Qe { get; private set; }
private async void Start()
{
Qe = new QuestEngineClient(QuestEngineClient.DefaultBaseUrl, "qe_pk_…");
try
{
var session = await Qe.Auth.LoginWithDeviceAsync();
var wallet = await Qe.Economy.GetWalletAsync();
Debug.Log($"Player {session.Player.Id} has {wallet.GetBalance("coins")} coins");
}
catch (QuestEngineException e)
{
Debug.LogWarning($"QuestEngine: {e.Code}: {e.Message}");
}
}
}
Create one client and keep it for the lifetime of the game. Call it from the main thread
(MonoBehaviour methods and the async methods they start); the SDK's continuations then stay on the
main thread, which UnityWebRequest and PlayerPrefs require. Never block on a task with .Result or
.Wait(): that deadlocks the main thread, and WebGL has no other thread.
Results such as Wallet or LevelAttempt live in the QuestEngine.Models namespace, so names like
Player or Item don't clash with your own classes. Add using QuestEngine.Models; when you name
these types; with var you don't need it.
Sign-in and sessions
| Method | Use it for |
|---|---|
Auth.LoginWithDeviceAsync() |
Guest accounts without any sign-up. The first call creates the player (session.Created). |
Auth.LoginWithCustomIdAsync(id, create: true) |
Your own stable user ID: Steam, Game Center, your account system. |
Auth.RegisterWithEmailAsync(email, password) / Auth.LoginWithEmailAsync(email, password) |
Email and password accounts. |
The device ID is SystemInfo.deviceUniqueIdentifier where the platform has one, otherwise a random
GUID. It is created on first use and kept in PlayerPrefs, so the same device signs in to the same
player. Profile fields for a new player go in a SignInProfile; the platform (ios, android,
webgl, editor…) is filled in for you:
await qe.Auth.LoginWithDeviceAsync(profile: new SignInProfile { DisplayName = "Mia", Country = "EE" });
Let guests secure their progress by linking another sign-in method, so they can recover the
account on a new device: Auth.LinkEmailAsync(email, password), Auth.LinkCustomIdAsync(id) or
Auth.LinkDeviceAsync(). Auth.UnlinkAsync(provider) removes one (a player keeps at least one).
Tokens. Every sign-in returns a token and its expiry (the game's session length in the console).
The client stores the session in its token store (PlayerPrefs in Unity) and sends it with every
player request. It renews the token automatically once half of its lifetime has passed
(AutoRefreshSession, on by default); Auth.RefreshAsync() renews it by hand.
if (!qe.IsSignedIn) // a stored, unexpired session exists
{
await qe.Auth.LoginWithDeviceAsync();
}
Debug.Log(qe.PlayerId);
Calling LoginWithDeviceAsync() on every launch is fine too: it returns the same player.
Events. SignedIn is raised after each sign-in. SessionExpired is raised when the server
rejects the stored token (expired, revoked or signed out elsewhere). The session is cleared before
the event and the failed call still throws unauthenticated, so sign in again:
qe.SessionExpired += OnSessionExpired;
private async void OnSessionExpired()
{
try
{
await qe.Auth.LoginWithDeviceAsync();
}
catch (QuestEngineException e)
{
Debug.LogWarning($"Could not sign in again: {e.Code}");
}
}
Signing out. qe.SignOut() forgets the session on this device; Auth.LogoutAsync() also revokes
the token on the server. Both keep the device ID, so a device sign-in returns the same player.
Auth.ResetDeviceId() switches to a new random device ID (a new guest player), which is handy for
testing.
Where the session is stored. PlayerPrefsTokenStore uses PlayerPrefs keys starting with
QuestEngine.; PlayerPrefs is not encrypted. To keep the session in the Keychain, the Android
Keystore or your own save system, implement ITokenStore (three methods: Load, Save, Delete)
and pass it to the constructor:
var qe = new QuestEngineClient(QuestEngineClient.DefaultBaseUrl, "qe_pk_…", store: new MySecureStore());
Error handling
Every failed call throws QuestEngineException:
| Property | Meaning |
|---|---|
Code |
Stable error code such as insufficient_funds. Branch on this; constants are in ErrorCodes. |
Message |
A description for developers and logs. |
Status |
HTTP status, or 0 when no response arrived. |
Details |
Extra data from the server as a JObject (empty when there is none). |
RetryAfter |
For rate_limited: how long to wait, when the server said so. |
IsNetworkError |
True for network_error: offline, DNS or TLS failure, or timeout. |
try
{
await qe.Store.PurchaseAsync("hammer_pack");
}
catch (QuestEngineException e) when (e.Code == ErrorCodes.InsufficientFunds)
{
long missing = (long)e.Details["required"] - (long)e.Details["balance"];
ShowCoinShop(missing);
}
catch (QuestEngineException e) when (e.IsNetworkError)
{
ShowOfflineBanner();
}
Common codes: unauthenticated and invalid_token (sign in again), player_banned, not_found,
validation_failed (Details lists the messages per field), insufficient_funds,
not_enough_energy, not_enough_items, level_locked, purchase_limit_reached,
already_claimed, nothing_to_claim, version_conflict, rate_limited, network_error. The
server may add codes over time, so keep a default branch.
Other exceptions: a cancelled CancellationToken throws OperationCanceledException, and invalid
arguments (an empty code, a negative quantity) throw ArgumentException. Reading Details uses
Newtonsoft.Json types; if your scripts are in an assembly definition with Override References,
add Newtonsoft.Json.dll to it.
Purchases
With game currency
var result = await qe.Store.PurchaseAsync("hammer_pack");
Debug.Log($"Got {string.Join(", ", result.Purchase.Rewards)}; coins left: {result.Wallet.GetBalance("coins")}");
Each purchase request carries an Idempotency-Key, so a repeated request returns the original
purchase instead of buying twice, and the SDK retries once by itself after a network error. To
retry later yourself (for example after the app restarts), create a key once and pass the same key
on every attempt: PurchaseAsync("hammer_pack", idempotencyKey: savedKey).
result.Created is false when the server returned an earlier purchase.
With real money (Unity IAP)
Real-money offers in Store.GetOffersAsync() list their store product IDs in
offer.Price.AppleProductId and offer.Price.GoogleProductId; use these IDs for your Unity IAP
products. Buy through Unity IAP, then pass the receipt to VerifyPurchaseAsync. QuestEngine checks it
with the store, grants the offer's contents once per transaction and acknowledges Google purchases.
Confirm the purchase in Unity IAP only after QuestEngine accepted it:
using QuestEngine;
using UnityEngine;
using UnityEngine.Purchasing;
// In your Unity IAP store listener (Unity IAP 4 API)
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
VerifyPurchase(args.purchasedProduct);
return PurchaseProcessingResult.Pending; // confirmed once QuestEngine granted the contents
}
private async void VerifyPurchase(Product product)
{
try
{
var receipt = StoreReceipt.FromUnityIap(product.receipt, product.definition.id);
var result = await Backend.Qe.Store.VerifyPurchaseAsync(receipt);
storeController.ConfirmPendingPurchase(product);
ShowRewards(result.Purchase.Rewards); // result.Wallet has the new balances
}
catch (QuestEngineException e) when (e.Code == ErrorCodes.InvalidReceipt
|| e.Code == ErrorCodes.PurchaseRevoked
|| e.Code == ErrorCodes.TransactionAlreadyUsed)
{
// Rejected for good: finish the transaction without granting anything.
Debug.LogWarning($"Purchase rejected: {e.Code}: {e.Message}");
storeController.ConfirmPendingPurchase(product);
}
catch (QuestEngineException e)
{
// Offline, store outage or a console setting to fix (iap_not_configured, unknown_product…):
// leave it pending. Unity IAP delivers it again on the next launch.
Debug.LogWarning($"Purchase not verified yet: {e.Code}: {e.Message}");
}
}
StoreReceipt.FromUnityIap reads Unity IAP's receipt JSON:
- Google Play: sends the product ID and purchase token.
- App Store: sends the transaction ID; QuestEngine looks it up with the App Store Server API, which needs the App Store Connect API key in the console.
- Fake store (Unity IAP in the editor): sends a test purchase, accepted while the game's IAP mode is sandbox. Pass the product ID as the second argument.
Verifying the same transaction again returns the original purchase (result.Created is false), so
it is safe to retry. Without Unity IAP, build the receipt yourself:
StoreReceipt.AppleSignedTransaction(jwsRepresentation) (StoreKit 2),
StoreReceipt.AppleTransactionId(id), StoreReceipt.GooglePlay(productId, purchaseToken) or
StoreReceipt.Test(productId). Store.GetPurchasesAsync() lists the player's purchases.
Remote config
var config = await qe.Game.GetConfigAsync();
int adEvery = config.GetInt("ads.interstitial_every", 3);
bool maintenance = config.GetBool("maintenance");
ShopSale sale = config.Get<ShopSale>("shop.sale"); // your own class, read with Newtonsoft.Json
Keys are flat names: the dot in shop.sale is part of the key. Every getter takes a default that
is returned when the key is missing or has another type, so ship sensible defaults.
The client keeps the last config with its ETag and sends If-None-Match on the next call. When
nothing changed the server answers 304 Not Modified and you get the cached values with
config.NotModified set. qe.Game.Config holds the last fetched config. The config does not need a
signed-in player, so you can read it (for example a maintenance flag) before signing in.
Server time
Use the server clock for timers and daily resets; players can change the device clock.
var time = await qe.Game.GetTimeAsync();
TimeSpan untilReset = time.Daily.ResetsAt.Value - time.Now; // daily periods reset at 00:00 UTC
DateTimeOffset now = qe.Game.ServerNow; // device clock corrected by the last GetTimeAsync
Cloud saves
var saved = await qe.Player.SetDataAsync("progress", new Progress { World = 2, Stars = 41 });
var entry = await qe.Player.GetDataEntryAsync("progress");
Progress progress = entry.GetValue<Progress>();
// Protect against overwriting a newer save from another device
try
{
await qe.Player.SetDataAsync("progress", progress, expectedVersion: entry.Version);
}
catch (QuestEngineException e) when (e.Code == ErrorCodes.VersionConflict)
{
var newer = e.Details["value"]; // the current save, at version e.Details["version"]
}
Values are any JSON up to 64 KB, serialised with Newtonsoft.Json: plain classes, dictionaries,
lists or JToken. A player has at most 100 keys.
Method reference
All methods are asynchronous and take an optional CancellationToken as their last parameter.
qe.Auth
| Method | API | Returns |
|---|---|---|
LoginWithDeviceAsync(deviceId = null, profile = null) |
POST /auth/device |
AuthSession |
LoginWithCustomIdAsync(customId, create = true, profile = null) |
POST /auth/custom |
AuthSession |
RegisterWithEmailAsync(email, password, profile = null) |
POST /auth/email/register |
AuthSession |
LoginWithEmailAsync(email, password) |
POST /auth/email/login |
AuthSession |
RefreshAsync() |
POST /auth/refresh |
AuthSession |
LogoutAsync() |
POST /auth/logout |
– |
LinkAsync(provider, identifier, password = null) |
POST /auth/link |
linked providers (List<string>) |
LinkDeviceAsync(deviceId = null), LinkCustomIdAsync(customId), LinkEmailAsync(email, password) |
POST /auth/link |
linked providers |
UnlinkAsync(provider) |
DELETE /auth/link/{provider} |
linked providers |
DeviceId, ResetDeviceId() |
– | the device ID |
qe.Player
| Method | API | Returns |
|---|---|---|
GetProfileAsync() |
GET /me |
PlayerProfile (player, wallet, boosters, unread messages) |
UpdateProfileAsync(new PlayerUpdate { … }) |
PATCH /me |
Player |
GetPublicProfileAsync(playerIdOrFriendCode) |
GET /players/{player} |
PublicProfile |
GetDataAsync(keys = null) |
GET /me/data |
Dictionary<string, PlayerDataEntry> |
GetDataEntryAsync(key) |
GET /me/data?keys= |
PlayerDataEntry, or null |
SetDataAsync(key, value, expectedVersion = null, isPublic = null) |
PUT /me/data/{key} |
PlayerDataEntry |
DeleteDataAsync(key) |
DELETE /me/data/{key} |
bool (the key existed) |
GetStatsAsync() |
GET /me/stats |
Dictionary<string, long> |
SubmitStatsAsync(stats), SubmitStatAsync(code, value) |
POST /me/stats |
the new values |
qe.Economy
| Method | API | Returns |
|---|---|---|
GetCurrenciesAsync() |
GET /currencies |
List<Currency> |
GetWalletAsync() |
GET /me/wallet |
Wallet (wallet["coins"].Balance, GetBalance, refill timers) |
GetTransactionsAsync(limit = 50) |
GET /me/transactions |
List<WalletTransaction> |
GetItemsAsync(kind = null, category = null) |
GET /items |
List<Item> |
GetInventoryAsync() |
GET /me/inventory |
Inventory (items and running boosters) |
UseItemAsync(itemCode, quantity = 1) |
POST /me/inventory/{code}/use |
ItemUseResult |
qe.Store
| Method | API | Returns |
|---|---|---|
GetOffersAsync() |
GET /store |
List<StoreOffer> |
PurchaseAsync(offerCode, idempotencyKey = null) |
POST /store/{code}/purchase |
PurchaseResult |
VerifyPurchaseAsync(receipt) |
POST /purchases/verify |
PurchaseResult |
GetPurchasesAsync() |
GET /me/purchases |
List<Purchase> |
qe.Levels
| Method | API | Returns |
|---|---|---|
ListAsync(includeData = false) |
GET /levels |
LevelList |
GetAsync(number) |
GET /levels/{number} |
Level with its definition (Data) |
StartAsync(number) |
POST /levels/{number}/start |
LevelAttempt (with Wallet after the energy cost) |
FinishAsync(attemptId, result, score = null, stars = null, durationSeconds = null, meta = null) |
POST /level-attempts/{id}/finish |
LevelFinishResult |
qe.Missions
| Method | API | Returns |
|---|---|---|
ListAsync() |
GET /missions |
List<Mission> |
ClaimAsync(code) |
POST /missions/{code}/claim |
MissionClaimResult |
qe.Events
| Method | API | Returns |
|---|---|---|
ListAsync() |
GET /events |
List<LiveEvent> |
GetAsync(code) |
GET /events/{code} |
LiveEvent |
JoinAsync(code) |
POST /events/{code}/join |
EventJoinResult |
ClaimAsync(code, tier = null) |
POST /events/{code}/claim |
EventClaimResult |
GetStandingsAsync(code, limit = 50) |
GET /events/{code}/standings |
EventStandings |
qe.Leaderboards
| Method | API | Returns |
|---|---|---|
ListAsync() |
GET /leaderboards |
List<Leaderboard> |
GetTopAsync(code, limit = 50, offset = 0, period = Current) |
GET /leaderboards/{code} |
LeaderboardTop |
GetAroundMeAsync(code, range = 5, period = Current) |
GET /leaderboards/{code}/me |
LeaderboardAroundMe |
GetFriendsAsync(code, period = Current) |
GET /leaderboards/{code}/friends |
LeaderboardRanking |
SubmitScoreAsync(code, score, metadata = null) |
POST /leaderboards/{code}/scores |
ScoreSubmission |
period is LeaderboardPeriod.Current or LeaderboardPeriod.Previous (the last closed period).
qe.Friends
| Method | API | Returns |
|---|---|---|
ListAsync() |
GET /friends |
FriendList (friends, incoming and outgoing requests) |
SendRequestByCodeAsync(friendCode), SendRequestByPlayerIdAsync(playerId) |
POST /friends |
FriendshipResult |
AcceptAsync(requestId), DeclineAsync(requestId) |
POST /friends/requests/{id}/accept, …/decline |
FriendshipResult |
RemoveAsync(playerId) |
DELETE /friends/{player} |
– |
ImportFacebookFriendsAsync(accessToken) |
POST /friends/facebook |
friends added (int) |
qe.Inbox
| Method | API | Returns |
|---|---|---|
ListAsync() |
GET /inbox |
List<InboxMessage> |
MarkReadAsync(messageId) |
POST /inbox/{id}/read |
InboxMessage |
ClaimAsync(messageId) |
POST /inbox/{id}/claim |
InboxClaimResult |
DeleteAsync(messageId) |
DELETE /inbox/{id} |
– |
qe.Game (no signed-in player needed)
| Method | API | Returns |
|---|---|---|
GetTimeAsync() |
GET /time |
ServerTime (also updates ServerNow) |
GetConfigAsync() |
GET /config |
RemoteConfig (cached with ETag) |
GetHealthAsync() |
GET /health |
HealthStatus |
The client
| Member | Description |
|---|---|
IsSignedIn, PlayerId, SessionExpiresAt |
The stored session. |
SignOut() |
Forgets the session on this device. |
SignedIn, SessionExpired |
Events (see Sign-in and sessions). |
Timeout |
Time limit per request, default 30 seconds. |
AutoRefreshSession |
Renew the token halfway through its lifetime, default true. |
Logger |
Receives one line per request, e.g. qe.Logger = Debug.Log;. Tokens and bodies are never logged. |
SendAsync(method, path, body = null) |
Calls any endpoint and returns its data as a JToken. |
Rewards everywhere use the Reward type: Type (currency, item or chest), Code,
Quantity, and for granted rewards Name and, for opened chests, Contents.
Platform notes
WebGL. The default transport, UnityWebRequestTransport, uses the browser's networking, and
PlayerPrefs is stored in IndexedDB. The QuestEngine API allows cross-origin requests from any site.
Code stripping. The SDK's models are created by Newtonsoft.Json through reflection and are marked
with [Preserve], so the default stripping level keeps them. Unity does not read link.xml files
inside packages; if you use a high stripping level and see empty fields, add this link.xml to
your Assets folder:
<linker>
<assembly fullname="QuestEngine.Runtime" preserve="all" />
</linker>
Your own classes that you save or read with Newtonsoft.Json (cloud saves, RemoteConfig.Get<T>)
need the same care, or use dictionaries and JObject.
Custom networking. Implement IQuestEngineTransport (one method that sends a request and returns
the status, headers and body) and pass it to the constructor.
Using the SDK outside Unity
The core does not depend on UnityEngine: the Unity parts are in Runtime/Unity behind
#if UNITY_5_3_OR_NEWER. To use it in tests, tools or a .NET server, add the .cs files under
Runtime to a project that references Newtonsoft.Json (netstandard2.0 or later). There the defaults
are HttpClientTransport and MemoryTokenStore:
var qe = new QuestEngineClient("https://questengine.eu/api/v1", "qe_pk_…", new HttpClientTransport(), new MemoryTokenStore());
For unit tests, pass a fake IQuestEngineTransport that returns canned responses.
Security
The client key is public. The server key (qe_sk_…) is secret and belongs only on your own
servers; the constructor refuses it. Server-only operations (granting currency, moderation, scores
for server-only leaderboards) use the /server endpoints with the server key and are not part of
this SDK.
License
MIT. See LICENSE.md.