How to build a Minecraft server store: payment and automatic delivery

Two ways to hand over an item after payment: a command over RCON, and a queue the plugin pulls deliveries from. We show both, with what each one cannot do, on the code of the store in Flaem.

What you will do

The player types /shop vip-30, clicks a link, pays, and a few seconds later gets the rank on the server. If they left the game meanwhile, the rank waits until they come back. Nobody types commands by hand and nobody gets the rank twice.

We show two ways to deliver. RCON is the simplest but has limits you need to know about. A queue the plugin pulls deliveries from takes more code and removes those limits. That is how the store in Flaem works.

Level
advanced
Code
Java
Steps
6 steps
  1. In game /shop vip-30 The plugin opens an order for this player.
  2. Browser Payment A single-use link, the gateway, verification.
  3. Store Delivery queue A paid order waits for the server.
  4. Server Delivery The plugin delivers when the player is online.

What you need

  • A Paper 26.3 server and a plugin

    The plugin code in this guide compiles against Paper API 26.3 and Java 25. If you have not written a plugin before, start with the guide to your first Paper plugin.

  • A payment gateway

    Registration, notification and payment verification. We describe it on the Przelewy24 example in a separate guide. An order is paid only after verification, not when the player comes back from the payment page.

  • A database for the store

    Orders, their payment state and delivery state in one row. The SQL examples are for PostgreSQL.

  • The rules for selling on a server

    Mojang's guidelines allow charging for server access and selling cosmetics and entitlements that do not ruin the game for others or give a competitive advantage. Check them before you put together your offer.

RCON or a queue with a plugin

QuestionRCONQueue with a plugin
An open port on the game serverYes, TCP, unencryptedNo, the plugin connects out over HTTPS
Player offline when payingThe command runs without the playerThe delivery waits until the player joins
Protection against double deliveryNone, you have to add itLease and acknowledgement
Amount of codeSmallA plugin and two endpoints

Step by step

Each step with commands to copy. The list on the left shows where you are.

01

Describe items by keys, not commands

In the store database an item has a delivery key, for example vip-30, not a ready command. Only the plugin on the server knows what the key means, from its own config.yml. That way whoever edits prices in the store panel does not get access to the server console.

plugins/Shop/config.yml
# config.yml of the plugin: what each delivery key meansitems: vip-30: - "lp user {player} parent addtemp vip 30d" - "tellraw {player} {\"text\":\"Thank you for the VIP!\",\"color\":\"gold\"}" diamonds-64: - "give {player} minecraft:diamond 64"
02

Open the order from the game, not from a form

A name is not an identity: anyone can type someone else's, and on many servers names change. So the plugin, which knows the player's UUID, opens the order and receives a single-use payment link. The player's browser never tells the store who is buying.

The HTTP request goes asynchronously, and the reply to the player comes back to the server thread with runTask. The link expires after 60 minutes so an abandoned order is not an offer that can be used a month later at an old price.

ShopCommand.java
public final class ShopCommand implements BasicCommand { private final JavaPlugin plugin; private final HttpClient http = HttpClient.newHttpClient(); private final String api; private final String token; public ShopCommand(JavaPlugin plugin, String api, String token) { this.plugin = plugin; this.api = api; this.token = token; } @Override public void execute(CommandSourceStack source, String[] args) { if (!(source.getExecutor() instanceof Player player) || args.length != 1) { source.getSender().sendRichMessage("<gray>Usage: /shop <item>"); return; } JsonObject body = new JsonObject(); body.addProperty("player_uuid", player.getUniqueId().toString()); body.addProperty("player_name", player.getName()); body.addProperty("item", args[0]); HttpRequest request = HttpRequest.newBuilder(URI.create(api + "/orders")) .header("Authorization", "Bearer " + token) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(body.toString())) .build(); http.sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenAccept(response -> Bukkit.getScheduler().runTask(plugin, () -> { if (response.statusCode() != 201) { player.sendRichMessage("<red>Could not open the order. Try again in a moment."); return; } String link = JsonParser.parseString(response.body()).getAsJsonObject().get("link").getAsString(); player.sendMessage(Component.text("Click to pay (the link works for 60 minutes)", NamedTextColor.GREEN) .clickEvent(ClickEvent.openUrl(link))); })); }}
03

After verifying the payment, queue the delivery

When the gateway confirms the payment, in the same database transaction you mark the order paid and set its delivery state to queued. Money taken with nothing to deliver is a state the database should not be able to hold.

payment.sql
-- in the same transaction in which you verify the payment with the gatewayUPDATE orders SET paid_at = now(), delivery_state = 'queued' WHERE id = $1 AND paid_at IS NULL;
04

The simple way: a command over RCON

You enable RCON in server.properties: enable-rcon=true, rcon.password and rcon.port, 25575 by default. A packet has a length, a request id, a type and a payload, with little-endian integers. Type 3 is login, type 2 is a command. The server signals a wrong password with request id -1.

RCON is not encrypted, so the port must never be open to the internet: localhost or a private network between the store and the server only. And RCON does not know whether the player is online, so /give for an offline player fails, and a store that does not read the server's reply counts the delivery as done.

rcon.py
import socketimport structclass Rcon: """Minecraft RCON client: little-endian packets, type 3 is login, type 2 is a command.""" def __init__(self, host: str, port: int, password: str) -> None: self.sock = socket.create_connection((host, port), timeout=5) self.next_id = 0 request_id = self._send(3, password) reply_id, _ = self._read() if reply_id == -1 or reply_id != request_id: raise PermissionError("RCON: wrong password") def _send(self, kind: int, payload: str) -> int: self.next_id += 1 body = struct.pack("<ii", self.next_id, kind) + payload.encode("utf-8") + b"\x00\x00" self.sock.sendall(struct.pack("<i", len(body)) + body) return self.next_id def _read(self) -> tuple[int, str]: (length,) = struct.unpack("<i", self._exact(4)) data = self._exact(length) request_id, _kind = struct.unpack("<ii", data[:8]) return request_id, data[8:-2].decode("utf-8", "replace") def _exact(self, size: int) -> bytes: chunks = b"" while len(chunks) < size: chunk = self.sock.recv(size - len(chunks)) if not chunk: raise ConnectionError("RCON: connection closed") chunks += chunk return chunks def command(self, command: str) -> str: request_id = self._send(2, command) reply_id, text = self._read() if reply_id != request_id: raise RuntimeError("RCON: reply to a different request") return text
05

The full way: a queue with leases

Every few seconds the plugin asks the store for deliveries. The store does not just hand them out, it leases them: the rows get a token and an expiry, and until it passes no other request sees them. A plugin that asks twice therefore does not deliver twice.

The acknowledgement is one conditional UPDATE that only passes with the current token. A repeated acknowledgement changes nothing, and an expired lease goes back into the queue.

deliveries.sql
-- POST /deliveries/lease: at most 50 deliveries that this server is owedWITH due AS ( SELECT id FROM orders WHERE server_id = $1 AND (delivery_state = 'queued' OR (delivery_state = 'leased' AND lease_until < now())) ORDER BY paid_at LIMIT 50 FOR UPDATE SKIP LOCKED)UPDATE orders o SET delivery_state = 'leased', lease_token = $2, lease_until = now() + interval '10 minutes', attempts = o.attempts + 1 FROM due WHERE o.id = due.idRETURNING o.id, o.player_uuid, o.delivery_key, o.attempts;-- POST /deliveries/{id}/acknowledge: only the holder of the current lease countsUPDATE orders SET delivery_state = 'delivered', delivered_at = now() WHERE id = $1 AND server_id = $2 AND lease_token = $3 AND delivery_state = 'leased';
06

The plugin that delivers

Network polling runs in an asynchronous task every 15 seconds. The player check and the commands go back to the server's main thread, because only there may you call dispatchCommand. An offline player is an ordinary case: the plugin does not acknowledge, the lease expires after 10 minutes and the store offers the delivery again.

Deliveries.java
public final class Deliveries { private final JavaPlugin plugin; private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(); private final String api; // https://shop.example/api/server private final String token; // this server's token from the store panel public Deliveries(JavaPlugin plugin, String api, String token) { this.plugin = plugin; this.api = api; this.token = token; } public void start() { Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, this::poll, 20L, 20L * 15); } private void poll() { JsonObject lease = post("/deliveries/lease", "{}"); if (lease == null) return; String leaseToken = lease.get("lease_token").getAsString(); for (JsonElement element : lease.getAsJsonArray("deliveries")) { JsonObject delivery = element.getAsJsonObject(); UUID playerId = UUID.fromString(delivery.get("player_uuid").getAsString()); String key = delivery.get("delivery_key").getAsString(); String id = delivery.get("id").getAsString(); Bukkit.getScheduler().runTask(plugin, () -> deliver(leaseToken, id, playerId, key)); } } /** Server main thread: the only place where you may check the player and run a command. */ private void deliver(String leaseToken, String id, UUID uuid, String key) { Player player = Bukkit.getPlayer(uuid); if (player == null) return; // offline: the lease expires and the store offers the delivery again List<String> commands = plugin.getConfig().getStringList("items." + key); boolean all = !commands.isEmpty(); for (String command : commands) { all &= Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command.replace("{player}", player.getName())); } String note = all ? "delivered" : "unknown key or command"; Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> post("/deliveries/" + id + "/acknowledge", "{\"lease_token\":\"" + leaseToken + "\",\"note\":\"" + note + "\"}")); } private JsonObject post(String path, String body) { try { HttpRequest request = HttpRequest.newBuilder(URI.create(api + path)) .timeout(Duration.ofSeconds(15)) .header("Authorization", "Bearer " + token) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(body)) .build(); HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) return null; return JsonParser.parseString(response.body()).getAsJsonObject(); } catch (Exception e) { plugin.getLogger().fine("Store unavailable, retrying in 15 s: " + e.getMessage()); return null; } }}

How to check it works

We compiled both plugin classes, ShopCommand and Deliveries, against Paper API 26.3.build.157-beta with Java 25. We checked the RCON client against a test server written from the packet format on minecraft.wiki. The login packet with the password "secret" looks like the one below.

Environment
Paper API 26.3.build.157-beta, Java 25, a test RCON server
Result
Both classes compiled, the RCON login packet in the minecraft.wiki format

What you should see

  • /shop vip-30 answers in game with a clickable link.
  • After the payment is verified the order is in the queued state.
  • An online player gets the item within 15 seconds and the order moves to delivered.
  • An offline player gets the item after joining, and two parallel plugin polls do not produce two deliveries.
gradle build and rcon
Command
gradle build
Output
com/example/shop/Deliveries.classcom/example/shop/ShopCommand.class
Command
python rcon_test.py
Output
login packet (type 3, id 1, "secret"):10 00 00 00 01 00 00 00 03 00 00 00 73 65 63 72 65 74 00 00
  1. 1-3
    The plugin classes

    ShopCommand and Deliveries compiled against Paper API 26.3.build.157-beta with Java 25.

  2. 4-5
    The RCON client

    Checked against a test server written to the packet format of minecraft.wiki.

  3. 6
    The packet byte by byte

    Length 16, id 1, type 3, the password "secret" and two zero bytes at the end; numbers written least significant byte first.

The item shop in Flaem

How it looks in our project

This guide is a simplified version of the shop we built in Flaem. Players have no account or password there; they are identified by what the game itself reports, such as the Minecraft account UUID, and the plugin vouches for that identity with the server's token. An item cannot carry a console command, precisely so that permission to edit the shop is not console access.

Flaem also accepts purchases from ready-made stores: Tebex, CraftingStore and ItemShop.pl. We turn their HMAC-signed webhooks into the same delivery queue, and the server plugin pulls them like deliveries from the built-in shop.

See the project
A server store panel with the queue of rewards waiting for players
a game server store: the reward queue, where a delivery waits until the player joins the server
queue.rs
pub const LEASE_TTL_MINUTES: i64 = 10;

Common errors

Symptom, cause and fix, with the number of the step where the error shows up.

StepSymptomCauseFix
04 Connection refused on the RCON port enable-rcon=false or a different rcon.port than in the store. Enable RCON in server.properties and restart the server.
04 An RCON reply with request id -1 A wrong password, or a command sent before logging in. Log in with a type 3 packet carrying rcon.password before the first command.
04 The player paid and got nothing An RCON command run while the player was offline. Check the player is online before delivering, or switch to the plugin queue.
05 A rank delivered twice The plugin asked again after a timeout and the store returned the same deliveries. Lease deliveries with a token and acknowledge with a conditional UPDATE.
06 An exception from dispatchCommand in an async task The command was called off the server's main thread. Hand the delivery to the main thread with Bukkit.getScheduler().runTask.

Frequently asked questions

The questions that come up with this setup.

May I sell ranks and items on a Minecraft server?
Mojang's server guidelines allow charging for access and selling cosmetics and gameplay-affecting entitlements as long as they do not ruin the game for others or give a competitive advantage. Capes and anything imitating them are excluded. Read the full guidelines on minecraft.net before you put together your offer.
A ready-made store or your own?
Tebex, CraftingStore or ItemShop.pl get you running faster, but you pay a commission and work within their model. Your own store makes sense when you want your own gateways, your own limit rules or one panel for several servers.
Why does the plugin ask the store instead of the store calling the plugin?
Because then the game server needs no open port: it only connects out, over HTTPS. And a plugin that was off for a week simply collects the backlog in batches after it starts.
What about a one-per-player purchase limit?
Check it when the order is opened and again before payment. Two payments started at the same moment can exceed it by one, because a payment is a network call you cannot cover with a row lock. So check the limit once more after the payment is booked.

Sources

The documentation and specifications we compared the commands with.

Other guides

Tools

Glossary terms

Tell us what you want to build.

A free quote comes back within an hour during working hours. You talk to the person who writes the code.