Repositories | Polyback | Log in to see private repositories


polyback-website / fe552ae720b75aa69ca0c73f420ab929961b458d / api/gameserver/purchase.php

2,564 bytes | parent directory

<?php require $_SERVER['DOCUMENT_ROOT'].'/api/private/core.php';

// Buying things while playing, for game servers (X-Polygon-Gameserver-Key). A server can only act
// for players who are in the game it runs, and only sells what belongs to that place (or is for sale
// in the catalog). The engine asks the player first, in a window the place's scripts can't touch.
//   {"jobId","userId","op": "offer", "productId" or "assetId"} -> name, price, balance
//   {..., "op": "buy", "productId" or "assetId", "price", "nonce": 32 hex digits} -> receipt
//   {..., "op": "waiting"} -> receipts whose goods haven't been handed out
//   {..., "op": "granted", "purchaseId"}

use pizzaboxer\ProjectPolygon\Database;
use pizzaboxer\ProjectPolygon\Gameservers;
use pizzaboxer\ProjectPolygon\Products;

Gameservers::RequireAuthorized();
$body = Gameservers::Body();
function fail($message) { die(json_encode(["success" => false, "message" => $message])); }

$user = (int) ($body["userId"] ?? 0);
$job = Database::singleton()->run(
	"SELECT j.JobID, j.PlaceID FROM GameJobs j JOIN GameJobPlayers p ON p.JobID = j.JobID AND p.UserID = :u AND p.Active = 1
	 WHERE j.JobID = :j AND j.Status = 'Ready'",
	[":j" => (string) ($body["jobId"] ?? ""), ":u" => $user]
)->fetch(PDO::FETCH_OBJ);
if (!$job) fail("That player isn't in this game");

$product = (int) ($body["productId"] ?? 0);
$asset = (int) ($body["assetId"] ?? 0);

switch ($body["op"] ?? "")
{
case "offer":
	$offer = Products::Offer($job->PlaceID, $product, $asset, $user);
	if (is_string($offer)) fail($offer);
	die(json_encode(["success" => true, "name" => $offer->Name, "price" => $offer->Price, "balance" => $offer->Balance]));

case "buy":
	$nonce = (string) ($body["nonce"] ?? "");
	if (!preg_match('/^[0-9a-f]{32}$/', $nonce)) fail("Bad request");
	$offer = Products::Offer($job->PlaceID, $product, $asset, $user);
	if (is_string($offer)) fail($offer);
	$purchase = Products::Buy($job, $user, $offer, (int) ($body["price"] ?? -1), $nonce);
	if (is_string($purchase)) fail($purchase);
	die(json_encode(["success" => true, "receipt" => Products::Receipt($purchase)]));

case "waiting":
	die(json_encode(["success" => true, "receipts" => array_map([Products::class, "Receipt"], Products::Waiting($job->PlaceID, $user))]));

case "granted":
	Database::singleton()->run(
		"UPDATE GamePurchases SET Granted = 1 WHERE ID = :id AND UserID = :u AND PlaceID = :p",
		[":id" => (int) ($body["purchaseId"] ?? 0), ":u" => $user, ":p" => $job->PlaceID]
	);
	die(json_encode(["success" => true]));
}
fail("Unknown operation");