Skip to content
Longplay
Docs
Browse docs / Go

Go

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

Markdown
API v1Updated

Install#

terminalShell
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.

Related: Installation details

Client#

main.goGo
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.

Methods#

Every method takes a `context.Context` and returns a response pointer and an `error`.
MethodInputs and behaviorScope
GetOrCreateCustomerExternalUserID or email; optional profile and fingerprint, existing profiles unchanged.customers:write
GetCustomerLookupByID or LookupByExternalUserID.customers:read
ListCustomersExplicit filters, offset and limit; inspect HasMore.customers:read
UpdateCustomerLookup, a retained RequestID and a partial Patch; change tags with TagChanges.customers:write
ReadHoldingsCustomer ID and optional Entity ID.entitlements:read
CheckEntitlementCustomer and a positive decimal-string Feature requirement.entitlements:read
TrackUsageCustomer and a command with exactly one of EventName or InternalFeatureID, plus a retained IdempotencyKey.credits:consume
SendMessageSendMessageParams with the Customer, retained request ID, channel content and expiry.messaging:write
ReadMessageReadMessageParams; read dispatch state and verified receipts by message ID.messaging:write

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

  • GetOrCreateCustomer

    Inputs and behavior
    ExternalUserID or email; optional profile and fingerprint, existing profiles unchanged.
    Scope
    customers:write
  • GetCustomer

    Inputs and behavior
    LookupByID or LookupByExternalUserID.
    Scope
    customers:read
  • ListCustomers

    Inputs and behavior
    Explicit filters, offset and limit; inspect HasMore.
    Scope
    customers:read
  • UpdateCustomer

    Inputs and behavior
    Lookup, a retained RequestID and a partial Patch; change tags with TagChanges.
    Scope
    customers:write
  • ReadHoldings

    Inputs and behavior
    Customer ID and optional Entity ID.
    Scope
    entitlements:read
  • CheckEntitlement

    Inputs and behavior
    Customer and a positive decimal-string Feature requirement.
    Scope
    entitlements:read
  • TrackUsage

    Inputs and behavior
    Customer and a command with exactly one of EventName or InternalFeatureID, plus a retained IdempotencyKey.
    Scope
    credits:consume
  • SendMessage

    Inputs and behavior
    SendMessageParams with the Customer, retained request ID, channel content and expiry.
    Scope
    messaging:write
  • ReadMessage

    Inputs and behavior
    ReadMessageParams; read dispatch state and verified receipts by message ID.
    Scope
    messaging:write

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.goGo
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.

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
AreaMethods
Customer messaging and installationsSendMessage, ReadMessage
Customers, Guests and SessionsGetOrCreateCustomer, GetCustomer, ListCustomers, UpdateCustomer, CreateSession, RevokeSessions, CreateGuestCustomer, ResumeGuestSession, ClaimGuestCustomer
Entitlements and product presentationCheckEntitlement, ResolveOffering, ResolvePaywall, ReadHoldings
Balances, usage and ledgerReadBalanceSource, AdjustBalance, ReadUsage, SetUsage, ManageBalanceGrant, ListBalanceGrants, ManageUsageEntity, ReadUsageAnalytics, ReadCreditAnalytics, SubmitUsageBatch, ReadUsageBatch, ReadLedger, ReadCreditStatement, QuoteBalance, TrackUsage, MutateBalance
SeatsReadSeats, ManageSeat
Subscriptions and paymentsSetupPayment, ReadPaymentSetup, VerifySubscriptions, PreviewAttach, Attach, ReadSubscriptionOperation, PreviewUpdate, Update, ReadSubscriptionUpdate, ListSubscriptions, ListPurchases, ListSubscriptionConflicts, RetrySubscriptionConflict, ManageSubscriptionTrial, ReadSubscriptionTrial, PreviewSubscriptionBatch, ConfirmSubscriptionBatch, ReadSubscriptionBatch, AbandonSubscriptionBatch, RecordMerchantEvent
Invoices, refunds and billingListInvoiceTemplates, PreviewInvoice, CreateInvoice, ManageInvoice, ReadInvoiceOperation, ListInvoices, GetInvoice, PreviewRefund, Refund, ReadRefund, ManageBillingLimits, ReadBillingInvoice, PrepareBillingAdjustment
Coupons, rewards and referralsGrantOffer, GrantModelBenefit, ReadModelBenefit
Feature flags, evaluation and eventsGetFeatures, EvaluateFeatures, TrackEvents
Native purchasesRestoreNativePurchase
AI pricingReadAiPricing
CLI and CIResolveContent, GetCodeReferenceConfig, SubmitCodeReferences

Methods by area

  • Customer messaging and installations

    Methods
    SendMessage, ReadMessage
  • Customers, Guests and Sessions

    Methods
    GetOrCreateCustomer, GetCustomer, ListCustomers, UpdateCustomer, CreateSession, RevokeSessions, CreateGuestCustomer, ResumeGuestSession, ClaimGuestCustomer
  • Entitlements and product presentation

    Methods
    CheckEntitlement, ResolveOffering, ResolvePaywall, ReadHoldings
  • Balances, usage and ledger

    Methods
    ReadBalanceSource, AdjustBalance, ReadUsage, SetUsage, ManageBalanceGrant, ListBalanceGrants, ManageUsageEntity, ReadUsageAnalytics, ReadCreditAnalytics, SubmitUsageBatch, ReadUsageBatch, ReadLedger, ReadCreditStatement, QuoteBalance, TrackUsage, MutateBalance
  • Seats

    Methods
    ReadSeats, ManageSeat
  • Subscriptions and payments

    Methods
    SetupPayment, ReadPaymentSetup, VerifySubscriptions, PreviewAttach, Attach, ReadSubscriptionOperation, PreviewUpdate, Update, ReadSubscriptionUpdate, ListSubscriptions, ListPurchases, ListSubscriptionConflicts, RetrySubscriptionConflict, ManageSubscriptionTrial, ReadSubscriptionTrial, PreviewSubscriptionBatch, ConfirmSubscriptionBatch, ReadSubscriptionBatch, AbandonSubscriptionBatch, RecordMerchantEvent
  • Invoices, refunds and billing

    Methods
    ListInvoiceTemplates, PreviewInvoice, CreateInvoice, ManageInvoice, ReadInvoiceOperation, ListInvoices, GetInvoice, PreviewRefund, Refund, ReadRefund, ManageBillingLimits, ReadBillingInvoice, PrepareBillingAdjustment
  • Coupons, rewards and referrals

    Methods
    GrantOffer, GrantModelBenefit, ReadModelBenefit
  • Feature flags, evaluation and events

    Methods
    GetFeatures, EvaluateFeatures, TrackEvents
  • Native purchases

    Methods
    RestoreNativePurchase
  • AI pricing

    Methods
    ReadAiPricing
  • CLI and CI

    Methods
    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.goGo
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})}

Related: Support matrix·All operations·Request conventions