Check access from your backend

Gate server-side features on a customer's active perk grants.

Use the Go library to decide, on your server, whether a customer may use a feature. The check asks Voidhash for the customer's active perk grants, so nothing a customer reaches through your API depends on a client-side decision. Set up the Go library with a secret key first.

Check a perk

HasActivePerk answers one question: does this customer hold an active grant for this perk? The handler below gates an export route on the premium perk.

server/routes/export.go
func exportHandler(voidhash *voidhash.Client) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        hasPremium, err := voidhash.Entitlements.HasActivePerk(r.Context(), &voidhash.HasActivePerkParams{
            DistinctID: userIDFrom(r),
            PerkSlug:   voidhash.String("premium"),
        })
        if err != nil {
            http.Error(w, "upstream error", http.StatusInternalServerError)
            return
        }

        if !hasPremium {
            w.WriteHeader(http.StatusPaymentRequired)
            json.NewEncoder(w).Encode(map[string]string{"error": "premium_required"})
            return
        }

        buildExport(w, r, userIDFrom(r))
    }
}

DistinctID is the same identifier your app passed to identify(). Set exactly one of PerkID or PerkSlug. If you set both or neither, the call returns ErrConfiguration before any request is made.

Checking by PerkSlug is convenient, but it costs one extra request (Perks.ListPerks) to resolve the slug to an id. On a hot path, look the id up once when your server starts and set PerkID instead.

An unknown customer has no access

HasActivePerk returns false when Voidhash has never seen the DistinctID, and when the PerkSlug matches no perk. It does not hide authentication, authorization, 5xx, or transport failures. Those return an error, so a mistyped secret key can never look like "nobody has premium".

Read the grants yourself

HasActivePerk only returns a boolean. When you need to render an account page, show an expiry date, or branch on where access came from, read the grants directly.

grants, err := voidhash.Entitlements.GetGrantsByDistinctID(ctx, "user_123")

Each grant has these fields.

FieldTypeDescription
PerkIDstringThe perk this grant is for. Match it against the perk you care about.
Status"active"|"expired"Only active grants confer access.
ExpiresAt*time.Timenil means the grant never expires.
Source"subscription"|"purchase"|"manual"How the customer obtained the grant.
SourceIDstringThe subscription or purchase behind the grant. Empty when there is no backing source.
SourcePersonIDstringThe person who holds the source. On shared plans this differs from the person you asked about.

Unlike HasActivePerk, this call treats an unknown DistinctID as an error. That leaves the decision to you: whether "never seen" and "seen, but bought nothing" should mean the same thing.

If you already hold a person id, the same lookup is available as two separate calls.

person, err := voidhash.Persons.GetPersonByDistinctID(ctx, "user_123")

entitlements, err := voidhash.Persons.GetPersonEntitlements(ctx, person.PersonID)

Person is intentionally thin. It carries PersonID, DistinctID, Email, and Name, because it identifies the customer. It does not describe what they paid for.

Handle errors deliberately

When the API rejects a call, the error is a *voidhash.APIError. It carries the HTTP status and the decoded server error, and its Tag field is stable, so you can switch on it. Transport failures (DNS, TLS, timeouts) return a plain error that wraps *url.Error instead.

The example below treats an unknown person as "no access", treats a bad key as your own bug, returns every other API error as is, and treats a transport failure as an unknown answer.

grants, err := voidhash.Entitlements.GetGrantsByDistinctID(ctx, "user_123")
if err != nil {
    var apiErr *voidhash.APIError
    if errors.As(err, &apiErr) {
        switch apiErr.Tag {
        case "Api/PersonNotFoundError":
            // Never identified from a client: nothing was ever bought.
            return false
        case "Api/NotAuthenticatedError", "Api/ActionForbiddenError":
            // Our key is wrong. Our bug, not the customer's. Do not lock them out.
            return fmt.Errorf("voidhash secret key is invalid or lacks access: %w", apiErr)
        default:
            return err
        }
    }

    // Transport failure: unknown, not "no access".
    // Serve the last known good value or fail the request.
    return err
}

hasPremium := false
for _, grant := range grants.Grants {
    if grant.PerkID == premiumPerkID && grant.Status == "active" {
        hasPremium = true
    }
}

The tags you are most likely to see are Api/NotAuthenticatedError (401), Api/ActionForbiddenError (403), Api/PersonNotFoundError (404), Api/WebhookEndpointNotFoundError (404), and Api/WebhookValidationError (400).

Live and development data

Grants are scoped to an environment. The server picks the scope from the x-environment request header.

x-environmentGrants returned
absent or productionReal purchases, from both store production and store sandbox.
developmentOnly simulated purchases made by an SDK in a debug build.
allBoth of the above.

The library never sends this header for you, so a plain client always reads production and sandbox grants. To read development purchases, create a second client that sets the header.

voidhashDevelopment, err := voidhash.New(
    os.Getenv("VOIDHASH_SECRET_KEY"),
    voidhash.WithHeader("x-environment", "development"),
)

Secret keys are not scoped to an environment. Which key you use does not change the answer. Only the header does.

Any other value silently means production

An unrecognized x-environment value falls back to production instead of failing. Never wire the header directly to a variable like GO_ENV. A value of "test" would quietly read production grants.

Caching and failures

The library does not cache, retry, or de-duplicate. Every call is a live HTTP round trip.

If you check access on every request, cache the result yourself for a short window and refresh it in the background. 60 seconds is a reasonable starting point. A single-flight wrapper (golang.org/x/sync/singleflight) in front of the cache collapses concurrent checks for the same person into one request.

When a call fails with a transport error or a 5xx, treat the answer as unknown, not as no access. Serve the last known good value, or fail the request. Revoking a paying customer's access because of a network blip is worse than serving a slightly stale cache.

To keep the cache warm without polling, subscribe to webhooks and invalidate the cached entry when a subscription or purchase event arrives for that person.

Next steps