Author
Dan Ribbens headshot
Dan Ribbens
Published On

Can a headless CMS be used as the admin for managing a video game?

Author
Dan Ribbens headshot
Dan Ribbens
Published On
Can a headless CMS be used as the admin for managing a video game?
Can a headless CMS be used as the admin for managing a video game?

Game developers need a way to manage players, ban users and monetize their work with in-app purchases—is a CMS the right tool?

Each time I get a new computer I convince myself to install Unity, as I dream of building my indie game ideas. Since that will never happen, I decided to take the tools I know and apply it to something I wish I knew. The real inspiration for this post came from a recent conversation with an actual game developer. I wanted to demonstrate how Payload CMS could be used as the Admin tool and API for managing a video game.

With the right CMS built up, we can enable admin users to manage players, games and achievements as well as completing in-app purchases and handle authentication and access control. Since Payload CMS is headless, an online game can call the API to perform all the needed backend functionality.

Overview

All the code written for this guide can be found on Github. It only includes the admin portion of the project. As for now the 'game' is as made-up as that really cool kickstarter project you funded back in 2012.

The features for the admin panel of our fictional game are:

  • Manage player accounts
  • Record games with teams, players and scores
  • Manage and automatically award achievements based on player stats
  • Handle in-app purchases
  • Image uploads for achievements and purchases
  • Access controls for security

First, let's go over the collections at a high level:

Admins - Can log in to the admin UI and do most things Players - User accounts that can also hold player stats and unlock achievements and make in-app purchases Games - Contain teams and players along with scores, when saved player stats are updated Achievements - Admins can manage achievements and set thresholds needed to earn them In-App Purchases - The things players will be able to purchase Player Purchases - Who, what and how much it cost Images - File upload to store images for In-App purchases and Achievements

Payload CMS Player List Screenshot

If you haven't developed with Payload CMS before then you'll be surprised by how little effort it takes to add and change fields in your app. Simply providing the config will build the admin UI as well as the APIs and manage the database.

Now the fields for our game collection are made up of an array of teams, with an array of players so that player scores are tracked independently of the team score. For the computer science nerds, that is what we call a two-dimensional array. We'll later use this scoring to assign experience points and achievements.

1
import { CollectionConfig } from 'payload/types'
2
import { isAdmin } from '../shared/access/isAdmin'
3
import { gamesAfterChangeHook } from './gamesAfterChangeHook'
4
5
export const games: CollectionConfig = {
6
slug: 'games',
7
hooks: {
8
afterChange: [ gamesAfterChangeHook ],
9
},
10
access: {
11
update: () => false,
12
delete: () => false,
13
create: isAdmin,
14
},
15
fields: [
16
{
17
name: 'teams',
18
type: 'array',
19
required: true,
20
fields: [
21
{
22
name: 'score',
23
type: 'number',
24
required: true,
25
},
26
{
27
name: 'players',
28
type: 'array',
29
fields: [
30
{
31
name: 'player',
32
type: 'relationship',
33
relationTo: 'players',
34
required: true,
35
},
36
{
37
name: 'score',
38
type: 'number',
39
required: true,
40
},
41
],
42
},
43
],
44
},
45
],
46
}

You could easily add more interesting stats beyond simple scores for other things happening in game and allow users to unlock more achievements. Adding them here as well as in the achievement collection as new type options would allow admins that ability.

The types that you see in the code are all generated based on the config using Payload's type generation feature. You may also notice in my code there are a few places I like to use Partial<{...}> which allows me to be a little less strict and get work done.

Authentication and banning players

Another feature that will get you going ultra-fast with Payload is authentication. By setting auth: true in the collection, we can take the defaults for how user authentication works for our players.

Payload CMS Player Login Postman

Now that we have an authenticated a user, let's see how we can implement banning a player. It should come as no surprise that we have a field on the players to be managed by admins.

1
{
2
name: 'banned',
3
label: 'Ban Player',
4
type: 'checkbox',
5
admin: {
6
position: 'sidebar',
7
},
8
},

That gives the admin UI a checkbox in the sidebar to ban the player.

Payload CMS Ban Player Screenshot

It doesn't do anything yet. To make Payload refuse our banned players on login, we can add the after login hook to keep them out!

1
import { AfterLoginHook } from 'payload/dist/collections/config/types'
2
import { APIError } from 'payload/errors'
3
4
export const playerLoginHook: AfterLoginHook = async ({ doc }) => {
5
if (doc.banned) {
6
throw new APIError('You have been banned, goodbye', 403);
7
}
8
}

Payload has an APIError that is useful for returning errors with status codes which we can see in action when we try to login with a banned player.

Payload CMS API Error Screenshot

API key

Another point about authentication is that in the admins collection, we've turned on useAPIKey. What that allows you to do is generate an API key that your game or any other third party could use to call the API with the full privileges of being an Admin. This is how our fictional game will call the API to store game scores and other actions.

Managing achievements

Before we get in to how achievements work, take a look at the admin experience for adding them and assigning the parameters with which they'll be awarded.

An admin can use this interface to create new in-game achievements complete with image uploads to be served on the web or the game interface.

Payload CMS Manage Achievements Screenshot

Awarding player achievements

I want to dive in to how our game takes game data, which we saw the structure for above. When a game is created we have an after-change hook which will do the heavy lifting of updating the player stats and awarding achievements. An admin can view a player with some experience in the Admin UI and see their stats and achievements.

Payload CMS Player Achievements

Notice that the fields are all disabled since we have it set to read only, that is because we want hooks to manage this for us. Let's review the code for the hook that automates this process.

1
export const gamesAfterChangeHook: AfterChangeHook = async ({ doc, req }: Args) => {
2
const achievements = fetchAchievements(req.payload)
3
const playerData: { [id: string]: Player } = {}
4
const playerIDs: string[] = doc.teams.flatMap((team) => team.players)
5
.map((player) => (player.player as string))
6
const players = await fetchPlayers(req.payload, playerIDs)
7
const winners = getWinningTeamID(doc.teams)
8
9
// structure the player data by id to reduce looping
10
for (let player of players) {
11
playerData[player.id] = player
12
}
13
14
// loop over each team their players
15
doc.teams.forEach((team) => {
16
team.players.forEach(async (teamPlayer: { player: string, score: number }) => {
17
const player = playerData[teamPlayer.player as string]
18
updatePlayerAfterGame(req.payload, await achievements, player, teamPlayer, team, winners);
19
})
20
})
21
}

Each new game will call this code in the hook that updates players with new stats and achievements, all dynamically. Here is the function that to add up the stats, achievements and update the players.

1
/**
2
* Assign experience amounts for player outcomes
3
*/
4
const exp = {
5
winner: 500,
6
played: 100,
7
playerScore: 10,
8
teamScore: 5,
9
}
10
11
/**
12
* Update players with accumulated stats and achievements based on game outcomes
13
*/
14
export const updatePlayerAfterGame = (
15
payload: Payload,
16
achievements: Achievement[],
17
player: Player,
18
teamPlayer: Partial<{score: number, player: string}>,
19
team: Partial<{ score: number, id: string}>,
20
winners: string
21
) => {
22
const experience = player.stats.experience
23
+ (winners === team.id ? exp.winner : 0)
24
+ (team.score * exp.teamScore)
25
+ (teamPlayer.score * exp.playerScore)
26
+ exp.played
27
28
const stats = {
29
experience,
30
played: player.stats.played + 1,
31
wins: (winners === team.id ? 1 : 0) + player.stats.wins,
32
losses: (winners === team.id ? 0 : 1) + player.stats.losses,
33
}
34
35
// update player collection
36
const ignoreResult = payload.update({
37
collection: 'players',
38
id: player.id,
39
data: {
40
achievements: getPlayerAchievements(stats, achievements),
41
stats,
42
},
43
})
44
}

The last delicious detail is in how player achievements are filtered. As long as we have player stats that match the achievement.type it will just work.

1
/**
2
* get player achievements based on experience, wins and losses
3
*/
4
export const getPlayerAchievements = (playerStats: {[key: string]: number}, achievements: Achievement[]) => {
5
const playerAchievements = []
6
achievements.forEach((achievement) => {
7
if (playerStats[achievement.type] >= achievement.amount) {
8
playerAchievements.push(achievement.id)
9
}
10
})
11
return playerAchievements
12
}

In-App Purchases

From an admin perspective, the purchasable items look much the same as achievements except that they also have a price field.

The relationships for the purchases are slightly different from achievements in that it has been given its own collection instead of living in the player document. First, we can better segment our data as we won't always want to have it on the player. Second, it gives us a place to add more data like the amount paid and the Stripe charge id which we didn't need for achievements.

When a new player registers we are calling on Stripe to create a customer ID so that we're ready to handle any purchases in the game.

Then as a player purchase request comes in, it must have the token for the payment from stripe in order to complete the request.

1
import { CollectionBeforeChangeHook } from 'payload/types'
2
import { stripe } from '../../shared/stripe'
3
import { APIError } from 'payload/errors'
4
5
export const playerPurchaseHook: CollectionBeforeChangeHook = async ({ req, data }) => {
6
if (req.user.collection === 'admin') {
7
return
8
}
9
10
if (!req.body.stripeToken) {
11
throw new APIError('Could not complete transaction, missing payment', 400);
12
}
13
14
// get the amount from the purchase item
15
const result = await req.payload.find({
16
collection: 'purchases',
17
limit: 1,
18
where: {
19
id: {
20
equals: data.purchase,
21
},
22
},
23
})
24
25
const purchase = result.docs[0];
26
27
// `source` is obtained with Stripe.js;
28
// see https://stripe.com/docs/payments/accept-a-payment-charges#web-create-token
29
const charge = await stripe.charges.create({
30
amount: purchase.price,
31
currency: 'usd',
32
customer: req.user.customer as string,
33
capture: true,
34
source: req.body.stripeToken,
35
description: `In-App Purchase - ${purchase.name}`,
36
})
37
38
// set the charge id
39
data.charge = charge.id
40
}

Final thoughts

The code presented in this article and the accompanying repository was written in a matter of two days and shouldn't be considered production ready without testing.

Give us a shout if you liked this guide on Twitter @payloadcms or in our Discord!

If you want to hire me for game development you should absolutely talk to somebody else.