# Go

A goroutine-safe server client for sessions, payments, invoices, balances, Customer messaging and Funnel decisions.

Last updated: 2026-11-06

[Web version](https://www.longplayai.com/docs/sdk/go)

<a id="install"></a>

## Install

**terminal**

```bash
SDK_VERSION="$(curl -fsS 'https://cdn.longplayai.com/sdk/longplay/stable?package=go')" &&
go get longplayai.com/sdk/go@v"$SDK_VERSION"
```

Resolve the latest stable release; go.mod and go.sum retain the exact version. Go 1.23+. Installs through Go's default module proxy and checksum database.

- [Installation details](https://www.longplayai.com/docs/install.md#go)

<a id="client"></a>

## Client

**main.go**

```go
package main

import (
	"context"
	"log"
	"os"

	longplay "longplayai.com/sdk/go"
)

func main() {
	client, err := longplay.NewClient(longplay.Config{
		APIKey:      os.Getenv("LONGPLAY_SERVER_KEY"),
		ProjectID:   os.Getenv("LONGPLAY_PROJECT_ID"),
		Environment: longplay.Sandbox,
		BaseURL:     os.Getenv("LONGPLAY_API_URL"),
	})
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	ctx := context.Background()
	customer, err := client.GetOrCreateCustomer(ctx, longplay.CreateCustomerParams{
		ExternalUserID: longplay.Ptr("merchant-user-123"),
	})
	if err != nil {
		log.Fatal(err)
	}

	access, err := client.CheckEntitlement(ctx, longplay.CheckEntitlementParams{
		CustomerID: customer.Customer.ID,
		Requirement: longplay.CheckEntitlementParamsRequirement{
			InternalFeatureID: os.Getenv("LONGPLAY_FEATURE_ID"),
			Quantity:          "1",
			Properties:        map[string]any{},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	if !access.Check.Allowed {
		return
	}

	usage, err := client.TrackUsage(ctx, longplay.TrackUsageParams{
		CustomerID: customer.Customer.ID,
		Command: longplay.TrackUsageParamsCommand{
			EventName:      longplay.Ptr("image_generated"),
			Quantity:       longplay.Ptr("1.25"),
			IdempotencyKey: "merchant-event-123",
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	for _, receipt := range usage.Receipts {
		log.Println("usage accepted:", receipt.Accepted)
	}
}
```

- A `nil` pointer omits an optional field; use `longplay.Ptr(value)` to send an explicit empty string, empty map or zero.
- Response structs and JSON names are generated from the public contract, with Go initialisms such as `CustomerID` and `RequestID`. Quantities and amounts stay decimal strings.
- `longplay.LookupByID(id)` and `longplay.LookupByExternalUserID(id)` build the lookup for `GetCustomer` and `UpdateCustomer`.

<a id="methods"></a>

## Methods

**Every method takes a `context.Context` and returns a response pointer and an `error`.**

| Method | Inputs and behavior | Scope |
| --- | --- | --- |
| `GetOrCreateCustomer` | `ExternalUserID` or email; optional profile and fingerprint, existing profiles unchanged. | `customers:write` |
| `GetCustomer` | `LookupByID` or `LookupByExternalUserID`. | `customers:read` |
| `ListCustomers` | Explicit filters, offset and limit; inspect `HasMore`. | `customers:read` |
| `UpdateCustomer` | Lookup, a retained `RequestID` and a partial `Patch`; change tags with `TagChanges`. | `customers:write` |
| `ReadHoldings` | Customer ID and optional Entity ID. | `entitlements:read` |
| `CheckEntitlement` | Customer and a positive decimal-string Feature requirement. | `entitlements:read` |
| `TrackUsage` | Customer and a command with exactly one of `EventName` or `InternalFeatureID`, plus a retained `IdempotencyKey`. | `credits:consume` |
| `SendMessage` | `SendMessageParams` with the Customer, retained request ID, channel content and expiry. | `messaging:write` |
| `ReadMessage` | `ReadMessageParams`; read dispatch state and verified receipts by message ID. | `messaging:write` |

<a id="context"></a>

## Concurrency, timeouts and errors

Reuse one client across goroutines. Cancellation and deadlines use ordinary contexts. `Config.Timeout` bounds the whole request and body read (default 10 seconds, maximum 120). `Close()` refuses new calls and releases idle connections; an injected `HTTPClient` is cloned and its transport stays caller-owned. Ambient proxies, cookies and redirects are not used.

**errors.go**

```go
package billing

import (
	"context"
	"errors"
	"log"

	longplay "longplayai.com/sdk/go"
)

func readHoldings(ctx context.Context, client *longplay.Client, customerID string) error {
	_, err := client.ReadHoldings(ctx, longplay.ReadHoldingsParams{CustomerID: customerID})
	var sdkError *longplay.Error
	if errors.As(err, &sdkError) {
		log.Println(sdkError.Code, sdkError.Status, sdkError.RequestID, sdkError.Recovery)
	}
	if errors.Is(err, context.Canceled) {
		// The caller cancelled. An accepted write may still have committed.
	}
	return err
}
```

`longplay.Error` exposes `Code`, `Status`, `RequestID`, `Retryable`, `Recovery`, and optional `Reason` and `RetryAfterSeconds`. The SDK never retries; after an unknown result, replay usage events and Customer updates with the original `IdempotencyKey`/`RequestID` and input.

<a id="other-operations"></a>

## Sessions and full coverage

The Go SDK provides methods for current Server-Key/mixed-credential operations, including sessions, payments, offers, invoices, balance management and Customer messaging. Reserved operations still return 501; check reference pages for other unsupported branches. Use the SDK's Funnel client for Funnel decisions. See available methods below and the full support matrix, which also includes reserved entries.

**Methods by area**

| Area | Methods |
| --- | --- |
| Customer messaging and installations | `SendMessage`, `ReadMessage` |
| Customers, Guests and Sessions | `GetOrCreateCustomer`, `GetCustomer`, `ListCustomers`, `UpdateCustomer`, `CreateSession`, `RevokeSessions`, `CreateGuestCustomer`, `ResumeGuestSession`, `ClaimGuestCustomer` |
| Entitlements and product presentation | `CheckEntitlement`, `ResolveOffering`, `ResolvePaywall`, `ReadHoldings` |
| Balances, usage and ledger | `ReadBalanceSource`, `AdjustBalance`, `ReadUsage`, `SetUsage`, `ManageBalanceGrant`, `ListBalanceGrants`, `ManageUsageEntity`, `ReadUsageAnalytics`, `ReadCreditAnalytics`, `SubmitUsageBatch`, `ReadUsageBatch`, `ReadLedger`, `ReadCreditStatement`, `QuoteBalance`, `TrackUsage`, `MutateBalance` |
| Seats | `ReadSeats`, `ManageSeat` |
| Subscriptions and payments | `SetupPayment`, `ReadPaymentSetup`, `VerifySubscriptions`, `PreviewAttach`, `Attach`, `ReadSubscriptionOperation`, `PreviewUpdate`, `Update`, `ReadSubscriptionUpdate`, `ListSubscriptions`, `ListPurchases`, `ListSubscriptionConflicts`, `RetrySubscriptionConflict`, `ManageSubscriptionTrial`, `ReadSubscriptionTrial`, `PreviewSubscriptionBatch`, `ConfirmSubscriptionBatch`, `ReadSubscriptionBatch`, `AbandonSubscriptionBatch`, `RecordMerchantEvent` |
| Invoices, refunds and billing | `ListInvoiceTemplates`, `PreviewInvoice`, `CreateInvoice`, `ManageInvoice`, `ReadInvoiceOperation`, `ListInvoices`, `GetInvoice`, `PreviewRefund`, `Refund`, `ReadRefund`, `ManageBillingLimits`, `ReadBillingInvoice`, `PrepareBillingAdjustment` |
| Coupons, rewards and referrals | `GrantOffer`, `GrantModelBenefit`, `ReadModelBenefit` |
| Feature flags, evaluation and events | `GetFeatures`, `EvaluateFeatures`, `TrackEvents` |
| Native purchases | `RestoreNativePurchase` |
| AI pricing | `ReadAiPricing` |
| CLI and CI | `ResolveContent`, `GetCodeReferenceConfig`, `SubmitCodeReferences` |

After authenticating the user and resolving their Customer on your backend, issue the session with a Server Key holding `sessions:create`. Return the complete session, including `customerId`, `sessionId`, `accessToken`, `refreshToken`, `expiresAt` and `refreshExpiresAt`, to that user's frontend and pass it to `identify(session)`; the frontend SDK handles subsequent refreshes.

**sessions.go**

```go
package sessions

import (
	"context"

	longplay "longplayai.com/sdk/go"
)

// Resolve customerID from your authenticated user on the backend.
// Return the complete session to the same user's browser or app.
func IssueCustomerSession(ctx context.Context, client *longplay.Client, customerID string) (*longplay.CreateSessionResponse, error) {
	return client.CreateSession(ctx, longplay.CreateSessionParams{CustomerID: customerID})
}
```

- [Support matrix](https://www.longplayai.com/docs/guides/platforms.md)
- [All operations](https://www.longplayai.com/docs/api/operations.md)
- [Request conventions](https://www.longplayai.com/docs/api.md)
