Developer-friendly & type-safe Go SDK specifically catered to leverage github.com/polarsource/polar-go API.
Important
This SDK is not yet ready for production use. To complete setup please follow the steps outlined in your workspace. Delete this section before > publishing to a package manager.
Polar API: Polar HTTP and Webhooks API
Read the docs at https://docs.polar.sh/api
To add the SDK as a dependency to your project:
go get github.com/polarsource/polar-go
package main
import (
"context"
polargo "github.com/polarsource/polar-go"
"github.com/polarsource/polar-go/models/components"
"github.com/polarsource/polar-go/types"
"log"
)
func main() {
ctx := context.Background()
s := polargo.New()
res, err := s.EndpointcheckoutCreatedPost(ctx, components.WebhookCheckoutCreatedPayload{
Data: components.Checkout{
CreatedAt: types.MustTimeFromString("2024-11-12T14:26:42.882Z"),
ModifiedAt: types.MustNewTimeFromString("2023-05-28T05:08:06.235Z"),
ID: "<value>",
PaymentProcessor: components.PaymentProcessorStripe,
Status: components.CheckoutStatusFailed,
ClientSecret: "<value>",
URL: "https://heavy-beret.com/",
ExpiresAt: types.MustTimeFromString("2022-02-25T02:26:48.460Z"),
SuccessURL: "https://sardonic-final.info/",
EmbedOrigin: polargo.String("<value>"),
Amount: polargo.Int64(962818),
TaxAmount: polargo.Int64(6400),
Currency: polargo.String("Yen"),
SubtotalAmount: polargo.Int64(648726),
TotalAmount: polargo.Int64(210702),
ProductID: "<value>",
ProductPriceID: "<value>",
DiscountID: polargo.String("<value>"),
AllowDiscountCodes: true,
IsDiscountApplicable: false,
IsFreeProductPrice: false,
IsPaymentRequired: false,
IsPaymentSetupRequired: false,
IsPaymentFormRequired: false,
CustomerID: polargo.String("<value>"),
CustomerName: polargo.String("<value>"),
CustomerEmail: polargo.String("Ryley_Erdman@hotmail.com"),
CustomerIPAddress: polargo.String("<value>"),
CustomerBillingAddress: &components.Address{
Country: "South Africa",
},
CustomerTaxID: polargo.String("<id>"),
PaymentProcessorMetadata: components.PaymentProcessorMetadata{},
Metadata: map[string]components.CheckoutMetadata{
"key": components.CreateCheckoutMetadataInteger(
18677,
),
"key1": components.CreateCheckoutMetadataInteger(
95370,
),
},
Product: components.CheckoutProduct{
CreatedAt: types.MustTimeFromString("2022-04-02T00:05:42.586Z"),
ModifiedAt: types.MustNewTimeFromString("2023-12-16T03:02:38.803Z"),
ID: "<value>",
Name: "<value>",
Description: polargo.String("for embarrassment untidy long-term near honestly separate yet"),
IsRecurring: true,
IsArchived: false,
OrganizationID: "<value>",
Prices: []components.ProductPrice{
components.CreateProductPriceProductPriceOneTime(
components.CreateProductPriceOneTimeProductPriceOneTimeCustom(
components.ProductPriceOneTimeCustom{
CreatedAt: types.MustTimeFromString("2024-02-07T04:30:48.802Z"),
ModifiedAt: types.MustNewTimeFromString("2025-06-25T22:47:14.264Z"),
ID: "<value>",
IsArchived: false,
ProductID: "<value>",
PriceCurrency: "<value>",
MinimumAmount: polargo.Int64(691423),
MaximumAmount: polargo.Int64(499526),
PresetAmount: polargo.Int64(18677),
},
),
),
},
Benefits: []components.BenefitBase{
components.BenefitBase{
CreatedAt: types.MustTimeFromString("2023-08-22T00:47:02.059Z"),
ModifiedAt: types.MustNewTimeFromString("2023-06-04T10:32:44.101Z"),
ID: "<value>",
Type: components.BenefitTypeLicenseKeys,
Description: "within jacket unless",
Selectable: false,
Deletable: false,
OrganizationID: "<value>",
},
},
Medias: []components.ProductMediaFileRead{
components.ProductMediaFileRead{
ID: "<value>",
OrganizationID: "<value>",
Name: "<value>",
Path: "/private/var",
MimeType: "<value>",
Size: 245189,
StorageVersion: polargo.String("<value>"),
ChecksumEtag: polargo.String("<value>"),
ChecksumSha256Base64: polargo.String("<value>"),
ChecksumSha256Hex: polargo.String("<value>"),
LastModifiedAt: types.MustNewTimeFromString("2022-11-03T15:00:03.276Z"),
Version: polargo.String("<value>"),
IsUploaded: false,
CreatedAt: types.MustTimeFromString("2024-06-07T13:47:02.365Z"),
SizeReadable: "<value>",
PublicURL: "https://webbed-experience.name/",
},
},
},
ProductPrice: components.CreateProductPriceProductPriceOneTime(
components.CreateProductPriceOneTimeProductPriceOneTimeFixed(
components.ProductPriceOneTimeFixed{
CreatedAt: types.MustTimeFromString("2023-04-02T00:05:42.586Z"),
ModifiedAt: types.MustNewTimeFromString("2024-12-15T03:02:38.803Z"),
ID: "<value>",
IsArchived: false,
ProductID: "<value>",
PriceCurrency: "<value>",
PriceAmount: 740296,
},
),
),
Discount: components.CreateCheckoutDiscountCheckoutDiscountPercentageOnceForeverDuration(
components.CheckoutDiscountPercentageOnceForeverDuration{
Duration: components.DiscountDurationRepeating,
Type: components.DiscountTypeFixed,
BasisPoints: 341163,
ID: "<value>",
Name: "<value>",
Code: polargo.String("<value>"),
},
),
SubscriptionID: polargo.String("<value>"),
AttachedCustomFields: []components.AttachedCustomField{
components.AttachedCustomField{
CustomFieldID: "<value>",
CustomField: components.CreateCustomFieldCustomFieldNumber(
components.CustomFieldNumber{
CreatedAt: types.MustTimeFromString("2025-06-23T16:57:50.081Z"),
ModifiedAt: types.MustNewTimeFromString("2024-12-13T18:25:33.693Z"),
ID: "<value>",
Metadata: map[string]components.CustomFieldNumberMetadata{
"key": components.CreateCustomFieldNumberMetadataStr(
"<value>",
),
},
Slug: "<value>",
Name: "<value>",
OrganizationID: "<value>",
Properties: components.CustomFieldNumberProperties{},
},
),
Order: 996863,
Required: false,
},
components.AttachedCustomField{
CustomFieldID: "<value>",
CustomField: components.CreateCustomFieldCustomFieldSelect(
components.CustomFieldSelect{
CreatedAt: types.MustTimeFromString("2023-04-26T22:34:57.487Z"),
ModifiedAt: types.MustNewTimeFromString("2023-08-07T19:57:51.694Z"),
ID: "<value>",
Metadata: map[string]components.CustomFieldSelectMetadata{
"key": components.CreateCustomFieldSelectMetadataInteger(
856200,
),
},
Slug: "<value>",
Name: "<value>",
OrganizationID: "<value>",
Properties: components.CustomFieldSelectProperties{
Options: []components.CustomFieldSelectOption{
components.CustomFieldSelectOption{
Value: "<value>",
Label: "<value>",
},
},
},
},
),
Order: 72589,
Required: true,
},
components.AttachedCustomField{
CustomFieldID: "<value>",
CustomField: components.CreateCustomFieldCustomFieldCheckbox(
components.CustomFieldCheckbox{
CreatedAt: types.MustTimeFromString("2025-05-25T15:20:50.694Z"),
ModifiedAt: types.MustNewTimeFromString("2024-11-27T14:29:40.329Z"),
ID: "<value>",
Metadata: map[string]components.CustomFieldCheckboxMetadata{
"key": components.CreateCustomFieldCheckboxMetadataBoolean(
false,
),
},
Slug: "<value>",
Name: "<value>",
OrganizationID: "<value>",
Properties: components.CustomFieldCheckboxProperties{},
},
),
Order: 161325,
Required: true,
},
},
CustomerMetadata: map[string]components.CustomerMetadata{
"key": components.CreateCustomerMetadataStr(
"<value>",
),
"key1": components.CreateCustomerMetadataStr(
"<value>",
),
},
},
})
if err != nil {
log.Fatal(err)
}
if res.Any != nil {
// handle response
}
}
This SDK supports the following security scheme globally:
Name | Type | Scheme | Environment Variable |
---|---|---|---|
AccessToken |
http | HTTP Bearer | POLAR_ACCESS_TOKEN |
You can configure it using the WithSecurity
option when initializing the SDK client instance. For example:
package main
import (
"context"
polargo "github.com/polarsource/polar-go"
"github.com/polarsource/polar-go/models/operations"
"log"
"os"
)
func main() {
ctx := context.Background()
s := polargo.New(
polargo.WithSecurity(os.Getenv("POLAR_ACCESS_TOKEN")),
)
res, err := s.ExternalOrganizations.List(ctx, operations.ExternalOrganizationsListRequest{})
if err != nil {
log.Fatal(err)
}
if res.ListResourceExternalOrganization != nil {
for {
// handle items
res, err = res.Next()
if err != nil {
// handle error
}
if res == nil {
break
}
}
}
}
Available methods
- List - List Benefits
- Create - Create Benefit
- Get - Get Benefit
- Update - Update Benefit
- Delete - Delete Benefit
- Grants - List Benefit Grants
- List - List Checkout Links
- Create - Create Checkout Link
- Get - Get Checkout Link
- Update - Update Checkout Link
- Delete - Delete Checkout Link
- List - List Checkout Sessions
- Create - Create Checkout Session
- Get - Get Checkout Session
- Update - Update Checkout Session
- ClientGet - Get Checkout Session from Client
- ClientUpdate - Update Checkout Session from Client
- ClientConfirm - Confirm Checkout Session from Client
- Get - Get Customer
- List - List License Keys
- Get - Get License Key
- Validate - Validate License Key
- Activate - Activate License Key
- Deactivate - Deactivate License Key
- Get - Get Organization
- List - List Subscriptions
- Get - Get Subscription
- Update - Update Subscription
- Cancel - Cancel Subscription
- List - List Customers
- Create - Create Customer
- Get - Get Customer
- Update - Update Customer
- Delete - Delete Customer
- Create - Create Customer Session
- List - List Custom Fields
- Create - Create Custom Field
- Get - Get Custom Field
- Update - Update Custom Field
- Delete - Delete Custom Field
- List - List Discounts
- Create - Create Discount
- Get - Get Discount
- Update - Update Discount
- Delete - Delete Discount
- List - List External Organizations
- List - List Files
- Create - Create File
- Uploaded - Complete File Upload
- Update - Update File
- Delete - Delete File
- List - List License Keys
- Get - Get License Key
- Update - Update License Key
- GetActivation - Get Activation
- Authorize - Authorize
- Token - Request Token
- Revoke - Revoke Token
- Introspect - Introspect Token
- Userinfo - Get User Info
- List - List Clients
- Create - Create Client
- Get - Get Client
- Update - Update Client
- Delete - Delete Client
- List - List Organizations
- Create - Create Organization
- Get - Get Organization
- Update - Update Organization
- List - List Products
- Create - Create Product
- Get - Get Product
- Update - Update Product
- UpdateBenefits - Update Product Benefits
Some of the endpoints in this SDK support pagination. To use pagination, you make your SDK calls as usual, but the
returned response object will have a Next
method that can be called to pull down the next group of results. If the
return value of Next
is nil
, then there are no more pages to be fetched.
Here's an example of one such pagination call:
package main
import (
"context"
polargo "github.com/polarsource/polar-go"
"github.com/polarsource/polar-go/models/operations"
"log"
"os"
)
func main() {
ctx := context.Background()
s := polargo.New(
polargo.WithSecurity(os.Getenv("POLAR_ACCESS_TOKEN")),
)
res, err := s.ExternalOrganizations.List(ctx, operations.ExternalOrganizationsListRequest{})
if err != nil {
log.Fatal(err)
}
if res.ListResourceExternalOrganization != nil {
for {
// handle items
res, err = res.Next()
if err != nil {
// handle error
}
if res == nil {
break
}
}
}
}
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retry.Config
object to the call by using the WithRetries
option:
package main
import (
"context"
polargo "github.com/polarsource/polar-go"
"github.com/polarsource/polar-go/models/operations"
"github.com/polarsource/polar-go/retry"
"log"
"models/operations"
"os"
)
func main() {
ctx := context.Background()
s := polargo.New(
polargo.WithSecurity(os.Getenv("POLAR_ACCESS_TOKEN")),
)
res, err := s.ExternalOrganizations.List(ctx, operations.ExternalOrganizationsListRequest{}, operations.WithRetries(
retry.Config{
Strategy: "backoff",
Backoff: &retry.BackoffStrategy{
InitialInterval: 1,
MaxInterval: 50,
Exponent: 1.1,
MaxElapsedTime: 100,
},
RetryConnectionErrors: false,
}))
if err != nil {
log.Fatal(err)
}
if res.ListResourceExternalOrganization != nil {
for {
// handle items
res, err = res.Next()
if err != nil {
// handle error
}
if res == nil {
break
}
}
}
}
If you'd like to override the default retry strategy for all operations that support retries, you can use the WithRetryConfig
option at SDK initialization:
package main
import (
"context"
polargo "github.com/polarsource/polar-go"
"github.com/polarsource/polar-go/models/operations"
"github.com/polarsource/polar-go/retry"
"log"
"os"
)
func main() {
ctx := context.Background()
s := polargo.New(
polargo.WithRetryConfig(
retry.Config{
Strategy: "backoff",
Backoff: &retry.BackoffStrategy{
InitialInterval: 1,
MaxInterval: 50,
Exponent: 1.1,
MaxElapsedTime: 100,
},
RetryConnectionErrors: false,
}),
polargo.WithSecurity(os.Getenv("POLAR_ACCESS_TOKEN")),
)
res, err := s.ExternalOrganizations.List(ctx, operations.ExternalOrganizationsListRequest{})
if err != nil {
log.Fatal(err)
}
if res.ListResourceExternalOrganization != nil {
for {
// handle items
res, err = res.Next()
if err != nil {
// handle error
}
if res == nil {
break
}
}
}
}
Handling errors in this SDK should largely match your expectations. All operations return a response object or an error, they will never return both.
By Default, an API error will return apierrors.APIError
. When custom error responses are specified for an operation, the SDK may also return their associated error. You can refer to respective Errors tables in SDK docs for more details on possible error types for each operation.
For example, the List
function may return the following errors:
Error Type | Status Code | Content Type |
---|---|---|
apierrors.HTTPValidationError | 422 | application/json |
apierrors.APIError | 4XX, 5XX | */* |
package main
import (
"context"
"errors"
polargo "github.com/polarsource/polar-go"
"github.com/polarsource/polar-go/models/apierrors"
"github.com/polarsource/polar-go/models/operations"
"log"
"os"
)
func main() {
ctx := context.Background()
s := polargo.New(
polargo.WithSecurity(os.Getenv("POLAR_ACCESS_TOKEN")),
)
res, err := s.ExternalOrganizations.List(ctx, operations.ExternalOrganizationsListRequest{})
if err != nil {
var e *apierrors.HTTPValidationError
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
var e *apierrors.APIError
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
}
}
You can override the default server globally using the WithServer(server string)
option when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:
Name | Server |
---|---|
production |
https://api.polar.sh |
sandbox |
https://sandbox-api.polar.sh |
package main
import (
"context"
polargo "github.com/polarsource/polar-go"
"github.com/polarsource/polar-go/models/operations"
"log"
"os"
)
func main() {
ctx := context.Background()
s := polargo.New(
polargo.WithServer("sandbox"),
polargo.WithSecurity(os.Getenv("POLAR_ACCESS_TOKEN")),
)
res, err := s.ExternalOrganizations.List(ctx, operations.ExternalOrganizationsListRequest{})
if err != nil {
log.Fatal(err)
}
if res.ListResourceExternalOrganization != nil {
for {
// handle items
res, err = res.Next()
if err != nil {
// handle error
}
if res == nil {
break
}
}
}
}
The default server can also be overridden globally using the WithServerURL(serverURL string)
option when initializing the SDK client instance. For example:
package main
import (
"context"
polargo "github.com/polarsource/polar-go"
"github.com/polarsource/polar-go/models/operations"
"log"
"os"
)
func main() {
ctx := context.Background()
s := polargo.New(
polargo.WithServerURL("https://api.polar.sh"),
polargo.WithSecurity(os.Getenv("POLAR_ACCESS_TOKEN")),
)
res, err := s.ExternalOrganizations.List(ctx, operations.ExternalOrganizationsListRequest{})
if err != nil {
log.Fatal(err)
}
if res.ListResourceExternalOrganization != nil {
for {
// handle items
res, err = res.Next()
if err != nil {
// handle error
}
if res == nil {
break
}
}
}
}
The Go SDK makes API calls that wrap an internal HTTP client. The requirements for the HTTP client are very simple. It must match this interface:
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
The built-in net/http
client satisfies this interface and a default client based on the built-in is provided by default. To replace this default with a client of your own, you can implement this interface yourself or provide your own client configured as desired. Here's a simple example, which adds a client with a 30 second timeout.
import (
"net/http"
"time"
"github.com/myorg/your-go-sdk"
)
var (
httpClient = &http.Client{Timeout: 30 * time.Second}
sdkClient = sdk.New(sdk.WithClient(httpClient))
)
This can be a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration.
This SDK defines the following custom types to assist with marshalling and unmarshalling data.
types.Date
is a wrapper around time.Time that allows for JSON marshaling a date string formatted as "2006-01-02".
d1 := types.NewDate(time.Now()) // returns *types.Date
d2 := types.DateFromTime(time.Now()) // returns types.Date
d3, err := types.NewDateFromString("2019-01-01") // returns *types.Date, error
d4, err := types.DateFromString("2019-01-01") // returns types.Date, error
d5 := types.MustNewDateFromString("2019-01-01") // returns *types.Date and panics on error
d6 := types.MustDateFromString("2019-01-01") // returns types.Date and panics on error
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.