Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

feat: free game acquisition in 1-click (F2P direct license claim)

Rafael Abud Ferreira51be7892d5ae
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 94d8a41..254daa4 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -35,6 +35,7 @@ add_library(xcloud_core STATIC
src/xcloud/titlehub.cpp
src/xcloud/regions.cpp
src/xcloud/prices.cpp
+ src/xcloud/purchase.cpp
src/input/controller_common.cpp
src/input/kbm_map.cpp
src/input/key_map.cpp
diff --git a/src/app/app_core.cpp b/src/app/app_core.cpp
index c28b398..8f9e308 100644
--- a/src/app/app_core.cpp
+++ b/src/app/app_core.cpp
@@ -620,6 +620,12 @@ bool Core::frame() {
g_command = kPlay;
break;
}
+ case ui::Action::ClaimFreeGame: {
+ std::lock_guard<std::mutex> lock(g_argMutex);
+ g_playTile = ev.game;
+ g_command = kClaimFree;
+ break;
+ }
case ui::Action::SignOut:
g_cancel = true;
g_command = kSignOut;
diff --git a/src/app/app_state.h b/src/app/app_state.h
index 9241a12..ce813eb 100644
--- a/src/app/app_state.h
+++ b/src/app/app_state.h
@@ -37,7 +37,7 @@ bool allow1440Locked();
void refreshSettingsUiLocked();
// --- Worker commands (worker.cpp) ----------------------------------------------
-enum Command { kNone, kSignIn, kPlay, kSignOut, kReloadLibrary, kConsoles, kUpdate };
+enum Command { kNone, kSignIn, kPlay, kSignOut, kReloadLibrary, kConsoles, kUpdate, kClaimFree };
extern std::atomic<int> g_command;
extern std::atomic<bool> g_cancel;
extern std::mutex g_argMutex;
diff --git a/src/app/library.cpp b/src/app/library.cpp
index dbf6b25..d766786 100644
--- a/src/app/library.cpp
+++ b/src/app/library.cpp
@@ -425,6 +425,13 @@ void Library::saveCache() const {
if (!platform::writeFileAtomic(cachePath_, root.dump())) XC_LOGW("library: could not write %s", cachePath_.c_str());
}
+void Library::markAsOwned(const std::string& productId, const std::string& titleId) {
+ if (!productId.empty()) ownedProducts_.insert(productId);
+ if (!titleId.empty()) ownedTitles_.insert(titleId);
+ ownershipKnown_ = true;
+ saveCache();
+}
+
bool Library::load(xcloud::GssvClient& gssv, const std::string& language, const Changed& changed, std::string& err) {
market_ = gssv.session().market.empty() ? "US" : gssv.session().market;
language_ = language;
diff --git a/src/app/library.h b/src/app/library.h
index eb32fe5..d935527 100644
--- a/src/app/library.h
+++ b/src/app/library.h
@@ -92,6 +92,8 @@ public:
// loaded yet). load() reads it without them, as it builds the rows fresh.
bool loadCache(bool withLayout = false);
void saveCache() const;
+ // Marks a product/title as owned immediately upon successful purchase/claim.
+ void markAsOwned(const std::string& productId, const std::string& titleId = {});
private:
using Item = std::pair<std::string, std::string>; // productId, titleId
diff --git a/src/app/worker.cpp b/src/app/worker.cpp
index e860cef..f02daeb 100644
--- a/src/app/worker.cpp
+++ b/src/app/worker.cpp
@@ -20,6 +20,7 @@
#include "xcloud/catalog.h"
#include "xcloud/gssv.h"
#include "xcloud/regions.h"
+#include "xcloud/purchase.h"
#include <chrono>
#include <condition_variable>
@@ -1036,6 +1037,63 @@ void worker() {
autoplayFinished(result);
break;
}
+ case kClaimFree: {
+ ui::GameTile tile;
+ {
+ std::lock_guard<std::mutex> lock(g_argMutex);
+ tile = g_playTile;
+ }
+ g_ui->showToast(ui::tr(ui::Str::Claiming));
+ platform::notify(ui::tr(ui::Str::Claiming));
+ XC_LOGI("claiming free game: %s (productId=%s, titleId=%s)",
+ tile.name.c_str(), tile.productId.c_str(), tile.titleId.c_str());
+
+ std::string err;
+ xcloud::PurchaseOffer offer;
+ std::string market = gssv.session().market.empty() ? "US" : gssv.session().market;
+ std::string lang = ui::catalogLanguage();
+ if (!xcloud::fetchPurchaseOffer(tile.productId, market, lang, offer, err)) {
+ XC_LOGW("claim: fetch offer failed: %s", err.c_str());
+ g_ui->showPlayError(ui::trf(ui::Str::ClaimFailed, err), tile);
+ break;
+ }
+ if (!offer.isFree) {
+ XC_LOGW("claim refused: product %s is not free (list=%.2f, msrp=%.2f)",
+ tile.productId.c_str(), offer.listPrice, offer.msrp);
+ g_ui->showPlayError(ui::tr(ui::Str::ProductNotFree), tile);
+ break;
+ }
+ std::string authHeader;
+ if (!am.marketplaceAuthorization(authHeader, err)) {
+ XC_LOGW("claim: marketplace auth failed: %s", err.c_str());
+ g_ui->showPlayError(ui::trf(ui::Str::ClaimFailed, err), tile);
+ break;
+ }
+ if (!xcloud::claimFreeProduct(authHeader, offer, market, err)) {
+ XC_LOGW("claim: order failed: %s", err.c_str());
+ g_ui->showPlayError(ui::trf(ui::Str::ClaimFailed, err), tile);
+ break;
+ }
+ XC_LOGI("claim: successfully acquired %s (%s)", tile.productId.c_str(), tile.name.c_str());
+ std::shared_ptr<app::Library> lib;
+ {
+ std::lock_guard<std::mutex> lock(s_libraryMutex);
+ lib = s_library;
+ }
+ if (lib) {
+ lib->markAsOwned(tile.productId, tile.titleId);
+ g_ui->markTileOwned(tile.productId, tile.titleId);
+ g_ui->showToast(ui::tr(ui::Str::ClaimSuccess));
+ platform::notify(ui::tr(ui::Str::ClaimSuccess));
+
+ // Re-sync owned titles in background
+ lib->loadOwned(gssv, [lib]() {
+ g_ui->setRows(lib->rows());
+ g_ui->setOwned(lib->owned(), lib->purchasable(), lib->ownedKnown());
+ });
+ }
+ break;
+ }
default: {
// Idle and signed in: the sign-in renewed before it expires
// (a clock check once a minute, the network only when due),
diff --git a/src/auth/auth_manager.cpp b/src/auth/auth_manager.cpp
index 9a24317..479dc7b 100644
--- a/src/auth/auth_manager.cpp
+++ b/src/auth/auth_manager.cpp
@@ -73,6 +73,7 @@ void AuthManager::signOut() {
tokens_ = {};
profile_ = {};
gssvXsts_ = {};
+ marketplaceXsts_ = {};
std::remove(storePath_.c_str());
}
@@ -320,6 +321,7 @@ void AuthManager::fetchSubscription(const XblToken& userToken, const std::string
XC_LOGW("subscription: store XSTS: %s", err.c_str());
return;
}
+ marketplaceXsts_ = mp;
net::Request req;
req.method = "POST";
req.url = "https://emerald.xboxservices.com/xboxcomfd/entitlements/bulk?locale=en-US";
@@ -448,4 +450,26 @@ bool AuthManager::consoleTransferToken(std::string& out, std::string& err) {
return true;
}
+bool AuthManager::marketplaceAuthorization(std::string& outAuthHeader, std::string& err) {
+ if (!marketplaceXsts_.token.empty() && !refreshDue(parseIsoUtc(marketplaceXsts_.notAfter), unixNow())) {
+ outAuthHeader = marketplaceXsts_.authorizationHeader();
+ return true;
+ }
+ if (tokens_.accessToken.empty()) {
+ err = "not signed in";
+ return false;
+ }
+ XblToken userToken;
+ if (!xblUserToken(tokens_.accessToken, "t=", userToken, err, &redirectUrl_)) {
+ std::string err2;
+ if (!xblUserToken(tokens_.accessToken, "d=", userToken, err2, &redirectUrl_)) return false;
+ err.clear();
+ }
+ if (!xstsToken(userToken, rp::kMarketplace, marketplaceXsts_, err, &redirectUrl_)) {
+ return false;
+ }
+ outAuthHeader = marketplaceXsts_.authorizationHeader();
+ return true;
+}
+
} // namespace xc::auth
diff --git a/src/auth/auth_manager.h b/src/auth/auth_manager.h
index 5b93ad9..0555b98 100644
--- a/src/auth/auth_manager.h
+++ b/src/auth/auth_manager.h
@@ -87,6 +87,8 @@ public:
void signOut();
const Profile& profile() const { return profile_; }
const std::string& redirectUrl() const { return redirectUrl_; }
+ // Returns Authorization header ("XBL3.0 x=...;token") for Microsoft Store calls (rp::kMarketplace).
+ bool marketplaceAuthorization(std::string& outAuthHeader, std::string& err);
private:
bool load();
@@ -104,6 +106,7 @@ private:
MsaTokens tokens_;
Profile profile_;
XblToken gssvXsts_; // in memory only, for loginOffering()
+ XblToken marketplaceXsts_; // in memory only, for Microsoft Store operations
std::string redirectUrl_;
bool signedIn_ = false;
};
diff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cpp
index b060c41..f229f98 100644
--- a/src/ui/app_ui.cpp
+++ b/src/ui/app_ui.cpp
@@ -985,6 +985,24 @@ void AppUi::showHome(const std::string& toast) {
dirty_ = true;
}
+void AppUi::showToast(const std::string& toast) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (!toast.empty()) {
+ toast_ = toast;
+ toastUntil_ = 0;
+ dirty_ = true;
+ }
+}
+
+void AppUi::markTileOwned(const std::string& productId, const std::string& titleId) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (detail_.productId == productId || (!titleId.empty() && detail_.titleId == titleId)) {
+ detail_.playable = true;
+ detail_.purchasable = false;
+ dirty_ = true;
+ }
+}
+
void AppUi::showLaunching(const GameTile& game, const std::string& status) {
std::lock_guard<std::mutex> lock(mutex_);
screen_ = Screen::Launching;
@@ -2624,11 +2642,15 @@ UiEvent AppUi::handle(const NavInput& in) {
dirty_ = true;
break;
}
- // A free game not on the account yet may already be (got on the
- // phone a moment ago): Play tries, and the server says.
+ // A free game not on the account yet triggers direct claim.
if (in.accept && (detail_.playable || detail_.freeInStore) && !detail_.titleId.empty()) {
- ev.action = Action::Play;
- ev.game = detail_;
+ if (detail_.playable) {
+ ev.action = Action::Play;
+ ev.game = detail_;
+ } else if (detail_.freeInStore) {
+ ev.action = Action::ClaimFreeGame;
+ ev.game = detail_;
+ }
}
if (in.square) toggleHidden(detail_, ev); // the page stays open
if (in.triangle) toggleFavorite(detail_, ev);
@@ -2643,8 +2665,13 @@ UiEvent AppUi::handle(const NavInput& in) {
case Screen::Error:
if (!errorGame_.titleId.empty()) {
if (in.accept) {
- ev.action = Action::Play;
- ev.game = errorGame_;
+ if (errorGame_.freeInStore && !errorGame_.playable) {
+ ev.action = Action::ClaimFreeGame;
+ ev.game = errorGame_;
+ } else {
+ ev.action = Action::Play;
+ ev.game = errorGame_;
+ }
} else if (in.back && errorGame_.homeConsole) {
screen_ = Screen::Home; // back to My consoles
tab_ = Tab::Consoles;
@@ -3651,7 +3678,7 @@ void AppUi::drawDetails(Canvas& c, uint64_t nowMs) {
if (!drawHero(c, nowMs, g->heroUrl, true)) {
// No hero art (yet): the cover, until the art arrives and fades in.
drawBackground(c);
- if (!g->purchasable) { // a game to buy has its QR code there instead
+ if (!g->purchasable || g->freeInStore) { // paid games show their QR code there instead
if (auto img = images_.get(g->tileUrl, kCover, kCover)) c.drawImage(*img, cover.x, cover.y, 255, 16);
else c.fillRect(cover, kPlaceholder, 16);
}
@@ -3694,23 +3721,22 @@ void AppUi::drawDetails(Canvas& c, uint64_t nowMs) {
int ty = y + 30;
auto price = prices_.find(g->productId);
if (g->freeInStore) {
- // Free to play: got once in the store (the QR code), then Play.
+ // Free to play: "Get Free" button to claim license directly.
fonts_.bold.draw(c, tr(Str::Free), kMargin, ty, 52, kWhite);
ty += 84;
fonts_.semibold.draw(c, tr(Str::FreeToPlay), kMargin, ty, 28, kWhite);
ty += 48;
- for (const auto& line : fonts_.regular.wrap(tr(Str::FreeHint), 24, 820, 3)) {
+ for (const auto& line : fonts_.regular.wrap(tr(Str::FreeAcquireHint), 24, 820, 3)) {
fonts_.regular.draw(c, line, kMargin, ty, 24, kGray);
ty += 34;
}
- Rect play{kMargin, ty + 30, 300, 76};
- c.strokeRect({play.x - 7, play.y - 7, play.w + 14, play.h + 14}, kWhite, 4, 45);
- c.fillRect(play, kGreen, 38);
- float tx = play.x + 70, my = play.y + play.h / 2.0f;
- c.line(tx - 8, my - 13, tx - 8, my + 13, 4, kWhite);
- c.line(tx - 8, my - 13, tx + 13, my, 4, kWhite);
- c.line(tx - 8, my + 13, tx + 13, my, 4, kWhite);
- fonts_.semibold.draw(c, tr(Str::Play), play.x + 108, play.y + 20, 32, kWhite);
+ const char* label = tr(Str::ClaimFree);
+ int tw = fonts_.semibold.measure(label, 30);
+ int btnW = std::max(320, tw + 64);
+ Rect claimBtn{kMargin, ty + 30, btnW, 76};
+ c.strokeRect({claimBtn.x - 7, claimBtn.y - 7, claimBtn.w + 14, claimBtn.h + 14}, kWhite, 4, 45);
+ c.fillRect(claimBtn, kGreen, 38);
+ fonts_.semibold.draw(c, label, claimBtn.x + (claimBtn.w - tw) / 2, claimBtn.y + 22, 30, kWhite);
} else if (price != prices_.end()) {
// The price, and the regular one crossed out while on sale.
int px = kMargin;
@@ -3732,15 +3758,15 @@ void AppUi::drawDetails(Canvas& c, uint64_t nowMs) {
fonts_.regular.draw(c, line, kMargin, ty, 24, kGray);
ty += 34;
}
- }
- Rect box = drawQr(c, "https://www.xbox.com/games/store/p/" + g->productId, kW - kMargin, 190, 440);
- if (box.w > 0) {
- const char* scan = tr(g->freeInStore ? Str::ScanToGet : Str::ScanToBuy);
- int w = fonts_.semibold.measure(scan, 26);
- fonts_.semibold.draw(c, scan, box.x + (box.w - w) / 2, box.y + box.h + 22, 26, kWhite);
+ Rect box = drawQr(c, "https://www.xbox.com/games/store/p/" + g->productId, kW - kMargin, 190, 440);
+ if (box.w > 0) {
+ const char* scan = tr(Str::ScanToBuy);
+ int w = fonts_.semibold.measure(scan, 26);
+ fonts_.semibold.draw(c, scan, box.x + (box.w - w) / 2, box.y + box.h + 22, 26, kWhite);
+ }
}
if (g->freeInStore)
- drawHints(c, {{kIconCross, tr(Str::Play)},
+ drawHints(c, {{kIconCross, tr(Str::ClaimFree)},
{kIconOptions, tr(Str::GameSettings)},
{kIconTriangle, tr(favorites_.count(g->productId) ? Str::RemoveFavorite : Str::AddFavorite)},
{kIconSquare, tr(hidden_.count(g->productId) ? Str::Unhide : Str::Hide)},
diff --git a/src/ui/app_ui.h b/src/ui/app_ui.h
index fd32aeb..323ff81 100644
--- a/src/ui/app_ui.h
+++ b/src/ui/app_ui.h
@@ -202,7 +202,8 @@ enum class Action {
Report, // "Report a problem" (Triangle on an error or in Settings): reportWhat is the error shown
LoginCountry, // the sign-in country changed (settings): save them and sign in again
OpenUrl, // a link on screen to open in the browser (UiCaps::openUrl): `url`
- Quit // desktop: the user closed the app from the home screen
+ Quit, // desktop: the user closed the app from the home screen
+ ClaimFreeGame // claim a free-to-play game license directly
};
// How "Your games" is sorted (R3).
@@ -303,6 +304,8 @@ public:
// The game with this xCloud title id on the home screen or in Your games.
bool findTile(const std::string& titleId, GameTile& out) const;
void showHome(const std::string& toast = {});
+ void showToast(const std::string& toast);
+ void markTileOwned(const std::string& productId, const std::string& titleId = {});
void showLaunching(const GameTile& game, const std::string& status);
void setLaunchStatus(const std::string& status);
void showStreaming();
diff --git a/src/ui/strings.cpp b/src/ui/strings.cpp
index 9be5056..70d72b5 100644
--- a/src/ui/strings.cpp
+++ b/src/ui/strings.cpp
@@ -334,6 +334,12 @@ constexpr Column kEnglish = {
"Video quality (QP)", // StatsIndicatorQp
"Microphone status", // StatsIndicatorMic
"Scan the QR code on your phone to resolve this with Microsoft, then press Cross to try again", // ScanQrToResolve
+ "Get Free", // ClaimFree
+ "Claiming free license...", // Claiming
+ "Game added to your account!", // ClaimSuccess
+ "Failed to claim free game: %s", // ClaimFailed
+ "This game is not free in the store", // ProductNotFree
+ "Free game. Press Cross to add to your account and start playing", // FreeAcquireHint
};
constexpr Column kPortugueseBR = {
@@ -638,6 +644,12 @@ constexpr Column kPortugueseBR = {
"Qualidade do vídeo (QP)", // StatsIndicatorQp
"Status do microfone", // StatsIndicatorMic
"Use seu celular para ler o código QR ao lado e resolver na Microsoft, depois pressione Cruz para tentar novamente", // ScanQrToResolve
+ "Adquirir Grátis", // ClaimFree
+ "Adquirindo licença gratuita...", // Claiming
+ "Jogo adicionado à sua conta com sucesso!", // ClaimSuccess
+ "Falha ao adquirir o jogo gratuito: %s", // ClaimFailed
+ "Este jogo não é gratuito na loja", // ProductNotFree
+ "Jogo gratuito. Pressione Cruz para adicionar à sua conta e começar a jogar", // FreeAcquireHint
};
constexpr Column kSpanish = {
@@ -942,6 +954,12 @@ constexpr Column kSpanish = {
"Calidad de vídeo (QP)", // StatsIndicatorQp
"Estado del micrófono", // StatsIndicatorMic
"Usa tu teléfono para escanear el código QR y resolver con Microsoft, luego presiona Cruz para reintentar", // ScanQrToResolve
+ "Obtener Gratis", // ClaimFree
+ "Obteniendo licencia gratuita...", // Claiming
+ "¡Juego añadido a tu cuenta con éxito!", // ClaimSuccess
+ "Error al adquirir el juego gratuito: %s", // ClaimFailed
+ "Este juego no es gratuito en la tienda", // ProductNotFree
+ "Juego gratuito. Presiona Cruz para añadirlo a tu cuenta y empezar a jugar", // FreeAcquireHint
};
constexpr Column kFrench = {
@@ -1246,6 +1264,12 @@ constexpr Column kFrench = {
"Qualité vidéo (QP)", // StatsIndicatorQp
"État du microphone", // StatsIndicatorMic
"Scannez le code QR avec votre téléphone pour résoudre ceci chez Microsoft, puis appuyez sur Croix pour réessayer", // ScanQrToResolve
+ "Obtenir gratuitement", // ClaimFree
+ "Obtention de la licence gratuite...", // Claiming
+ "Jeu ajouté à votre compte avec succès !", // ClaimSuccess
+ "Échec de l'obtention du jeu gratuit : %s", // ClaimFailed
+ "Ce jeu n'est pas gratuit sur le store", // ProductNotFree
+ "Jeu gratuit. Appuyez sur Croix pour l'ajouter à votre compte et jouer", // FreeAcquireHint
};
constexpr Column kGerman = {
@@ -1550,6 +1574,12 @@ constexpr Column kGerman = {
"Videoqualität (QP)", // StatsIndicatorQp
"Mikrofonstatus", // StatsIndicatorMic
"Scannen Sie den QR-Code mit dem Smartphone, um dies bei Microsoft zu beheben, und drücken Sie dann Kreuz zum Wiederholen", // ScanQrToResolve
+ "Kostenlos holen", // ClaimFree
+ "Kostenlose Lizenz wird angefordert...", // Claiming
+ "Spiel erfolgreich zu Ihrem Konto hinzugefügt!", // ClaimSuccess
+ "Kostenloses Spiel konnte nicht angefordert werden: %s", // ClaimFailed
+ "Dieses Spiel ist im Store nicht kostenlos", // ProductNotFree
+ "Kostenloses Spiel. Drücken Sie Kreuz, um es zu Ihrem Konto hinzuzufügen und zu spielen", // FreeAcquireHint
};
constexpr Column kItalian = {
@@ -1854,6 +1884,12 @@ constexpr Column kItalian = {
"Qualità video (QP)", // StatsIndicatorQp
"Stato microfono", // StatsIndicatorMic
"Inquadra il codice QR con lo smartphone per risolvere con Microsoft, poi premi Croce per riprovare", // ScanQrToResolve
+ "Ottieni gratis", // ClaimFree
+ "Acquisizione licenza gratuita in corso...", // Claiming
+ "Gioco aggiunto al tuo account con successo!", // ClaimSuccess
+ "Impossibile ottenere il gioco gratuito: %s", // ClaimFailed
+ "Questo gioco non è gratuito nello store", // ProductNotFree
+ "Gioco gratuito. Premi Croce per aggiungerlo al tuo account e iniziare a giocare", // FreeAcquireHint
};
constexpr std::array<const Column*, kLangs> kTable = {&kEnglish, &kPortugueseBR, &kSpanish,
diff --git a/src/ui/strings.h b/src/ui/strings.h
index 3f23076..e1959d9 100644
--- a/src/ui/strings.h
+++ b/src/ui/strings.h
@@ -311,6 +311,12 @@ enum class Str {
StatsIndicatorQp,
StatsIndicatorMic,
ScanQrToResolve, // Error screen with redirect URL: scan QR to fix account
+ ClaimFree, // details: "Get Free"
+ Claiming, // toast: "Claiming license..."
+ ClaimSuccess, // toast: "Game added to your account!"
+ ClaimFailed, // error: "Failed to claim free game: %s"
+ ProductNotFree, // error: "This game is not free in the store"
+ FreeAcquireHint, // details: "Free game. Press Cross to add to your account and start playing"
Count
};
diff --git a/src/xcloud/purchase.cpp b/src/xcloud/purchase.cpp
new file mode 100644
index 0000000..18f5e4e
--- /dev/null
+++ b/src/xcloud/purchase.cpp
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+#include "xcloud/purchase.h"
+
+#include "net/http.h"
+#include "util/json.h"
+#include "util/log.h"
+
+#include <cmath>
+
+namespace xc::xcloud {
+
+bool fetchPurchaseOffer(const std::string& productId, const std::string& market, const std::string& language,
+ PurchaseOffer& out, std::string& err) {
+ if (productId.empty()) {
+ err = "empty product id";
+ return false;
+ }
+ net::Request req;
+ req.url = "https://displaycatalog.mp.microsoft.com/v7.0/products?bigIds=" + productId +
+ "&market=" + (market.empty() ? "US" : market) +
+ "&languages=" + (language.empty() ? "en-us" : language);
+ auto r = net::perform(req);
+ auto j = json::parse(r.body);
+ if (!r.ok() || !j) {
+ err = "catalog offer lookup failed: " + (r.status ? "HTTP " + std::to_string(r.status) : r.error);
+ return false;
+ }
+ const auto& prods = (*j)["Products"];
+ if (!prods.isArray() || prods.size() == 0) {
+ err = "product not found in catalog: " + productId;
+ return false;
+ }
+ const auto& p = prods[0];
+ out.productId = productId;
+ out.isFree = false;
+ out.listPrice = 0.0;
+ out.msrp = 0.0;
+ out.skuId.clear();
+ out.availabilityId.clear();
+
+ for (const auto& dsa : p["DisplaySkuAvailabilities"].items()) {
+ std::string skuId = dsa["Sku"]["SkuId"].str();
+ for (const auto& av : dsa["Availabilities"].items()) {
+ bool purchase = false;
+ for (const auto& a : av["Actions"].items()) purchase |= (a.str() == "Purchase");
+ const auto& price = av["OrderManagementData"]["Price"];
+ if (!purchase || !price.isObject()) continue;
+
+ out.skuId = skuId.empty() ? av["SkuId"].str() : skuId;
+ out.availabilityId = av["AvailabilityId"].str();
+ out.listPrice = price["ListPrice"].asNumber();
+ out.msrp = price["MSRP"].asNumber();
+ out.currency = price["CurrencyCode"].str();
+ if (out.listPrice <= 0.005 && out.msrp <= 0.005) {
+ out.isFree = true;
+ }
+ if (!out.availabilityId.empty()) {
+ return true;
+ }
+ }
+ }
+ err = "no purchase availability found for " + productId;
+ return false;
+}
+
+bool claimFreeProduct(const std::string& marketplaceAuthHeader, const PurchaseOffer& offer,
+ const std::string& market, std::string& err) {
+ // Rigid safety check: NEVER allow purchases that cost money.
+ if (!offer.isFree || offer.listPrice > 0.005 || offer.msrp > 0.005) {
+ err = "safety block: product is not free (price > 0)";
+ XC_LOGE("claimFreeProduct blocked: product %s is not free (list=%.2f, msrp=%.2f)",
+ offer.productId.c_str(), offer.listPrice, offer.msrp);
+ return false;
+ }
+ if (offer.productId.empty() || offer.skuId.empty() || offer.availabilityId.empty()) {
+ err = "incomplete offer data (missing skuId or availabilityId)";
+ return false;
+ }
+ if (marketplaceAuthHeader.empty()) {
+ err = "missing marketplace authorization";
+ return false;
+ }
+
+ json::Value item = json::Value::object();
+ item.set("productId", offer.productId);
+ item.set("skuId", offer.skuId);
+ item.set("availabilityId", offer.availabilityId);
+ item.set("quantity", int64_t(1));
+ item.set("price", 0.0);
+ item.set("currencyCode", offer.currency.empty() ? "USD" : offer.currency);
+
+ json::Value items = json::Value::array();
+ items.push(item);
+
+ json::Value body = json::Value::object();
+ body.set("orderItems", items);
+
+ net::Request req;
+ req.method = "POST";
+ req.url = "https://purchase.mp.microsoft.com/v7.0/users/me/orders" +
+ (market.empty() ? "" : "?market=" + market);
+ req.headers = {
+ {"Authorization", marketplaceAuthHeader},
+ {"Content-Type", "application/json"},
+ {"MS-CV", "PSBoxPurchase.1"}
+ };
+ req.body = body.dump();
+
+ auto r = net::perform(req);
+ if (!r.ok()) {
+ auto j = json::parse(r.body);
+ std::string detail;
+ if (j) {
+ if ((*j)["message"].isString()) detail = (*j)["message"].str();
+ else if ((*j)["innererror"]["message"].isString()) detail = (*j)["innererror"]["message"].str();
+ }
+ err = detail.empty() ? ("HTTP " + std::to_string(r.status) + ": " + r.error) : detail;
+ XC_LOGW("claimFreeProduct failed for %s: %s (status %d)", offer.productId.c_str(), err.c_str(), r.status);
+ return false;
+ }
+ XC_LOGI("claimFreeProduct succeeded for %s (%s/%s)", offer.productId.c_str(), offer.skuId.c_str(), offer.availabilityId.c_str());
+ return true;
+}
+
+} // namespace xc::xcloud
diff --git a/src/xcloud/purchase.h b/src/xcloud/purchase.h
new file mode 100644
index 0000000..547f136
--- /dev/null
+++ b/src/xcloud/purchase.h
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// Microsoft Store Free Game Acquisition / Entitlement Service
+#pragma once
+
+#include <string>
+
+namespace xc::xcloud {
+
+struct PurchaseOffer {
+ std::string productId;
+ std::string skuId;
+ std::string availabilityId;
+ double listPrice = 0.0;
+ double msrp = 0.0;
+ std::string currency;
+ bool isFree = false;
+};
+
+// Queries displaycatalog without fieldsTemplate=browse to retrieve full SkuId and AvailabilityId.
+bool fetchPurchaseOffer(const std::string& productId, const std::string& market, const std::string& language,
+ PurchaseOffer& out, std::string& err);
+
+// Claims a 100% free product (price == 0.00) via https://purchase.mp.microsoft.com/v7.0/users/me/orders.
+// Rejects immediately if offer.isFree is false or listPrice > 0.005.
+bool claimFreeProduct(const std::string& marketplaceAuthHeader, const PurchaseOffer& offer,
+ const std::string& market, std::string& err);
+
+} // namespace xc::xcloud
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index 94d8bd4..affe614 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -44,6 +44,7 @@
#include "xcloud/gssv.h"
#include "xcloud/titlehub.h"
#include "xcloud/prices.h"
+#include "xcloud/purchase.h"
#include "xcloud/regions.h"
#include <algorithm>
@@ -2343,7 +2344,126 @@ static void testNullBackendsM1() {
CHECK(!mic.isRecording() && !called);
}
+static void testPurchase() {
+ using namespace xcloud;
+ std::string err;
+ int status = 200;
+ std::string body;
+ net::Request lastReq;
+
+ net::setTestTransport([&](const net::Request& req) {
+ lastReq = req;
+ net::Response r;
+ r.status = status;
+ r.body = body;
+ return r;
+ });
+
+ // 1. fetchPurchaseOffer for a free product
+ body = R"({
+ "Products": [
+ {
+ "ProductId": "FREE123",
+ "DisplaySkuAvailabilities": [
+ {
+ "Sku": {"SkuId": "0001"},
+ "Availabilities": [
+ {
+ "AvailabilityId": "AVAIL_FREE",
+ "Actions": ["Details", "Purchase"],
+ "OrderManagementData": {
+ "Price": {
+ "ListPrice": 0.0,
+ "MSRP": 0.0,
+ "CurrencyCode": "USD"
+ }
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ })";
+
+ PurchaseOffer offer;
+ CHECK(fetchPurchaseOffer("FREE123", "US", "en-us", offer, err));
+ CHECK(offer.productId == "FREE123");
+ CHECK(offer.skuId == "0001");
+ CHECK(offer.availabilityId == "AVAIL_FREE");
+ CHECK(offer.isFree);
+ CHECK(offer.listPrice == 0.0);
+ CHECK(lastReq.url.find("displaycatalog.mp.microsoft.com") != std::string::npos);
+
+ // 2. fetchPurchaseOffer for a paid product: isFree must be false
+ body = R"({
+ "Products": [
+ {
+ "ProductId": "PAID123",
+ "DisplaySkuAvailabilities": [
+ {
+ "Sku": {"SkuId": "0002"},
+ "Availabilities": [
+ {
+ "AvailabilityId": "AVAIL_PAID",
+ "Actions": ["Purchase"],
+ "OrderManagementData": {
+ "Price": {
+ "ListPrice": 69.99,
+ "MSRP": 69.99,
+ "CurrencyCode": "USD"
+ }
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ })";
+ PurchaseOffer paidOffer;
+ CHECK(fetchPurchaseOffer("PAID123", "US", "en-us", paidOffer, err));
+ CHECK(!paidOffer.isFree);
+ CHECK(paidOffer.listPrice == 69.99);
+
+ // 3. Safety check: claimFreeProduct MUST refuse paid products
+ CHECK(!claimFreeProduct("XBL3.0 x=test;token", paidOffer, "US", err));
+ CHECK(err.find("safety block") != std::string::npos);
+
+ // 4. claimFreeProduct with empty auth or incomplete offer
+ PurchaseOffer invalidOffer = offer;
+ invalidOffer.availabilityId.clear();
+ CHECK(!claimFreeProduct("XBL3.0 x=test;token", invalidOffer, "US", err));
+ CHECK(!claimFreeProduct("", offer, "US", err));
+
+ // 5. Successful claim of free product
+ status = 200;
+ body = R"({"orderId":"ORDER-12345","status":"Purchased"})";
+ CHECK(claimFreeProduct("XBL3.0 x=test;token", offer, "US", err));
+ CHECK(lastReq.url.find("purchase.mp.microsoft.com/v7.0/users/me/orders") != std::string::npos);
+ std::string authVal;
+ for (const auto& h : lastReq.headers) {
+ if (h.first == "Authorization") authVal = h.second;
+ }
+ CHECK(authVal == "XBL3.0 x=test;token");
+ auto j = json::parse(lastReq.body);
+ CHECK(j && (*j)["orderItems"].isArray());
+ CHECK((*j)["orderItems"][0]["productId"].str() == "FREE123");
+ CHECK((*j)["orderItems"][0]["skuId"].str() == "0001");
+ CHECK((*j)["orderItems"][0]["availabilityId"].str() == "AVAIL_FREE");
+ CHECK((*j)["orderItems"][0]["price"].asNumber() == 0.0);
+
+ // 6. claimFreeProduct error handling
+ status = 400;
+ body = R"({"code":"PaymentRequired","message":"Payment method needed"})";
+ CHECK(!claimFreeProduct("XBL3.0 x=test;token", offer, "US", err));
+ CHECK(err.find("Payment method needed") != std::string::npos);
+
+ net::setTestTransport({});
+}
+
int main() {
+ testPurchase();
testNullBackends();
testPadGlyphs();
testToasts();