View as Markdown

IAP providers

IAP providers let you plug any store into Nakama as a first-class validation target. In addition to the stores Nakama supports natively, you can connect a platform store, a regional distributor, or your own storefront. Purchases and subscriptions from your provider are validated, persisted and read back through the same APIs as the built-in stores.

How it works #

An IAP provider is a runtime module that sits between Nakama and an external store. Nakama provides the client API endpoints, keeps track of the providers you register, persists the results, and exposes them through the purchase and subscription APIs.

Purchase validation flow #

The client sends Nakama a provider name and an opaque payload. Nakama passes the payload to your IAP provider module, which verifies the receipt with the store and returns the purchases or subscriptions it represents.

A sequence diagram with four participants: game client, Nakama, IAP provider module, and store. The game client sends a provider name and payload to Nakama. Nakama sends the payload to the IAP provider module, which sends the receipt to the store. The store returns purchase data to the IAP provider module, which returns purchases or subscriptions to Nakama. Nakama persists them against the session user, then returns the validated purchases to the game client.

The sequence is:

  1. The client sends a provider name and payload to Nakama. The payload is opaque JSON. See Define the client payload.
  2. Nakama passes the payload to your IAP provider module.
  3. Your provider verifies the receipt. The module communicates with the store and confirms the purchase is genuine.
  4. Your provider returns one or more purchases or subscriptions.
  5. Nakama persists the results against the authenticated user and returns them to the client.

This is the client-initiated path. Your server runtime can also call the provider directly, which runs the same steps 2 to 4 without a client request. See Validating from the server runtime.

Creating an IAP provider #

In Go, a provider satisfies the following interface:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
type IAPProvider interface {
    // Name selects the provider in validation requests.
    Name() string
    // NotificationEndpointId is the last path segment of the provider's notification endpoint.
    NotificationEndpointId() string
    // Code identifies the provider's purchases and subscriptions in storage.
    Code() int

    ValidatePurchase(ctx context.Context, logger Logger, db *sql.DB, nk NakamaModule,
        payload map[string]any, overrides map[string]any) ([]*IAPProviderPurchase, error)

    ValidateSubscription(ctx context.Context, logger Logger, db *sql.DB, nk NakamaModule,
        payload map[string]any, overrides map[string]any) ([]*IAPProviderSubscription, error)

    HandleNotification(ctx context.Context, logger Logger, db *sql.DB, nk NakamaModule,
        body []byte, headers, query map[string][]string) ([]*IAPProviderNotification, error)
}

Let’s work through an example implementation. First we declare our type:

1
type PlatformXProvider struct{}

The steps below implement that type one method at a time.

1. Define the IAP provider name #

The name is the identifier everywhere in the APIs. Both the client API and the server runtime select by name. Your provider returns it from Name():

1
2
3
const providerName = "platform_x"

func (p *PlatformXProvider) Name() string { return providerName }

Requirements:

  • Letters, numbers, underscores and hyphens ([a-zA-Z0-9_-]), up to 128 bytes.
  • Lowercased at registration and on lookup, so Platform_X and platform_x resolve to the same provider.
  • Cannot be a built-in store name: apple, google, huawei, facebookinstant, samsung.

2. Define the IAP provider code #

The code is a number you choose that pairs one-to-one with your provider name. It is the value Nakama records in its underlying storage layer to mark which provider a purchase or subscription came from, the same way it marks purchases from the built-in stores.

The code is never used to call anything. It exists only as the persistence key.

1
2
3
const providerCode = 100

func (p *PlatformXProvider) Code() int { return providerCode }

Requirements: Must fit in a signed 16-bit integer. Must not use 0 through 4, which belong to the built-in stores. Must be unique across registered providers.

Define the name and code as constants in your provider code. Nakama does not persist the pairing, so use version control to keep a record of your name and code pairing.

3. Define the client payload #

The payload is how your game client tells your provider what to validate. It travels on every validation request: the client sends a JSON object, Nakama parses it and hands it straight to your ValidatePurchase or ValidateSubscription function as the payload argument, without inspecting the contents.

The shape is whatever your store needs: a receipt string, a transaction ID, a signed token, or several values together.

Anything the client must not be able to set belongs in overrides instead.

4. Implement the validation functions #

ValidatePurchase and ValidateSubscription are where your module talks to the store. Each receives the payload the client sent, verifies it, and returns what the receipt contains.

Validate purchase example #

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
func (p *PlatformXProvider) ValidatePurchase(ctx context.Context, logger runtime.Logger,
    db *sql.DB, nk runtime.NakamaModule, payload map[string]any,
    overrides map[string]any) ([]*runtime.IAPProviderPurchase, error) {

    // overrides carries values the server set, such as credentials.
    // It is empty for requests that came from the client API.

    receipt, _ := payload["receipt"].(string)
    if receipt == "" {
        return nil, runtime.NewError("payload is missing receipt", 3)
    }

    // Verify the receipt with the store and read back what it contains.
    // Replace this with a real call to the store's API.
    result, err := verifyWithPlatformX(ctx, receipt)
    if err != nil {
        return nil, runtime.NewError("receipt rejected by store", 9)
    }

    // Some stores bundle several transactions into one receipt, so both
    // validation functions return a slice. Append one entry per transaction.
    purchases := make([]*runtime.IAPProviderPurchase, 0, len(result.Items))
    for _, item := range result.Items {
        purchases = append(purchases, &runtime.IAPProviderPurchase{
            // The store's unique identifier for this transaction. Required.
            // Nakama de-duplicates on it, which prevents a receipt being replayed.
            TransactionId: item.TransactionID,
            ProductId:     item.ProductID,
            PurchaseTime:  item.PurchasedAt,
            Environment:   api.StoreEnvironment_PRODUCTION,
            RawResponse:   item.Raw,
        })
    }

    return purchases, nil
}

Validate subscription example #

ValidateSubscription follows the same shape, returning IAPProviderSubscription values instead.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
func (p *PlatformXProvider) ValidateSubscription(ctx context.Context, logger runtime.Logger,
    db *sql.DB, nk runtime.NakamaModule, payload map[string]any,
    overrides map[string]any) ([]*runtime.IAPProviderSubscription, error) {

    receipt, _ := payload["receipt"].(string)
    if receipt == "" {
        return nil, runtime.NewError("payload is missing receipt", 3)
    }

    result, err := verifyWithPlatformX(ctx, receipt)
    if err != nil {
        return nil, runtime.NewError("receipt rejected by store", 9)
    }

    subscriptions := make([]*runtime.IAPProviderSubscription, 0, len(result.Subscriptions))
    for _, sub := range result.Subscriptions {
        subscriptions = append(subscriptions, &runtime.IAPProviderSubscription{
            // The store's identifier for the subscription itself, stable across
            // renewals. Required, and used in place of TransactionId.
            OriginalTransactionId: sub.SubscriptionID,
            // When the current period ends. Required. Nakama reads this to
            // decide whether the subscription is active.
            ExpiryTime:            sub.ExpiresAt,
            ProductId:             sub.ProductID,
            PurchaseTime:          sub.PurchasedAt,
            Environment:           api.StoreEnvironment_PRODUCTION,
            RawResponse:           sub.Raw,
        })
    }

    return subscriptions, nil
}

When a receipt is invalid, return an error rather than an empty slice. An empty slice fails the request with a generic FailedPrecondition, while an error lets you set the status code the client sees.

5. Register the provider #

Register your provider during runtime initialization with RegisterIAPProvider.

1
2
3
4
func InitModule(ctx context.Context, logger runtime.Logger, db *sql.DB,
    nk runtime.NakamaModule, initializer runtime.Initializer) error {
    return initializer.RegisterIAPProvider(&PlatformXProvider{})
}

6. Handle store notifications #

Most stores report post-sale events, such as subscription renewals and purchase refunds, to a callback URL as they occur. This is what keeps the stored purchase and subscription state accurate after the sale, and it lets you run custom code when a player’s entitlement changes.

NotificationEndpointId() and HandleNotification() are part of the IAPProvider interface, so both must be implemented. If your store has no post-sale callback, return an empty string and a nil slice.

The built-in store providers in Nakama work the same way. See Handle refunds and subscription changes for how this looks with the Apple App Store.

Notification flow #

Nakama serves a callback endpoint for your IAP provider, applies whatever you return, and fires the notification hooks.

A sequence diagram with four participants: store, Nakama, IAP provider module, and notification hook. The store sends a notification to Nakama. Nakama passes the body and headers to the IAP provider module, which verifies and maps them, then returns a RENEWED event with its subscription. Nakama upserts the record, then calls the notification hook, which grants the entitlement. Nakama acknowledges the callback to the store with 200 OK.

The sequence is:

  1. The store posts a notification to your provider’s callback endpoint.
  2. Nakama passes the request body, headers and query to HandleNotification, the function implemented in your IAP provider module.
  3. Your module verifies the request came from the store, parses it, and returns the events as Nakama notification types.
  4. Nakama resolves the user, then persists the purchase or subscription.
  5. Nakama calls your notification hook with the stored record. The hook is registered separately from the provider module.
  6. Nakama acknowledges the callback to the store.

There are a few things to set up before this flow works: the callback endpoint, the handler that translates the store’s request and the hook that reacts to the result.

Set up the notification callback #

Nakama registers a callback endpoint for every provider you register. The value you return from NotificationEndpointId() becomes the last segment of its path:

1
2
3
const notificationEndpointId = "7f3a9c21e84b4d6fa0c5"

func (p *PlatformXProvider) NotificationEndpointId() string { return notificationEndpointId }

This gives the following endpoint path:

1
  /v2/console/platform_x/notifications/7f3a9c21e84b4d6fa0c5

An empty string leaves the route registered at /v2/console/platform_x/notifications.

Configure this URL with your store, using whatever mechanism it provides for registering a server callback. Note that these endpoints are public and unauthenticated. Nakama does not verify the caller. Ensure your provider verifies the request.

Implement the notification handler #

In your provider module, implement HandleNotification. It receives the raw request and returns the events you want Nakama to apply.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
func (p *PlatformXProvider) HandleNotification(ctx context.Context, logger runtime.Logger,
    db *sql.DB, nk runtime.NakamaModule, body []byte,
    headers, query map[string][]string) ([]*runtime.IAPProviderNotification, error) {

    // Verify the callback came from the store before acting on it.
    // Replace this with the scheme your store uses to sign callbacks.
    if err := verifyPlatformXSignature(headers, body); err != nil {
        return nil, runtime.NewError("notification signature rejected", 16)
    }

    event, err := parsePlatformXNotification(body)
    if err != nil {
        return nil, err
    }

    // Map the store's event name onto one of Nakama's notification types.
    var notificationType runtime.NotificationType
    switch event.Kind {
    case "subscription.renewed":
        notificationType = runtime.IAPNotificationRenewed
    case "subscription.cancelled":
        notificationType = runtime.IAPNotificationCancelled
    case "subscription.expired":
        notificationType = runtime.IAPNotificationExpired
    default:
        // Acknowledge events you do not act on.
        return nil, nil
    }

    return []*runtime.IAPProviderNotification{{
        Type: notificationType,
        Subscription: &runtime.IAPProviderSubscription{
            OriginalTransactionId: event.SubscriptionID,
            ProductId:             event.ProductID,
            ExpiryTime:            event.ExpiresAt,
        },
    }}, nil
}

More on the return type used in the code example above. The full signature of IAPProviderNotification is:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type IAPProviderNotification struct {
    // One of the five types Nakama normalizes every store onto:
    // SUBSCRIBED, RENEWED, EXPIRED, CANCELLED or REFUNDED.
    Type         NotificationType
    // Set this when the store tells you who the event belongs to.
    // Otherwise Nakama resolves the user from the existing stored row.
    UserId       string
    // Purchase notifications support REFUNDED only.
    // Other types are logged and skipped.
    Purchase     *IAPProviderPurchase
    // Subscription notifications support the full set of types.
    Subscription *IAPProviderSubscription
}

See Notification types for what each type means.

Note that if a notification carries both a purchase and a subscription, only the subscription is processed.

Return an error to respond with HTTP 500, which prompts most stores to retry. Return an empty slice to acknowledge and ignore the callback with HTTP 200.

React to notifications #

Now that you have the notification all set up, the next step is to act on them in your game, such as revoking a subscription. You do this via the notification hooks in your runtime code.

1
2
3
4
5
6
7
RegisterIAPPurchaseNotification(fn func(ctx context.Context, logger Logger, db *sql.DB,
    nk NakamaModule, provider string, notificationType NotificationType,
    purchase *api.ValidatedPurchase, providerPayload string) error) error

RegisterIAPSubscriptionNotification(fn func(ctx context.Context, logger Logger, db *sql.DB,
    nk NakamaModule, provider string, notificationType NotificationType,
    subscription *api.ValidatedSubscription, providerPayload string) error) error

Register the hook on the Initializer in InitModule.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
func InitModule(ctx context.Context, logger runtime.Logger, db *sql.DB,
    nk runtime.NakamaModule, initializer runtime.Initializer) error {

    if err := initializer.RegisterIAPProvider(&PlatformXProvider{}); err != nil {
        return err
    }

    return initializer.RegisterIAPSubscriptionNotification(func(ctx context.Context,
        logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, provider string,
        notificationType runtime.NotificationType, subscription *api.ValidatedSubscription,
        providerPayload string) error {

        switch notificationType {
        case runtime.IAPNotificationRenewed:
            return grantEntitlement(ctx, nk, subscription)
        case runtime.IAPNotificationExpired:
            return revokeEntitlement(ctx, nk, subscription)
        }

        return nil
    })
}

Note that a cancellation stops the subscription renewing while leaving it active until its expiry time, so revoking is safer when the subscription expires rather than when cancellation fires.

Each hook is registered once per server. Use the provider argument to identify which provider the notification came from.

Invoke purchase validation #

Now your provider is registered, your client can call it. This is the first step in the purchase validation flow: the client sends your provider name and payload to Nakama.

The endpoints are similar to the built-in stores except with your provider name in the path:

1
2
  POST /v2/iap/purchase/{provider}
  POST /v2/iap/subscription/{provider}

The request carries the provider name, the payload your ValidatePurchase reads, and an optional persist flag. persist defaults to true, which stores the result and enables replay protection. Set it to false to validate without writing anything.

For the full request and response shape, see the Client API reference.

Subscriptions use ValidateSubscriptionAsync with the same arguments. Both methods take persist as an optional argument.

Validating from the server runtime #

You can also validate from your server runtime, calling the provider directly instead of waiting for a client request.

One reason to do this is secrets. Validation might need a store API key or a shared secret, and that is not a value you want the client sending.

The relevant methods on NakamaModule are PurchaseValidate and SubscriptionValidate. When you call these methods, they will run the ValidatePurchase or ValidateSubscription implementations that you wrote.

1
2
3
4
5
PurchaseValidate(ctx context.Context, provider, userID string, payload map[string]any,
    persist bool, overrides ...map[string]any) (*api.ValidateIAPPurchaseResponse, error)

SubscriptionValidate(ctx context.Context, provider, userID string, payload map[string]any,
    persist bool, overrides ...map[string]any) (*api.ValidateIAPSubscriptionResponse, error)

Note the overrides map in the above functions. This is the server-trusted channel into your provider. It arrives as the overrides argument on ValidatePurchase and ValidateSubscription. Requests that come from the client API should always pass an empty overrides map.

In practice you can call these from an RPC, for example validatePurchaseRpc. The client sends the receipt to your RPC, and your RPC adds the sensitive values the client doesn’t hold.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
func validatePurchaseRpc(ctx context.Context, logger runtime.Logger, db *sql.DB,
    nk runtime.NakamaModule, payload string) (string, error) {

    userId, ok := ctx.Value(runtime.RUNTIME_CTX_USER_ID).(string)
    if !ok {
        return "", runtime.NewError("no user id in context", 3)
    }

    var request struct {
        Receipt string `json:"receipt"`
    }
    if err := json.Unmarshal([]byte(payload), &request); err != nil {
        return "", runtime.NewError("invalid request", 3)
    }

    result, err := nk.PurchaseValidate(ctx, providerName, userId,
        map[string]any{"receipt": request.Receipt}, true,
        // Reaches your provider as the overrides argument. The client
        // has no way to set or read this.
        map[string]any{"api_key": platformXApiKey})
    if err != nil {
        return "", err
    }

    response, err := json.Marshal(result)
    if err != nil {
        return "", err
    }

    return string(response), nil
}

Register your RPC in InitModule, alongside the provider:

1
2
3
if err := initializer.RegisterRpc("validate_purchase", validatePurchaseRpc); err != nil {
    return err
}

Hooks #

As with the built-in stores, you can run custom logic around each validation request with before and after hooks. See Hooks.

1
2
3
4
RegisterBeforeValidatePurchase
RegisterAfterValidatePurchase
RegisterBeforeValidateSubscription
RegisterAfterValidateSubscription

Separately, you can react to store notifications after Nakama has applied them. If you run more than one provider, register a single hook and branch on the provider argument it receives.

1
2
RegisterIAPPurchaseNotification
RegisterIAPSubscriptionNotification

Related Pages