QuestEngine SDK for Godot 4

A GDScript client for the QuestEngine game backend: player sign-in, wallets and items, the store with App Store and Google Play receipt checks, levels, missions, live events, leaderboards, friends, the inbox and remote config.

It is a Godot editor plugin that adds one autoload, QuestEngine. Every API call is a coroutine that you await. It returns a QuestEngineResult and never raises an error.

Requires Godot 4.2 or later. Tested with Godot 4.7.2. Pure GDScript, no native libraries.

Install

  1. Download questengine-godot.zip and copy its addons/questengine folder into your project, so that the project contains res://addons/questengine/plugin.cfg.

    If you have the QuestEngine repository, you can copy sdk/godot/addons/questengine from it instead.

  2. Open Project → Project Settings → Plugins and enable QuestEngine. This adds the QuestEngine autoload (see Project Settings → Globals → Autoload). Disabling the plugin removes it.

You need your game's client key (qe_pk_…). It is on the console's API & SDKs page. The client key is public and is meant to ship in your game. Never put the secret server key (qe_sk_…) in a game build. The /server/* endpoints that use it are not part of this SDK.

Quickstart

func _ready() -> void:
    QuestEngine.configure("https://questengine.eu/api/v1", "qe_pk_…")
    var login := await QuestEngine.login_device()
    if login.ok:
        var wallet := await QuestEngine.get_wallet()
        var attempt := await QuestEngine.start_level(1)
        await QuestEngine.finish_level(attempt.data.attempt.id, "won", 1200, 3)

example/example.tscn, next to addons/ in the SDK folder, is a small scene that signs in, shows the wallet, plays level 1 and claims a free offer. To try it, copy the example folder to res://example/, set your client key on the scene's root node, and run the scene.

Results

Every method except a few local helpers returns a QuestEngineResult:

Field Meaning
ok: bool True for a 2xx response, or 304 for a cached get_config().
status: int HTTP status. 0 when no response arrived.
data: Variant The response's data value, usually a Dictionary or an Array. Null on errors.
error_code: String Stable error code, e.g. insufficient_funds. Empty when ok.
error_message: String Readable message for logs.
details: Dictionary Extra error data, e.g. {"currency": "coins", "balance": 40, "required": 100}.
headers: Dictionary Response headers, with lowercase names.
method, path The request, e.g. "POST" and "/store/hammer_pack/purchase".
idempotency_key: String The Idempotency-Key that was sent (always set by purchase_offer()).

is_error(code := "") returns true when the call failed, or only for that code if you pass one. is_network_error() returns true when no response arrived.

Response dictionaries support dot access: result.data.attempt.id is the same as result.data["attempt"]["id"]. Godot's JSON parser reads every number as a float. The SDK turns whole numbers back into int, so a balance is 500 and not 500.0. Set QuestEngine.parse_integers = false to keep Godot's behaviour.

Signing in and tokens

Method Use
login_device(device_id := "", profile := {}) Guest sign-in with a stable device ID. The first call creates the player.
login_custom(custom_id, create := true, profile := {}) Your own user ID (Steam, Game Center, your accounts). create = false only signs in existing players.
register_email(email, password, profile := {}) Creates an email account. The password needs at least 8 characters.
login_email(email, password) Email sign-in. A wrong pair returns invalid_credentials.
link(provider, identifier, password := "") Adds a sign-in method ("device", "custom" or "email") to the current player, so the account can be recovered on a new device.
unlink(provider) Removes one. The last method cannot be removed (last_identity).

profile can set display_name, platform, country (two letters) and locale. These are used when the call creates a player. If you leave out platform and locale, the SDK fills them in from the OS.

Device ID. get_device_id() is created once and saved. Where the platform provides OS.get_unique_id(), the ID is a SHA-256 hash of it. The raw ID is never sent, and a reinstall usually signs back into the same player. On the web, and on platforms without a unique ID, it is a random UUID.

Tokens. A successful sign-in returns a token with an expiry (data.token, data.expires_at). The SDK:

QuestEngine.configure(API_URL, CLIENT_KEY)
if not QuestEngine.is_signed_in():
    await QuestEngine.login_device()

Tokens last for the game's session length, which you set in the console. get_token_expires_at() gives the expiry as a Unix time. refresh_session() issues a new token and revokes the old one. Every sign-in and every refresh adds 1 to the player's logins stat, which login missions use.

sign_out() revokes the token on the server and forgets it locally. The local session is cleared even if the request fails, for example while offline. A player call made while signed out fails locally with unauthenticated and status 0, without a request.

Signals

Signal When
signed_in(player: Dictionary, created: bool) After any successful sign-in.
signed_out When sign_out() ends the session.
session_expired The API rejected the token (401 unauthenticated). The SDK has already cleared it: sign in again.
request_failed(code: String, message: String) After every failed call, including expected failures such as insufficient_funds.
request_finished(result: QuestEngineResult) After every call.
wallet_updated(wallet: Array) When a response contains the whole wallet: get_me, get_wallet, purchase_offer, verify_purchase, start_level, finish_level.
func _ready() -> void:
    QuestEngine.session_expired.connect(_on_session_expired)

func _on_session_expired() -> void:
    await QuestEngine.login_device()

Errors

Check ok, then branch on error_code. Codes are stable, but messages can change.

var result := await QuestEngine.purchase_offer("hammer_pack")
if result.ok:
    show_rewards(result.data.purchase.rewards)
elif result.is_error("insufficient_funds"):
    show_message("You need %d %s." % [result.details.required - result.details.balance, result.details.currency])
elif result.is_network_error():
    show_message("No connection. Try again.")
else:
    push_warning("Purchase failed: %s (%s)" % [result.error_message, result.error_code])

Codes from the SDK itself:

Code Status Meaning
network_error 0 No response. details.reason is cant_resolve, cant_connect, tls_handshake_error, connection_error, no_response or timeout (see QuestEngine.timeout, 30 s by default).
invalid_response 2xx The response was not valid JSON.
http_error any An error response without the API's error format, e.g. from a proxy or a wrong base URL. A redirect also gives http_error, with the target in details.location.
unauthenticated 0 A player call was made before signing in. No request was sent.
not_configured 0 configure() has not been called.
invalid_argument 0 request() got an unknown HTTP method.
not_in_tree 0 No running SceneTree to poll requests from.

Common API codes:

HTTP Codes
401 invalid_game_key, unauthenticated, invalid_credentials
403 game_disabled, player_banned, auth_method_disabled, stat_not_writable, test_purchases_disabled
404 not_found, player_not_found, unknown_product
409 insufficient_funds, not_enough_energy, not_enough_items, item_locked, level_locked, attempt_finished, offer_unavailable, offer_locked, purchase_limit_reached, real_money_offer, purchase_not_completed, purchase_revoked, mission_incomplete, mission_unavailable, event_unavailable, already_claimed, nothing_to_claim, version_conflict, too_many_keys, email_taken, identity_in_use, last_identity
413 value_too_large (cloud-save values over 64 KB, score metadata over 2 KB)
422 validation_failed (details lists each invalid field), invalid_receipt, score_out_of_range, unknown_stat
429 rate_limited (see the retry-after header)
502 / 503 store_unavailable, iap_not_configured, facebook_not_configured

The SDK does not retry failed calls. Retrying a read is always safe. For purchases, use the idempotency key described below.

Purchases

In-game currency

var result := await QuestEngine.purchase_offer("hammer_pack")
if result.is_network_error():
    # The purchase may or may not have happened. Retrying with the same key cannot buy twice.
    result = await QuestEngine.purchase_offer("hammer_pack", result.idempotency_key)

purchase_offer(code, idempotency_key := "") sends an Idempotency-Key header and generates one when you pass none. When the server receives a key a second time, it returns the original purchase (status 200 instead of 201). data is {purchase, wallet}.

Real money (Google Play and App Store)

Real-money offers in get_store() have price.type == "real", with price.google_product_id, price.apple_product_id and price.display_price. Sell them with a billing plugin, such as the Google Play Billing plugin for Godot on Android or a StoreKit plugin on iOS. Then let QuestEngine verify the purchase and grant its contents:

# Android: call this when your Google Play Billing plugin reports a completed purchase.
func _on_google_purchase(product_id: String, purchase_token: String) -> void:
    var result := await QuestEngine.verify_google_purchase(product_id, purchase_token)
    if result.ok:
        show_rewards(result.data.purchase.rewards)
        # QuestEngine acknowledges the purchase with Google. For consumable products, still consume
        # the purchase in the billing plugin so that the player can buy it again.

# iOS: call this when your StoreKit plugin reports a completed transaction.
func _on_apple_transaction(signed_transaction: String, transaction_id: String) -> void:
    # Pass the StoreKit 2 signed transaction (jwsRepresentation) when you have it, otherwise the transaction ID.
    var result := await QuestEngine.verify_apple_purchase(signed_transaction, transaction_id)
    if result.ok:
        show_rewards(result.data.purchase.rewards)
        # Finish the transaction in the StoreKit plugin now.

get_purchases() lists the player's purchases.

Remote config

var config := await QuestEngine.get_config()
var every := int(QuestEngine.get_config_value("ads.interstitial_every", 3))

get_config() returns every active config value as one Dictionary and keeps it in QuestEngine.remote_config. The SDK remembers the response's ETag and sends it back as If-None-Match. When nothing changed, the API answers 304 Not Modified, and the result has ok == true, status == 304 and the cached config in data. get_config(false) downloads the config again. get_config_value(key, default) reads from the last config fetched. The cache lasts while the game runs.

Other features

# Cloud save with conflict detection: send the version you last read.
var saved := await QuestEngine.set_player_data("progress", {"world": 2}, last_version)
if saved.is_error("version_conflict"):
    var theirs: Variant = saved.details.value   # the newer save from another device
    last_version = saved.details.version        # merge, then save again with this version
elif saved.ok:
    last_version = saved.data.version

# Leaderboards
await QuestEngine.submit_score("weekly_score", 1200, {"level": 3})
var top := await QuestEngine.get_leaderboard("weekly_score", 10)
var around_me := await QuestEngine.get_leaderboard_me("weekly_score")

# Server time for timers, instead of the device clock
var now := await QuestEngine.get_time()
print(now.data.periods.daily.resets_at)

Reference

Every method that returns a QuestEngineResult is a coroutine: call it with await.

Setup and session

Method Returns
configure(base_url: String, client_key: String) void
is_signed_in() -> bool, get_token() -> String, get_token_expires_at() -> int, get_player_id() -> String session state
get_device_id() -> String the ID used by login_device()
generate_uuid() -> String a random UUID v4
refresh_session() POST /auth/refresh
sign_out(revoke := true) POST /auth/logout

Authentication: login_device(device_id := "", profile := {}), login_custom(custom_id, create := true, profile := {}), register_email(email, password, profile := {}), login_email(email, password), link(provider, identifier, password := ""), unlink(provider).

Player

Method Endpoint
get_me() GET /me: {player, wallet, boosters, unread_messages}
update_me(changes: Dictionary) PATCH /me (display_name, avatar_url, country, locale, platform)
get_player_data(keys := PackedStringArray()) GET /me/data: {key: {value, version, public, updated_at}}
set_player_data(key, value, version := -1, is_public = null) PUT /me/data/{key}. A version of -1 skips the conflict check. is_public null keeps the current visibility.
delete_player_data(key) DELETE /me/data/{key}
get_stats() GET /me/stats
submit_stats(stats: Dictionary) POST /me/stats ({"best_combo": 7}; client-writable stats only)
get_player(player_id_or_friend_code) GET /players/{player}

Economy

Method Endpoint
get_currencies() GET /currencies
get_wallet() GET /me/wallet
get_transactions(limit := 50) GET /me/transactions
get_items(kind := "", category := "") GET /items
get_inventory() GET /me/inventory: {items, boosters}
use_item(code, quantity := 1) POST /me/inventory/{code}/use
get_balance(currency) -> int No request. Reads the last known wallet.

Store

Method Endpoint
get_store() GET /store
purchase_offer(code, idempotency_key := "") POST /store/{code}/purchase
verify_purchase(platform, params := {}) POST /purchases/verify
verify_google_purchase(product_id, purchase_token) POST /purchases/verify with platform: "google"
verify_apple_purchase(signed_transaction, transaction_id := "") POST /purchases/verify with platform: "apple"
get_purchases() GET /me/purchases

Missions and live events

Method Endpoint
get_missions() GET /missions
claim_mission(code) POST /missions/{code}/claim
get_events() GET /events
get_event(code) GET /events/{code}
join_event(code) POST /events/{code}/join
claim_event(code, tier := -1) POST /events/{code}/claim (-1 claims every reached tier)
get_event_standings(code, limit := 50) GET /events/{code}/standings

Leaderboards

Method Endpoint
get_leaderboards() GET /leaderboards
get_leaderboard(code, limit := 50, offset := 0, previous := false) GET /leaderboards/{code} (previous: the last closed period)
get_leaderboard_me(code, around := 5, previous := false) GET /leaderboards/{code}/me
get_leaderboard_friends(code, previous := false) GET /leaderboards/{code}/friends
submit_score(code, score: int, metadata := {}) POST /leaderboards/{code}/scores

Levels

Method Endpoint
get_levels(include_data := false) GET /levels: {progress_level, levels}
get_level(number: int) GET /levels/{number}, with the level data
start_level(number: int) POST /levels/{number}/start: {attempt, wallet}
finish_level(attempt_id: int, result: String, score = null, stars = null, duration_seconds := -1, meta := {}) POST /level-attempts/{id}/finish. result is "won" or "lost". A null score or stars is left out. A duration_seconds of -1 lets the server measure it.

Friends

Method Endpoint
get_friends() GET /friends: {friends, incoming, outgoing}
send_friend_request(friend_code_or_player_id) POST /friends
accept_friend_request(request_id: int) POST /friends/requests/{id}/accept
decline_friend_request(request_id: int) POST /friends/requests/{id}/decline
remove_friend(player_id) DELETE /friends/{player}
import_facebook_friends(access_token) POST /friends/facebook

Inbox

Method Endpoint
get_inbox() GET /inbox
mark_message_read(message_id: int) POST /inbox/{id}/read
claim_message(message_id: int) POST /inbox/{id}/claim
delete_message(message_id: int) DELETE /inbox/{id}

Game

Method Endpoint
health() GET /health (needs no client key)
get_time() GET /time
get_config(use_cache := true) GET /config, with ETag caching
get_config_value(key, default = null) -> Variant No request. Reads remote_config.
request(method, path, body = null, headers := {}) Any endpoint, e.g. request("GET", "/me/wallet"). It sends the client key, and the token when signed in. headers replace the defaults.

Properties: base_url, client_key (set them with configure()), timeout (seconds, default 30, 0 waits forever), save_path (default user://questengine.cfg), persist_session (default true), parse_integers (default true), log_requests (prints each call, never tokens or bodies), and the last known player, wallet and remote_config.

The autoload script is also the class QuestEngineClient, so QuestEngineClient.new() creates a separate client, for example for a second game or a test. Give each client its own save_path.

Notes