revenuecat

package module
v0.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 13, 2026 License: MIT Imports: 10 Imported by: 0

README

RevenueCat

PkgGoDev Test

Go package for interacting with the RevenueCat API v1 and the RevenueCat REST API v2. Inspired by the official TS/JS client

Installation

To install the RevenueCat Go SDK, use go get:

go get github.com/claywarren/revenuecat

Usage

REST API v1

All existing APIs use RevenueCat REST API v1 and remain unchanged.

package main

import (
	"fmt"

	"github.com/claywarren/revenuecat"
)

func main() {
	rc := revenuecat.New("apikey")
	sub, _ := rc.GetSubscriber("123")
	entitled := sub.IsEntitledTo("premium")

	fmt.Printf("user entitled: %t\n", entitled)
}
REST API v2

API v2 uses a separate client because its customer, entitlement, pagination, and error schemas are not v1 Subscriber schemas. Create the client with a v2 secret key and the RevenueCat project ID. The key needs the customer_information:customers:read permission for these operations.

package main

import (
	"context"
	"errors"
	"fmt"
	"os"
	"time"

	"github.com/claywarren/revenuecat"
)

func main() {
	rc := revenuecat.NewV2(
		os.Getenv("REVENUECAT_V2_SECRET_KEY"),
		os.Getenv("REVENUECAT_PROJECT_ID"),
	)

	customer, err := rc.GetCustomer(context.Background(), "app-user-id")
	if err != nil {
		var apiErr *revenuecat.V2Error
		if errors.As(err, &apiErr) && apiErr.Retryable {
			delay := apiErr.RetryAfter
			if apiErr.BackoffMilliseconds != nil {
				delay = time.Duration(*apiErr.BackoffMilliseconds) * time.Millisecond
			}
			fmt.Printf("RevenueCat asked us to retry after %s\n", delay)
		}
		panic(err)
	}
	fmt.Printf("customer: %s\n", customer.ID)

	// GetCustomer includes the first active-entitlement page. Use this method
	// when the entitlement check must be exhaustive across all pages.
	entitlements, err := rc.ListAllActiveEntitlements(context.Background(), customer.ID)
	if err != nil {
		panic(err)
	}
	for _, entitlement := range entitlements {
		if entitlement.EntitlementID == "premium" {
			fmt.Println("customer has premium access")
		}
	}
}

To fetch one page explicitly, use ListActiveEntitlements with V2ListOptions{StartingAfter: cursor, Limit: 20}. RevenueCat returns timestamps as Unix milliseconds; this package exposes them as time.Time or *time.Time. A nil V2ActiveEntitlement.ExpiresAt means the entitlement does not expire.

Migrating server-side checks from v1
  • Keep New and GetSubscriber for existing v1 call sites; adding v2 does not change their behavior.
  • Create a v2 secret key in RevenueCat with customer_information:customers:read; v1 keys do not authenticate to v2.
  • Pass the project ID (for example, proj1ab2c3d4) to NewV2 in addition to the secret key.
  • Replace assumptions about Subscriber.Entitlements with V2Customer.ActiveEntitlements or ListAllActiveEntitlements. The nested list on V2Customer can be paginated.
  • Handle *V2Error instead of the v1 *Error. In particular, honor Retryable, BackoffMilliseconds, and RetryAfter for rate limiting or transient failures.
  • A missing customer is a v2 resource_missing error. Unlike the v1 GetSubscriber endpoint, GetCustomer does not create a missing customer.
V2 public API
func NewV2(apiKey, projectID string, opts ...V2Option) *V2Client
func WithV2HTTPClient(client V2HTTPClient) V2Option
func WithV2APIURL(rawURL string) V2Option

func (c *V2Client) GetCustomer(ctx context.Context, customerID string) (V2Customer, error)
func (c *V2Client) ListActiveEntitlements(ctx context.Context, customerID string, opts *V2ListOptions) (V2ActiveEntitlementList, error)
func (c *V2Client) ListAllActiveEntitlements(ctx context.Context, customerID string) ([]V2ActiveEntitlement, error)

Response and support types are V2Customer, V2ExperimentEnrollment, V2CustomerAttribute, V2CustomerAttributeList, V2ActiveEntitlement, V2ActiveEntitlementList, V2ListOptions, V2Error, V2Option, and V2HTTPClient.

V1 client with options
package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/claywarren/revenuecat"
)

func main() {
	customClient := &http.Client{
		Timeout: 20 * time.Second,
	}

	rc := revenuecat.New("apikey", revenuecat.WithHTTPClient(customClient), revenuecat.WithSandboxEnabled(true))

	sub, _ := rc.GetSubscriber("123")
	entitled := sub.IsEntitledTo("premium")

	fmt.Printf("user entitled: %t\n", entitled)
}
Documentation

WithAPIURL is available for RevenueCat-owned API hosts and rejects non-HTTPS or non-RevenueCat URLs before sending authenticated requests.

For full documentation, see pkg.go.dev/github.com/claywarren/revenuecat

func (*Client) AddUserAttribution
func (c *Client) AddUserAttribution(userID string, network Network, data AttributionData) error

AddUserAttribution attaches attribution data to a subscriber from specific supported networks. RevenueCat documents this endpoint as deprecated. https://www.revenuecat.com/docs/api-v1#tag/customers/operation/subscribersattribution

func (*Client) CreatePurchase
func (c *Client) CreatePurchase(userID string, receipt string, opt *CreatePurchaseOptions) (Subscriber, error)

CreatePurchase records a purchase for a user from iOS, Android, Amazon, macOS, UIKit for Mac, Stripe, Roku, or Paddle and will create a user if they don't already exist. https://www.revenuecat.com/docs/api-v1#tag/transactions/operation/receipts

func (*Client) DeferGoogleSubscription
func (c *Client) DeferGoogleSubscription(userID string, id string, nextExpiry time.Time) (Subscriber, error)

DeferGoogleSubscription defers the purchase of a Google Subscription to a later date. https://www.revenuecat.com/docs/api-v1#defer-a-google-subscription

func (*Client) DeferGoogleSubscriptionByDays
func (c *Client) DeferGoogleSubscriptionByDays(userID string, id string, days int) (Subscriber, error)

DeferGoogleSubscriptionByDays defers a Google Subscription by a number of days. https://www.revenuecat.com/docs/api-v1#tag/transactions/operation/defer-a-google-subscription

func (*Client) DeleteOfferingOverride
func (c *Client) DeleteOfferingOverride(userID string) (Subscriber, error)

DeleteOfferingOverride reset the offering overrides back to the current offering for a specific user. https://www.revenuecat.com/docs/api-v1#delete-offering-override

func (*Client) DeleteSubscriber
func (c *Client) DeleteSubscriber(userID string) error

DeleteSubscriber permanently deletes a subscriber. https://www.revenuecat.com/docs/api-v1#subscribersapp_user_id

func (*Client) GetSubscriber
func (c *Client) GetSubscriber(userID string) (Subscriber, error)

GetSubscriber gets the latest subscriber info or creates one if it doesn't exist. https://www.revenuecat.com/docs/api-v1#subscribers

func (*Client) GetSubscriberWithPlatform
func (c *Client) GetSubscriberWithPlatform(userID string, platform string) (Subscriber, error)

GetSubscriberWithPlatform gets the latest subscriber info or creates one if it doesn't exist, updating the subscriber record's last_seen value for the platform provided. https://www.revenuecat.com/docs/api-v1#subscribers

func (*Client) GrantEntitlement
func (c *Client) GrantEntitlement(userID string, id string, duration Duration, startTime time.Time) (Subscriber, error)

GrantEntitlement grants a user a promotional entitlement. https://www.revenuecat.com/docs/api-v1#tag/entitlements/operation/grant-a-promotional-entitlement

func (*Client) GrantEntitlementUntil
func (c *Client) GrantEntitlementUntil(userID string, id string, endTime time.Time) (Subscriber, error)

GrantEntitlementUntil grants a user a promotional entitlement until a specific expiration time. https://www.revenuecat.com/docs/api-v1#tag/entitlements/operation/grant-a-promotional-entitlement

func (*Client) OverrideOffering
func (c *Client) OverrideOffering(userID string, offeringUUID string) (Subscriber, error)

OverrideOffering overrides the current Offering for a specific user. https://www.revenuecat.com/docs/api-v1#override-offering

func (*Client) CancelGoogleSubscription
func (c *Client) CancelGoogleSubscription(userID string, transactionID string) (Subscriber, error)

CancelGoogleSubscription cancels a Google subscription without immediately revoking access. https://www.revenuecat.com/docs/api-v1#tag/transactions/operation/cancel-a-google-subscription

func (*Client) ExtendAppStoreSubscription
func (c *Client) ExtendAppStoreSubscription(userID string, transactionID string, days int) (Subscriber, error)

ExtendAppStoreSubscription extends an App Store subscription renewal date. https://www.revenuecat.com/docs/api-v1#tag/transactions/operation/extend-an-app-store-subscription

func (*Client) RefundGooglePurchase
func (c *Client) RefundGooglePurchase(userID string, transactionID string) (Subscriber, error)

RefundGooglePurchase issues a refund for a Google transaction and revokes access. https://www.revenuecat.com/docs/api-v1#tag/transactions/operation/refund-a-google-purchase

func (*Client) RefundGoogleSubscription
func (c *Client) RefundGoogleSubscription(userID string, id string) (Subscriber, error)

RefundGoogleSubscription immediately revokes access to a Google Subscription and issues a refund for the last purchase. https://www.revenuecat.com/docs/api-v1#revoke-a-google-subscription

func (*Client) RevokeEntitlement
func (c *Client) RevokeEntitlement(userID string, id string) (Subscriber, error)

RevokeEntitlement revokes all promotional entitlements for a given entitlement identifier and app user ID. https://www.revenuecat.com/docs/api-v1#revoke-promotional-entitlements

func (*Client) UpdateSubscriberAttributes
func (c *Client) UpdateSubscriberAttributes(userID string, attributes map[string]SubscriberAttribute) error

UpdateSubscriberAttributes updates subscriber attributes for a user. https://www.revenuecat.com/docs/api-v1#update-subscriber-attributes

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AttributionData

type AttributionData struct {
	IDFA           string `json:"rc_idfa,omitempty"`
	PlayServicesID string `json:"rc_gps_adid,omitempty"`
}

AttributionData holds the identifier value for either the App Store or Play Services.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client makes authorized calls to the RevenueCat API.

func New

func New(apiKey string, opts ...Option) *Client

New returns a new *Client for the provided API key. For more information on authentication, see https://docs.revenuecat.com/docs/authentication.

func (*Client) AddUserAttribution

func (c *Client) AddUserAttribution(userID string, network Network, data AttributionData) error

AddUserAttribution attaches attribution data to a subscriber from specific supported networks. https://www.revenuecat.com/docs/api-v1#subscribersattribution

func (*Client) CancelGoogleSubscription added in v0.11.0

func (c *Client) CancelGoogleSubscription(userID string, transactionID string) (Subscriber, error)

CancelGoogleSubscription cancels a Google subscription without immediately revoking access. https://www.revenuecat.com/docs/api-v1#tag/transactions/operation/cancel-a-google-subscription

func (*Client) CreatePurchase

func (c *Client) CreatePurchase(userID string, receipt string, opt *CreatePurchaseOptions) (Subscriber, error)

CreatePurchase records a purchase for a user from iOS, Android, or Stripe and will create a user if they don't already exist. https://www.revenuecat.com/docs/api-v1#receipts

func (*Client) DeferGoogleSubscription

func (c *Client) DeferGoogleSubscription(userID string, id string, nextExpiry time.Time) (Subscriber, error)

DeferGoogleSubscription defers the purchase of a Google Subscription to a later date. https://www.revenuecat.com/docs/api-v1#defer-a-google-subscription

func (*Client) DeferGoogleSubscriptionByDays added in v0.11.0

func (c *Client) DeferGoogleSubscriptionByDays(userID string, id string, days int) (Subscriber, error)

DeferGoogleSubscriptionByDays defers a Google Subscription by a number of days. https://www.revenuecat.com/docs/api-v1#tag/transactions/operation/defer-a-google-subscription

func (*Client) DeleteOfferingOverride

func (c *Client) DeleteOfferingOverride(userID string) (Subscriber, error)

DeleteOfferingOverride reset the offering overrides back to the current offering for a specific user. https://www.revenuecat.com/docs/api-v1#delete-offering-override

func (*Client) DeleteSubscriber

func (c *Client) DeleteSubscriber(userID string) error

DeleteSubscriber permanently deletes a subscriber. https://www.revenuecat.com/docs/api-v1#subscribersapp_user_id

func (*Client) ExtendAppStoreSubscription added in v0.11.0

func (c *Client) ExtendAppStoreSubscription(userID string, transactionID string, days int) (Subscriber, error)

ExtendAppStoreSubscription extends an App Store subscription renewal date. https://www.revenuecat.com/docs/api-v1#tag/transactions/operation/extend-an-app-store-subscription

func (*Client) GetOfferings

func (c *Client) GetOfferings(userID string) (*Offerings, error)

GetOfferings gets the offerings for a specific user. https://www.revenuecat.com/docs/api-v1#get-offerings

func (*Client) GetSubscriber

func (c *Client) GetSubscriber(userID string) (Subscriber, error)

GetSubscriber gets the latest subscriber info or creates one if it doesn't exist. https://www.revenuecat.com/docs/api-v1#subscribers

func (*Client) GetSubscriberWithPlatform

func (c *Client) GetSubscriberWithPlatform(userID string, platform string) (Subscriber, error)

GetSubscriberWithPlatform gets the latest subscriber info or creates one if it doesn't exist, updating the subscriber record's last_seen value for the platform provided. https://www.revenuecat.com/docs/api-v1#subscribers

func (*Client) GrantEntitlement

func (c *Client) GrantEntitlement(userID string, id string, duration Duration, startTime time.Time) (Subscriber, error)

GrantEntitlement grants a user a promotional entitlement. https://www.revenuecat.com/docs/api-v1#grant-a-promotional-entitlement

func (*Client) GrantEntitlementUntil added in v0.11.0

func (c *Client) GrantEntitlementUntil(userID string, id string, endTime time.Time) (Subscriber, error)

GrantEntitlementUntil grants a user a promotional entitlement until a specific expiration time. https://www.revenuecat.com/docs/api-v1#tag/entitlements/operation/grant-a-promotional-entitlement

func (*Client) OverrideOffering

func (c *Client) OverrideOffering(userID string, offeringUUID string) (Subscriber, error)

OverrideOffering overrides the current Offering for a specific user. https://www.revenuecat.com/docs/api-v1#override-offering

func (*Client) RefundGooglePurchase added in v0.11.0

func (c *Client) RefundGooglePurchase(userID string, transactionID string) (Subscriber, error)

RefundGooglePurchase issues a refund for a Google transaction and revokes access. https://www.revenuecat.com/docs/api-v1#tag/transactions/operation/refund-a-google-purchase

func (*Client) RefundGoogleSubscription

func (c *Client) RefundGoogleSubscription(userID string, id string) (Subscriber, error)

RefundGoogleSubscription immediately revokes access to a Google Subscription and issues a refund for the last purchase. https://www.revenuecat.com/docs/api-v1#revoke-a-google-subscription

func (*Client) RevokeEntitlement

func (c *Client) RevokeEntitlement(userID string, id string) (Subscriber, error)

RevokeEntitlement revokes all promotional entitlements for a given entitlement identifier and app user ID. https://www.revenuecat.com/docs/api-v1#revoke-promotional-entitlements

func (*Client) UpdateSubscriberAttributes

func (c *Client) UpdateSubscriberAttributes(userID string, attributes map[string]SubscriberAttribute) error

UpdateSubscriberAttributes updates subscriber attributes for a user. https://www.revenuecat.com/docs/api-v1#update-subscriber-attributes

type CreatePurchaseOptions

type CreatePurchaseOptions struct {
	Platform string `json:"-"`

	ProductID                   string                         `json:"product_id,omitempty"`
	Price                       float32                        `json:"price,omitempty"`
	Currency                    string                         `json:"currency,omitempty"`
	PaymentMode                 string                         `json:"payment_mode,omitempty"`
	IntroductoryPrice           float32                        `json:"introductory_price,omitempty"`
	IsRestore                   bool                           `json:"is_restore,omitempty"`
	PresentedOfferingIdentifier string                         `json:"presented_offering_identifier,omitempty"`
	Attributes                  map[string]SubscriberAttribute `json:"attributes,omitempty"`
}

CreatePurchaseOptions holds the optional values for creating a purchase. https://www.revenuecat.com/docs/api-v1#receipts

type Duration

type Duration string

Duration holds a predefined entitlement duration.

const (
	Daily      Duration = "daily"
	Weekly     Duration = "weekly"
	Monthly    Duration = "monthly"
	TwoMonth   Duration = "two_month"
	ThreeMonth Duration = "three_month"
	SixMonth   Duration = "six_month"
	Yearly     Duration = "yearly"
	Lifetime   Duration = "lifetime"
)

https://www.revenuecat.com/docs/api-v1#duration-values

type Entitlement

type Entitlement struct {
	ExpiresDate            *time.Time `json:"expires_date"`
	GracePeriodExpiresDate *time.Time `json:"grace_period_expires_date"`
	PurchaseDate           time.Time  `json:"purchase_date"`
	ProductIdentifier      string     `json:"product_identifier"`
	ProductPlanIdentifier  string     `json:"product_plan_identifier"`
}

https://www.revenuecat.com/docs/api-v1#the-entitlement-object

type Error

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

Error represents an error returned by RevenueCat

func (Error) Error

func (err Error) Error() string

type Network

type Network int

Network represents a predefined attribution channel.

const (
	AppleSearchAds Network = iota
	Adjust
	AppsFlyer
	Branch
	Tenjin
	Facebook
)

https://www.revenuecat.com/docs/api-v1#attribution-source-network-codes

type NonSubscription

type NonSubscription struct {
	ID           string    `json:"id"`
	PurchaseDate time.Time `json:"purchase_date"`
	Store        Store     `json:"store"`
	IsSandbox    bool      `json:"is_sandbox"`
}

https://www.revenuecat.com/docs/api-v1#section-the-non-subscription-object

type Offering

type Offering struct {
	Description string                 `json:"description"`
	Identifier  string                 `json:"identifier"`
	Packages    []Package              `json:"packages"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

Offering holds an offering.

type Offerings

type Offerings struct {
	Current *Offering           `json:"current"`
	All     map[string]Offering `json:"all"`
}

Offerings holds the offerings for a user.

type Option

type Option func(*Client)

func WithAPIURL

func WithAPIURL(rawURL string) Option

WithAPIURL - Option to set the API URL. Custom URLs must use HTTPS and a RevenueCat-owned host.

func WithHTTPClient

func WithHTTPClient(client doer) Option

WithHTTPClient - Option to set the HTTP client

func WithSandboxEnabled

func WithSandboxEnabled(enabled bool) Option

WithSandboxEnabled - Option to enable or disable sandbox mode

type OwnershipType

type OwnershipType string

OwnershipType holds the predefined values for a subscription ownership type.

const (
	PurchasedOwnershipType    OwnershipType = "PURCHASED"
	FamilySharedOwnershipType OwnershipType = "FAMILY_SHARED"
)

type Package

type Package struct {
	Identifier                string                 `json:"identifier"`
	PlatformProductIdentifier string                 `json:"platform_product_identifier"`
	PackageType               PackageType            `json:"package_type"`
	Metadata                  map[string]interface{} `json:"metadata,omitempty"`
}

Package holds a package.

type PackageType

type PackageType string

PackageType holds the predefined values for a package type.

const (
	UnknownPackageType    PackageType = "UNKNOWN"
	CustomPackageType     PackageType = "CUSTOM"
	LifetimePackageType   PackageType = "LIFETIME"
	AnnualPackageType     PackageType = "ANNUAL"
	SixMonthPackageType   PackageType = "SIX_MONTH"
	ThreeMonthPackageType PackageType = "THREE_MONTH"
	TwoMonthPackageType   PackageType = "TWO_MONTH"
	MonthlyPackageType    PackageType = "MONTHLY"
	WeeklyPackageType     PackageType = "WEEKLY"
)

https://docs.revenuecat.com/docs/displaying-products#package-types

type PeriodType

type PeriodType string

PeriodType holds the predefined values for a subscription period.

const (
	NormalPeriodType PeriodType = "normal"
	TrialPeriodType  PeriodType = "trial"
	IntroPeriodType  PeriodType = "intro"
)

https://www.revenuecat.com/docs/api-v1#the-subscription-object

type Store

type Store string

Store holds the predefined values for a store.

const (
	AppStore         Store = "app_store"
	MacAppStore      Store = "mac_app_store"
	PlayStore        Store = "play_store"
	StripeStore      Store = "stripe"
	PromotionalStore Store = "promotional"
)

https://www.revenuecat.com/docs/api-v1#the-subscription-object

type Subscriber

type Subscriber struct {
	OriginalAppUserID          string                         `json:"original_app_user_id"`
	OriginalApplicationVersion *string                        `json:"original_application_version"`
	FirstSeen                  time.Time                      `json:"first_seen"`
	LastSeen                   time.Time                      `json:"last_seen"`
	ManagementURL              *string                        `json:"management_url"`
	Entitlements               map[string]Entitlement         `json:"entitlements"`
	Subscriptions              map[string]Subscription        `json:"subscriptions"`
	NonSubscriptions           map[string][]NonSubscription   `json:"non_subscriptions"`
	SubscriberAttributes       map[string]SubscriberAttribute `json:"subscriber_attributes"`
}

Subscriber holds a subscriber returned by the RevenueCat API.

func (Subscriber) ActiveSubscriptions

func (s Subscriber) ActiveSubscriptions() []string

ActiveSubscriptions returns the identifiers of all active subscriptions.

func (Subscriber) AllPurchasedProductIdentifiers

func (s Subscriber) AllPurchasedProductIdentifiers() []string

AllPurchasedProductIdentifiers returns the identifiers of all products ever purchased.

func (Subscriber) IsEntitledTo

func (s Subscriber) IsEntitledTo(entitlement string) bool

IsEntitledTo returns true if the Subscriber has the given entitlement.

type SubscriberAttribute

type SubscriberAttribute struct {
	Value     string
	UpdatedAt time.Time
}

https://www.revenuecat.com/docs/api-v1#section-the-subscriber-attribute-object

func (SubscriberAttribute) MarshalJSON

func (attr SubscriberAttribute) MarshalJSON() ([]byte, error)

func (*SubscriberAttribute) UnmarshalJSON

func (attr *SubscriberAttribute) UnmarshalJSON(data []byte) error

type Subscription

type Subscription struct {
	ExpiresDate             *time.Time    `json:"expires_date"`
	PurchaseDate            time.Time     `json:"purchase_date"`
	OriginalPurchaseDate    time.Time     `json:"original_purchase_date"`
	PeriodType              PeriodType    `json:"period_type"`
	Store                   Store         `json:"store"`
	IsSandbox               bool          `json:"is_sandbox"`
	UnsubscribeDetectedAt   *time.Time    `json:"unsubscribe_detected_at"`
	BillingIssuesDetectedAt *time.Time    `json:"billing_issues_detected_at"`
	AutoResumeDate          *time.Time    `json:"auto_resume_date"`
	GracePeriodExpiresDate  *time.Time    `json:"grace_period_expires_date"`
	RefundedAt              *time.Time    `json:"refunded_at"`
	OwnershipType           OwnershipType `json:"ownership_type"`
	StoreTransactionID      string        `json:"store_transaction_id"`
	ProductPlanIdentifier   string        `json:"product_plan_identifier"`
}

https://www.revenuecat.com/docs/api-v1#the-subscription-object

type V2ActiveEntitlement added in v0.13.0

type V2ActiveEntitlement struct {
	Object        string     `json:"object"`
	EntitlementID string     `json:"entitlement_id"`
	ExpiresAt     *time.Time `json:"-"`
}

V2ActiveEntitlement is an entitlement currently granting a customer access. A nil ExpiresAt represents non-expiring access.

func (*V2ActiveEntitlement) UnmarshalJSON added in v0.13.0

func (entitlement *V2ActiveEntitlement) UnmarshalJSON(data []byte) error

type V2ActiveEntitlementList added in v0.13.0

type V2ActiveEntitlementList struct {
	Object   string                `json:"object"`
	Items    []V2ActiveEntitlement `json:"items"`
	NextPage *string               `json:"next_page"`
	URL      string                `json:"url"`
}

V2ActiveEntitlementList is one page of a customer's active entitlements.

type V2Client added in v0.13.0

type V2Client struct {
	// contains filtered or unexported fields
}

V2Client makes authorized calls to the RevenueCat REST API v2 for one project. It is independent from Client, which continues to use the REST API v1.

func NewV2 added in v0.13.0

func NewV2(apiKey string, projectID string, opts ...V2Option) *V2Client

NewV2 returns a client for the provided v2 secret API key and RevenueCat project ID. The key must have the customer_information:customers:read permission for the customer operations in this package.

func (*V2Client) GetCustomer added in v0.13.0

func (c *V2Client) GetCustomer(ctx context.Context, customerID string) (V2Customer, error)

GetCustomer gets a v2 customer, including the first page of active entitlements. Unlike the v1 GetSubscriber endpoint, a missing customer produces a resource_missing V2Error instead of creating one.

func (*V2Client) ListActiveEntitlements added in v0.13.0

func (c *V2Client) ListActiveEntitlements(ctx context.Context, customerID string, opts *V2ListOptions) (V2ActiveEntitlementList, error)

ListActiveEntitlements gets one page of a customer's active entitlements.

func (*V2Client) ListAllActiveEntitlements added in v0.13.0

func (c *V2Client) ListAllActiveEntitlements(ctx context.Context, customerID string) ([]V2ActiveEntitlement, error)

ListAllActiveEntitlements follows RevenueCat's cursor pagination until all currently active entitlements for the customer have been returned.

type V2Customer added in v0.13.0

type V2Customer struct {
	Object                  string                   `json:"object"`
	ID                      string                   `json:"id"`
	ProjectID               string                   `json:"project_id"`
	FirstSeenAt             time.Time                `json:"-"`
	LastSeenAt              *time.Time               `json:"-"`
	LastSeenAppVersion      *string                  `json:"last_seen_app_version"`
	LastSeenCountry         *string                  `json:"last_seen_country"`
	LastSeenPlatform        *string                  `json:"last_seen_platform"`
	LastSeenPlatformVersion *string                  `json:"last_seen_platform_version"`
	ActiveEntitlements      *V2ActiveEntitlementList `json:"active_entitlements,omitempty"`
	Experiment              *V2ExperimentEnrollment  `json:"experiment,omitempty"`
	Attributes              *V2CustomerAttributeList `json:"attributes,omitempty"`
}

V2Customer is a RevenueCat REST API v2 customer. It intentionally does not alias or embed the v1 Subscriber type because the APIs have different data and pagination semantics.

func (*V2Customer) UnmarshalJSON added in v0.13.0

func (customer *V2Customer) UnmarshalJSON(data []byte) error

type V2CustomerAttribute added in v0.13.0

type V2CustomerAttribute struct {
	Object    string    `json:"object"`
	Name      string    `json:"name"`
	Value     *string   `json:"value"`
	UpdatedAt time.Time `json:"-"`
}

V2CustomerAttribute is an attribute returned by the v2 customer API.

func (*V2CustomerAttribute) UnmarshalJSON added in v0.13.0

func (attribute *V2CustomerAttribute) UnmarshalJSON(data []byte) error

type V2CustomerAttributeList added in v0.13.0

type V2CustomerAttributeList struct {
	Object   string                `json:"object"`
	Items    []V2CustomerAttribute `json:"items"`
	NextPage *string               `json:"next_page"`
	URL      string                `json:"url"`
}

V2CustomerAttributeList is the paginated v2 representation of attributes.

type V2Error added in v0.13.0

type V2Error struct {
	Object              string        `json:"object"`
	Type                string        `json:"type"`
	Param               *string       `json:"param"`
	DocURL              string        `json:"doc_url"`
	Message             string        `json:"message"`
	Retryable           bool          `json:"retryable"`
	BackoffMilliseconds *int64        `json:"backoff_ms"`
	ReferencedObjectIDs []string      `json:"referenced_object_ids"`
	StatusCode          int           `json:"-"`
	RetryAfter          time.Duration `json:"-"`
}

V2Error is an error response from the RevenueCat REST API v2.

func (V2Error) Error added in v0.13.0

func (err V2Error) Error() string

type V2ExperimentEnrollment added in v0.13.0

type V2ExperimentEnrollment struct {
	Object  string `json:"object"`
	ID      string `json:"id"`
	Name    string `json:"name"`
	Variant string `json:"variant"`
}

V2ExperimentEnrollment describes a customer's v2 experiment enrollment.

type V2HTTPClient added in v0.13.0

type V2HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

V2HTTPClient is the subset of http.Client used by V2Client.

type V2ListOptions added in v0.13.0

type V2ListOptions struct {
	StartingAfter string
	Limit         int
}

V2ListOptions controls cursor pagination for v2 list endpoints. Limit is omitted when zero, allowing RevenueCat's default (currently 20) to apply.

type V2Option added in v0.13.0

type V2Option func(*V2Client)

V2Option configures a V2Client.

func WithV2APIURL added in v0.13.0

func WithV2APIURL(rawURL string) V2Option

WithV2APIURL sets the v2 API base URL. Custom URLs must use HTTPS and a RevenueCat-owned host.

func WithV2HTTPClient added in v0.13.0

func WithV2HTTPClient(client V2HTTPClient) V2Option

WithV2HTTPClient sets the HTTP client used by a V2Client.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL