dodopayments package - github.com/dodopayments/dodopayments-go - Go Packages

dodopayments

package module
v1.116.0 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: Apache-2.0 Imports: 21 Imported by: 3

README

Dodo Payments Go API Library

Go Reference

The Dodo Payments Go library provides convenient access to the Dodo Payments REST API from applications written in Go.

MCP Server

Use the Dodo Payments MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.

Add to Cursor

Note: You may need to set environment variables in your MCP client.

Installation

import (
	"github.com/dodopayments/dodopayments-go" // imported as dodopayments
)

Or to pin the version:

go get -u 'github.com/dodopayments/dodopayments-go@v1.116.0'

Requirements

This library requires Go 1.22+.

Usage

The full API of this library can be found in api.md.

package main

import (
	"context"
	"fmt"

	"github.com/dodopayments/dodopayments-go"
	"github.com/dodopayments/dodopayments-go/option"
)

func main() {
	client := dodopayments.NewClient(
		option.WithBearerToken("My Bearer Token"), // defaults to os.LookupEnv("DODO_PAYMENTS_API_KEY")
		option.WithEnvironmentTestMode(),          // defaults to option.WithEnvironmentLiveMode()
	)
	checkoutSessionResponse, err := client.CheckoutSessions.New(context.TODO(), dodopayments.CheckoutSessionNewParams{
		CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{
			ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{
				ProductID: dodopayments.F("product_id"),
				Quantity:  dodopayments.F(int64(0)),
			}}),
		},
	})
	if err != nil {
		panic(err.Error())
	}
	fmt.Printf("%+v\n", checkoutSessionResponse.SessionID)
}

Request fields

All request parameters are wrapped in a generic Field type, which we use to distinguish zero values from null or omitted fields.

This prevents accidentally sending a zero value if you forget a required parameter, and enables explicitly sending null, false, '', or 0 on optional parameters. Any field not specified is not sent.

To construct fields with values, use the helpers String(), Int(), Float(), or most commonly, the generic F[T](). To send a null, use Null[T](), and to send a nonconforming value, use Raw[T](any). For example:

params := FooParams{
	Name: dodopayments.F("hello"),

	// Explicitly send `"description": null`
	Description: dodopayments.Null[string](),

	Point: dodopayments.F(dodopayments.Point{
		X: dodopayments.Int(0),
		Y: dodopayments.Int(1),

		// In cases where the API specifies a given type,
		// but you want to send something else, use `Raw`:
		Z: dodopayments.Raw[int64](0.01), // sends a float
	}),
}
Response objects

All fields in response structs are value types (not pointers or wrappers).

If a given field is null, not present, or invalid, the corresponding field will simply be its zero value.

All response structs also include a special JSON field, containing more detailed information about each property, which you can use like so:

if res.Name == "" {
	// true if `"name"` is either not present or explicitly null
	res.JSON.Name.IsNull()

	// true if the `"name"` key was not present in the response JSON at all
	res.JSON.Name.IsMissing()

	// When the API returns data that cannot be coerced to the expected type:
	if res.JSON.Name.IsInvalid() {
		raw := res.JSON.Name.Raw()

		legacyName := struct{
			First string `json:"first"`
			Last  string `json:"last"`
		}{}
		json.Unmarshal([]byte(raw), &legacyName)
		name = legacyName.First + " " + legacyName.Last
	}
}

These .JSON structs also include an Extras map containing any properties in the json response that were not specified in the struct. This can be useful for API features not yet present in the SDK.

body := res.JSON.ExtraFields["my_unexpected_field"].Raw()
RequestOptions

This library uses the functional options pattern. Functions defined in the option package return a RequestOption, which is a closure that mutates a RequestConfig. These options can be supplied to the client or at individual requests. For example:

client := dodopayments.NewClient(
	// Adds a header to every request made by the client
	option.WithHeader("X-Some-Header", "custom_header_info"),
)

client.CheckoutSessions.New(context.TODO(), ...,
	// Override the header
	option.WithHeader("X-Some-Header", "some_other_custom_header_info"),
	// Add an undocumented field to the request body, using sjson syntax
	option.WithJSONSet("some.json.path", map[string]string{"my": "object"}),
)

See the full list of request options.

Pagination

This library provides some conveniences for working with paginated list endpoints.

You can use .ListAutoPaging() methods to iterate through items across all pages:

iter := client.Payments.ListAutoPaging(context.TODO(), dodopayments.PaymentListParams{})
// Automatically fetches more pages as needed.
for iter.Next() {
	paymentListResponse := iter.Current()
	fmt.Printf("%+v\n", paymentListResponse)
}
if err := iter.Err(); err != nil {
	panic(err.Error())
}

Or you can use simple .List() methods to fetch a single page and receive a standard response object with additional helper methods like .GetNextPage(), e.g.:

page, err := client.Payments.List(context.TODO(), dodopayments.PaymentListParams{})
for page != nil {
	for _, payment := range page.Items {
		fmt.Printf("%+v\n", payment)
	}
	page, err = page.GetNextPage()
}
if err != nil {
	panic(err.Error())
}
Errors

When the API returns a non-success status code, we return an error with type *dodopayments.Error. This contains the StatusCode, *http.Request, and *http.Response values of the request, as well as the JSON of the error body (much like other response objects in the SDK).

To handle errors, we recommend that you use the errors.As pattern:

_, err := client.CheckoutSessions.New(context.TODO(), dodopayments.CheckoutSessionNewParams{
	CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{
		ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{
			ProductID: dodopayments.F("product_id"),
			Quantity:  dodopayments.F(int64(0)),
		}}),
	},
})
if err != nil {
	var apierr *dodopayments.Error
	if errors.As(err, &apierr) {
		println(string(apierr.DumpRequest(true)))  // Prints the serialized HTTP request
		println(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response
	}
	panic(err.Error()) // GET "/checkouts": 400 Bad Request { ... }
}

When other errors occur, they are returned unwrapped; for example, if HTTP transport fails, you might receive *url.Error wrapping *net.OpError.

Timeouts

Requests do not time out by default; use context to configure a timeout for a request lifecycle.

Note that if a request is retried, the context timeout does not start over. To set a per-retry timeout, use option.WithRequestTimeout().

// This sets the timeout for the request, including all the retries.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
client.CheckoutSessions.New(
	ctx,
	dodopayments.CheckoutSessionNewParams{
		CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{
			ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{
				ProductID: dodopayments.F("product_id"),
				Quantity:  dodopayments.F(int64(0)),
			}}),
		},
	},
	// This sets the per-retry timeout
	option.WithRequestTimeout(20*time.Second),
)
File uploads

Request parameters that correspond to file uploads in multipart requests are typed as param.Field[io.Reader]. The contents of the io.Reader will by default be sent as a multipart form part with the file name of "anonymous_file" and content-type of "application/octet-stream".

The file name and content-type can be customized by implementing Name() string or ContentType() string on the run-time type of io.Reader. Note that os.File implements Name() string, so a file returned by os.Open will be sent with the file name on disk.

We also provide a helper dodopayments.FileParam(reader io.Reader, filename string, contentType string) which can be used to wrap any io.Reader with the appropriate file name and content type.

Retries

Certain errors will be automatically retried 2 times by default, with a short exponential backoff. We retry by default all connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors.

You can use the WithMaxRetries option to configure or disable this:

// Configure the default for all requests:
client := dodopayments.NewClient(
	option.WithMaxRetries(0), // default is 2
)

// Override per-request:
client.CheckoutSessions.New(
	context.TODO(),
	dodopayments.CheckoutSessionNewParams{
		CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{
			ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{
				ProductID: dodopayments.F("product_id"),
				Quantity:  dodopayments.F(int64(0)),
			}}),
		},
	},
	option.WithMaxRetries(5),
)
Accessing raw response data (e.g. response headers)

You can access the raw HTTP response data by using the option.WithResponseInto() request option. This is useful when you need to examine response headers, status codes, or other details.

// Create a variable to store the HTTP response
var response *http.Response
checkoutSessionResponse, err := client.CheckoutSessions.New(
	context.TODO(),
	dodopayments.CheckoutSessionNewParams{
		CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{
			ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{
				ProductID: dodopayments.F("product_id"),
				Quantity:  dodopayments.F(int64(0)),
			}}),
		},
	},
	option.WithResponseInto(&response),
)
if err != nil {
	// handle error
}
fmt.Printf("%+v\n", checkoutSessionResponse)

fmt.Printf("Status Code: %d\n", response.StatusCode)
fmt.Printf("Headers: %+#v\n", response.Header)
Making custom/undocumented requests

This library is typed for convenient access to the documented API. If you need to access undocumented endpoints, params, or response properties, the library can still be used.

Undocumented endpoints

To make requests to undocumented endpoints, you can use client.Get, client.Post, and other HTTP verbs. RequestOptions on the client, such as retries, will be respected when making these requests.

var (
    // params can be an io.Reader, a []byte, an encoding/json serializable object,
    // or a "…Params" struct defined in this library.
    params map[string]interface{}

    // result can be an []byte, *http.Response, a encoding/json deserializable object,
    // or a model defined in this library.
    result *http.Response
)
err := client.Post(context.Background(), "/unspecified", params, &result)
if err != nil {
    …
}
Undocumented request params

To make requests using undocumented parameters, you may use either the option.WithQuerySet() or the option.WithJSONSet() methods.

params := FooNewParams{
    ID:   dodopayments.F("id_xxxx"),
    Data: dodopayments.F(FooNewParamsData{
        FirstName: dodopayments.F("John"),
    }),
}
client.Foo.New(context.Background(), params, option.WithJSONSet("data.last_name", "Doe"))
Undocumented response properties

To access undocumented response properties, you may either access the raw JSON of the response as a string with result.JSON.RawJSON(), or get the raw JSON of a particular field on the result with result.JSON.Foo.Raw().

Any fields that are not present on the response struct will be saved and can be accessed by result.JSON.ExtraFields() which returns the extra fields as a map[string]Field.

Middleware

We provide option.WithMiddleware which applies the given middleware to requests.

func Logger(req *http.Request, next option.MiddlewareNext) (res *http.Response, err error) {
	// Before the request
	start := time.Now()
	LogReq(req)

	// Forward the request to the next handler
	res, err = next(req)

	// Handle stuff after the request
	end := time.Now()
	LogRes(res, err, start - end)

    return res, err
}

client := dodopayments.NewClient(
	option.WithMiddleware(Logger),
)

When multiple middlewares are provided as variadic arguments, the middlewares are applied left to right. If option.WithMiddleware is given multiple times, for example first in the client then the method, the middleware in the client will run first and the middleware given in the method will run next.

You may also replace the default http.Client with option.WithHTTPClient(client). Only one http client is accepted (this overwrites any previous client) and receives requests after any middleware has been applied.

Semantic versioning

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals.)
  2. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an issue with questions, bugs, or suggestions.

Contributing

See the contributing documentation.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool

func Bool(value bool) param.Field[bool]

Bool is a param field helper which helps specify bools.

func DefaultClientOptions added in v1.6.3

func DefaultClientOptions() []option.RequestOption

DefaultClientOptions read from the environment (DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_WEBHOOK_KEY, DODO_PAYMENTS_BASE_URL). This should be used to initialize new clients.

func F

func F[T any](value T) param.Field[T]

F is a param field helper used to initialize a param.Field generic struct. This helps specify null, zero values, and overrides, as well as normal values. You can read more about this in our README.

func FileParam

func FileParam(reader io.Reader, filename string, contentType string) param.Field[io.Reader]

FileParam is a param field helper which helps files with a mime content-type.

func Float

func Float(value float64) param.Field[float64]

Float is a param field helper which helps specify floats.

func Int

func Int(value int64) param.Field[int64]

Int is a param field helper which helps specify integers. This is particularly helpful when specifying integer constants for fields.

func Null

func Null[T any]() param.Field[T]

Null is a param field helper which explicitly sends null to the API.

func Raw

func Raw[T any](value any) param.Field[T]

Raw is a param field helper for specifying values for fields when the type you are looking to send is different from the type that is specified in the SDK. For example, if the type of the field is an integer, but you want to send a float, you could do that by setting the corresponding field with Raw[int](0.5).

func String

func String(value string) param.Field[string]

String is a param field helper which helps specify strings.

Types

type AbandonedCheckoutDetectedWebhookEvent added in v1.93.0

type AbandonedCheckoutDetectedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Webhook payload for abandoned_checkout.detected and abandoned_checkout.recovered
	// events
	Data AbandonedCheckoutDetectedWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type AbandonedCheckoutDetectedWebhookEventType `json:"type" api:"required"`
	JSON abandonedCheckoutDetectedWebhookEventJSON `json:"-"`
}

func (*AbandonedCheckoutDetectedWebhookEvent) UnmarshalJSON added in v1.93.0

func (r *AbandonedCheckoutDetectedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type AbandonedCheckoutDetectedWebhookEventData added in v1.93.0

type AbandonedCheckoutDetectedWebhookEventData struct {
	AbandonedAt       time.Time                                                  `json:"abandoned_at" api:"required" format:"date-time"`
	AbandonmentReason AbandonedCheckoutDetectedWebhookEventDataAbandonmentReason `json:"abandonment_reason" api:"required"`
	// Brand id this abandoned checkout belongs to
	BrandID            string                                          `json:"brand_id" api:"required"`
	CustomerID         string                                          `json:"customer_id" api:"required"`
	PaymentID          string                                          `json:"payment_id" api:"required"`
	Status             AbandonedCheckoutDetectedWebhookEventDataStatus `json:"status" api:"required"`
	RecoveredPaymentID string                                          `json:"recovered_payment_id" api:"nullable"`
	JSON               abandonedCheckoutDetectedWebhookEventDataJSON   `json:"-"`
}

Webhook payload for abandoned_checkout.detected and abandoned_checkout.recovered events

func (*AbandonedCheckoutDetectedWebhookEventData) UnmarshalJSON added in v1.93.0

func (r *AbandonedCheckoutDetectedWebhookEventData) UnmarshalJSON(data []byte) (err error)

type AbandonedCheckoutDetectedWebhookEventDataAbandonmentReason added in v1.93.0

type AbandonedCheckoutDetectedWebhookEventDataAbandonmentReason string
const (
	AbandonedCheckoutDetectedWebhookEventDataAbandonmentReasonPaymentFailed      AbandonedCheckoutDetectedWebhookEventDataAbandonmentReason = "payment_failed"
	AbandonedCheckoutDetectedWebhookEventDataAbandonmentReasonCheckoutIncomplete AbandonedCheckoutDetectedWebhookEventDataAbandonmentReason = "checkout_incomplete"
)

func (AbandonedCheckoutDetectedWebhookEventDataAbandonmentReason) IsKnown added in v1.93.0

type AbandonedCheckoutDetectedWebhookEventDataStatus added in v1.93.0

type AbandonedCheckoutDetectedWebhookEventDataStatus string
const (
	AbandonedCheckoutDetectedWebhookEventDataStatusAbandoned  AbandonedCheckoutDetectedWebhookEventDataStatus = "abandoned"
	AbandonedCheckoutDetectedWebhookEventDataStatusRecovering AbandonedCheckoutDetectedWebhookEventDataStatus = "recovering"
	AbandonedCheckoutDetectedWebhookEventDataStatusRecovered  AbandonedCheckoutDetectedWebhookEventDataStatus = "recovered"
	AbandonedCheckoutDetectedWebhookEventDataStatusExhausted  AbandonedCheckoutDetectedWebhookEventDataStatus = "exhausted"
	AbandonedCheckoutDetectedWebhookEventDataStatusOptedOut   AbandonedCheckoutDetectedWebhookEventDataStatus = "opted_out"
)

func (AbandonedCheckoutDetectedWebhookEventDataStatus) IsKnown added in v1.93.0

type AbandonedCheckoutDetectedWebhookEventType added in v1.93.0

type AbandonedCheckoutDetectedWebhookEventType string

The event type

const (
	AbandonedCheckoutDetectedWebhookEventTypeAbandonedCheckoutDetected AbandonedCheckoutDetectedWebhookEventType = "abandoned_checkout.detected"
)

func (AbandonedCheckoutDetectedWebhookEventType) IsKnown added in v1.93.0

type AbandonedCheckoutRecoveredWebhookEvent added in v1.93.0

type AbandonedCheckoutRecoveredWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Webhook payload for abandoned_checkout.detected and abandoned_checkout.recovered
	// events
	Data AbandonedCheckoutRecoveredWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type AbandonedCheckoutRecoveredWebhookEventType `json:"type" api:"required"`
	JSON abandonedCheckoutRecoveredWebhookEventJSON `json:"-"`
}

func (*AbandonedCheckoutRecoveredWebhookEvent) UnmarshalJSON added in v1.93.0

func (r *AbandonedCheckoutRecoveredWebhookEvent) UnmarshalJSON(data []byte) (err error)

type AbandonedCheckoutRecoveredWebhookEventData added in v1.93.0

type AbandonedCheckoutRecoveredWebhookEventData struct {
	AbandonedAt       time.Time                                                   `json:"abandoned_at" api:"required" format:"date-time"`
	AbandonmentReason AbandonedCheckoutRecoveredWebhookEventDataAbandonmentReason `json:"abandonment_reason" api:"required"`
	// Brand id this abandoned checkout belongs to
	BrandID            string                                           `json:"brand_id" api:"required"`
	CustomerID         string                                           `json:"customer_id" api:"required"`
	PaymentID          string                                           `json:"payment_id" api:"required"`
	Status             AbandonedCheckoutRecoveredWebhookEventDataStatus `json:"status" api:"required"`
	RecoveredPaymentID string                                           `json:"recovered_payment_id" api:"nullable"`
	JSON               abandonedCheckoutRecoveredWebhookEventDataJSON   `json:"-"`
}

Webhook payload for abandoned_checkout.detected and abandoned_checkout.recovered events

func (*AbandonedCheckoutRecoveredWebhookEventData) UnmarshalJSON added in v1.93.0

func (r *AbandonedCheckoutRecoveredWebhookEventData) UnmarshalJSON(data []byte) (err error)

type AbandonedCheckoutRecoveredWebhookEventDataAbandonmentReason added in v1.93.0

type AbandonedCheckoutRecoveredWebhookEventDataAbandonmentReason string
const (
	AbandonedCheckoutRecoveredWebhookEventDataAbandonmentReasonPaymentFailed      AbandonedCheckoutRecoveredWebhookEventDataAbandonmentReason = "payment_failed"
	AbandonedCheckoutRecoveredWebhookEventDataAbandonmentReasonCheckoutIncomplete AbandonedCheckoutRecoveredWebhookEventDataAbandonmentReason = "checkout_incomplete"
)

func (AbandonedCheckoutRecoveredWebhookEventDataAbandonmentReason) IsKnown added in v1.93.0

type AbandonedCheckoutRecoveredWebhookEventDataStatus added in v1.93.0

type AbandonedCheckoutRecoveredWebhookEventDataStatus string
const (
	AbandonedCheckoutRecoveredWebhookEventDataStatusAbandoned  AbandonedCheckoutRecoveredWebhookEventDataStatus = "abandoned"
	AbandonedCheckoutRecoveredWebhookEventDataStatusRecovering AbandonedCheckoutRecoveredWebhookEventDataStatus = "recovering"
	AbandonedCheckoutRecoveredWebhookEventDataStatusRecovered  AbandonedCheckoutRecoveredWebhookEventDataStatus = "recovered"
	AbandonedCheckoutRecoveredWebhookEventDataStatusExhausted  AbandonedCheckoutRecoveredWebhookEventDataStatus = "exhausted"
	AbandonedCheckoutRecoveredWebhookEventDataStatusOptedOut   AbandonedCheckoutRecoveredWebhookEventDataStatus = "opted_out"
)

func (AbandonedCheckoutRecoveredWebhookEventDataStatus) IsKnown added in v1.93.0

type AbandonedCheckoutRecoveredWebhookEventType added in v1.93.0

type AbandonedCheckoutRecoveredWebhookEventType string

The event type

const (
	AbandonedCheckoutRecoveredWebhookEventTypeAbandonedCheckoutRecovered AbandonedCheckoutRecoveredWebhookEventType = "abandoned_checkout.recovered"
)

func (AbandonedCheckoutRecoveredWebhookEventType) IsKnown added in v1.93.0

type AddMeterToPrice added in v1.52.4

type AddMeterToPrice struct {
	MeterID string `json:"meter_id" api:"required"`
	// Optional credit entitlement ID to link this meter to for credit-based billing
	CreditEntitlementID string `json:"credit_entitlement_id" api:"nullable"`
	// Meter description. Will ignored on Request, but will be shown in response
	Description   string `json:"description" api:"nullable"`
	FreeThreshold int64  `json:"free_threshold" api:"nullable"`
	// Meter measurement unit. Will ignored on Request, but will be shown in response
	MeasurementUnit string `json:"measurement_unit" api:"nullable"`
	// Number of meter units that equal one credit. Required when credit_entitlement_id
	// is set.
	MeterUnitsPerCredit string `json:"meter_units_per_credit" api:"nullable"`
	// Meter name. Will ignored on Request, but will be shown in response
	Name string `json:"name" api:"nullable"`
	// The price per unit in lowest denomination. Must be greater than zero. Supports
	// up to 5 digits before decimal point and 12 decimal places.
	PricePerUnit string              `json:"price_per_unit" api:"nullable"`
	JSON         addMeterToPriceJSON `json:"-"`
}

func (*AddMeterToPrice) UnmarshalJSON added in v1.52.4

func (r *AddMeterToPrice) UnmarshalJSON(data []byte) (err error)

type AddMeterToPriceParam added in v1.52.4

type AddMeterToPriceParam struct {
	MeterID param.Field[string] `json:"meter_id" api:"required"`
	// Optional credit entitlement ID to link this meter to for credit-based billing
	CreditEntitlementID param.Field[string] `json:"credit_entitlement_id"`
	// Meter description. Will ignored on Request, but will be shown in response
	Description   param.Field[string] `json:"description"`
	FreeThreshold param.Field[int64]  `json:"free_threshold"`
	// Meter measurement unit. Will ignored on Request, but will be shown in response
	MeasurementUnit param.Field[string] `json:"measurement_unit"`
	// Number of meter units that equal one credit. Required when credit_entitlement_id
	// is set.
	MeterUnitsPerCredit param.Field[string] `json:"meter_units_per_credit"`
	// Meter name. Will ignored on Request, but will be shown in response
	Name param.Field[string] `json:"name"`
	// The price per unit in lowest denomination. Must be greater than zero. Supports
	// up to 5 digits before decimal point and 12 decimal places.
	PricePerUnit param.Field[string] `json:"price_per_unit"`
}

func (AddMeterToPriceParam) MarshalJSON added in v1.52.4

func (r AddMeterToPriceParam) MarshalJSON() (data []byte, err error)

type AddonCartResponseItem added in v1.20.0

type AddonCartResponseItem struct {
	AddonID  string                    `json:"addon_id" api:"required"`
	Quantity int64                     `json:"quantity" api:"required"`
	JSON     addonCartResponseItemJSON `json:"-"`
}

Response struct representing subscription details

func (*AddonCartResponseItem) UnmarshalJSON added in v1.20.0

func (r *AddonCartResponseItem) UnmarshalJSON(data []byte) (err error)

type AddonListParams added in v1.20.0

type AddonListParams struct {
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
}

func (AddonListParams) URLQuery added in v1.20.0

func (r AddonListParams) URLQuery() (v url.Values)

URLQuery serializes AddonListParams's query parameters as `url.Values`.

type AddonNewParams added in v1.20.0

type AddonNewParams struct {
	// The currency of the Addon
	Currency param.Field[Currency] `json:"currency" api:"required"`
	// Name of the Addon
	Name param.Field[string] `json:"name" api:"required"`
	// Amount of the addon
	Price param.Field[int64] `json:"price" api:"required"`
	// Tax category applied to this Addon
	TaxCategory param.Field[TaxCategory] `json:"tax_category" api:"required"`
	// Optional description of the Addon
	Description param.Field[string] `json:"description"`
}

func (AddonNewParams) MarshalJSON added in v1.20.0

func (r AddonNewParams) MarshalJSON() (data []byte, err error)

type AddonResponse added in v1.20.0

type AddonResponse struct {
	// id of the Addon
	ID string `json:"id" api:"required"`
	// Unique identifier for the business to which the addon belongs.
	BusinessID string `json:"business_id" api:"required"`
	// Created time
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Currency of the Addon
	Currency Currency `json:"currency" api:"required"`
	// Name of the Addon
	Name string `json:"name" api:"required"`
	// Amount of the addon
	Price int64 `json:"price" api:"required"`
	// Tax category applied to this Addon
	TaxCategory TaxCategory `json:"tax_category" api:"required"`
	// Updated time
	UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
	// Optional description of the Addon
	Description string `json:"description" api:"nullable"`
	// Image of the Addon
	Image string            `json:"image" api:"nullable"`
	JSON  addonResponseJSON `json:"-"`
}

func (*AddonResponse) UnmarshalJSON added in v1.20.0

func (r *AddonResponse) UnmarshalJSON(data []byte) (err error)

type AddonService added in v1.20.0

type AddonService struct {
	Options []option.RequestOption
}

AddonService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewAddonService method instead.

func NewAddonService added in v1.20.0

func NewAddonService(opts ...option.RequestOption) (r *AddonService)

NewAddonService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*AddonService) Get added in v1.20.0

func (r *AddonService) Get(ctx context.Context, id string, opts ...option.RequestOption) (res *AddonResponse, err error)

func (*AddonService) List added in v1.20.0

func (*AddonService) ListAutoPaging added in v1.20.0

func (*AddonService) New added in v1.20.0

func (r *AddonService) New(ctx context.Context, body AddonNewParams, opts ...option.RequestOption) (res *AddonResponse, err error)

func (*AddonService) Update added in v1.20.0

func (r *AddonService) Update(ctx context.Context, id string, body AddonUpdateParams, opts ...option.RequestOption) (res *AddonResponse, err error)

func (*AddonService) UpdateImages added in v1.20.0

func (r *AddonService) UpdateImages(ctx context.Context, id string, opts ...option.RequestOption) (res *AddonUpdateImagesResponse, err error)

type AddonUpdateImagesResponse added in v1.20.0

type AddonUpdateImagesResponse struct {
	ImageID string                        `json:"image_id" api:"required" format:"uuid"`
	URL     string                        `json:"url" api:"required"`
	JSON    addonUpdateImagesResponseJSON `json:"-"`
}

func (*AddonUpdateImagesResponse) UnmarshalJSON added in v1.20.0

func (r *AddonUpdateImagesResponse) UnmarshalJSON(data []byte) (err error)

type AddonUpdateParams added in v1.20.0

type AddonUpdateParams struct {
	// The currency of the Addon
	Currency param.Field[Currency] `json:"currency"`
	// Description of the Addon, optional and must be at most 1000 characters.
	Description param.Field[string] `json:"description"`
	// Addon image id after its uploaded to S3. Pass `null` to remove the existing
	// image, omit to keep it unchanged.
	ImageID param.Field[string] `json:"image_id" format:"uuid"`
	// Name of the Addon, optional and must be at most 100 characters.
	Name param.Field[string] `json:"name"`
	// Amount of the addon
	Price param.Field[int64] `json:"price"`
	// Tax category of the Addon.
	TaxCategory param.Field[TaxCategory] `json:"tax_category"`
}

func (AddonUpdateParams) MarshalJSON added in v1.20.0

func (r AddonUpdateParams) MarshalJSON() (data []byte, err error)

type AttachAddonParam added in v1.43.0

type AttachAddonParam struct {
	AddonID param.Field[string] `json:"addon_id" api:"required"`
	// Number of units of this addon.
	Quantity param.Field[int64] `json:"quantity" api:"required"`
}

func (AttachAddonParam) MarshalJSON added in v1.43.0

func (r AttachAddonParam) MarshalJSON() (data []byte, err error)

type AttachCreditEntitlementParam added in v1.86.0

type AttachCreditEntitlementParam struct {
	// ID of the credit entitlement to attach
	CreditEntitlementID param.Field[string] `json:"credit_entitlement_id" api:"required"`
	// Number of credits to grant when this product is purchased
	CreditsAmount param.Field[string] `json:"credits_amount" api:"required"`
	// Currency for credit-related pricing
	Currency param.Field[Currency] `json:"currency"`
	// Number of days after which credits expire
	ExpiresAfterDays param.Field[int64] `json:"expires_after_days"`
	// Balance threshold percentage for low balance notifications (0-100)
	LowBalanceThresholdPercent param.Field[int64] `json:"low_balance_threshold_percent"`
	// Maximum number of rollover cycles allowed
	MaxRolloverCount param.Field[int64] `json:"max_rollover_count"`
	// Controls how overage is handled at billing cycle end.
	OverageBehavior param.Field[CbbOverageBehavior] `json:"overage_behavior"`
	// Whether overage usage is allowed beyond credit balance
	OverageEnabled param.Field[bool] `json:"overage_enabled"`
	// Maximum amount of overage allowed
	OverageLimit param.Field[string] `json:"overage_limit"`
	// Price per credit unit for purchasing additional credits
	PricePerUnit param.Field[string] `json:"price_per_unit"`
	// Proration behavior for credit grants during plan changes
	ProrationBehavior param.Field[CbbProrationBehavior] `json:"proration_behavior"`
	// Whether unused credits can roll over to the next billing period
	RolloverEnabled param.Field[bool] `json:"rollover_enabled"`
	// Percentage of unused credits that can roll over (0-100)
	RolloverPercentage param.Field[int64] `json:"rollover_percentage"`
	// Number of timeframe units for rollover window
	RolloverTimeframeCount param.Field[int64] `json:"rollover_timeframe_count"`
	// Time interval for rollover window (day, week, month, year)
	RolloverTimeframeInterval param.Field[TimeInterval] `json:"rollover_timeframe_interval"`
	// Credits granted during trial period
	TrialCredits param.Field[string] `json:"trial_credits"`
	// Whether trial credits expire when trial ends
	TrialCreditsExpireAfterTrial param.Field[bool] `json:"trial_credits_expire_after_trial"`
}

Request struct for attaching a credit entitlement to a product

func (AttachCreditEntitlementParam) MarshalJSON added in v1.86.0

func (r AttachCreditEntitlementParam) MarshalJSON() (data []byte, err error)

type AttachExistingCustomerParam added in v1.6.3

type AttachExistingCustomerParam struct {
	CustomerID param.Field[string] `json:"customer_id" api:"required"`
}

func (AttachExistingCustomerParam) MarshalJSON added in v1.6.3

func (r AttachExistingCustomerParam) MarshalJSON() (data []byte, err error)

type AttachProductEntitlementParam added in v1.97.0

type AttachProductEntitlementParam struct {
	// ID of the entitlement to attach to the product
	EntitlementID param.Field[string] `json:"entitlement_id" api:"required"`
}

Request struct for attaching an entitlement to a product.

Mirrors the `credit_entitlements` attach shape — every "attach something to a product" array takes objects, not bare IDs. Uniform shape leaves room for per-attachment settings later without another API break.

func (AttachProductEntitlementParam) MarshalJSON added in v1.97.0

func (r AttachProductEntitlementParam) MarshalJSON() (data []byte, err error)

type BalanceGetLedgerParams added in v1.81.0

type BalanceGetLedgerParams struct {
	// Get events after this created time
	CreatedAtGte param.Field[time.Time] `query:"created_at_gte" format:"date-time"`
	// Get events created before this time
	CreatedAtLte param.Field[time.Time] `query:"created_at_lte" format:"date-time"`
	// Filter by currency
	Currency param.Field[BalanceGetLedgerParamsCurrency] `query:"currency"`
	// Filter by Ledger Event Type
	EventType param.Field[BalanceGetLedgerParamsEventType] `query:"event_type"`
	// Min : 1, Max : 100, default 10
	Limit param.Field[int64] `query:"limit"`
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
	// Get events history of a specific object like payment/subscription/refund/dispute
	ReferenceObjectID param.Field[string] `query:"reference_object_id"`
}

func (BalanceGetLedgerParams) URLQuery added in v1.81.0

func (r BalanceGetLedgerParams) URLQuery() (v url.Values)

URLQuery serializes BalanceGetLedgerParams's query parameters as `url.Values`.

type BalanceGetLedgerParamsCurrency added in v1.81.0

type BalanceGetLedgerParamsCurrency string

Filter by currency

const (
	BalanceGetLedgerParamsCurrencyAed BalanceGetLedgerParamsCurrency = "AED"
	BalanceGetLedgerParamsCurrencyAll BalanceGetLedgerParamsCurrency = "ALL"
	BalanceGetLedgerParamsCurrencyAmd BalanceGetLedgerParamsCurrency = "AMD"
	BalanceGetLedgerParamsCurrencyAng BalanceGetLedgerParamsCurrency = "ANG"
	BalanceGetLedgerParamsCurrencyAoa BalanceGetLedgerParamsCurrency = "AOA"
	BalanceGetLedgerParamsCurrencyArs BalanceGetLedgerParamsCurrency = "ARS"
	BalanceGetLedgerParamsCurrencyAud BalanceGetLedgerParamsCurrency = "AUD"
	BalanceGetLedgerParamsCurrencyAwg BalanceGetLedgerParamsCurrency = "AWG"
	BalanceGetLedgerParamsCurrencyAzn BalanceGetLedgerParamsCurrency = "AZN"
	BalanceGetLedgerParamsCurrencyBam BalanceGetLedgerParamsCurrency = "BAM"
	BalanceGetLedgerParamsCurrencyBbd BalanceGetLedgerParamsCurrency = "BBD"
	BalanceGetLedgerParamsCurrencyBdt BalanceGetLedgerParamsCurrency = "BDT"
	BalanceGetLedgerParamsCurrencyBgn BalanceGetLedgerParamsCurrency = "BGN"
	BalanceGetLedgerParamsCurrencyBhd BalanceGetLedgerParamsCurrency = "BHD"
	BalanceGetLedgerParamsCurrencyBif BalanceGetLedgerParamsCurrency = "BIF"
	BalanceGetLedgerParamsCurrencyBmd BalanceGetLedgerParamsCurrency = "BMD"
	BalanceGetLedgerParamsCurrencyBnd BalanceGetLedgerParamsCurrency = "BND"
	BalanceGetLedgerParamsCurrencyBob BalanceGetLedgerParamsCurrency = "BOB"
	BalanceGetLedgerParamsCurrencyBrl BalanceGetLedgerParamsCurrency = "BRL"
	BalanceGetLedgerParamsCurrencyBsd BalanceGetLedgerParamsCurrency = "BSD"
	BalanceGetLedgerParamsCurrencyBwp BalanceGetLedgerParamsCurrency = "BWP"
	BalanceGetLedgerParamsCurrencyByn BalanceGetLedgerParamsCurrency = "BYN"
	BalanceGetLedgerParamsCurrencyBzd BalanceGetLedgerParamsCurrency = "BZD"
	BalanceGetLedgerParamsCurrencyCad BalanceGetLedgerParamsCurrency = "CAD"
	BalanceGetLedgerParamsCurrencyChf BalanceGetLedgerParamsCurrency = "CHF"
	BalanceGetLedgerParamsCurrencyClp BalanceGetLedgerParamsCurrency = "CLP"
	BalanceGetLedgerParamsCurrencyCny BalanceGetLedgerParamsCurrency = "CNY"
	BalanceGetLedgerParamsCurrencyCop BalanceGetLedgerParamsCurrency = "COP"
	BalanceGetLedgerParamsCurrencyCrc BalanceGetLedgerParamsCurrency = "CRC"
	BalanceGetLedgerParamsCurrencyCup BalanceGetLedgerParamsCurrency = "CUP"
	BalanceGetLedgerParamsCurrencyCve BalanceGetLedgerParamsCurrency = "CVE"
	BalanceGetLedgerParamsCurrencyCzk BalanceGetLedgerParamsCurrency = "CZK"
	BalanceGetLedgerParamsCurrencyDjf BalanceGetLedgerParamsCurrency = "DJF"
	BalanceGetLedgerParamsCurrencyDkk BalanceGetLedgerParamsCurrency = "DKK"
	BalanceGetLedgerParamsCurrencyDop BalanceGetLedgerParamsCurrency = "DOP"
	BalanceGetLedgerParamsCurrencyDzd BalanceGetLedgerParamsCurrency = "DZD"
	BalanceGetLedgerParamsCurrencyEgp BalanceGetLedgerParamsCurrency = "EGP"
	BalanceGetLedgerParamsCurrencyEtb BalanceGetLedgerParamsCurrency = "ETB"
	BalanceGetLedgerParamsCurrencyEur BalanceGetLedgerParamsCurrency = "EUR"
	BalanceGetLedgerParamsCurrencyFjd BalanceGetLedgerParamsCurrency = "FJD"
	BalanceGetLedgerParamsCurrencyFkp BalanceGetLedgerParamsCurrency = "FKP"
	BalanceGetLedgerParamsCurrencyGbp BalanceGetLedgerParamsCurrency = "GBP"
	BalanceGetLedgerParamsCurrencyGel BalanceGetLedgerParamsCurrency = "GEL"
	BalanceGetLedgerParamsCurrencyGhs BalanceGetLedgerParamsCurrency = "GHS"
	BalanceGetLedgerParamsCurrencyGip BalanceGetLedgerParamsCurrency = "GIP"
	BalanceGetLedgerParamsCurrencyGmd BalanceGetLedgerParamsCurrency = "GMD"
	BalanceGetLedgerParamsCurrencyGnf BalanceGetLedgerParamsCurrency = "GNF"
	BalanceGetLedgerParamsCurrencyGtq BalanceGetLedgerParamsCurrency = "GTQ"
	BalanceGetLedgerParamsCurrencyGyd BalanceGetLedgerParamsCurrency = "GYD"
	BalanceGetLedgerParamsCurrencyHkd BalanceGetLedgerParamsCurrency = "HKD"
	BalanceGetLedgerParamsCurrencyHnl BalanceGetLedgerParamsCurrency = "HNL"
	BalanceGetLedgerParamsCurrencyHrk BalanceGetLedgerParamsCurrency = "HRK"
	BalanceGetLedgerParamsCurrencyHtg BalanceGetLedgerParamsCurrency = "HTG"
	BalanceGetLedgerParamsCurrencyHuf BalanceGetLedgerParamsCurrency = "HUF"
	BalanceGetLedgerParamsCurrencyIdr BalanceGetLedgerParamsCurrency = "IDR"
	BalanceGetLedgerParamsCurrencyIls BalanceGetLedgerParamsCurrency = "ILS"
	BalanceGetLedgerParamsCurrencyInr BalanceGetLedgerParamsCurrency = "INR"
	BalanceGetLedgerParamsCurrencyIqd BalanceGetLedgerParamsCurrency = "IQD"
	BalanceGetLedgerParamsCurrencyJmd BalanceGetLedgerParamsCurrency = "JMD"
	BalanceGetLedgerParamsCurrencyJod BalanceGetLedgerParamsCurrency = "JOD"
	BalanceGetLedgerParamsCurrencyJpy BalanceGetLedgerParamsCurrency = "JPY"
	BalanceGetLedgerParamsCurrencyKes BalanceGetLedgerParamsCurrency = "KES"
	BalanceGetLedgerParamsCurrencyKgs BalanceGetLedgerParamsCurrency = "KGS"
	BalanceGetLedgerParamsCurrencyKhr BalanceGetLedgerParamsCurrency = "KHR"
	BalanceGetLedgerParamsCurrencyKmf BalanceGetLedgerParamsCurrency = "KMF"
	BalanceGetLedgerParamsCurrencyKrw BalanceGetLedgerParamsCurrency = "KRW"
	BalanceGetLedgerParamsCurrencyKwd BalanceGetLedgerParamsCurrency = "KWD"
	BalanceGetLedgerParamsCurrencyKyd BalanceGetLedgerParamsCurrency = "KYD"
	BalanceGetLedgerParamsCurrencyKzt BalanceGetLedgerParamsCurrency = "KZT"
	BalanceGetLedgerParamsCurrencyLak BalanceGetLedgerParamsCurrency = "LAK"
	BalanceGetLedgerParamsCurrencyLbp BalanceGetLedgerParamsCurrency = "LBP"
	BalanceGetLedgerParamsCurrencyLkr BalanceGetLedgerParamsCurrency = "LKR"
	BalanceGetLedgerParamsCurrencyLrd BalanceGetLedgerParamsCurrency = "LRD"
	BalanceGetLedgerParamsCurrencyLsl BalanceGetLedgerParamsCurrency = "LSL"
	BalanceGetLedgerParamsCurrencyLyd BalanceGetLedgerParamsCurrency = "LYD"
	BalanceGetLedgerParamsCurrencyMad BalanceGetLedgerParamsCurrency = "MAD"
	BalanceGetLedgerParamsCurrencyMdl BalanceGetLedgerParamsCurrency = "MDL"
	BalanceGetLedgerParamsCurrencyMga BalanceGetLedgerParamsCurrency = "MGA"
	BalanceGetLedgerParamsCurrencyMkd BalanceGetLedgerParamsCurrency = "MKD"
	BalanceGetLedgerParamsCurrencyMmk BalanceGetLedgerParamsCurrency = "MMK"
	BalanceGetLedgerParamsCurrencyMnt BalanceGetLedgerParamsCurrency = "MNT"
	BalanceGetLedgerParamsCurrencyMop BalanceGetLedgerParamsCurrency = "MOP"
	BalanceGetLedgerParamsCurrencyMru BalanceGetLedgerParamsCurrency = "MRU"
	BalanceGetLedgerParamsCurrencyMur BalanceGetLedgerParamsCurrency = "MUR"
	BalanceGetLedgerParamsCurrencyMvr BalanceGetLedgerParamsCurrency = "MVR"
	BalanceGetLedgerParamsCurrencyMwk BalanceGetLedgerParamsCurrency = "MWK"
	BalanceGetLedgerParamsCurrencyMxn BalanceGetLedgerParamsCurrency = "MXN"
	BalanceGetLedgerParamsCurrencyMyr BalanceGetLedgerParamsCurrency = "MYR"
	BalanceGetLedgerParamsCurrencyMzn BalanceGetLedgerParamsCurrency = "MZN"
	BalanceGetLedgerParamsCurrencyNad BalanceGetLedgerParamsCurrency = "NAD"
	BalanceGetLedgerParamsCurrencyNgn BalanceGetLedgerParamsCurrency = "NGN"
	BalanceGetLedgerParamsCurrencyNio BalanceGetLedgerParamsCurrency = "NIO"
	BalanceGetLedgerParamsCurrencyNok BalanceGetLedgerParamsCurrency = "NOK"
	BalanceGetLedgerParamsCurrencyNpr BalanceGetLedgerParamsCurrency = "NPR"
	BalanceGetLedgerParamsCurrencyNzd BalanceGetLedgerParamsCurrency = "NZD"
	BalanceGetLedgerParamsCurrencyOmr BalanceGetLedgerParamsCurrency = "OMR"
	BalanceGetLedgerParamsCurrencyPab BalanceGetLedgerParamsCurrency = "PAB"
	BalanceGetLedgerParamsCurrencyPen BalanceGetLedgerParamsCurrency = "PEN"
	BalanceGetLedgerParamsCurrencyPgk BalanceGetLedgerParamsCurrency = "PGK"
	BalanceGetLedgerParamsCurrencyPhp BalanceGetLedgerParamsCurrency = "PHP"
	BalanceGetLedgerParamsCurrencyPkr BalanceGetLedgerParamsCurrency = "PKR"
	BalanceGetLedgerParamsCurrencyPln BalanceGetLedgerParamsCurrency = "PLN"
	BalanceGetLedgerParamsCurrencyPyg BalanceGetLedgerParamsCurrency = "PYG"
	BalanceGetLedgerParamsCurrencyQar BalanceGetLedgerParamsCurrency = "QAR"
	BalanceGetLedgerParamsCurrencyRon BalanceGetLedgerParamsCurrency = "RON"
	BalanceGetLedgerParamsCurrencyRsd BalanceGetLedgerParamsCurrency = "RSD"
	BalanceGetLedgerParamsCurrencyRub BalanceGetLedgerParamsCurrency = "RUB"
	BalanceGetLedgerParamsCurrencyRwf BalanceGetLedgerParamsCurrency = "RWF"
	BalanceGetLedgerParamsCurrencySar BalanceGetLedgerParamsCurrency = "SAR"
	BalanceGetLedgerParamsCurrencySbd BalanceGetLedgerParamsCurrency = "SBD"
	BalanceGetLedgerParamsCurrencyScr BalanceGetLedgerParamsCurrency = "SCR"
	BalanceGetLedgerParamsCurrencySek BalanceGetLedgerParamsCurrency = "SEK"
	BalanceGetLedgerParamsCurrencySgd BalanceGetLedgerParamsCurrency = "SGD"
	BalanceGetLedgerParamsCurrencyShp BalanceGetLedgerParamsCurrency = "SHP"
	BalanceGetLedgerParamsCurrencySle BalanceGetLedgerParamsCurrency = "SLE"
	BalanceGetLedgerParamsCurrencySll BalanceGetLedgerParamsCurrency = "SLL"
	BalanceGetLedgerParamsCurrencySos BalanceGetLedgerParamsCurrency = "SOS"
	BalanceGetLedgerParamsCurrencySrd BalanceGetLedgerParamsCurrency = "SRD"
	BalanceGetLedgerParamsCurrencySsp BalanceGetLedgerParamsCurrency = "SSP"
	BalanceGetLedgerParamsCurrencyStn BalanceGetLedgerParamsCurrency = "STN"
	BalanceGetLedgerParamsCurrencySvc BalanceGetLedgerParamsCurrency = "SVC"
	BalanceGetLedgerParamsCurrencySzl BalanceGetLedgerParamsCurrency = "SZL"
	BalanceGetLedgerParamsCurrencyThb BalanceGetLedgerParamsCurrency = "THB"
	BalanceGetLedgerParamsCurrencyTnd BalanceGetLedgerParamsCurrency = "TND"
	BalanceGetLedgerParamsCurrencyTop BalanceGetLedgerParamsCurrency = "TOP"
	BalanceGetLedgerParamsCurrencyTry BalanceGetLedgerParamsCurrency = "TRY"
	BalanceGetLedgerParamsCurrencyTtd BalanceGetLedgerParamsCurrency = "TTD"
	BalanceGetLedgerParamsCurrencyTwd BalanceGetLedgerParamsCurrency = "TWD"
	BalanceGetLedgerParamsCurrencyTzs BalanceGetLedgerParamsCurrency = "TZS"
	BalanceGetLedgerParamsCurrencyUah BalanceGetLedgerParamsCurrency = "UAH"
	BalanceGetLedgerParamsCurrencyUgx BalanceGetLedgerParamsCurrency = "UGX"
	BalanceGetLedgerParamsCurrencyUsd BalanceGetLedgerParamsCurrency = "USD"
	BalanceGetLedgerParamsCurrencyUyu BalanceGetLedgerParamsCurrency = "UYU"
	BalanceGetLedgerParamsCurrencyUzs BalanceGetLedgerParamsCurrency = "UZS"
	BalanceGetLedgerParamsCurrencyVes BalanceGetLedgerParamsCurrency = "VES"
	BalanceGetLedgerParamsCurrencyVnd BalanceGetLedgerParamsCurrency = "VND"
	BalanceGetLedgerParamsCurrencyVuv BalanceGetLedgerParamsCurrency = "VUV"
	BalanceGetLedgerParamsCurrencyWst BalanceGetLedgerParamsCurrency = "WST"
	BalanceGetLedgerParamsCurrencyXaf BalanceGetLedgerParamsCurrency = "XAF"
	BalanceGetLedgerParamsCurrencyXcd BalanceGetLedgerParamsCurrency = "XCD"
	BalanceGetLedgerParamsCurrencyXof BalanceGetLedgerParamsCurrency = "XOF"
	BalanceGetLedgerParamsCurrencyXpf BalanceGetLedgerParamsCurrency = "XPF"
	BalanceGetLedgerParamsCurrencyYer BalanceGetLedgerParamsCurrency = "YER"
	BalanceGetLedgerParamsCurrencyZar BalanceGetLedgerParamsCurrency = "ZAR"
	BalanceGetLedgerParamsCurrencyZmw BalanceGetLedgerParamsCurrency = "ZMW"
)

func (BalanceGetLedgerParamsCurrency) IsKnown added in v1.81.0

type BalanceGetLedgerParamsEventType added in v1.81.0

type BalanceGetLedgerParamsEventType string

Filter by Ledger Event Type

const (
	BalanceGetLedgerParamsEventTypePayment                  BalanceGetLedgerParamsEventType = "payment"
	BalanceGetLedgerParamsEventTypeRefund                   BalanceGetLedgerParamsEventType = "refund"
	BalanceGetLedgerParamsEventTypeRefundReversal           BalanceGetLedgerParamsEventType = "refund_reversal"
	BalanceGetLedgerParamsEventTypeDispute                  BalanceGetLedgerParamsEventType = "dispute"
	BalanceGetLedgerParamsEventTypeDisputeReversal          BalanceGetLedgerParamsEventType = "dispute_reversal"
	BalanceGetLedgerParamsEventTypeTax                      BalanceGetLedgerParamsEventType = "tax"
	BalanceGetLedgerParamsEventTypeTaxReversal              BalanceGetLedgerParamsEventType = "tax_reversal"
	BalanceGetLedgerParamsEventTypePaymentFees              BalanceGetLedgerParamsEventType = "payment_fees"
	BalanceGetLedgerParamsEventTypeRefundFees               BalanceGetLedgerParamsEventType = "refund_fees"
	BalanceGetLedgerParamsEventTypeRefundFeesReversal       BalanceGetLedgerParamsEventType = "refund_fees_reversal"
	BalanceGetLedgerParamsEventTypeDisputeFees              BalanceGetLedgerParamsEventType = "dispute_fees"
	BalanceGetLedgerParamsEventTypePayout                   BalanceGetLedgerParamsEventType = "payout"
	BalanceGetLedgerParamsEventTypePayoutFees               BalanceGetLedgerParamsEventType = "payout_fees"
	BalanceGetLedgerParamsEventTypePayoutReversal           BalanceGetLedgerParamsEventType = "payout_reversal"
	BalanceGetLedgerParamsEventTypePayoutFeesReversal       BalanceGetLedgerParamsEventType = "payout_fees_reversal"
	BalanceGetLedgerParamsEventTypeDodoCredits              BalanceGetLedgerParamsEventType = "dodo_credits"
	BalanceGetLedgerParamsEventTypeAdjustment               BalanceGetLedgerParamsEventType = "adjustment"
	BalanceGetLedgerParamsEventTypeCurrencyConversion       BalanceGetLedgerParamsEventType = "currency_conversion"
	BalanceGetLedgerParamsEventTypeAbandonedCartRecoveryFee BalanceGetLedgerParamsEventType = "abandoned_cart_recovery_fee"
	BalanceGetLedgerParamsEventTypeDunningFees              BalanceGetLedgerParamsEventType = "dunning_fees"
	BalanceGetLedgerParamsEventTypePaymentRetryFee          BalanceGetLedgerParamsEventType = "payment_retry_fee"
	BalanceGetLedgerParamsEventTypeByopFee                  BalanceGetLedgerParamsEventType = "byop_fee"
	BalanceGetLedgerParamsEventTypeEthocaFees               BalanceGetLedgerParamsEventType = "ethoca_fees"
	BalanceGetLedgerParamsEventTypeEthocaFeesReversal       BalanceGetLedgerParamsEventType = "ethoca_fees_reversal"
)

func (BalanceGetLedgerParamsEventType) IsKnown added in v1.81.0

type BalanceLedgerEntry added in v1.81.0

type BalanceLedgerEntry struct {
	ID                  string                      `json:"id" api:"required"`
	Amount              int64                       `json:"amount" api:"required"`
	BusinessID          string                      `json:"business_id" api:"required"`
	CreatedAt           time.Time                   `json:"created_at" api:"required" format:"date-time"`
	Currency            Currency                    `json:"currency" api:"required"`
	EventType           BalanceLedgerEntryEventType `json:"event_type" api:"required"`
	IsCredit            bool                        `json:"is_credit" api:"required"`
	UsdEquivalentAmount int64                       `json:"usd_equivalent_amount" api:"required"`
	AfterBalance        int64                       `json:"after_balance" api:"nullable"`
	BeforeBalance       int64                       `json:"before_balance" api:"nullable"`
	Description         string                      `json:"description" api:"nullable"`
	PayoutID            string                      `json:"payout_id" api:"nullable"`
	ReferenceObjectID   string                      `json:"reference_object_id" api:"nullable"`
	JSON                balanceLedgerEntryJSON      `json:"-"`
}

func (*BalanceLedgerEntry) UnmarshalJSON added in v1.81.0

func (r *BalanceLedgerEntry) UnmarshalJSON(data []byte) (err error)

type BalanceLedgerEntryEventType added in v1.81.0

type BalanceLedgerEntryEventType string
const (
	BalanceLedgerEntryEventTypePayment                  BalanceLedgerEntryEventType = "payment"
	BalanceLedgerEntryEventTypeRefund                   BalanceLedgerEntryEventType = "refund"
	BalanceLedgerEntryEventTypeRefundReversal           BalanceLedgerEntryEventType = "refund_reversal"
	BalanceLedgerEntryEventTypeDispute                  BalanceLedgerEntryEventType = "dispute"
	BalanceLedgerEntryEventTypeDisputeReversal          BalanceLedgerEntryEventType = "dispute_reversal"
	BalanceLedgerEntryEventTypeTax                      BalanceLedgerEntryEventType = "tax"
	BalanceLedgerEntryEventTypeTaxReversal              BalanceLedgerEntryEventType = "tax_reversal"
	BalanceLedgerEntryEventTypePaymentFees              BalanceLedgerEntryEventType = "payment_fees"
	BalanceLedgerEntryEventTypeRefundFees               BalanceLedgerEntryEventType = "refund_fees"
	BalanceLedgerEntryEventTypeRefundFeesReversal       BalanceLedgerEntryEventType = "refund_fees_reversal"
	BalanceLedgerEntryEventTypeDisputeFees              BalanceLedgerEntryEventType = "dispute_fees"
	BalanceLedgerEntryEventTypePayout                   BalanceLedgerEntryEventType = "payout"
	BalanceLedgerEntryEventTypePayoutFees               BalanceLedgerEntryEventType = "payout_fees"
	BalanceLedgerEntryEventTypePayoutReversal           BalanceLedgerEntryEventType = "payout_reversal"
	BalanceLedgerEntryEventTypePayoutFeesReversal       BalanceLedgerEntryEventType = "payout_fees_reversal"
	BalanceLedgerEntryEventTypeDodoCredits              BalanceLedgerEntryEventType = "dodo_credits"
	BalanceLedgerEntryEventTypeAdjustment               BalanceLedgerEntryEventType = "adjustment"
	BalanceLedgerEntryEventTypeCurrencyConversion       BalanceLedgerEntryEventType = "currency_conversion"
	BalanceLedgerEntryEventTypeAbandonedCartRecoveryFee BalanceLedgerEntryEventType = "abandoned_cart_recovery_fee"
	BalanceLedgerEntryEventTypeDunningFees              BalanceLedgerEntryEventType = "dunning_fees"
	BalanceLedgerEntryEventTypePaymentRetryFee          BalanceLedgerEntryEventType = "payment_retry_fee"
	BalanceLedgerEntryEventTypeByopFee                  BalanceLedgerEntryEventType = "byop_fee"
	BalanceLedgerEntryEventTypeEthocaFees               BalanceLedgerEntryEventType = "ethoca_fees"
	BalanceLedgerEntryEventTypeEthocaFeesReversal       BalanceLedgerEntryEventType = "ethoca_fees_reversal"
)

func (BalanceLedgerEntryEventType) IsKnown added in v1.81.0

func (r BalanceLedgerEntryEventType) IsKnown() bool

type BalanceService added in v1.81.0

type BalanceService struct {
	Options []option.RequestOption
}

BalanceService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewBalanceService method instead.

func NewBalanceService added in v1.81.0

func NewBalanceService(opts ...option.RequestOption) (r *BalanceService)

NewBalanceService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*BalanceService) GetLedger added in v1.81.0

func (*BalanceService) GetLedgerAutoPaging added in v1.81.0

type BillingAddress added in v1.14.0

type BillingAddress struct {
	// Two-letter ISO country code (ISO 3166-1 alpha-2)
	Country CountryCode `json:"country" api:"required"`
	// City name
	City string `json:"city" api:"nullable"`
	// State or province name
	State string `json:"state" api:"nullable"`
	// Street address including house number and unit/apartment if applicable
	Street string `json:"street" api:"nullable"`
	// Postal code or ZIP code
	Zipcode string             `json:"zipcode" api:"nullable"`
	JSON    billingAddressJSON `json:"-"`
}

func (*BillingAddress) UnmarshalJSON added in v1.14.0

func (r *BillingAddress) UnmarshalJSON(data []byte) (err error)

type BillingAddressParam added in v1.6.3

type BillingAddressParam struct {
	// Two-letter ISO country code (ISO 3166-1 alpha-2)
	Country param.Field[CountryCode] `json:"country" api:"required"`
	// City name
	City param.Field[string] `json:"city"`
	// State or province name
	State param.Field[string] `json:"state"`
	// Street address including house number and unit/apartment if applicable
	Street param.Field[string] `json:"street"`
	// Postal code or ZIP code
	Zipcode param.Field[string] `json:"zipcode"`
}

func (BillingAddressParam) MarshalJSON added in v1.6.3

func (r BillingAddressParam) MarshalJSON() (data []byte, err error)

type BlockByCustomerIDParam added in v1.115.0

type BlockByCustomerIDParam struct {
	// Customer to block. The block still applies to that customer's email.
	CustomerID param.Field[string] `json:"customer_id" api:"required"`
}

func (BlockByCustomerIDParam) MarshalJSON added in v1.115.0

func (r BlockByCustomerIDParam) MarshalJSON() (data []byte, err error)

type BlockByEmailParam added in v1.115.0

type BlockByEmailParam struct {
	// Email to block. It must belong to an existing customer of this business.
	Email param.Field[string] `json:"email" api:"required"`
}

func (BlockByEmailParam) MarshalJSON added in v1.115.0

func (r BlockByEmailParam) MarshalJSON() (data []byte, err error)

type BlockedCustomer added in v1.115.0

type BlockedCustomer struct {
	ID            string    `json:"id" api:"required"`
	CreatedAt     time.Time `json:"created_at" api:"required" format:"date-time"`
	CustomerEmail string    `json:"customer_email" api:"required"`
	CustomerID    string    `json:"customer_id" api:"required"`
	CustomerName  string    `json:"customer_name" api:"required"`
	// Customer id or email that the merchant supplied.
	Identifier string `json:"identifier" api:"required"`
	// Where a block came from. `Api` marks an API-key caller, which carries no
	// dashboard actor. The other values name the screen the merchant used.
	Source BlockedCustomerSource `json:"source" api:"required"`
	// Dashboard user who blocked the customer. `null` for an API-key caller.
	BlockedByEmail string `json:"blocked_by_email" api:"nullable"`
	// Subscriptions this block cancelled. Present on the create response only.
	CancelledSubscriptionIDs []string `json:"cancelled_subscription_ids" api:"nullable"`
	// Activity log. Present on the detail response only.
	Notes  []BlockedCustomerNote `json:"notes" api:"nullable"`
	Reason string                `json:"reason" api:"nullable"`
	// Subscriptions this block left live, because the cancel failed or the inline
	// batch filled up. Repeat the create call to continue; the block itself is already
	// in force.
	RemainingSubscriptionIDs []string `json:"remaining_subscription_ids" api:"nullable"`
	// False when the block left live subscriptions behind, including the case where
	// the sweep could not list them and `remaining_subscription_ids` is therefore
	// unknown. Repeat the create call until it reads true.
	SubscriptionsSwept bool                `json:"subscriptions_swept" api:"nullable"`
	UnblockedAt        time.Time           `json:"unblocked_at" api:"nullable" format:"date-time"`
	JSON               blockedCustomerJSON `json:"-"`
}

func (*BlockedCustomer) UnmarshalJSON added in v1.115.0

func (r *BlockedCustomer) UnmarshalJSON(data []byte) (err error)

type BlockedCustomerNote added in v1.115.0

type BlockedCustomerNote struct {
	ID          string                  `json:"id" api:"required"`
	CreatedAt   time.Time               `json:"created_at" api:"required" format:"date-time"`
	Note        string                  `json:"note" api:"required"`
	AuthorEmail string                  `json:"author_email" api:"nullable"`
	UpdatedAt   time.Time               `json:"updated_at" api:"nullable" format:"date-time"`
	JSON        blockedCustomerNoteJSON `json:"-"`
}

func (*BlockedCustomerNote) UnmarshalJSON added in v1.115.0

func (r *BlockedCustomerNote) UnmarshalJSON(data []byte) (err error)

type BlockedCustomerSource added in v1.115.0

type BlockedCustomerSource string

Where a block came from. `Api` marks an API-key caller, which carries no dashboard actor. The other values name the screen the merchant used.

const (
	BlockedCustomerSourceBlocklistPage BlockedCustomerSource = "blocklist_page"
	BlockedCustomerSourceCustomerPage  BlockedCustomerSource = "customer_page"
	BlockedCustomerSourcePaymentPage   BlockedCustomerSource = "payment_page"
	BlockedCustomerSourceDisputePage   BlockedCustomerSource = "dispute_page"
	BlockedCustomerSourceAPI           BlockedCustomerSource = "api"
)

func (BlockedCustomerSource) IsKnown added in v1.115.0

func (r BlockedCustomerSource) IsKnown() bool

type BlocklistCustomerListParams added in v1.115.0

type BlocklistCustomerListParams struct {
	// Filter by the dashboard user who blocked the customer.
	BlockedByEmail param.Field[string] `query:"blocked_by_email"`
	// Blocked on or after this time.
	CreatedAtGte param.Field[time.Time] `query:"created_at_gte" format:"date-time"`
	// Blocked on or before this time.
	CreatedAtLte param.Field[time.Time] `query:"created_at_lte" format:"date-time"`
	// Partial, case-insensitive match on the email and on the customer id.
	Identifier param.Field[string] `query:"identifier"`
	// Page number. Default 0.
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size. Default 10, maximum 100.
	PageSize param.Field[int64] `query:"page_size"`
}

func (BlocklistCustomerListParams) URLQuery added in v1.115.0

func (r BlocklistCustomerListParams) URLQuery() (v url.Values)

URLQuery serializes BlocklistCustomerListParams's query parameters as `url.Values`.

type BlocklistCustomerNewParams added in v1.115.0

type BlocklistCustomerNewParams struct {
	CreateBlockedCustomerRequest CreateBlockedCustomerRequestUnionParam `json:"create_blocked_customer_request" api:"required"`
}

func (BlocklistCustomerNewParams) MarshalJSON added in v1.115.0

func (r BlocklistCustomerNewParams) MarshalJSON() (data []byte, err error)

type BlocklistCustomerNoteNewParams added in v1.115.0

type BlocklistCustomerNoteNewParams struct {
	NoteRequest NoteRequestParam `json:"note_request" api:"required"`
}

func (BlocklistCustomerNoteNewParams) MarshalJSON added in v1.115.0

func (r BlocklistCustomerNoteNewParams) MarshalJSON() (data []byte, err error)

type BlocklistCustomerNoteService added in v1.115.0

type BlocklistCustomerNoteService struct {
	Options []option.RequestOption
}

BlocklistCustomerNoteService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewBlocklistCustomerNoteService method instead.

func NewBlocklistCustomerNoteService added in v1.115.0

func NewBlocklistCustomerNoteService(opts ...option.RequestOption) (r *BlocklistCustomerNoteService)

NewBlocklistCustomerNoteService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*BlocklistCustomerNoteService) New added in v1.115.0

func (*BlocklistCustomerNoteService) Update added in v1.115.0

type BlocklistCustomerNoteUpdateParams added in v1.115.0

type BlocklistCustomerNoteUpdateParams struct {
	NoteRequest NoteRequestParam `json:"note_request" api:"required"`
}

func (BlocklistCustomerNoteUpdateParams) MarshalJSON added in v1.115.0

func (r BlocklistCustomerNoteUpdateParams) MarshalJSON() (data []byte, err error)

type BlocklistCustomerService added in v1.115.0

type BlocklistCustomerService struct {
	Options []option.RequestOption
	Notes   *BlocklistCustomerNoteService
}

BlocklistCustomerService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewBlocklistCustomerService method instead.

func NewBlocklistCustomerService added in v1.115.0

func NewBlocklistCustomerService(opts ...option.RequestOption) (r *BlocklistCustomerService)

NewBlocklistCustomerService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*BlocklistCustomerService) Delete added in v1.115.0

func (r *BlocklistCustomerService) Delete(ctx context.Context, entryID string, opts ...option.RequestOption) (err error)

func (*BlocklistCustomerService) Get added in v1.115.0

func (r *BlocklistCustomerService) Get(ctx context.Context, entryID string, opts ...option.RequestOption) (res *BlockedCustomer, err error)

func (*BlocklistCustomerService) List added in v1.115.0

func (*BlocklistCustomerService) ListAutoPaging added in v1.115.0

func (*BlocklistCustomerService) New added in v1.115.0

type BlocklistService added in v1.115.0

type BlocklistService struct {
	Options   []option.RequestOption
	Customers *BlocklistCustomerService
}

BlocklistService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewBlocklistService method instead.

func NewBlocklistService added in v1.115.0

func NewBlocklistService(opts ...option.RequestOption) (r *BlocklistService)

NewBlocklistService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

type Brand added in v1.43.0

type Brand struct {
	BrandID             string                  `json:"brand_id" api:"required"`
	BusinessID          string                  `json:"business_id" api:"required"`
	Enabled             bool                    `json:"enabled" api:"required"`
	StatementDescriptor string                  `json:"statement_descriptor" api:"required"`
	VerificationEnabled bool                    `json:"verification_enabled" api:"required"`
	VerificationStatus  BrandVerificationStatus `json:"verification_status" api:"required"`
	// Time the brand was archived. Null for an active brand.
	ArchivedAt  time.Time `json:"archived_at" api:"nullable" format:"date-time"`
	Description string    `json:"description" api:"nullable"`
	Image       string    `json:"image" api:"nullable"`
	Name        string    `json:"name" api:"nullable"`
	// Incase the brand verification fails or is put on hold
	ReasonForHold string    `json:"reason_for_hold" api:"nullable"`
	SupportEmail  string    `json:"support_email" api:"nullable"`
	URL           string    `json:"url" api:"nullable"`
	JSON          brandJSON `json:"-"`
}

func (*Brand) UnmarshalJSON added in v1.43.0

func (r *Brand) UnmarshalJSON(data []byte) (err error)

type BrandArchiveParams added in v1.113.0

type BrandArchiveParams struct {
	// Brand that takes over the products and the live subscriptions of the brand you
	// archive. It must be a brand of the same business, and it must not be archived.
	// The primary brand (its brand id is the business id) is a valid target. Omit this
	// field only when the brand holds no products and no live subscriptions.
	MoveProductsTo param.Field[string] `json:"move_products_to"`
}

func (BrandArchiveParams) MarshalJSON added in v1.113.0

func (r BrandArchiveParams) MarshalJSON() (data []byte, err error)

type BrandArchiveResponse added in v1.113.0

type BrandArchiveResponse struct {
	// Time the brand was archived.
	ArchivedAt time.Time `json:"archived_at" api:"required" format:"date-time"`
	// The archived brand.
	BrandID string `json:"brand_id" api:"required"`
	// Count of product collections moved to the target brand.
	CollectionsMoved int64 `json:"collections_moved" api:"required"`
	// Count of products moved to the target brand.
	ProductsMoved int64 `json:"products_moved" api:"required"`
	// Count of live subscriptions moved to the target brand.
	SubscriptionsMoved int64 `json:"subscriptions_moved" api:"required"`
	// Brand that received the moved records. Null when no target was given.
	MovedToBrandID string                   `json:"moved_to_brand_id" api:"nullable"`
	JSON           brandArchiveResponseJSON `json:"-"`
}

func (*BrandArchiveResponse) UnmarshalJSON added in v1.113.0

func (r *BrandArchiveResponse) UnmarshalJSON(data []byte) (err error)

type BrandListParams added in v1.113.0

type BrandListParams struct {
	// Set to true to also list archived brands. Default false.
	IncludeArchived param.Field[bool] `query:"include_archived"`
}

func (BrandListParams) URLQuery added in v1.113.0

func (r BrandListParams) URLQuery() (v url.Values)

URLQuery serializes BrandListParams's query parameters as `url.Values`.

type BrandListResponse added in v1.27.0

type BrandListResponse struct {
	// List of brands for this business
	Items []Brand               `json:"items" api:"required"`
	JSON  brandListResponseJSON `json:"-"`
}

func (*BrandListResponse) UnmarshalJSON added in v1.27.0

func (r *BrandListResponse) UnmarshalJSON(data []byte) (err error)

type BrandNewParams added in v1.27.0

type BrandNewParams struct {
	Description         param.Field[string] `json:"description"`
	Name                param.Field[string] `json:"name"`
	StatementDescriptor param.Field[string] `json:"statement_descriptor"`
	SupportEmail        param.Field[string] `json:"support_email"`
	URL                 param.Field[string] `json:"url"`
}

func (BrandNewParams) MarshalJSON added in v1.27.0

func (r BrandNewParams) MarshalJSON() (data []byte, err error)

type BrandService added in v1.27.0

type BrandService struct {
	Options []option.RequestOption
}

BrandService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewBrandService method instead.

func NewBrandService added in v1.27.0

func NewBrandService(opts ...option.RequestOption) (r *BrandService)

NewBrandService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*BrandService) Archive added in v1.113.0

func (r *BrandService) Archive(ctx context.Context, id string, body BrandArchiveParams, opts ...option.RequestOption) (res *BrandArchiveResponse, err error)

Archive a brand. Its products, live subscriptions, and product collections move to the `move_products_to` brand. Archive is permanent.

func (*BrandService) Get added in v1.27.0

func (r *BrandService) Get(ctx context.Context, id string, opts ...option.RequestOption) (res *Brand, err error)

Thin handler just calls `get_brand` and wraps in `Json(...)`

func (*BrandService) List added in v1.27.0

func (r *BrandService) List(ctx context.Context, query BrandListParams, opts ...option.RequestOption) (res *BrandListResponse, err error)

func (*BrandService) New added in v1.27.0

func (r *BrandService) New(ctx context.Context, body BrandNewParams, opts ...option.RequestOption) (res *Brand, err error)

func (*BrandService) Update added in v1.27.0

func (r *BrandService) Update(ctx context.Context, id string, body BrandUpdateParams, opts ...option.RequestOption) (res *Brand, err error)

func (*BrandService) UpdateImages added in v1.27.0

func (r *BrandService) UpdateImages(ctx context.Context, id string, opts ...option.RequestOption) (res *BrandUpdateImagesResponse, err error)

type BrandUpdateImagesResponse added in v1.27.0

type BrandUpdateImagesResponse struct {
	// UUID that will be used as the image identifier/key suffix
	ImageID string `json:"image_id" api:"required" format:"uuid"`
	// Presigned URL to upload the image
	URL  string                        `json:"url" api:"required"`
	JSON brandUpdateImagesResponseJSON `json:"-"`
}

func (*BrandUpdateImagesResponse) UnmarshalJSON added in v1.27.0

func (r *BrandUpdateImagesResponse) UnmarshalJSON(data []byte) (err error)

type BrandUpdateParams added in v1.27.0

type BrandUpdateParams struct {
	Description param.Field[string] `json:"description"`
	// The UUID you got back from the presigned‐upload call
	ImageID             param.Field[string] `json:"image_id" format:"uuid"`
	Name                param.Field[string] `json:"name"`
	StatementDescriptor param.Field[string] `json:"statement_descriptor"`
	SupportEmail        param.Field[string] `json:"support_email"`
	URL                 param.Field[string] `json:"url"`
}

func (BrandUpdateParams) MarshalJSON added in v1.27.0

func (r BrandUpdateParams) MarshalJSON() (data []byte, err error)

type BrandVerificationStatus added in v1.43.0

type BrandVerificationStatus string
const (
	BrandVerificationStatusSuccess BrandVerificationStatus = "Success"
	BrandVerificationStatusFail    BrandVerificationStatus = "Fail"
	BrandVerificationStatusReview  BrandVerificationStatus = "Review"
	BrandVerificationStatusHold    BrandVerificationStatus = "Hold"
)

func (BrandVerificationStatus) IsKnown added in v1.43.0

func (r BrandVerificationStatus) IsKnown() bool

type CancellationFeedback added in v1.97.0

type CancellationFeedback string
const (
	CancellationFeedbackTooExpensive    CancellationFeedback = "too_expensive"
	CancellationFeedbackMissingFeatures CancellationFeedback = "missing_features"
	CancellationFeedbackSwitchedService CancellationFeedback = "switched_service"
	CancellationFeedbackUnused          CancellationFeedback = "unused"
	CancellationFeedbackCustomerService CancellationFeedback = "customer_service"
	CancellationFeedbackLowQuality      CancellationFeedback = "low_quality"
	CancellationFeedbackTooComplex      CancellationFeedback = "too_complex"
	CancellationFeedbackOther           CancellationFeedback = "other"
)

func (CancellationFeedback) IsKnown added in v1.97.0

func (r CancellationFeedback) IsKnown() bool

type CbbOverageBehavior added in v1.86.0

type CbbOverageBehavior string

Controls how overage is handled at the end of a billing cycle.

| Preset | Charge at billing | Credits reduce overage | Preserve overage at reset | | -------------------------- | :---------------: | :--------------------: | :-----------------------: | | `forgive_at_reset` | No | No | No | | `invoice_at_billing` | Yes | No | No | | `carry_deficit` | No | No | Yes | | `carry_deficit_auto_repay` | No | Yes | Yes |

const (
	CbbOverageBehaviorForgiveAtReset        CbbOverageBehavior = "forgive_at_reset"
	CbbOverageBehaviorInvoiceAtBilling      CbbOverageBehavior = "invoice_at_billing"
	CbbOverageBehaviorCarryDeficit          CbbOverageBehavior = "carry_deficit"
	CbbOverageBehaviorCarryDeficitAutoRepay CbbOverageBehavior = "carry_deficit_auto_repay"
)

func (CbbOverageBehavior) IsKnown added in v1.86.0

func (r CbbOverageBehavior) IsKnown() bool

type CbbProrationBehavior added in v1.86.0

type CbbProrationBehavior string
const (
	CbbProrationBehaviorProrate   CbbProrationBehavior = "prorate"
	CbbProrationBehaviorNoProrate CbbProrationBehavior = "no_prorate"
)

func (CbbProrationBehavior) IsKnown added in v1.86.0

func (r CbbProrationBehavior) IsKnown() bool

type CheckoutSessionBillingAddressParam added in v1.81.0

type CheckoutSessionBillingAddressParam struct {
	// Two-letter ISO country code (ISO 3166-1 alpha-2)
	Country param.Field[CountryCode] `json:"country" api:"required"`
	// City name
	City param.Field[string] `json:"city"`
	// State or province name
	State param.Field[string] `json:"state"`
	// Street address including house number and unit/apartment if applicable
	Street param.Field[string] `json:"street"`
	// Postal code or ZIP code
	Zipcode param.Field[string] `json:"zipcode"`
}

func (CheckoutSessionBillingAddressParam) MarshalJSON added in v1.81.0

func (r CheckoutSessionBillingAddressParam) MarshalJSON() (data []byte, err error)

type CheckoutSessionCustomizationParam added in v1.81.0

type CheckoutSessionCustomizationParam struct {
	// Force the checkout interface to render in a specific language (e.g. `en`, `es`)
	ForceLanguage param.Field[string] `json:"force_language"`
	// Show on demand tag
	//
	// Default is true
	ShowOnDemandTag param.Field[bool] `json:"show_on_demand_tag"`
	// Show order details by default
	//
	// Default is true
	ShowOrderDetails param.Field[bool] `json:"show_order_details"`
	// Theme of the page (determines which mode - light/dark/system - to use)
	//
	// If not provided, uses the business-configured theme from business_themes table.
	Theme param.Field[CheckoutSessionCustomizationTheme] `json:"theme"`
	// Optional custom theme configuration with colors for light and dark modes
	ThemeConfig param.Field[ThemeConfigParam] `json:"theme_config"`
}

func (CheckoutSessionCustomizationParam) MarshalJSON added in v1.81.0

func (r CheckoutSessionCustomizationParam) MarshalJSON() (data []byte, err error)

type CheckoutSessionCustomizationTheme added in v1.81.0

type CheckoutSessionCustomizationTheme string

Theme of the page (determines which mode - light/dark/system - to use)

If not provided, uses the business-configured theme from business_themes table.

const (
	CheckoutSessionCustomizationThemeDark   CheckoutSessionCustomizationTheme = "dark"
	CheckoutSessionCustomizationThemeLight  CheckoutSessionCustomizationTheme = "light"
	CheckoutSessionCustomizationThemeSystem CheckoutSessionCustomizationTheme = "system"
)

func (CheckoutSessionCustomizationTheme) IsKnown added in v1.81.0

type CheckoutSessionFlagsParam added in v1.81.0

type CheckoutSessionFlagsParam struct {
	// if customer is allowed to change currency, set it to true
	//
	// Default is true
	AllowCurrencySelection param.Field[bool] `json:"allow_currency_selection"`
	// If true, the customer can supply or edit the business name associated with the
	// tax id during checkout. Works independently of `allow_customer_editing_tax_id` —
	// either flag (or `allow_tax_id`) is sufficient to let the customer override the
	// session's business name. Typically set together with
	// `allow_customer_editing_tax_id`.
	//
	// Default is false
	AllowCustomerEditingBusinessName param.Field[bool] `json:"allow_customer_editing_business_name"`
	AllowCustomerEditingCity         param.Field[bool] `json:"allow_customer_editing_city"`
	AllowCustomerEditingCountry      param.Field[bool] `json:"allow_customer_editing_country"`
	AllowCustomerEditingEmail        param.Field[bool] `json:"allow_customer_editing_email"`
	AllowCustomerEditingName         param.Field[bool] `json:"allow_customer_editing_name"`
	AllowCustomerEditingState        param.Field[bool] `json:"allow_customer_editing_state"`
	AllowCustomerEditingStreet       param.Field[bool] `json:"allow_customer_editing_street"`
	AllowCustomerEditingTaxID        param.Field[bool] `json:"allow_customer_editing_tax_id"`
	AllowCustomerEditingZipcode      param.Field[bool] `json:"allow_customer_editing_zipcode"`
	// If the customer is allowed to apply discount code, set it to true.
	//
	// Default is true
	AllowDiscountCode param.Field[bool] `json:"allow_discount_code"`
	// If true, the customer can add or remove addons on a subscription product during
	// checkout.
	//
	// Default is false
	AllowEditingAddons param.Field[bool] `json:"allow_editing_addons"`
	// If phone number is collected from customer, set it to rue
	//
	// Default is true
	AllowPhoneNumberCollection param.Field[bool] `json:"allow_phone_number_collection"`
	// If the customer is allowed to add tax id, set it to true
	//
	// Default is true
	AllowTaxID param.Field[bool] `json:"allow_tax_id"`
	// Set to true if a new customer object should be created. By default email is used
	// to find an existing customer to attach the session to
	//
	// Default is false
	AlwaysCreateNewCustomer param.Field[bool] `json:"always_create_new_customer"`
	// If true, redirects the customer immediately after payment completion
	//
	// Default is false
	RedirectImmediately param.Field[bool] `json:"redirect_immediately"`
	// If true, the customer must provide a phone number to complete checkout. Requires
	// `allow_phone_number_collection` to also be true.
	//
	// Default is false
	RequirePhoneNumber param.Field[bool] `json:"require_phone_number"`
	// If true, the session uses the single-page checkout flow: the page initializes
	// the payment at load time and confirms it in place, with no separate payment
	// page.
	//
	// Default is false
	SinglePage param.Field[bool] `json:"single_page"`
}

func (CheckoutSessionFlagsParam) MarshalJSON added in v1.81.0

func (r CheckoutSessionFlagsParam) MarshalJSON() (data []byte, err error)

type CheckoutSessionNewParams added in v1.51.0

type CheckoutSessionNewParams struct {
	CheckoutSessionRequest CheckoutSessionRequestParam `json:"checkout_session_request" api:"required"`
}

func (CheckoutSessionNewParams) MarshalJSON added in v1.51.0

func (r CheckoutSessionNewParams) MarshalJSON() (data []byte, err error)

type CheckoutSessionPreviewParams added in v1.73.0

type CheckoutSessionPreviewParams struct {
	CheckoutSessionRequest CheckoutSessionRequestParam `json:"checkout_session_request" api:"required"`
}

func (CheckoutSessionPreviewParams) MarshalJSON added in v1.73.0

func (r CheckoutSessionPreviewParams) MarshalJSON() (data []byte, err error)

type CheckoutSessionPreviewResponse added in v1.73.0

type CheckoutSessionPreviewResponse struct {
	// Billing country
	BillingCountry CountryCode `json:"billing_country" api:"required"`
	// Currency in which the calculations were made
	Currency Currency `json:"currency" api:"required"`
	// Breakup of the current payment
	CurrentBreakup CheckoutSessionPreviewResponseCurrentBreakup `json:"current_breakup" api:"required"`
	// Whether the payment will be routed through the merchant's own processor (BYOP).
	// True when the session's business has a BYOP route configured for the billing
	// country; in that case the quoted amounts exclude Dodo-computed tax because the
	// merchant is MoR and owns tax.
	IsByop bool `json:"is_byop" api:"required"`
	// False when the customer can confirm this session with no card. True for every
	// other cart, including a one-time cart.
	PaymentMethodRequired bool `json:"payment_method_required" api:"required"`
	// The total product cart
	ProductCart []CheckoutSessionPreviewResponseProductCart `json:"product_cart" api:"required"`
	// Total calculate price of the product cart
	TotalPrice int64 `json:"total_price" api:"required"`
	// The upcoming billing date for subscriptions, computed relative to now: with a
	// trial it is `now + trial_period_days`, otherwise `now + payment frequency`.
	// `None` for one-time-only carts. This is a preview estimate; the authoritative
	// value is set when the subscription activates.
	NextBillingDate time.Time `json:"next_billing_date" api:"nullable" format:"date-time"`
	// Breakup of recurring payments (None for one-time only)
	RecurringBreakup CheckoutSessionPreviewResponseRecurringBreakup `json:"recurring_breakup" api:"nullable"`
	// Registered business name from the official registry (EU/GB/AU) when found
	TaxIDBusinessName string `json:"tax_id_business_name" api:"nullable"`
	// Error message if tax ID validation failed
	TaxIDErrMsg string `json:"tax_id_err_msg" api:"nullable"`
	// The matched tax ID notation (e.g. "VAT Number", "GSTIN") when valid
	TaxIDFormatName string `json:"tax_id_format_name" api:"nullable"`
	// Total tax
	TotalTax int64 `json:"total_tax" api:"nullable"`
	// Per-unit trial amount after discounts, in the price currency's minor units
	// (pre-quantity, pre-tax; see `current_breakup` for the taxed total due today).
	// Only present for a paid trial; `None` for a free trial or no trial.
	TrialAmount int64 `json:"trial_amount" api:"nullable"`
	// Effective trial duration in days for the subscription line, when there's a trial
	// (free or paid). `None` if no subscription or no trial.
	TrialPeriodDays int64                              `json:"trial_period_days" api:"nullable"`
	JSON            checkoutSessionPreviewResponseJSON `json:"-"`
}

Data returned by the calculate checkout session API

func (*CheckoutSessionPreviewResponse) UnmarshalJSON added in v1.73.0

func (r *CheckoutSessionPreviewResponse) UnmarshalJSON(data []byte) (err error)

type CheckoutSessionPreviewResponseCurrentBreakup added in v1.73.0

type CheckoutSessionPreviewResponseCurrentBreakup struct {
	// Total discount amount
	Discount int64 `json:"discount" api:"required"`
	// Subtotal before discount (pre-tax original prices)
	Subtotal int64 `json:"subtotal" api:"required"`
	// Total amount to be charged (final amount after all calculations)
	TotalAmount int64 `json:"total_amount" api:"required"`
	// Total tax amount
	Tax  int64                                            `json:"tax" api:"nullable"`
	JSON checkoutSessionPreviewResponseCurrentBreakupJSON `json:"-"`
}

Breakup of the current payment

func (*CheckoutSessionPreviewResponseCurrentBreakup) UnmarshalJSON added in v1.73.0

func (r *CheckoutSessionPreviewResponseCurrentBreakup) UnmarshalJSON(data []byte) (err error)

type CheckoutSessionPreviewResponseProductCart added in v1.73.0

type CheckoutSessionPreviewResponseProductCart struct {
	// Credit entitlements that will be granted upon purchase
	CreditEntitlements []CheckoutSessionPreviewResponseProductCartCreditEntitlement `json:"credit_entitlements" api:"required"`
	// the currency in which the calculatiosn were made
	Currency Currency `json:"currency" api:"required"`
	// discounted price
	DiscountedPrice int64 `json:"discounted_price" api:"required"`
	// Whether this is a subscription product (affects tax calculation in breakup)
	IsSubscription bool                                             `json:"is_subscription" api:"required"`
	IsUsageBased   bool                                             `json:"is_usage_based" api:"required"`
	Meters         []CheckoutSessionPreviewResponseProductCartMeter `json:"meters" api:"required"`
	// the product currency
	OgCurrency Currency `json:"og_currency" api:"required"`
	// original price of the product
	OgPrice int64 `json:"og_price" api:"required"`
	// unique id of the product
	ProductID string `json:"product_id" api:"required"`
	// Quanitity
	Quantity int64 `json:"quantity" api:"required"`
	// tax category
	TaxCategory TaxCategory `json:"tax_category" api:"required"`
	// Whether tax is included in the price
	TaxInclusive bool `json:"tax_inclusive" api:"required"`
	// tax rate
	TaxRate     int64                                            `json:"tax_rate" api:"required"`
	Addons      []CheckoutSessionPreviewResponseProductCartAddon `json:"addons" api:"nullable"`
	Description string                                           `json:"description" api:"nullable"`
	// Percentage rate (basis points) of the applicable percentage code; null for flat
	// codes (their deduction is `og_price - discounted_price`).
	DiscountAmount int64 `json:"discount_amount" api:"nullable"`
	// number of cycles the discount will apply
	DiscountCycle int64 `json:"discount_cycle" api:"nullable"`
	// name of the product
	Name string `json:"name" api:"nullable"`
	// total tax
	Tax  int64                                         `json:"tax" api:"nullable"`
	JSON checkoutSessionPreviewResponseProductCartJSON `json:"-"`
}

func (*CheckoutSessionPreviewResponseProductCart) UnmarshalJSON added in v1.73.0

func (r *CheckoutSessionPreviewResponseProductCart) UnmarshalJSON(data []byte) (err error)

type CheckoutSessionPreviewResponseProductCartAddon added in v1.73.0

type CheckoutSessionPreviewResponseProductCartAddon struct {
	AddonID         string   `json:"addon_id" api:"required"`
	Currency        Currency `json:"currency" api:"required"`
	DiscountedPrice int64    `json:"discounted_price" api:"required"`
	Name            string   `json:"name" api:"required"`
	OgCurrency      Currency `json:"og_currency" api:"required"`
	OgPrice         int64    `json:"og_price" api:"required"`
	Quantity        int64    `json:"quantity" api:"required"`
	// Per-unit price in `currency`, converted and adaptive-priced but pre-tax and
	// pre-discount (both depend on quantity and the rest of the cart). Set even when
	// `quantity` is 0, so the checkout page can price the addon before the buyer has
	// selected any.
	SingleQuantityPrice int64 `json:"single_quantity_price" api:"required"`
	// Represents the different categories of taxation applicable to various products
	// and services.
	TaxCategory  TaxCategory `json:"tax_category" api:"required"`
	TaxInclusive bool        `json:"tax_inclusive" api:"required"`
	TaxRate      int64       `json:"tax_rate" api:"required"`
	Description  string      `json:"description" api:"nullable"`
	// Percentage rate (basis points) of the applicable percentage code; null for flat
	// codes (their deduction is `og_price - discounted_price`).
	DiscountAmount int64                                              `json:"discount_amount" api:"nullable"`
	Tax            int64                                              `json:"tax" api:"nullable"`
	JSON           checkoutSessionPreviewResponseProductCartAddonJSON `json:"-"`
}

func (*CheckoutSessionPreviewResponseProductCartAddon) UnmarshalJSON added in v1.73.0

func (r *CheckoutSessionPreviewResponseProductCartAddon) UnmarshalJSON(data []byte) (err error)

type CheckoutSessionPreviewResponseProductCartCreditEntitlement added in v1.84.0

type CheckoutSessionPreviewResponseProductCartCreditEntitlement struct {
	// ID of the credit entitlement
	CreditEntitlementID string `json:"credit_entitlement_id" api:"required"`
	// Name of the credit entitlement
	CreditEntitlementName string `json:"credit_entitlement_name" api:"required"`
	// Unit label (e.g. "API Calls", "Tokens")
	CreditEntitlementUnit string `json:"credit_entitlement_unit" api:"required"`
	// Number of credits granted
	CreditsAmount string                                                         `json:"credits_amount" api:"required"`
	JSON          checkoutSessionPreviewResponseProductCartCreditEntitlementJSON `json:"-"`
}

Minimal credit entitlement info shown at checkout — what credits the customer will receive

func (*CheckoutSessionPreviewResponseProductCartCreditEntitlement) UnmarshalJSON added in v1.84.0

type CheckoutSessionPreviewResponseProductCartMeter added in v1.73.0

type CheckoutSessionPreviewResponseProductCartMeter struct {
	MeasurementUnit string                                             `json:"measurement_unit" api:"required"`
	Name            string                                             `json:"name" api:"required"`
	PricePerUnit    string                                             `json:"price_per_unit" api:"required"`
	Description     string                                             `json:"description" api:"nullable"`
	FreeThreshold   int64                                              `json:"free_threshold" api:"nullable"`
	JSON            checkoutSessionPreviewResponseProductCartMeterJSON `json:"-"`
}

func (*CheckoutSessionPreviewResponseProductCartMeter) UnmarshalJSON added in v1.73.0

func (r *CheckoutSessionPreviewResponseProductCartMeter) UnmarshalJSON(data []byte) (err error)

type CheckoutSessionPreviewResponseRecurringBreakup added in v1.73.0

type CheckoutSessionPreviewResponseRecurringBreakup struct {
	// Total discount amount
	Discount int64 `json:"discount" api:"required"`
	// Subtotal before discount (pre-tax original prices)
	Subtotal int64 `json:"subtotal" api:"required"`
	// Total recurring amount including tax
	TotalAmount int64 `json:"total_amount" api:"required"`
	// Total tax on recurring payments
	Tax  int64                                              `json:"tax" api:"nullable"`
	JSON checkoutSessionPreviewResponseRecurringBreakupJSON `json:"-"`
}

Breakup of recurring payments (None for one-time only)

func (*CheckoutSessionPreviewResponseRecurringBreakup) UnmarshalJSON added in v1.73.0

func (r *CheckoutSessionPreviewResponseRecurringBreakup) UnmarshalJSON(data []byte) (err error)

type CheckoutSessionRequestParam added in v1.51.0

type CheckoutSessionRequestParam struct {
	ProductCart param.Field[[]ProductItemReqParam] `json:"product_cart" api:"required"`
	// Customers will never see payment methods that are not in this list. However,
	// adding a method here does not guarantee customers will see it. Availability
	// still depends on other factors (e.g., customer location, merchant settings).
	//
	// Disclaimar: Always provide 'credit' and 'debit' as a fallback. If all payment
	// methods are unavailable, checkout session will fail.
	AllowedPaymentMethodTypes param.Field[[]PaymentMethodTypes] `json:"allowed_payment_method_types"`
	// Billing address information for the session
	BillingAddress param.Field[CheckoutSessionBillingAddressParam] `json:"billing_address"`
	// This field is ingored if adaptive pricing is disabled
	BillingCurrency param.Field[Currency] `json:"billing_currency"`
	// The URL to redirect the customer if they cancel or go back from the checkout. If
	// not provided, the back button will not be displayed.
	CancelURL param.Field[string] `json:"cancel_url"`
	// If confirm is true, all the details will be finalized. If required data is
	// missing, an API error is thrown.
	Confirm param.Field[bool] `json:"confirm"`
	// Custom fields to collect from customer during checkout (max 5 fields)
	CustomFields param.Field[[]CustomFieldParam] `json:"custom_fields"`
	// Customer details for the session
	Customer param.Field[CustomerRequestUnionParam] `json:"customer"`
	// Optional business / legal name associated with the tax id. When provided
	// together with a valid tax id for a B2B purchase, this name is rendered on the
	// invoice instead of the customer's personal name.
	CustomerBusinessName param.Field[string] `json:"customer_business_name"`
	// Customization for the checkout session page
	Customization param.Field[CheckoutSessionCustomizationParam] `json:"customization"`
	// DEPRECATED: Use discount_codes instead. Cannot be used together with
	// discount_codes.
	//
	// Deprecated: Use `discount_id` instead.
	DiscountCode param.Field[string] `json:"discount_code"`
	// Stacked discount codes to apply, in order. Max 20. Cannot be used together with
	// discount_code.
	DiscountCodes param.Field[[]string]                  `json:"discount_codes"`
	FeatureFlags  param.Field[CheckoutSessionFlagsParam] `json:"feature_flags"`
	// Override merchant default 3DS behaviour for this session
	Force3DS param.Field[bool] `json:"force_3ds"`
	// Override the merchant-level mandate floor (in INR paise) for INR e-mandates on
	// Indian-card recurring payments. The mandate amount sent to the processor is
	// `max(this_floor, actual_billing_amount)`, so this is effectively the
	// customer-facing authorization ceiling whenever billing is lower. When unset, the
	// merchant setting applies; when that's also unset, the system default of ₹15,000
	// applies.
	MandateMinAmountInrPaise param.Field[int64] `json:"mandate_min_amount_inr_paise"`
	// Additional metadata associated with the payment. Defaults to empty if not
	// provided.
	Metadata param.Field[MetadataParam] `json:"metadata"`
	// If true, only zipcode is required when confirm is true; other address fields
	// remain optional
	MinimalAddress param.Field[bool] `json:"minimal_address"`
	// Optional payment method ID to use for this checkout session. Only allowed when
	// `confirm` is true. If provided, existing customer id must also be provided.
	PaymentMethodID param.Field[string] `json:"payment_method_id"`
	// Product collection ID for collection-based checkout flow
	ProductCollectionID param.Field[string] `json:"product_collection_id"`
	// The url to redirect after payment failure or success.
	ReturnURL param.Field[string] `json:"return_url"`
	// If true, returns a shortened checkout URL. Defaults to false if not specified.
	ShortLink param.Field[bool] `json:"short_link"`
	// Display saved payment methods of a returning customer False by default
	ShowSavedPaymentMethods param.Field[bool]                  `json:"show_saved_payment_methods"`
	SubscriptionData        param.Field[SubscriptionDataParam] `json:"subscription_data"`
	// Tax ID for the customer (e.g. VAT number). Requires billing_address with
	// country.
	TaxID param.Field[string] `json:"tax_id"`
}

func (CheckoutSessionRequestParam) MarshalJSON added in v1.51.0

func (r CheckoutSessionRequestParam) MarshalJSON() (data []byte, err error)

type CheckoutSessionResponse added in v1.51.0

type CheckoutSessionResponse struct {
	// The ID of the created checkout session
	SessionID string `json:"session_id" api:"required"`
	// Checkout url (None when payment_method_id is provided)
	CheckoutURL string `json:"checkout_url" api:"nullable"`
	// Client secret used to load the Dodo Payments checkout SDK. Returned when
	// `confirm: true` was passed and a PaymentIntent was created at session-creation
	// time. `None` otherwise.
	ClientSecret string `json:"client_secret" api:"nullable"`
	// Underlying payment id when `confirm: true` was passed and a PaymentIntent was
	// created at session-creation time. `None` otherwise.
	PaymentID string `json:"payment_id" api:"nullable"`
	// Publishable key for the Dodo Payments checkout SDK. Returned when
	// `confirm: true` was passed and a PaymentIntent was created at session-creation
	// time. `None` otherwise.
	PublishableKey string                      `json:"publishable_key" api:"nullable"`
	JSON           checkoutSessionResponseJSON `json:"-"`
}

func (*CheckoutSessionResponse) UnmarshalJSON added in v1.51.0

func (r *CheckoutSessionResponse) UnmarshalJSON(data []byte) (err error)

type CheckoutSessionService added in v1.51.0

type CheckoutSessionService struct {
	Options []option.RequestOption
}

CheckoutSessionService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewCheckoutSessionService method instead.

func NewCheckoutSessionService added in v1.51.0

func NewCheckoutSessionService(opts ...option.RequestOption) (r *CheckoutSessionService)

NewCheckoutSessionService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*CheckoutSessionService) Get added in v1.56.2

func (*CheckoutSessionService) New added in v1.51.0

func (*CheckoutSessionService) Preview added in v1.73.0

type CheckoutSessionStatus added in v1.56.2

type CheckoutSessionStatus struct {
	// Id of the checkout session
	ID string `json:"id" api:"required"`
	// Created at timestamp
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Customer email: prefers payment's customer, falls back to session
	CustomerEmail string `json:"customer_email" api:"nullable"`
	// Customer name: prefers payment's customer, falls back to session
	CustomerName string `json:"customer_name" api:"nullable"`
	// Id of the payment created by the checkout sessions.
	//
	// Null if checkout sessions is still at the details collection stage.
	PaymentID string `json:"payment_id" api:"nullable"`
	// status of the payment.
	//
	// Null if checkout sessions is still at the details collection stage.
	PaymentStatus IntentStatus              `json:"payment_status" api:"nullable"`
	JSON          checkoutSessionStatusJSON `json:"-"`
}

func (*CheckoutSessionStatus) UnmarshalJSON added in v1.56.2

func (r *CheckoutSessionStatus) UnmarshalJSON(data []byte) (err error)

type Client

type Client struct {
	Options             []option.RequestOption
	CheckoutSessions    *CheckoutSessionService
	Payments            *PaymentService
	Subscriptions       *SubscriptionService
	Invoices            *InvoiceService
	Licenses            *LicenseService
	LicenseKeys         *LicenseKeyService
	LicenseKeyInstances *LicenseKeyInstanceService
	Customers           *CustomerService
	Blocklist           *BlocklistService
	Refunds             *RefundService
	Disputes            *DisputeService
	Payouts             *PayoutService
	Products            *ProductService
	Misc                *MiscService
	Discounts           *DiscountService
	Addons              *AddonService
	Brands              *BrandService
	Webhooks            *WebhookService
	WebhookEvents       *WebhookEventService
	UsageEvents         *UsageEventService
	Meters              *MeterService
	Balances            *BalanceService
	CreditEntitlements  *CreditEntitlementService
	Entitlements        *EntitlementService
	ProductCollections  *ProductCollectionService
}

Client creates a struct with services and top level methods that help with interacting with the Dodo Payments API. You should not instantiate this client directly, and instead use the NewClient method instead.

func NewClient

func NewClient(opts ...option.RequestOption) (r *Client)

NewClient generates a new client with the default option read from the environment (DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_WEBHOOK_KEY, DODO_PAYMENTS_BASE_URL). The option passed in as arguments are applied after these default arguments, and all option will be passed down to the services and requests that this client makes.

func (*Client) Delete

func (r *Client) Delete(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Delete makes a DELETE request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Execute

func (r *Client) Execute(ctx context.Context, method string, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Execute makes a request with the given context, method, URL, request params, response, and request options. This is useful for hitting undocumented endpoints while retaining the base URL, auth, retries, and other options from the client.

If a byte slice or an io.Reader is supplied to params, it will be used as-is for the request body.

The params is by default serialized into the body using encoding/json. If your type implements a MarshalJSON function, it will be used instead to serialize the request. If a URLQuery method is implemented, the returned url.Values will be used as query strings to the url.

If your params struct uses param.Field, you must provide either [MarshalJSON], [URLQuery], and/or [MarshalForm] functions. It is undefined behavior to use a struct uses param.Field without specifying how it is serialized.

Any "…Params" object defined in this library can be used as the request argument. Note that 'path' arguments will not be forwarded into the url.

The response body will be deserialized into the res variable, depending on its type:

  • A pointer to a *http.Response is populated by the raw response.
  • A pointer to a byte array will be populated with the contents of the request body.
  • A pointer to any other type uses this library's default JSON decoding, which respects UnmarshalJSON if it is defined on the type.
  • A nil value will not read the response body.

For even greater flexibility, see option.WithResponseInto and option.WithResponseBodyInto.

func (*Client) Get

func (r *Client) Get(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Get makes a GET request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Patch

func (r *Client) Patch(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Patch makes a PATCH request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Post

func (r *Client) Post(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Post makes a POST request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

func (*Client) Put

func (r *Client) Put(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption) error

Put makes a PUT request with the given URL, params, and optionally deserializes to a response. See [Execute] documentation on the params and response.

type Conjunction added in v1.86.0

type Conjunction string
const (
	ConjunctionAnd Conjunction = "and"
	ConjunctionOr  Conjunction = "or"
)

func (Conjunction) IsKnown added in v1.86.0

func (r Conjunction) IsKnown() bool

type CountryCode

type CountryCode string

ISO country code alpha2 variant

const (
	CountryCodeAf CountryCode = "AF"
	CountryCodeAx CountryCode = "AX"
	CountryCodeAl CountryCode = "AL"
	CountryCodeDz CountryCode = "DZ"
	CountryCodeAs CountryCode = "AS"
	CountryCodeAd CountryCode = "AD"
	CountryCodeAo CountryCode = "AO"
	CountryCodeAI CountryCode = "AI"
	CountryCodeAq CountryCode = "AQ"
	CountryCodeAg CountryCode = "AG"
	CountryCodeAr CountryCode = "AR"
	CountryCodeAm CountryCode = "AM"
	CountryCodeAw CountryCode = "AW"
	CountryCodeAu CountryCode = "AU"
	CountryCodeAt CountryCode = "AT"
	CountryCodeAz CountryCode = "AZ"
	CountryCodeBs CountryCode = "BS"
	CountryCodeBh CountryCode = "BH"
	CountryCodeBd CountryCode = "BD"
	CountryCodeBb CountryCode = "BB"
	CountryCodeBy CountryCode = "BY"
	CountryCodeBe CountryCode = "BE"
	CountryCodeBz CountryCode = "BZ"
	CountryCodeBj CountryCode = "BJ"
	CountryCodeBm CountryCode = "BM"
	CountryCodeBt CountryCode = "BT"
	CountryCodeBo CountryCode = "BO"
	CountryCodeBq CountryCode = "BQ"
	CountryCodeBa CountryCode = "BA"
	CountryCodeBw CountryCode = "BW"
	CountryCodeBv CountryCode = "BV"
	CountryCodeBr CountryCode = "BR"
	CountryCodeIo CountryCode = "IO"
	CountryCodeBn CountryCode = "BN"
	CountryCodeBg CountryCode = "BG"
	CountryCodeBf CountryCode = "BF"
	CountryCodeBi CountryCode = "BI"
	CountryCodeKh CountryCode = "KH"
	CountryCodeCm CountryCode = "CM"
	CountryCodeCa CountryCode = "CA"
	CountryCodeCv CountryCode = "CV"
	CountryCodeKy CountryCode = "KY"
	CountryCodeCf CountryCode = "CF"
	CountryCodeTd CountryCode = "TD"
	CountryCodeCl CountryCode = "CL"
	CountryCodeCn CountryCode = "CN"
	CountryCodeCx CountryCode = "CX"
	CountryCodeCc CountryCode = "CC"
	CountryCodeCo CountryCode = "CO"
	CountryCodeKm CountryCode = "KM"
	CountryCodeCg CountryCode = "CG"
	CountryCodeCd CountryCode = "CD"
	CountryCodeCk CountryCode = "CK"
	CountryCodeCr CountryCode = "CR"
	CountryCodeCi CountryCode = "CI"
	CountryCodeHr CountryCode = "HR"
	CountryCodeCu CountryCode = "CU"
	CountryCodeCw CountryCode = "CW"
	CountryCodeCy CountryCode = "CY"
	CountryCodeCz CountryCode = "CZ"
	CountryCodeDk CountryCode = "DK"
	CountryCodeDj CountryCode = "DJ"
	CountryCodeDm CountryCode = "DM"
	CountryCodeDo CountryCode = "DO"
	CountryCodeEc CountryCode = "EC"
	CountryCodeEg CountryCode = "EG"
	CountryCodeSv CountryCode = "SV"
	CountryCodeGq CountryCode = "GQ"
	CountryCodeEr CountryCode = "ER"
	CountryCodeEe CountryCode = "EE"
	CountryCodeEt CountryCode = "ET"
	CountryCodeFk CountryCode = "FK"
	CountryCodeFo CountryCode = "FO"
	CountryCodeFj CountryCode = "FJ"
	CountryCodeFi CountryCode = "FI"
	CountryCodeFr CountryCode = "FR"
	CountryCodeGf CountryCode = "GF"
	CountryCodePf CountryCode = "PF"
	CountryCodeTf CountryCode = "TF"
	CountryCodeGa CountryCode = "GA"
	CountryCodeGm CountryCode = "GM"
	CountryCodeGe CountryCode = "GE"
	CountryCodeDe CountryCode = "DE"
	CountryCodeGh CountryCode = "GH"
	CountryCodeGi CountryCode = "GI"
	CountryCodeGr CountryCode = "GR"
	CountryCodeGl CountryCode = "GL"
	CountryCodeGd CountryCode = "GD"
	CountryCodeGp CountryCode = "GP"
	CountryCodeGu CountryCode = "GU"
	CountryCodeGt CountryCode = "GT"
	CountryCodeGg CountryCode = "GG"
	CountryCodeGn CountryCode = "GN"
	CountryCodeGw CountryCode = "GW"
	CountryCodeGy CountryCode = "GY"
	CountryCodeHt CountryCode = "HT"
	CountryCodeHm CountryCode = "HM"
	CountryCodeVa CountryCode = "VA"
	CountryCodeHn CountryCode = "HN"
	CountryCodeHk CountryCode = "HK"
	CountryCodeHu CountryCode = "HU"
	CountryCodeIs CountryCode = "IS"
	CountryCodeIn CountryCode = "IN"
	CountryCodeID CountryCode = "ID"
	CountryCodeIr CountryCode = "IR"
	CountryCodeIq CountryCode = "IQ"
	CountryCodeIe CountryCode = "IE"
	CountryCodeIm CountryCode = "IM"
	CountryCodeIl CountryCode = "IL"
	CountryCodeIt CountryCode = "IT"
	CountryCodeJm CountryCode = "JM"
	CountryCodeJp CountryCode = "JP"
	CountryCodeJe CountryCode = "JE"
	CountryCodeJo CountryCode = "JO"
	CountryCodeKz CountryCode = "KZ"
	CountryCodeKe CountryCode = "KE"
	CountryCodeKi CountryCode = "KI"
	CountryCodeKp CountryCode = "KP"
	CountryCodeKr CountryCode = "KR"
	CountryCodeKw CountryCode = "KW"
	CountryCodeKg CountryCode = "KG"
	CountryCodeLa CountryCode = "LA"
	CountryCodeLv CountryCode = "LV"
	CountryCodeLb CountryCode = "LB"
	CountryCodeLs CountryCode = "LS"
	CountryCodeLr CountryCode = "LR"
	CountryCodeLy CountryCode = "LY"
	CountryCodeLi CountryCode = "LI"
	CountryCodeLt CountryCode = "LT"
	CountryCodeLu CountryCode = "LU"
	CountryCodeMo CountryCode = "MO"
	CountryCodeMk CountryCode = "MK"
	CountryCodeMg CountryCode = "MG"
	CountryCodeMw CountryCode = "MW"
	CountryCodeMy CountryCode = "MY"
	CountryCodeMv CountryCode = "MV"
	CountryCodeMl CountryCode = "ML"
	CountryCodeMt CountryCode = "MT"
	CountryCodeMh CountryCode = "MH"
	CountryCodeMq CountryCode = "MQ"
	CountryCodeMr CountryCode = "MR"
	CountryCodeMu CountryCode = "MU"
	CountryCodeYt CountryCode = "YT"
	CountryCodeMx CountryCode = "MX"
	CountryCodeFm CountryCode = "FM"
	CountryCodeMd CountryCode = "MD"
	CountryCodeMc CountryCode = "MC"
	CountryCodeMn CountryCode = "MN"
	CountryCodeMe CountryCode = "ME"
	CountryCodeMs CountryCode = "MS"
	CountryCodeMa CountryCode = "MA"
	CountryCodeMz CountryCode = "MZ"
	CountryCodeMm CountryCode = "MM"
	CountryCodeNa CountryCode = "NA"
	CountryCodeNr CountryCode = "NR"
	CountryCodeNp CountryCode = "NP"
	CountryCodeNl CountryCode = "NL"
	CountryCodeNc CountryCode = "NC"
	CountryCodeNz CountryCode = "NZ"
	CountryCodeNi CountryCode = "NI"
	CountryCodeNe CountryCode = "NE"
	CountryCodeNg CountryCode = "NG"
	CountryCodeNu CountryCode = "NU"
	CountryCodeNf CountryCode = "NF"
	CountryCodeMp CountryCode = "MP"
	CountryCodeNo CountryCode = "NO"
	CountryCodeOm CountryCode = "OM"
	CountryCodePk CountryCode = "PK"
	CountryCodePw CountryCode = "PW"
	CountryCodePs CountryCode = "PS"
	CountryCodePa CountryCode = "PA"
	CountryCodePg CountryCode = "PG"
	CountryCodePy CountryCode = "PY"
	CountryCodePe CountryCode = "PE"
	CountryCodePh CountryCode = "PH"
	CountryCodePn CountryCode = "PN"
	CountryCodePl CountryCode = "PL"
	CountryCodePt CountryCode = "PT"
	CountryCodePr CountryCode = "PR"
	CountryCodeQa CountryCode = "QA"
	CountryCodeRe CountryCode = "RE"
	CountryCodeRo CountryCode = "RO"
	CountryCodeRu CountryCode = "RU"
	CountryCodeRw CountryCode = "RW"
	CountryCodeBl CountryCode = "BL"
	CountryCodeSh CountryCode = "SH"
	CountryCodeKn CountryCode = "KN"
	CountryCodeLc CountryCode = "LC"
	CountryCodeMf CountryCode = "MF"
	CountryCodePm CountryCode = "PM"
	CountryCodeVc CountryCode = "VC"
	CountryCodeWs CountryCode = "WS"
	CountryCodeSm CountryCode = "SM"
	CountryCodeSt CountryCode = "ST"
	CountryCodeSa CountryCode = "SA"
	CountryCodeSn CountryCode = "SN"
	CountryCodeRs CountryCode = "RS"
	CountryCodeSc CountryCode = "SC"
	CountryCodeSl CountryCode = "SL"
	CountryCodeSg CountryCode = "SG"
	CountryCodeSx CountryCode = "SX"
	CountryCodeSk CountryCode = "SK"
	CountryCodeSi CountryCode = "SI"
	CountryCodeSb CountryCode = "SB"
	CountryCodeSo CountryCode = "SO"
	CountryCodeZa CountryCode = "ZA"
	CountryCodeGs CountryCode = "GS"
	CountryCodeSS CountryCode = "SS"
	CountryCodeEs CountryCode = "ES"
	CountryCodeLk CountryCode = "LK"
	CountryCodeSd CountryCode = "SD"
	CountryCodeSr CountryCode = "SR"
	CountryCodeSj CountryCode = "SJ"
	CountryCodeSz CountryCode = "SZ"
	CountryCodeSe CountryCode = "SE"
	CountryCodeCh CountryCode = "CH"
	CountryCodeSy CountryCode = "SY"
	CountryCodeTw CountryCode = "TW"
	CountryCodeTj CountryCode = "TJ"
	CountryCodeTz CountryCode = "TZ"
	CountryCodeTh CountryCode = "TH"
	CountryCodeTl CountryCode = "TL"
	CountryCodeTg CountryCode = "TG"
	CountryCodeTk CountryCode = "TK"
	CountryCodeTo CountryCode = "TO"
	CountryCodeTt CountryCode = "TT"
	CountryCodeTn CountryCode = "TN"
	CountryCodeTr CountryCode = "TR"
	CountryCodeTm CountryCode = "TM"
	CountryCodeTc CountryCode = "TC"
	CountryCodeTv CountryCode = "TV"
	CountryCodeUg CountryCode = "UG"
	CountryCodeUa CountryCode = "UA"
	CountryCodeAe CountryCode = "AE"
	CountryCodeGB CountryCode = "GB"
	CountryCodeUm CountryCode = "UM"
	CountryCodeUs CountryCode = "US"
	CountryCodeUy CountryCode = "UY"
	CountryCodeUz CountryCode = "UZ"
	CountryCodeVu CountryCode = "VU"
	CountryCodeVe CountryCode = "VE"
	CountryCodeVn CountryCode = "VN"
	CountryCodeVg CountryCode = "VG"
	CountryCodeVi CountryCode = "VI"
	CountryCodeWf CountryCode = "WF"
	CountryCodeEh CountryCode = "EH"
	CountryCodeYe CountryCode = "YE"
	CountryCodeZm CountryCode = "ZM"
	CountryCodeZw CountryCode = "ZW"
)

func (CountryCode) IsKnown

func (r CountryCode) IsKnown() bool

type CreateBlockedCustomerRequestBlocklistCustomersBlockByCustomerIDParam added in v1.115.0

type CreateBlockedCustomerRequestBlocklistCustomersBlockByCustomerIDParam struct {
	// Why the merchant blocked this customer. The entry page shows it.
	Reason param.Field[string] `json:"reason"`
	// Screen the merchant blocked from. Ignored for an API-key caller, whose entry
	// always records `api`. A dashboard caller that omits it records `blocklist_page`.
	Source param.Field[BlockedCustomerSource] `json:"source"`
	BlockByCustomerIDParam
}

func (CreateBlockedCustomerRequestBlocklistCustomersBlockByCustomerIDParam) MarshalJSON added in v1.115.0

type CreateBlockedCustomerRequestBlocklistCustomersBlockByEmailParam added in v1.115.0

type CreateBlockedCustomerRequestBlocklistCustomersBlockByEmailParam struct {
	// Why the merchant blocked this customer. The entry page shows it.
	Reason param.Field[string] `json:"reason"`
	// Screen the merchant blocked from. Ignored for an API-key caller, whose entry
	// always records `api`. A dashboard caller that omits it records `blocklist_page`.
	Source param.Field[BlockedCustomerSource] `json:"source"`
	BlockByEmailParam
}

func (CreateBlockedCustomerRequestBlocklistCustomersBlockByEmailParam) MarshalJSON added in v1.115.0

type CreateBlockedCustomerRequestUnionParam added in v1.115.0

type CreateBlockedCustomerRequestUnionParam interface {
	// contains filtered or unexported methods
}

Satisfied by CreateBlockedCustomerRequestBlocklistCustomersBlockByCustomerIDParam, CreateBlockedCustomerRequestBlocklistCustomersBlockByEmailParam.

type CreditAddedWebhookEvent added in v1.86.0

type CreditAddedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Response for a ledger entry
	Data CreditLedgerEntry `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type CreditAddedWebhookEventType `json:"type" api:"required"`
	JSON creditAddedWebhookEventJSON `json:"-"`
}

func (*CreditAddedWebhookEvent) UnmarshalJSON added in v1.86.0

func (r *CreditAddedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type CreditAddedWebhookEventType added in v1.86.0

type CreditAddedWebhookEventType string

The event type

const (
	CreditAddedWebhookEventTypeCreditAdded CreditAddedWebhookEventType = "credit.added"
)

func (CreditAddedWebhookEventType) IsKnown added in v1.86.0

func (r CreditAddedWebhookEventType) IsKnown() bool

type CreditBalanceLowWebhookEvent added in v1.86.0

type CreditBalanceLowWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Webhook payload for credit.balance_low event
	Data CreditBalanceLowWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type CreditBalanceLowWebhookEventType `json:"type" api:"required"`
	JSON creditBalanceLowWebhookEventJSON `json:"-"`
}

func (*CreditBalanceLowWebhookEvent) UnmarshalJSON added in v1.86.0

func (r *CreditBalanceLowWebhookEvent) UnmarshalJSON(data []byte) (err error)

type CreditBalanceLowWebhookEventData added in v1.86.0

type CreditBalanceLowWebhookEventData struct {
	AvailableBalance string `json:"available_balance" api:"required"`
	// Brand id this credit entitlement belongs to
	BrandID                   string                               `json:"brand_id" api:"required"`
	CreditEntitlementID       string                               `json:"credit_entitlement_id" api:"required"`
	CreditEntitlementName     string                               `json:"credit_entitlement_name" api:"required"`
	CustomerID                string                               `json:"customer_id" api:"required"`
	SubscriptionCreditsAmount string                               `json:"subscription_credits_amount" api:"required"`
	SubscriptionID            string                               `json:"subscription_id" api:"required"`
	ThresholdAmount           string                               `json:"threshold_amount" api:"required"`
	ThresholdPercent          int64                                `json:"threshold_percent" api:"required"`
	JSON                      creditBalanceLowWebhookEventDataJSON `json:"-"`
}

Webhook payload for credit.balance_low event

func (*CreditBalanceLowWebhookEventData) UnmarshalJSON added in v1.86.0

func (r *CreditBalanceLowWebhookEventData) UnmarshalJSON(data []byte) (err error)

type CreditBalanceLowWebhookEventType added in v1.86.0

type CreditBalanceLowWebhookEventType string

The event type

const (
	CreditBalanceLowWebhookEventTypeCreditBalanceLow CreditBalanceLowWebhookEventType = "credit.balance_low"
)

func (CreditBalanceLowWebhookEventType) IsKnown added in v1.86.0

type CreditDeductedWebhookEvent added in v1.86.0

type CreditDeductedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Response for a ledger entry
	Data CreditLedgerEntry `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type CreditDeductedWebhookEventType `json:"type" api:"required"`
	JSON creditDeductedWebhookEventJSON `json:"-"`
}

func (*CreditDeductedWebhookEvent) UnmarshalJSON added in v1.86.0

func (r *CreditDeductedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type CreditDeductedWebhookEventType added in v1.86.0

type CreditDeductedWebhookEventType string

The event type

const (
	CreditDeductedWebhookEventTypeCreditDeducted CreditDeductedWebhookEventType = "credit.deducted"
)

func (CreditDeductedWebhookEventType) IsKnown added in v1.86.0

type CreditEntitlement added in v1.86.0

type CreditEntitlement struct {
	ID         string    `json:"id" api:"required"`
	BusinessID string    `json:"business_id" api:"required"`
	CreatedAt  time.Time `json:"created_at" api:"required" format:"date-time"`
	Name       string    `json:"name" api:"required"`
	// Controls how overage is handled at billing cycle end.
	OverageBehavior  CbbOverageBehavior `json:"overage_behavior" api:"required"`
	OverageEnabled   bool               `json:"overage_enabled" api:"required"`
	Precision        int64              `json:"precision" api:"required"`
	RolloverEnabled  bool               `json:"rollover_enabled" api:"required"`
	Unit             string             `json:"unit" api:"required"`
	UpdatedAt        time.Time          `json:"updated_at" api:"required" format:"date-time"`
	Currency         Currency           `json:"currency" api:"nullable"`
	Description      string             `json:"description" api:"nullable"`
	ExpiresAfterDays int64              `json:"expires_after_days" api:"nullable"`
	MaxRolloverCount int64              `json:"max_rollover_count" api:"nullable"`
	OverageLimit     int64              `json:"overage_limit" api:"nullable"`
	// Price per credit unit
	PricePerUnit           string `json:"price_per_unit" api:"nullable"`
	RolloverPercentage     int64  `json:"rollover_percentage" api:"nullable"`
	RolloverTimeframeCount int64  `json:"rollover_timeframe_count" api:"nullable"`
	// Unit of a duration count (e.g. license-key validity period).
	RolloverTimeframeInterval TimeInterval          `json:"rollover_timeframe_interval" api:"nullable"`
	JSON                      creditEntitlementJSON `json:"-"`
}

func (*CreditEntitlement) UnmarshalJSON added in v1.86.0

func (r *CreditEntitlement) UnmarshalJSON(data []byte) (err error)

type CreditEntitlementBalanceListGrantsParams added in v1.86.0

type CreditEntitlementBalanceListGrantsParams struct {
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
	// Filter by grant status: active, expired, depleted
	Status param.Field[CreditEntitlementBalanceListGrantsParamsStatus] `query:"status"`
}

func (CreditEntitlementBalanceListGrantsParams) URLQuery added in v1.86.0

URLQuery serializes CreditEntitlementBalanceListGrantsParams's query parameters as `url.Values`.

type CreditEntitlementBalanceListGrantsParamsStatus added in v1.86.0

type CreditEntitlementBalanceListGrantsParamsStatus string

Filter by grant status: active, expired, depleted

const (
	CreditEntitlementBalanceListGrantsParamsStatusActive   CreditEntitlementBalanceListGrantsParamsStatus = "active"
	CreditEntitlementBalanceListGrantsParamsStatusExpired  CreditEntitlementBalanceListGrantsParamsStatus = "expired"
	CreditEntitlementBalanceListGrantsParamsStatusDepleted CreditEntitlementBalanceListGrantsParamsStatus = "depleted"
)

func (CreditEntitlementBalanceListGrantsParamsStatus) IsKnown added in v1.86.0

type CreditEntitlementBalanceListGrantsResponse added in v1.86.0

type CreditEntitlementBalanceListGrantsResponse struct {
	ID                  string                                               `json:"id" api:"required"`
	CreatedAt           time.Time                                            `json:"created_at" api:"required" format:"date-time"`
	CreditEntitlementID string                                               `json:"credit_entitlement_id" api:"required"`
	CustomerID          string                                               `json:"customer_id" api:"required"`
	InitialAmount       string                                               `json:"initial_amount" api:"required"`
	IsExpired           bool                                                 `json:"is_expired" api:"required"`
	IsRolledOver        bool                                                 `json:"is_rolled_over" api:"required"`
	RemainingAmount     string                                               `json:"remaining_amount" api:"required"`
	RolloverCount       int64                                                `json:"rollover_count" api:"required"`
	SourceType          CreditEntitlementBalanceListGrantsResponseSourceType `json:"source_type" api:"required"`
	UpdatedAt           time.Time                                            `json:"updated_at" api:"required" format:"date-time"`
	ExpiresAt           time.Time                                            `json:"expires_at" api:"nullable" format:"date-time"`
	// Arbitrary key-value metadata. Values can be string, integer, number, or boolean.
	Metadata      Metadata                                       `json:"metadata" api:"nullable"`
	ParentGrantID string                                         `json:"parent_grant_id" api:"nullable"`
	SourceID      string                                         `json:"source_id" api:"nullable"`
	JSON          creditEntitlementBalanceListGrantsResponseJSON `json:"-"`
}

Response for a credit grant

func (*CreditEntitlementBalanceListGrantsResponse) UnmarshalJSON added in v1.86.0

func (r *CreditEntitlementBalanceListGrantsResponse) UnmarshalJSON(data []byte) (err error)

type CreditEntitlementBalanceListGrantsResponseSourceType added in v1.86.0

type CreditEntitlementBalanceListGrantsResponseSourceType string
const (
	CreditEntitlementBalanceListGrantsResponseSourceTypeSubscription CreditEntitlementBalanceListGrantsResponseSourceType = "subscription"
	CreditEntitlementBalanceListGrantsResponseSourceTypeOneTime      CreditEntitlementBalanceListGrantsResponseSourceType = "one_time"
	CreditEntitlementBalanceListGrantsResponseSourceTypeAddon        CreditEntitlementBalanceListGrantsResponseSourceType = "addon"
	CreditEntitlementBalanceListGrantsResponseSourceTypeAPI          CreditEntitlementBalanceListGrantsResponseSourceType = "api"
	CreditEntitlementBalanceListGrantsResponseSourceTypeRollover     CreditEntitlementBalanceListGrantsResponseSourceType = "rollover"
)

func (CreditEntitlementBalanceListGrantsResponseSourceType) IsKnown added in v1.86.0

type CreditEntitlementBalanceListLedgerParams added in v1.86.0

type CreditEntitlementBalanceListLedgerParams struct {
	// Filter by end date
	EndDate param.Field[time.Time] `query:"end_date" format:"date-time"`
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
	// Filter by start date
	StartDate param.Field[time.Time] `query:"start_date" format:"date-time"`
	// Filter by transaction type (snake_case: credit_added, credit_deducted,
	// credit_expired, etc.)
	TransactionType param.Field[string] `query:"transaction_type"`
}

func (CreditEntitlementBalanceListLedgerParams) URLQuery added in v1.86.0

URLQuery serializes CreditEntitlementBalanceListLedgerParams's query parameters as `url.Values`.

type CreditEntitlementBalanceListParams added in v1.86.0

type CreditEntitlementBalanceListParams struct {
	// Filter by specific customer ID
	CustomerID param.Field[string] `query:"customer_id"`
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
}

func (CreditEntitlementBalanceListParams) URLQuery added in v1.86.0

URLQuery serializes CreditEntitlementBalanceListParams's query parameters as `url.Values`.

type CreditEntitlementBalanceNewLedgerEntryParams added in v1.86.0

type CreditEntitlementBalanceNewLedgerEntryParams struct {
	// Amount to credit or debit. Bounded to a `NUMERIC(38,28)` column, so the integer
	// part must have fewer than 10 digits (< 10^10); larger values previously reached
	// the DB and failed with a 22003 overflow surfaced as a 500.
	Amount param.Field[string] `json:"amount" api:"required"`
	// Entry type: credit or debit
	EntryType param.Field[LedgerEntryType] `json:"entry_type" api:"required"`
	// Expiration for credited amount (only for credit type)
	ExpiresAt param.Field[time.Time] `json:"expires_at" format:"date-time"`
	// Idempotency key to prevent duplicate entries
	IdempotencyKey param.Field[string] `json:"idempotency_key"`
	// Optional metadata (max 50 key-value pairs, key max 40 chars, value max 500
	// chars).
	Metadata param.Field[MetadataParam] `json:"metadata"`
	// Human-readable reason for the entry
	Reason param.Field[string] `json:"reason"`
}

func (CreditEntitlementBalanceNewLedgerEntryParams) MarshalJSON added in v1.86.0

func (r CreditEntitlementBalanceNewLedgerEntryParams) MarshalJSON() (data []byte, err error)

type CreditEntitlementBalanceNewLedgerEntryResponse added in v1.86.0

type CreditEntitlementBalanceNewLedgerEntryResponse struct {
	ID                  string          `json:"id" api:"required"`
	Amount              string          `json:"amount" api:"required"`
	BalanceAfter        string          `json:"balance_after" api:"required"`
	BalanceBefore       string          `json:"balance_before" api:"required"`
	CreatedAt           time.Time       `json:"created_at" api:"required" format:"date-time"`
	CreditEntitlementID string          `json:"credit_entitlement_id" api:"required"`
	CustomerID          string          `json:"customer_id" api:"required"`
	EntryType           LedgerEntryType `json:"entry_type" api:"required"`
	IsCredit            bool            `json:"is_credit" api:"required"`
	// Metadata stored on this entry.
	Metadata      Metadata                                           `json:"metadata" api:"required"`
	OverageAfter  string                                             `json:"overage_after" api:"required"`
	OverageBefore string                                             `json:"overage_before" api:"required"`
	GrantID       string                                             `json:"grant_id" api:"nullable"`
	Reason        string                                             `json:"reason" api:"nullable"`
	JSON          creditEntitlementBalanceNewLedgerEntryResponseJSON `json:"-"`
}

Response for creating a ledger entry

func (*CreditEntitlementBalanceNewLedgerEntryResponse) UnmarshalJSON added in v1.86.0

func (r *CreditEntitlementBalanceNewLedgerEntryResponse) UnmarshalJSON(data []byte) (err error)

type CreditEntitlementBalanceService added in v1.86.0

type CreditEntitlementBalanceService struct {
	Options []option.RequestOption
}

CreditEntitlementBalanceService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewCreditEntitlementBalanceService method instead.

func NewCreditEntitlementBalanceService added in v1.86.0

func NewCreditEntitlementBalanceService(opts ...option.RequestOption) (r *CreditEntitlementBalanceService)

NewCreditEntitlementBalanceService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*CreditEntitlementBalanceService) Get added in v1.86.0

func (r *CreditEntitlementBalanceService) Get(ctx context.Context, creditEntitlementID string, customerID string, opts ...option.RequestOption) (res *CustomerCreditBalance, err error)

Returns the credit balance details for a specific customer and credit entitlement.

Authentication

Requires an API key with `Viewer` role or higher.

Path Parameters

- `credit_entitlement_id` - The unique identifier of the credit entitlement - `customer_id` - The unique identifier of the customer

Responses

- `200 OK` - Returns the customer's balance - `404 Not Found` - Credit entitlement or customer balance not found - `500 Internal Server Error` - Database or server error

func (*CreditEntitlementBalanceService) List added in v1.86.0

Returns a paginated list of customer credit balances for the given credit entitlement.

Authentication

Requires an API key with `Viewer` role or higher.

Path Parameters

- `credit_entitlement_id` - The unique identifier of the credit entitlement

Query Parameters

- `page_size` - Number of items per page (default: 10, max: 100) - `page_number` - Zero-based page number (default: 0) - `customer_id` - Optional filter by specific customer

Responses

- `200 OK` - Returns list of customer balances - `404 Not Found` - Credit entitlement not found - `500 Internal Server Error` - Database or server error

func (*CreditEntitlementBalanceService) ListAutoPaging added in v1.86.0

Returns a paginated list of customer credit balances for the given credit entitlement.

Authentication

Requires an API key with `Viewer` role or higher.

Path Parameters

- `credit_entitlement_id` - The unique identifier of the credit entitlement

Query Parameters

- `page_size` - Number of items per page (default: 10, max: 100) - `page_number` - Zero-based page number (default: 0) - `customer_id` - Optional filter by specific customer

Responses

- `200 OK` - Returns list of customer balances - `404 Not Found` - Credit entitlement not found - `500 Internal Server Error` - Database or server error

func (*CreditEntitlementBalanceService) ListGrants added in v1.86.0

Returns a paginated list of credit grants with optional filtering by status.

Authentication

Requires an API key with `Viewer` role or higher.

Path Parameters

- `credit_entitlement_id` - The unique identifier of the credit entitlement - `customer_id` - The unique identifier of the customer

Query Parameters

- `page_size` - Number of items per page (default: 10, max: 100) - `page_number` - Zero-based page number (default: 0) - `status` - Filter by status: active, expired, depleted

Responses

- `200 OK` - Returns list of grants - `404 Not Found` - Credit entitlement not found - `500 Internal Server Error` - Database or server error

func (*CreditEntitlementBalanceService) ListGrantsAutoPaging added in v1.86.0

Returns a paginated list of credit grants with optional filtering by status.

Authentication

Requires an API key with `Viewer` role or higher.

Path Parameters

- `credit_entitlement_id` - The unique identifier of the credit entitlement - `customer_id` - The unique identifier of the customer

Query Parameters

- `page_size` - Number of items per page (default: 10, max: 100) - `page_number` - Zero-based page number (default: 0) - `status` - Filter by status: active, expired, depleted

Responses

- `200 OK` - Returns list of grants - `404 Not Found` - Credit entitlement not found - `500 Internal Server Error` - Database or server error

func (*CreditEntitlementBalanceService) ListLedger added in v1.86.0

Returns a paginated list of credit transaction history with optional filtering.

Authentication

Requires an API key with `Viewer` role or higher.

Path Parameters

- `credit_entitlement_id` - The unique identifier of the credit entitlement - `customer_id` - The unique identifier of the customer

Query Parameters

- `page_size` - Number of items per page (default: 10, max: 100) - `page_number` - Zero-based page number (default: 0) - `transaction_type` - Filter by transaction type - `start_date` - Filter entries from this date - `end_date` - Filter entries until this date

Responses

- `200 OK` - Returns list of ledger entries - `404 Not Found` - Credit entitlement not found - `500 Internal Server Error` - Database or server error

func (*CreditEntitlementBalanceService) ListLedgerAutoPaging added in v1.86.0

Returns a paginated list of credit transaction history with optional filtering.

Authentication

Requires an API key with `Viewer` role or higher.

Path Parameters

- `credit_entitlement_id` - The unique identifier of the credit entitlement - `customer_id` - The unique identifier of the customer

Query Parameters

- `page_size` - Number of items per page (default: 10, max: 100) - `page_number` - Zero-based page number (default: 0) - `transaction_type` - Filter by transaction type - `start_date` - Filter entries from this date - `end_date` - Filter entries until this date

Responses

- `200 OK` - Returns list of ledger entries - `404 Not Found` - Credit entitlement not found - `500 Internal Server Error` - Database or server error

func (*CreditEntitlementBalanceService) NewLedgerEntry added in v1.86.0

For credit entries, a new grant is created. For debit entries, credits are deducted from existing grants using FIFO (oldest first).

Authentication

Requires an API key with `Editor` role.

Path Parameters

- `credit_entitlement_id` - The unique identifier of the credit entitlement - `customer_id` - The unique identifier of the customer

Request Body

- `entry_type` - "credit" or "debit" - `amount` - Amount to credit or debit - `reason` - Optional human-readable reason - `expires_at` - Optional expiration for credited amount (only for credit type) - `idempotency_key` - Optional key to prevent duplicate entries - `metadata` - Optional key-value pairs

Responses

- `201 Created` - Ledger entry created successfully - `400 Bad Request` - Invalid request (e.g., debit with insufficient balance) - `404 Not Found` - Credit entitlement or customer not found - `409 Conflict` - Idempotency key already exists - `500 Internal Server Error` - Database or server error

type CreditEntitlementCartResponse added in v1.86.0

type CreditEntitlementCartResponse struct {
	CreditEntitlementID   string `json:"credit_entitlement_id" api:"required"`
	CreditEntitlementName string `json:"credit_entitlement_name" api:"required"`
	CreditsAmount         string `json:"credits_amount" api:"required"`
	// Customer's current overage balance for this entitlement
	OverageBalance string `json:"overage_balance" api:"required"`
	// Controls how overage is handled at the end of a billing cycle.
	//
	// | Preset                     | Charge at billing | Credits reduce overage | Preserve overage at reset |
	// | -------------------------- | :---------------: | :--------------------: | :-----------------------: |
	// | `forgive_at_reset`         |        No         |           No           |            No             |
	// | `invoice_at_billing`       |        Yes        |           No           |            No             |
	// | `carry_deficit`            |        No         |           No           |            Yes            |
	// | `carry_deficit_auto_repay` |        No         |          Yes           |            Yes            |
	OverageBehavior CbbOverageBehavior `json:"overage_behavior" api:"required"`
	OverageEnabled  bool               `json:"overage_enabled" api:"required"`
	ProductID       string             `json:"product_id" api:"required"`
	// Customer's current remaining credit balance for this entitlement
	RemainingBalance string `json:"remaining_balance" api:"required"`
	RolloverEnabled  bool   `json:"rollover_enabled" api:"required"`
	// Unit label for the credit entitlement (e.g., "API Calls", "Tokens")
	Unit                       string `json:"unit" api:"required"`
	ExpiresAfterDays           int64  `json:"expires_after_days" api:"nullable"`
	LowBalanceThresholdPercent int64  `json:"low_balance_threshold_percent" api:"nullable"`
	MaxRolloverCount           int64  `json:"max_rollover_count" api:"nullable"`
	OverageLimit               string `json:"overage_limit" api:"nullable"`
	RolloverPercentage         int64  `json:"rollover_percentage" api:"nullable"`
	RolloverTimeframeCount     int64  `json:"rollover_timeframe_count" api:"nullable"`
	// Unit of a duration count (e.g. license-key validity period).
	RolloverTimeframeInterval TimeInterval                      `json:"rollover_timeframe_interval" api:"nullable"`
	JSON                      creditEntitlementCartResponseJSON `json:"-"`
}

Response struct representing credit entitlement cart details for a subscription

func (*CreditEntitlementCartResponse) UnmarshalJSON added in v1.86.0

func (r *CreditEntitlementCartResponse) UnmarshalJSON(data []byte) (err error)

type CreditEntitlementListParams added in v1.86.0

type CreditEntitlementListParams struct {
	// List deleted credit entitlements
	Deleted param.Field[bool] `query:"deleted"`
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
}

func (CreditEntitlementListParams) URLQuery added in v1.86.0

func (r CreditEntitlementListParams) URLQuery() (v url.Values)

URLQuery serializes CreditEntitlementListParams's query parameters as `url.Values`.

type CreditEntitlementMappingResponse added in v1.86.0

type CreditEntitlementMappingResponse struct {
	// Unique ID of this mapping
	ID string `json:"id" api:"required" format:"uuid"`
	// ID of the credit entitlement
	CreditEntitlementID string `json:"credit_entitlement_id" api:"required"`
	// Name of the credit entitlement
	CreditEntitlementName string `json:"credit_entitlement_name" api:"required"`
	// Unit label for the credit entitlement
	CreditEntitlementUnit string `json:"credit_entitlement_unit" api:"required"`
	// Number of credits granted
	CreditsAmount string `json:"credits_amount" api:"required"`
	// Controls how overage is handled at billing cycle end.
	OverageBehavior CbbOverageBehavior `json:"overage_behavior" api:"required"`
	// Whether overage is enabled
	OverageEnabled bool `json:"overage_enabled" api:"required"`
	// Proration behavior for credit grants during plan changes
	ProrationBehavior CbbProrationBehavior `json:"proration_behavior" api:"required"`
	// Whether rollover is enabled
	RolloverEnabled bool `json:"rollover_enabled" api:"required"`
	// Whether trial credits expire after trial
	TrialCreditsExpireAfterTrial bool `json:"trial_credits_expire_after_trial" api:"required"`
	// Currency
	Currency Currency `json:"currency" api:"nullable"`
	// Days until credits expire
	ExpiresAfterDays int64 `json:"expires_after_days" api:"nullable"`
	// Low balance threshold percentage
	LowBalanceThresholdPercent int64 `json:"low_balance_threshold_percent" api:"nullable"`
	// Maximum rollover cycles
	MaxRolloverCount int64 `json:"max_rollover_count" api:"nullable"`
	// Overage limit
	OverageLimit string `json:"overage_limit" api:"nullable"`
	// Price per unit
	PricePerUnit string `json:"price_per_unit" api:"nullable"`
	// Rollover percentage
	RolloverPercentage int64 `json:"rollover_percentage" api:"nullable"`
	// Rollover timeframe count
	RolloverTimeframeCount int64 `json:"rollover_timeframe_count" api:"nullable"`
	// Rollover timeframe interval
	RolloverTimeframeInterval TimeInterval `json:"rollover_timeframe_interval" api:"nullable"`
	// Trial credits
	TrialCredits string                               `json:"trial_credits" api:"nullable"`
	JSON         creditEntitlementMappingResponseJSON `json:"-"`
}

Response struct for credit entitlement mapping

func (*CreditEntitlementMappingResponse) UnmarshalJSON added in v1.86.0

func (r *CreditEntitlementMappingResponse) UnmarshalJSON(data []byte) (err error)

type CreditEntitlementNewParams added in v1.86.0

type CreditEntitlementNewParams struct {
	// Name of the credit entitlement
	Name param.Field[string] `json:"name" api:"required"`
	// Whether overage charges are enabled when credits run out
	OverageEnabled param.Field[bool] `json:"overage_enabled" api:"required"`
	// Precision for credit amounts (0-10 decimal places)
	Precision param.Field[int64] `json:"precision" api:"required"`
	// Whether rollover is enabled for unused credits
	RolloverEnabled param.Field[bool] `json:"rollover_enabled" api:"required"`
	// Unit of measurement for the credit (e.g., "API Calls", "Tokens", "Credits")
	Unit param.Field[string] `json:"unit" api:"required"`
	// Currency for pricing (required if price_per_unit is set)
	Currency param.Field[Currency] `json:"currency"`
	// Optional description of the credit entitlement
	Description param.Field[string] `json:"description"`
	// Number of days after which credits expire (optional)
	ExpiresAfterDays param.Field[int64] `json:"expires_after_days"`
	// Maximum number of times credits can be rolled over
	MaxRolloverCount param.Field[int64] `json:"max_rollover_count"`
	// Controls how overage is handled at billing cycle end. Defaults to
	// forgive_at_reset if not specified.
	OverageBehavior param.Field[CbbOverageBehavior] `json:"overage_behavior"`
	// Maximum overage units allowed (optional)
	OverageLimit param.Field[int64] `json:"overage_limit"`
	// Price per credit unit
	PricePerUnit param.Field[string] `json:"price_per_unit"`
	// Percentage of unused credits that can rollover (0-100)
	RolloverPercentage param.Field[int64] `json:"rollover_percentage"`
	// Count of timeframe periods for rollover limit
	RolloverTimeframeCount param.Field[int64] `json:"rollover_timeframe_count"`
	// Interval type for rollover timeframe
	RolloverTimeframeInterval param.Field[TimeInterval] `json:"rollover_timeframe_interval"`
}

func (CreditEntitlementNewParams) MarshalJSON added in v1.86.0

func (r CreditEntitlementNewParams) MarshalJSON() (data []byte, err error)

type CreditEntitlementService added in v1.86.0

type CreditEntitlementService struct {
	Options  []option.RequestOption
	Balances *CreditEntitlementBalanceService
}

CreditEntitlementService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewCreditEntitlementService method instead.

func NewCreditEntitlementService added in v1.86.0

func NewCreditEntitlementService(opts ...option.RequestOption) (r *CreditEntitlementService)

NewCreditEntitlementService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*CreditEntitlementService) Delete added in v1.86.0

func (r *CreditEntitlementService) Delete(ctx context.Context, id string, opts ...option.RequestOption) (err error)

func (*CreditEntitlementService) Get added in v1.86.0

Returns the full details of a single credit entitlement including all configuration settings for expiration, rollover, and overage policies.

Authentication

Requires an API key with `Viewer` role or higher.

Path Parameters

- `id` - The unique identifier of the credit entitlement (format: `cde_...`)

Responses

  • `200 OK` - Returns the full credit entitlement object
  • `404 Not Found` - Credit entitlement does not exist or does not belong to the authenticated business
  • `500 Internal Server Error` - Database or server error

Business Logic

  • Only non-deleted credit entitlements can be retrieved through this endpoint
  • The entitlement must belong to the authenticated business (business_id check)
  • Deleted entitlements return a 404 error and must be retrieved via the list endpoint with `deleted=true`

func (*CreditEntitlementService) List added in v1.86.0

Returns a paginated list of credit entitlements, allowing filtering of deleted entitlements. By default, only non-deleted entitlements are returned.

Authentication

Requires an API key with `Viewer` role or higher.

Query Parameters

  • `page_size` - Number of items per page (default: 10, max: 100)
  • `page_number` - Zero-based page number (default: 0)
  • `deleted` - Boolean flag to list deleted entitlements instead of active ones (default: false)

Responses

- `200 OK` - Returns a list of credit entitlements wrapped in a response object - `422 Unprocessable Entity` - Invalid query parameters (e.g., page_size > 100) - `500 Internal Server Error` - Database or server error

Business Logic

- Results are ordered by creation date in descending order (newest first) - Only entitlements belonging to the authenticated business are returned - The `deleted` parameter controls visibility of soft-deleted entitlements - Pagination uses offset-based pagination (offset = page_number \* page_size)

func (*CreditEntitlementService) ListAutoPaging added in v1.86.0

Returns a paginated list of credit entitlements, allowing filtering of deleted entitlements. By default, only non-deleted entitlements are returned.

Authentication

Requires an API key with `Viewer` role or higher.

Query Parameters

  • `page_size` - Number of items per page (default: 10, max: 100)
  • `page_number` - Zero-based page number (default: 0)
  • `deleted` - Boolean flag to list deleted entitlements instead of active ones (default: false)

Responses

- `200 OK` - Returns a list of credit entitlements wrapped in a response object - `422 Unprocessable Entity` - Invalid query parameters (e.g., page_size > 100) - `500 Internal Server Error` - Database or server error

Business Logic

- Results are ordered by creation date in descending order (newest first) - Only entitlements belonging to the authenticated business are returned - The `deleted` parameter controls visibility of soft-deleted entitlements - Pagination uses offset-based pagination (offset = page_number \* page_size)

func (*CreditEntitlementService) New added in v1.86.0

Credit entitlements define reusable credit templates that can be attached to products. Each entitlement defines how credits behave in terms of expiration, rollover, and overage.

Authentication

Requires an API key with `Editor` role.

Request Body

  • `name` - Human-readable name of the credit entitlement (1-255 characters, required)
  • `description` - Optional description (max 1000 characters)
  • `precision` - Decimal precision for credit amounts (0-10 decimal places)
  • `unit` - Unit of measurement for the credit (e.g., "API Calls", "Tokens", "Credits")
  • `expires_after_days` - Number of days after which credits expire (optional)
  • `rollover_enabled` - Whether unused credits can rollover to the next period
  • `rollover_percentage` - Percentage of unused credits that rollover (0-100)
  • `rollover_timeframe_count` - Count of timeframe periods for rollover limit
  • `rollover_timeframe_interval` - Interval type (day, week, month, year)
  • `max_rollover_count` - Maximum number of times credits can be rolled over
  • `overage_enabled` - Whether overage charges apply when credits run out (requires price_per_unit)
  • `overage_limit` - Maximum overage units allowed (optional)
  • `currency` - Currency for pricing (required if price_per_unit is set)
  • `price_per_unit` - Price per credit unit (decimal)

Responses

  • `201 Created` - Credit entitlement created successfully, returns the full entitlement object
  • `422 Unprocessable Entity` - Invalid request parameters or validation failure
  • `500 Internal Server Error` - Database or server error

Business Logic

  • A unique ID with prefix `cde_` is automatically generated for the entitlement
  • Created and updated timestamps are automatically set
  • Currency is required when price_per_unit is set
  • price_per_unit is required when overage_enabled is true
  • rollover_timeframe_count and rollover_timeframe_interval must both be set or both be null

func (*CreditEntitlementService) Undelete added in v1.86.0

func (r *CreditEntitlementService) Undelete(ctx context.Context, id string, opts ...option.RequestOption) (err error)

Undeletes a soft-deleted credit entitlement by clearing `deleted_at`, making it available again through standard list and get endpoints.

Authentication

Requires an API key with `Editor` role.

Path Parameters

  • `id` - The unique identifier of the credit entitlement to restore (format: `cde_...`)

Responses

  • `200 OK` - Credit entitlement restored successfully
  • `500 Internal Server Error` - Database error, entitlement not found, or entitlement is not deleted

Business Logic

  • Only deleted credit entitlements can be restored
  • The query filters for `deleted_at IS NOT NULL`, so non-deleted entitlements will result in 0 rows affected
  • If no rows are affected (entitlement doesn't exist, doesn't belong to business, or is not deleted), returns 500
  • The `updated_at` timestamp is automatically updated on successful restoration
  • Once restored, the entitlement becomes immediately available in the standard list and get endpoints
  • All configuration settings are preserved during delete/restore operations

Error Handling

This endpoint returns 500 Internal Server Error in several cases:

- The credit entitlement does not exist - The credit entitlement belongs to a different business - The credit entitlement is not currently deleted (already active)

Callers should verify the entitlement exists and is deleted before calling this endpoint.

func (*CreditEntitlementService) Update added in v1.86.0

Allows partial updates to a credit entitlement's configuration. Only the fields provided in the request body will be updated; all other fields remain unchanged. This endpoint supports nullable fields using the double option pattern.

Authentication

Requires an API key with `Editor` role.

Path Parameters

  • `id` - The unique identifier of the credit entitlement to update (format: `cde_...`)

Request Body (all fields optional)

- `name` - Human-readable name of the credit entitlement (1-255 characters) - `description` - Optional description (max 1000 characters) - `unit` - Unit of measurement for the credit (1-50 characters)

Note: `precision` cannot be modified after creation as it would invalidate existing grants.

  • `expires_after_days` - Number of days after which credits expire (use `null` to remove expiration)
  • `rollover_enabled` - Whether unused credits can rollover to the next period
  • `rollover_percentage` - Percentage of unused credits that rollover (0-100, nullable)
  • `rollover_timeframe_count` - Count of timeframe periods for rollover limit (nullable)
  • `rollover_timeframe_interval` - Interval type (day, week, month, year, nullable)
  • `max_rollover_count` - Maximum number of times credits can be rolled over (nullable)
  • `overage_enabled` - Whether overage charges apply when credits run out
  • `overage_limit` - Maximum overage units allowed (nullable)
  • `currency` - Currency for pricing (nullable)
  • `price_per_unit` - Price per credit unit (decimal, nullable)

Responses

  • `200 OK` - Credit entitlement updated successfully
  • `404 Not Found` - Credit entitlement does not exist or does not belong to the authenticated business
  • `422 Unprocessable Entity` - Invalid request parameters or validation failure
  • `500 Internal Server Error` - Database or server error

Business Logic

  • Only non-deleted credit entitlements can be updated
  • Fields set to `null` explicitly will clear the database value (using double option pattern)
  • The `updated_at` timestamp is automatically updated on successful modification
  • Changes take effect immediately but do not retroactively affect existing credit grants
  • The merged state is validated: currency required with price, rollover timeframe fields together, price required for overage

type CreditEntitlementUpdateParams added in v1.86.0

type CreditEntitlementUpdateParams struct {
	// Currency for pricing
	Currency param.Field[Currency] `json:"currency"`
	// Optional description of the credit entitlement
	Description param.Field[string] `json:"description"`
	// Number of days after which credits expire
	ExpiresAfterDays param.Field[int64] `json:"expires_after_days"`
	// Maximum number of times credits can be rolled over
	MaxRolloverCount param.Field[int64] `json:"max_rollover_count"`
	// Name of the credit entitlement
	Name param.Field[string] `json:"name"`
	// Controls how overage is handled at billing cycle end.
	OverageBehavior param.Field[CbbOverageBehavior] `json:"overage_behavior"`
	// Whether overage charges are enabled when credits run out
	OverageEnabled param.Field[bool] `json:"overage_enabled"`
	// Maximum overage units allowed
	OverageLimit param.Field[int64] `json:"overage_limit"`
	// Price per credit unit
	PricePerUnit param.Field[string] `json:"price_per_unit"`
	// Whether rollover is enabled for unused credits
	RolloverEnabled param.Field[bool] `json:"rollover_enabled"`
	// Percentage of unused credits that can rollover (0-100)
	RolloverPercentage param.Field[int64] `json:"rollover_percentage"`
	// Count of timeframe periods for rollover limit
	RolloverTimeframeCount param.Field[int64] `json:"rollover_timeframe_count"`
	// Interval type for rollover timeframe
	RolloverTimeframeInterval param.Field[TimeInterval] `json:"rollover_timeframe_interval"`
	// Unit of measurement for the credit (e.g., "API Calls", "Tokens", "Credits")
	Unit param.Field[string] `json:"unit"`
}

func (CreditEntitlementUpdateParams) MarshalJSON added in v1.86.0

func (r CreditEntitlementUpdateParams) MarshalJSON() (data []byte, err error)

type CreditExpiredWebhookEvent added in v1.86.0

type CreditExpiredWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Response for a ledger entry
	Data CreditLedgerEntry `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type CreditExpiredWebhookEventType `json:"type" api:"required"`
	JSON creditExpiredWebhookEventJSON `json:"-"`
}

func (*CreditExpiredWebhookEvent) UnmarshalJSON added in v1.86.0

func (r *CreditExpiredWebhookEvent) UnmarshalJSON(data []byte) (err error)

type CreditExpiredWebhookEventType added in v1.86.0

type CreditExpiredWebhookEventType string

The event type

const (
	CreditExpiredWebhookEventTypeCreditExpired CreditExpiredWebhookEventType = "credit.expired"
)

func (CreditExpiredWebhookEventType) IsKnown added in v1.86.0

func (r CreditExpiredWebhookEventType) IsKnown() bool

type CreditLedgerEntry added in v1.86.0

type CreditLedgerEntry struct {
	ID            string `json:"id" api:"required"`
	Amount        string `json:"amount" api:"required"`
	BalanceAfter  string `json:"balance_after" api:"required"`
	BalanceBefore string `json:"balance_before" api:"required"`
	// Brand id this credit ledger entry belongs to
	BrandID             string    `json:"brand_id" api:"required"`
	BusinessID          string    `json:"business_id" api:"required"`
	CreatedAt           time.Time `json:"created_at" api:"required" format:"date-time"`
	CreditEntitlementID string    `json:"credit_entitlement_id" api:"required"`
	CustomerID          string    `json:"customer_id" api:"required"`
	IsCredit            bool      `json:"is_credit" api:"required"`
	// Metadata associated with this entry.
	Metadata        Metadata                         `json:"metadata" api:"required"`
	OverageAfter    string                           `json:"overage_after" api:"required"`
	OverageBefore   string                           `json:"overage_before" api:"required"`
	TransactionType CreditLedgerEntryTransactionType `json:"transaction_type" api:"required"`
	Description     string                           `json:"description" api:"nullable"`
	GrantID         string                           `json:"grant_id" api:"nullable"`
	ReferenceID     string                           `json:"reference_id" api:"nullable"`
	ReferenceType   string                           `json:"reference_type" api:"nullable"`
	JSON            creditLedgerEntryJSON            `json:"-"`
}

Response for a ledger entry

func (*CreditLedgerEntry) UnmarshalJSON added in v1.86.0

func (r *CreditLedgerEntry) UnmarshalJSON(data []byte) (err error)

type CreditLedgerEntryTransactionType added in v1.86.0

type CreditLedgerEntryTransactionType string
const (
	CreditLedgerEntryTransactionTypeCreditAdded       CreditLedgerEntryTransactionType = "credit_added"
	CreditLedgerEntryTransactionTypeCreditDeducted    CreditLedgerEntryTransactionType = "credit_deducted"
	CreditLedgerEntryTransactionTypeCreditExpired     CreditLedgerEntryTransactionType = "credit_expired"
	CreditLedgerEntryTransactionTypeCreditRolledOver  CreditLedgerEntryTransactionType = "credit_rolled_over"
	CreditLedgerEntryTransactionTypeRolloverForfeited CreditLedgerEntryTransactionType = "rollover_forfeited"
	CreditLedgerEntryTransactionTypeOverageCharged    CreditLedgerEntryTransactionType = "overage_charged"
	CreditLedgerEntryTransactionTypeOverageReset      CreditLedgerEntryTransactionType = "overage_reset"
	CreditLedgerEntryTransactionTypeAutoTopUp         CreditLedgerEntryTransactionType = "auto_top_up"
	CreditLedgerEntryTransactionTypeManualAdjustment  CreditLedgerEntryTransactionType = "manual_adjustment"
	CreditLedgerEntryTransactionTypeRefund            CreditLedgerEntryTransactionType = "refund"
)

func (CreditLedgerEntryTransactionType) IsKnown added in v1.86.0

type CreditManualAdjustmentWebhookEvent added in v1.86.0

type CreditManualAdjustmentWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Response for a ledger entry
	Data CreditLedgerEntry `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type CreditManualAdjustmentWebhookEventType `json:"type" api:"required"`
	JSON creditManualAdjustmentWebhookEventJSON `json:"-"`
}

func (*CreditManualAdjustmentWebhookEvent) UnmarshalJSON added in v1.86.0

func (r *CreditManualAdjustmentWebhookEvent) UnmarshalJSON(data []byte) (err error)

type CreditManualAdjustmentWebhookEventType added in v1.86.0

type CreditManualAdjustmentWebhookEventType string

The event type

const (
	CreditManualAdjustmentWebhookEventTypeCreditManualAdjustment CreditManualAdjustmentWebhookEventType = "credit.manual_adjustment"
)

func (CreditManualAdjustmentWebhookEventType) IsKnown added in v1.86.0

type CreditOverageChargedWebhookEvent added in v1.86.0

type CreditOverageChargedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Response for a ledger entry
	Data CreditLedgerEntry `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type CreditOverageChargedWebhookEventType `json:"type" api:"required"`
	JSON creditOverageChargedWebhookEventJSON `json:"-"`
}

func (*CreditOverageChargedWebhookEvent) UnmarshalJSON added in v1.86.0

func (r *CreditOverageChargedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type CreditOverageChargedWebhookEventType added in v1.86.0

type CreditOverageChargedWebhookEventType string

The event type

const (
	CreditOverageChargedWebhookEventTypeCreditOverageCharged CreditOverageChargedWebhookEventType = "credit.overage_charged"
)

func (CreditOverageChargedWebhookEventType) IsKnown added in v1.86.0

type CreditOverageResetWebhookEvent added in v1.97.0

type CreditOverageResetWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Response for a ledger entry
	Data CreditLedgerEntry `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type CreditOverageResetWebhookEventType `json:"type" api:"required"`
	JSON creditOverageResetWebhookEventJSON `json:"-"`
}

func (*CreditOverageResetWebhookEvent) UnmarshalJSON added in v1.97.0

func (r *CreditOverageResetWebhookEvent) UnmarshalJSON(data []byte) (err error)

type CreditOverageResetWebhookEventType added in v1.97.0

type CreditOverageResetWebhookEventType string

The event type

const (
	CreditOverageResetWebhookEventTypeCreditOverageReset CreditOverageResetWebhookEventType = "credit.overage_reset"
)

func (CreditOverageResetWebhookEventType) IsKnown added in v1.97.0

type CreditRolledOverWebhookEvent added in v1.86.0

type CreditRolledOverWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Response for a ledger entry
	Data CreditLedgerEntry `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type CreditRolledOverWebhookEventType `json:"type" api:"required"`
	JSON creditRolledOverWebhookEventJSON `json:"-"`
}

func (*CreditRolledOverWebhookEvent) UnmarshalJSON added in v1.86.0

func (r *CreditRolledOverWebhookEvent) UnmarshalJSON(data []byte) (err error)

type CreditRolledOverWebhookEventType added in v1.86.0

type CreditRolledOverWebhookEventType string

The event type

const (
	CreditRolledOverWebhookEventTypeCreditRolledOver CreditRolledOverWebhookEventType = "credit.rolled_over"
)

func (CreditRolledOverWebhookEventType) IsKnown added in v1.86.0

type CreditRolloverForfeitedWebhookEvent added in v1.86.0

type CreditRolloverForfeitedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Response for a ledger entry
	Data CreditLedgerEntry `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type CreditRolloverForfeitedWebhookEventType `json:"type" api:"required"`
	JSON creditRolloverForfeitedWebhookEventJSON `json:"-"`
}

func (*CreditRolloverForfeitedWebhookEvent) UnmarshalJSON added in v1.86.0

func (r *CreditRolloverForfeitedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type CreditRolloverForfeitedWebhookEventType added in v1.86.0

type CreditRolloverForfeitedWebhookEventType string

The event type

const (
	CreditRolloverForfeitedWebhookEventTypeCreditRolloverForfeited CreditRolloverForfeitedWebhookEventType = "credit.rollover_forfeited"
)

func (CreditRolloverForfeitedWebhookEventType) IsKnown added in v1.86.0

type Currency added in v1.20.0

type Currency string
const (
	CurrencyAed Currency = "AED"
	CurrencyAll Currency = "ALL"
	CurrencyAmd Currency = "AMD"
	CurrencyAng Currency = "ANG"
	CurrencyAoa Currency = "AOA"
	CurrencyArs Currency = "ARS"
	CurrencyAud Currency = "AUD"
	CurrencyAwg Currency = "AWG"
	CurrencyAzn Currency = "AZN"
	CurrencyBam Currency = "BAM"
	CurrencyBbd Currency = "BBD"
	CurrencyBdt Currency = "BDT"
	CurrencyBgn Currency = "BGN"
	CurrencyBhd Currency = "BHD"
	CurrencyBif Currency = "BIF"
	CurrencyBmd Currency = "BMD"
	CurrencyBnd Currency = "BND"
	CurrencyBob Currency = "BOB"
	CurrencyBrl Currency = "BRL"
	CurrencyBsd Currency = "BSD"
	CurrencyBwp Currency = "BWP"
	CurrencyByn Currency = "BYN"
	CurrencyBzd Currency = "BZD"
	CurrencyCad Currency = "CAD"
	CurrencyChf Currency = "CHF"
	CurrencyClp Currency = "CLP"
	CurrencyCny Currency = "CNY"
	CurrencyCop Currency = "COP"
	CurrencyCrc Currency = "CRC"
	CurrencyCup Currency = "CUP"
	CurrencyCve Currency = "CVE"
	CurrencyCzk Currency = "CZK"
	CurrencyDjf Currency = "DJF"
	CurrencyDkk Currency = "DKK"
	CurrencyDop Currency = "DOP"
	CurrencyDzd Currency = "DZD"
	CurrencyEgp Currency = "EGP"
	CurrencyEtb Currency = "ETB"
	CurrencyEur Currency = "EUR"
	CurrencyFjd Currency = "FJD"
	CurrencyFkp Currency = "FKP"
	CurrencyGbp Currency = "GBP"
	CurrencyGel Currency = "GEL"
	CurrencyGhs Currency = "GHS"
	CurrencyGip Currency = "GIP"
	CurrencyGmd Currency = "GMD"
	CurrencyGnf Currency = "GNF"
	CurrencyGtq Currency = "GTQ"
	CurrencyGyd Currency = "GYD"
	CurrencyHkd Currency = "HKD"
	CurrencyHnl Currency = "HNL"
	CurrencyHrk Currency = "HRK"
	CurrencyHtg Currency = "HTG"
	CurrencyHuf Currency = "HUF"
	CurrencyIdr Currency = "IDR"
	CurrencyIls Currency = "ILS"
	CurrencyInr Currency = "INR"
	CurrencyIqd Currency = "IQD"
	CurrencyJmd Currency = "JMD"
	CurrencyJod Currency = "JOD"
	CurrencyJpy Currency = "JPY"
	CurrencyKes Currency = "KES"
	CurrencyKgs Currency = "KGS"
	CurrencyKhr Currency = "KHR"
	CurrencyKmf Currency = "KMF"
	CurrencyKrw Currency = "KRW"
	CurrencyKwd Currency = "KWD"
	CurrencyKyd Currency = "KYD"
	CurrencyKzt Currency = "KZT"
	CurrencyLak Currency = "LAK"
	CurrencyLbp Currency = "LBP"
	CurrencyLkr Currency = "LKR"
	CurrencyLrd Currency = "LRD"
	CurrencyLsl Currency = "LSL"
	CurrencyLyd Currency = "LYD"
	CurrencyMad Currency = "MAD"
	CurrencyMdl Currency = "MDL"
	CurrencyMga Currency = "MGA"
	CurrencyMkd Currency = "MKD"
	CurrencyMmk Currency = "MMK"
	CurrencyMnt Currency = "MNT"
	CurrencyMop Currency = "MOP"
	CurrencyMru Currency = "MRU"
	CurrencyMur Currency = "MUR"
	CurrencyMvr Currency = "MVR"
	CurrencyMwk Currency = "MWK"
	CurrencyMxn Currency = "MXN"
	CurrencyMyr Currency = "MYR"
	CurrencyMzn Currency = "MZN"
	CurrencyNad Currency = "NAD"
	CurrencyNgn Currency = "NGN"
	CurrencyNio Currency = "NIO"
	CurrencyNok Currency = "NOK"
	CurrencyNpr Currency = "NPR"
	CurrencyNzd Currency = "NZD"
	CurrencyOmr Currency = "OMR"
	CurrencyPab Currency = "PAB"
	CurrencyPen Currency = "PEN"
	CurrencyPgk Currency = "PGK"
	CurrencyPhp Currency = "PHP"
	CurrencyPkr Currency = "PKR"
	CurrencyPln Currency = "PLN"
	CurrencyPyg Currency = "PYG"
	CurrencyQar Currency = "QAR"
	CurrencyRon Currency = "RON"
	CurrencyRsd Currency = "RSD"
	CurrencyRub Currency = "RUB"
	CurrencyRwf Currency = "RWF"
	CurrencySar Currency = "SAR"
	CurrencySbd Currency = "SBD"
	CurrencyScr Currency = "SCR"
	CurrencySek Currency = "SEK"
	CurrencySgd Currency = "SGD"
	CurrencyShp Currency = "SHP"
	CurrencySle Currency = "SLE"
	CurrencySll Currency = "SLL"
	CurrencySos Currency = "SOS"
	CurrencySrd Currency = "SRD"
	CurrencySsp Currency = "SSP"
	CurrencyStn Currency = "STN"
	CurrencySvc Currency = "SVC"
	CurrencySzl Currency = "SZL"
	CurrencyThb Currency = "THB"
	CurrencyTnd Currency = "TND"
	CurrencyTop Currency = "TOP"
	CurrencyTry Currency = "TRY"
	CurrencyTtd Currency = "TTD"
	CurrencyTwd Currency = "TWD"
	CurrencyTzs Currency = "TZS"
	CurrencyUah Currency = "UAH"
	CurrencyUgx Currency = "UGX"
	CurrencyUsd Currency = "USD"
	CurrencyUyu Currency = "UYU"
	CurrencyUzs Currency = "UZS"
	CurrencyVes Currency = "VES"
	CurrencyVnd Currency = "VND"
	CurrencyVuv Currency = "VUV"
	CurrencyWst Currency = "WST"
	CurrencyXaf Currency = "XAF"
	CurrencyXcd Currency = "XCD"
	CurrencyXof Currency = "XOF"
	CurrencyXpf Currency = "XPF"
	CurrencyYer Currency = "YER"
	CurrencyZar Currency = "ZAR"
	CurrencyZmw Currency = "ZMW"
)

func (Currency) IsKnown added in v1.20.0

func (r Currency) IsKnown() bool

type CustomFieldFieldType added in v1.81.0

type CustomFieldFieldType string

Type of field determining validation rules

const (
	CustomFieldFieldTypeText     CustomFieldFieldType = "text"
	CustomFieldFieldTypeNumber   CustomFieldFieldType = "number"
	CustomFieldFieldTypeEmail    CustomFieldFieldType = "email"
	CustomFieldFieldTypeURL      CustomFieldFieldType = "url"
	CustomFieldFieldTypeDate     CustomFieldFieldType = "date"
	CustomFieldFieldTypeDropdown CustomFieldFieldType = "dropdown"
	CustomFieldFieldTypeBoolean  CustomFieldFieldType = "boolean"
)

func (CustomFieldFieldType) IsKnown added in v1.81.0

func (r CustomFieldFieldType) IsKnown() bool

type CustomFieldParam added in v1.81.0

type CustomFieldParam struct {
	// Type of field determining validation rules
	FieldType param.Field[CustomFieldFieldType] `json:"field_type" api:"required"`
	// Unique identifier for this field (used as key in responses)
	Key param.Field[string] `json:"key" api:"required"`
	// Display label shown to customer
	Label param.Field[string] `json:"label" api:"required"`
	// Options for dropdown type (required for dropdown, ignored for others)
	Options param.Field[[]string] `json:"options"`
	// Placeholder text for the input
	Placeholder param.Field[string] `json:"placeholder"`
	// Whether this field is required
	Required param.Field[bool] `json:"required"`
}

Definition of a custom field for checkout

func (CustomFieldParam) MarshalJSON added in v1.81.0

func (r CustomFieldParam) MarshalJSON() (data []byte, err error)

type CustomFieldResponse added in v1.86.0

type CustomFieldResponse struct {
	// Key matching the custom field definition
	Key string `json:"key" api:"required"`
	// Value provided by customer
	Value string                  `json:"value" api:"required"`
	JSON  customFieldResponseJSON `json:"-"`
}

Customer's response to a custom field

func (*CustomFieldResponse) UnmarshalJSON added in v1.86.0

func (r *CustomFieldResponse) UnmarshalJSON(data []byte) (err error)

type Customer

type Customer struct {
	BusinessID string    `json:"business_id" api:"required"`
	CreatedAt  time.Time `json:"created_at" api:"required" format:"date-time"`
	CustomerID string    `json:"customer_id" api:"required"`
	Email      string    `json:"email" api:"required"`
	Name       string    `json:"name" api:"required"`
	// When the merchant blocked this customer. The dashboard shows the "Blocked" badge
	// and the unblock action from it. The list route leaves it empty; only the
	// single-customer route resolves it.
	BlockedAt time.Time `json:"blocked_at" api:"nullable" format:"date-time"`
	// Blocklist entry behind `blocked_at`, so the dashboard can link to it.
	BlocklistEntryID string `json:"blocklist_entry_id" api:"nullable"`
	// Additional metadata for the customer
	Metadata    Metadata     `json:"metadata"`
	PhoneNumber string       `json:"phone_number" api:"nullable"`
	JSON        customerJSON `json:"-"`
}

func (*Customer) UnmarshalJSON

func (r *Customer) UnmarshalJSON(data []byte) (err error)

type CustomerCreditBalance added in v1.86.0

type CustomerCreditBalance struct {
	ID                  string                    `json:"id" api:"required"`
	Balance             string                    `json:"balance" api:"required"`
	CreatedAt           time.Time                 `json:"created_at" api:"required" format:"date-time"`
	CreditEntitlementID string                    `json:"credit_entitlement_id" api:"required"`
	CustomerID          string                    `json:"customer_id" api:"required"`
	Overage             string                    `json:"overage" api:"required"`
	UpdatedAt           time.Time                 `json:"updated_at" api:"required" format:"date-time"`
	LastTransactionAt   time.Time                 `json:"last_transaction_at" api:"nullable" format:"date-time"`
	JSON                customerCreditBalanceJSON `json:"-"`
}

Response for a customer's credit balance

func (*CustomerCreditBalance) UnmarshalJSON added in v1.86.0

func (r *CustomerCreditBalance) UnmarshalJSON(data []byte) (err error)

type CustomerCustomerPortalNewParams added in v1.6.3

type CustomerCustomerPortalNewParams struct {
	// Optional return URL for this session. Overrides the business-level default. This
	// URL will be shown as a "Return to {business}" back button in the portal.
	ReturnURL param.Field[string] `query:"return_url"`
	// If true, will send link to user.
	SendEmail param.Field[bool] `query:"send_email"`
}

func (CustomerCustomerPortalNewParams) URLQuery added in v1.6.3

func (r CustomerCustomerPortalNewParams) URLQuery() (v url.Values)

URLQuery serializes CustomerCustomerPortalNewParams's query parameters as `url.Values`.

type CustomerCustomerPortalService added in v1.0.0

type CustomerCustomerPortalService struct {
	Options []option.RequestOption
}

CustomerCustomerPortalService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewCustomerCustomerPortalService method instead.

func NewCustomerCustomerPortalService added in v1.0.0

func NewCustomerCustomerPortalService(opts ...option.RequestOption) (r *CustomerCustomerPortalService)

NewCustomerCustomerPortalService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*CustomerCustomerPortalService) New added in v1.6.3

type CustomerEmailListParams added in v1.116.0

type CustomerEmailListParams struct {
	// Which page to return. The default is 0.
	PageNumber param.Field[int64] `query:"page_number"`
	// How many emails to return. The default is 10 and the maximum is 100.
	PageSize param.Field[int64] `query:"page_size"`
}

func (CustomerEmailListParams) URLQuery added in v1.116.0

func (r CustomerEmailListParams) URLQuery() (v url.Values)

URLQuery serializes CustomerEmailListParams's query parameters as `url.Values`.

type CustomerEmailService added in v1.116.0

type CustomerEmailService struct {
	Options []option.RequestOption
}

CustomerEmailService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewCustomerEmailService method instead.

func NewCustomerEmailService added in v1.116.0

func NewCustomerEmailService(opts ...option.RequestOption) (r *CustomerEmailService)

NewCustomerEmailService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*CustomerEmailService) GetBody added in v1.116.0

func (r *CustomerEmailService) GetBody(ctx context.Context, customerID string, emailLogID string, opts ...option.RequestOption) (res *EmailBody, err error)

Returns the email exactly as it was sent, plus the reason it failed when it did. Some emails have no body to show: an authentication email carries a live login token, a blocked email never reached the provider, and the provider clears bodies at 180 days.

func (*CustomerEmailService) List added in v1.116.0

Returns every transactional email sent to this customer in the last 180 days, newest first, with its delivery outcome. Delivery status comes from the email provider and is as fresh as replication, typically seconds.

func (*CustomerEmailService) ListAutoPaging added in v1.116.0

Returns every transactional email sent to this customer in the last 180 days, newest first, with its delivery outcome. Delivery status comes from the email provider and is as fresh as replication, typically seconds.

type CustomerGetPaymentMethodsResponse added in v1.60.0

type CustomerGetPaymentMethodsResponse struct {
	Items []CustomerGetPaymentMethodsResponseItem `json:"items" api:"required"`
	JSON  customerGetPaymentMethodsResponseJSON   `json:"-"`
}

func (*CustomerGetPaymentMethodsResponse) UnmarshalJSON added in v1.60.0

func (r *CustomerGetPaymentMethodsResponse) UnmarshalJSON(data []byte) (err error)

type CustomerGetPaymentMethodsResponseItem added in v1.60.0

type CustomerGetPaymentMethodsResponseItem struct {
	PaymentMethod   CustomerGetPaymentMethodsResponseItemsPaymentMethod `json:"payment_method" api:"required"`
	PaymentMethodID string                                              `json:"payment_method_id" api:"required"`
	Card            CustomerGetPaymentMethodsResponseItemsCard          `json:"card" api:"nullable"`
	LastUsedAt      time.Time                                           `json:"last_used_at" api:"nullable" format:"date-time"`
	// All supported payment method types.
	//
	// Used for disabled-payment-methods filtering and validation.
	PaymentMethodType PaymentMethodTypes                        `json:"payment_method_type" api:"nullable"`
	RecurringEnabled  bool                                      `json:"recurring_enabled" api:"nullable"`
	JSON              customerGetPaymentMethodsResponseItemJSON `json:"-"`
}

func (*CustomerGetPaymentMethodsResponseItem) UnmarshalJSON added in v1.60.0

func (r *CustomerGetPaymentMethodsResponseItem) UnmarshalJSON(data []byte) (err error)

type CustomerGetPaymentMethodsResponseItemsCard added in v1.60.0

type CustomerGetPaymentMethodsResponseItemsCard struct {
	CardHolderName string `json:"card_holder_name" api:"nullable"`
	// ISO country code alpha2 variant
	CardIssuingCountry CountryCode                                    `json:"card_issuing_country" api:"nullable"`
	CardNetwork        string                                         `json:"card_network" api:"nullable"`
	CardType           string                                         `json:"card_type" api:"nullable"`
	ExpiryMonth        string                                         `json:"expiry_month" api:"nullable"`
	ExpiryYear         string                                         `json:"expiry_year" api:"nullable"`
	Last4Digits        string                                         `json:"last4_digits" api:"nullable"`
	JSON               customerGetPaymentMethodsResponseItemsCardJSON `json:"-"`
}

func (*CustomerGetPaymentMethodsResponseItemsCard) UnmarshalJSON added in v1.60.0

func (r *CustomerGetPaymentMethodsResponseItemsCard) UnmarshalJSON(data []byte) (err error)

type CustomerGetPaymentMethodsResponseItemsPaymentMethod added in v1.60.0

type CustomerGetPaymentMethodsResponseItemsPaymentMethod string
const (
	CustomerGetPaymentMethodsResponseItemsPaymentMethodCard            CustomerGetPaymentMethodsResponseItemsPaymentMethod = "card"
	CustomerGetPaymentMethodsResponseItemsPaymentMethodCardRedirect    CustomerGetPaymentMethodsResponseItemsPaymentMethod = "card_redirect"
	CustomerGetPaymentMethodsResponseItemsPaymentMethodPayLater        CustomerGetPaymentMethodsResponseItemsPaymentMethod = "pay_later"
	CustomerGetPaymentMethodsResponseItemsPaymentMethodWallet          CustomerGetPaymentMethodsResponseItemsPaymentMethod = "wallet"
	CustomerGetPaymentMethodsResponseItemsPaymentMethodBankRedirect    CustomerGetPaymentMethodsResponseItemsPaymentMethod = "bank_redirect"
	CustomerGetPaymentMethodsResponseItemsPaymentMethodBankTransfer    CustomerGetPaymentMethodsResponseItemsPaymentMethod = "bank_transfer"
	CustomerGetPaymentMethodsResponseItemsPaymentMethodCrypto          CustomerGetPaymentMethodsResponseItemsPaymentMethod = "crypto"
	CustomerGetPaymentMethodsResponseItemsPaymentMethodBankDebit       CustomerGetPaymentMethodsResponseItemsPaymentMethod = "bank_debit"
	CustomerGetPaymentMethodsResponseItemsPaymentMethodReward          CustomerGetPaymentMethodsResponseItemsPaymentMethod = "reward"
	CustomerGetPaymentMethodsResponseItemsPaymentMethodRealTimePayment CustomerGetPaymentMethodsResponseItemsPaymentMethod = "real_time_payment"
	CustomerGetPaymentMethodsResponseItemsPaymentMethodUpi             CustomerGetPaymentMethodsResponseItemsPaymentMethod = "upi"
	CustomerGetPaymentMethodsResponseItemsPaymentMethodVoucher         CustomerGetPaymentMethodsResponseItemsPaymentMethod = "voucher"
	CustomerGetPaymentMethodsResponseItemsPaymentMethodGiftCard        CustomerGetPaymentMethodsResponseItemsPaymentMethod = "gift_card"
	CustomerGetPaymentMethodsResponseItemsPaymentMethodOpenBanking     CustomerGetPaymentMethodsResponseItemsPaymentMethod = "open_banking"
	CustomerGetPaymentMethodsResponseItemsPaymentMethodMobilePayment   CustomerGetPaymentMethodsResponseItemsPaymentMethod = "mobile_payment"
)

func (CustomerGetPaymentMethodsResponseItemsPaymentMethod) IsKnown added in v1.60.0

type CustomerLimitedDetails added in v1.6.3

type CustomerLimitedDetails struct {
	// Unique identifier for the customer
	CustomerID string `json:"customer_id" api:"required"`
	// Email address of the customer
	Email string `json:"email" api:"required"`
	// Full name of the customer
	Name string `json:"name" api:"required"`
	// Additional metadata associated with the customer
	Metadata Metadata `json:"metadata"`
	// Phone number of the customer
	PhoneNumber string                     `json:"phone_number" api:"nullable"`
	JSON        customerLimitedDetailsJSON `json:"-"`
}

func (*CustomerLimitedDetails) UnmarshalJSON added in v1.6.3

func (r *CustomerLimitedDetails) UnmarshalJSON(data []byte) (err error)

type CustomerListCreditEntitlementsResponse added in v1.86.0

type CustomerListCreditEntitlementsResponse struct {
	Items []CustomerListCreditEntitlementsResponseItem `json:"items" api:"required"`
	JSON  customerListCreditEntitlementsResponseJSON   `json:"-"`
}

func (*CustomerListCreditEntitlementsResponse) UnmarshalJSON added in v1.86.0

func (r *CustomerListCreditEntitlementsResponse) UnmarshalJSON(data []byte) (err error)

type CustomerListCreditEntitlementsResponseItem added in v1.86.0

type CustomerListCreditEntitlementsResponseItem struct {
	// Customer's current remaining credit balance
	Balance string `json:"balance" api:"required"`
	// Credit entitlement ID
	CreditEntitlementID string `json:"credit_entitlement_id" api:"required"`
	// Name of the credit entitlement
	Name string `json:"name" api:"required"`
	// Customer's current overage balance
	Overage string `json:"overage" api:"required"`
	// Unit label (e.g. "API Calls", "Tokens")
	Unit string `json:"unit" api:"required"`
	// Description of the credit entitlement
	Description string                                         `json:"description" api:"nullable"`
	JSON        customerListCreditEntitlementsResponseItemJSON `json:"-"`
}

A credit entitlement with the customer's current balance

func (*CustomerListCreditEntitlementsResponseItem) UnmarshalJSON added in v1.86.0

func (r *CustomerListCreditEntitlementsResponseItem) UnmarshalJSON(data []byte) (err error)

type CustomerListEntitlementGrantsParams added in v1.107.0

type CustomerListEntitlementGrantsParams struct {
	// Filter by integration type (e.g. `feature_flag`)
	IntegrationType param.Field[CustomerListEntitlementGrantsParamsIntegrationType] `query:"integration_type"`
	// Page number (default 0)
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size (default 10, max 100)
	PageSize param.Field[int64] `query:"page_size"`
	// Filter by grant status
	Status param.Field[CustomerListEntitlementGrantsParamsStatus] `query:"status"`
}

func (CustomerListEntitlementGrantsParams) URLQuery added in v1.107.0

URLQuery serializes CustomerListEntitlementGrantsParams's query parameters as `url.Values`.

type CustomerListEntitlementGrantsParamsIntegrationType added in v1.107.0

type CustomerListEntitlementGrantsParamsIntegrationType string

Filter by integration type (e.g. `feature_flag`)

const (
	CustomerListEntitlementGrantsParamsIntegrationTypeDiscord      CustomerListEntitlementGrantsParamsIntegrationType = "discord"
	CustomerListEntitlementGrantsParamsIntegrationTypeTelegram     CustomerListEntitlementGrantsParamsIntegrationType = "telegram"
	CustomerListEntitlementGrantsParamsIntegrationTypeGitHub       CustomerListEntitlementGrantsParamsIntegrationType = "github"
	CustomerListEntitlementGrantsParamsIntegrationTypeFigma        CustomerListEntitlementGrantsParamsIntegrationType = "figma"
	CustomerListEntitlementGrantsParamsIntegrationTypeFramer       CustomerListEntitlementGrantsParamsIntegrationType = "framer"
	CustomerListEntitlementGrantsParamsIntegrationTypeNotion       CustomerListEntitlementGrantsParamsIntegrationType = "notion"
	CustomerListEntitlementGrantsParamsIntegrationTypeDigitalFiles CustomerListEntitlementGrantsParamsIntegrationType = "digital_files"
	CustomerListEntitlementGrantsParamsIntegrationTypeLicenseKey   CustomerListEntitlementGrantsParamsIntegrationType = "license_key"
	CustomerListEntitlementGrantsParamsIntegrationTypeFeatureFlag  CustomerListEntitlementGrantsParamsIntegrationType = "feature_flag"
)

func (CustomerListEntitlementGrantsParamsIntegrationType) IsKnown added in v1.107.0

type CustomerListEntitlementGrantsParamsStatus added in v1.107.0

type CustomerListEntitlementGrantsParamsStatus string

Filter by grant status

const (
	CustomerListEntitlementGrantsParamsStatusPending   CustomerListEntitlementGrantsParamsStatus = "Pending"
	CustomerListEntitlementGrantsParamsStatusDelivered CustomerListEntitlementGrantsParamsStatus = "Delivered"
	CustomerListEntitlementGrantsParamsStatusFailed    CustomerListEntitlementGrantsParamsStatus = "Failed"
	CustomerListEntitlementGrantsParamsStatusRevoked   CustomerListEntitlementGrantsParamsStatus = "Revoked"
)

func (CustomerListEntitlementGrantsParamsStatus) IsKnown added in v1.107.0

type CustomerListEntitlementsResponse added in v1.97.0

type CustomerListEntitlementsResponse struct {
	Items []CustomerListEntitlementsResponseItem `json:"items" api:"required"`
	JSON  customerListEntitlementsResponseJSON   `json:"-"`
}

func (*CustomerListEntitlementsResponse) UnmarshalJSON added in v1.97.0

func (r *CustomerListEntitlementsResponse) UnmarshalJSON(data []byte) (err error)

type CustomerListEntitlementsResponseItem added in v1.97.0

type CustomerListEntitlementsResponseItem struct {
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// The entitlement this grant belongs to.
	EntitlementID   string `json:"entitlement_id" api:"required"`
	EntitlementName string `json:"entitlement_name" api:"required"`
	// Grant id (the per-customer row in `entitlement_grants`).
	GrantID                string                                      `json:"grant_id" api:"required"`
	IntegrationType        EntitlementIntegrationType                  `json:"integration_type" api:"required"`
	Status                 CustomerListEntitlementsResponseItemsStatus `json:"status" api:"required"`
	UpdatedAt              time.Time                                   `json:"updated_at" api:"required" format:"date-time"`
	DeliveredAt            time.Time                                   `json:"delivered_at" api:"nullable" format:"date-time"`
	EntitlementDescription string                                      `json:"entitlement_description" api:"nullable"`
	RevokedAt              time.Time                                   `json:"revoked_at" api:"nullable" format:"date-time"`
	JSON                   customerListEntitlementsResponseItemJSON    `json:"-"`
}

func (*CustomerListEntitlementsResponseItem) UnmarshalJSON added in v1.97.0

func (r *CustomerListEntitlementsResponseItem) UnmarshalJSON(data []byte) (err error)

type CustomerListEntitlementsResponseItemsStatus added in v1.97.0

type CustomerListEntitlementsResponseItemsStatus string
const (
	CustomerListEntitlementsResponseItemsStatusPending   CustomerListEntitlementsResponseItemsStatus = "pending"
	CustomerListEntitlementsResponseItemsStatusDelivered CustomerListEntitlementsResponseItemsStatus = "delivered"
	CustomerListEntitlementsResponseItemsStatusFailed    CustomerListEntitlementsResponseItemsStatus = "failed"
	CustomerListEntitlementsResponseItemsStatusRevoked   CustomerListEntitlementsResponseItemsStatus = "revoked"
)

func (CustomerListEntitlementsResponseItemsStatus) IsKnown added in v1.97.0

type CustomerListParams

type CustomerListParams struct {
	// Filter customers created on or after this timestamp
	CreatedAtGte param.Field[time.Time] `query:"created_at_gte" format:"date-time"`
	// Filter customers created on or before this timestamp
	CreatedAtLte param.Field[time.Time] `query:"created_at_lte" format:"date-time"`
	// Filter by customer email
	Email param.Field[string] `query:"email"`
	// Filter by customer name (partial match, case-insensitive)
	Name param.Field[string] `query:"name"`
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
}

func (CustomerListParams) URLQuery

func (r CustomerListParams) URLQuery() (v url.Values)

URLQuery serializes CustomerListParams's query parameters as `url.Values`.

type CustomerNewParams added in v0.12.0

type CustomerNewParams struct {
	Email param.Field[string] `json:"email" api:"required"`
	Name  param.Field[string] `json:"name" api:"required"`
	// Additional metadata for the customer
	Metadata    param.Field[MetadataParam] `json:"metadata"`
	PhoneNumber param.Field[string]        `json:"phone_number"`
}

func (CustomerNewParams) MarshalJSON added in v0.12.0

func (r CustomerNewParams) MarshalJSON() (data []byte, err error)

type CustomerPortalSession added in v1.10.3

type CustomerPortalSession struct {
	Link string                    `json:"link" api:"required"`
	JSON customerPortalSessionJSON `json:"-"`
}

func (*CustomerPortalSession) UnmarshalJSON added in v1.10.3

func (r *CustomerPortalSession) UnmarshalJSON(data []byte) (err error)

type CustomerRequestParam added in v1.6.3

type CustomerRequestParam struct {
	CustomerID param.Field[string] `json:"customer_id"`
	// Email is required for creating a new customer
	Email param.Field[string] `json:"email"`
	// Optional full name of the customer. If provided during session creation, it is
	// persisted and becomes immutable for the session. If omitted here, it can be
	// provided later via the confirm API.
	Name        param.Field[string] `json:"name"`
	PhoneNumber param.Field[string] `json:"phone_number"`
}

func (CustomerRequestParam) MarshalJSON added in v1.6.3

func (r CustomerRequestParam) MarshalJSON() (data []byte, err error)

type CustomerRequestUnionParam added in v1.6.3

type CustomerRequestUnionParam interface {
	// contains filtered or unexported methods
}

Satisfied by AttachExistingCustomerParam, NewCustomerParam, CustomerRequestParam.

type CustomerService

type CustomerService struct {
	Options        []option.RequestOption
	CustomerPortal *CustomerCustomerPortalService
	Wallets        *CustomerWalletService
	Emails         *CustomerEmailService
}

CustomerService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewCustomerService method instead.

func NewCustomerService

func NewCustomerService(opts ...option.RequestOption) (r *CustomerService)

NewCustomerService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*CustomerService) DeletePaymentMethod added in v1.92.0

func (r *CustomerService) DeletePaymentMethod(ctx context.Context, customerID string, paymentMethodID string, opts ...option.RequestOption) (err error)

func (*CustomerService) Get

func (r *CustomerService) Get(ctx context.Context, customerID string, opts ...option.RequestOption) (res *Customer, err error)

func (*CustomerService) GetPaymentMethods added in v1.60.0

func (r *CustomerService) GetPaymentMethods(ctx context.Context, customerID string, opts ...option.RequestOption) (res *CustomerGetPaymentMethodsResponse, err error)

func (*CustomerService) List

func (*CustomerService) ListCreditEntitlements added in v1.86.0

func (r *CustomerService) ListCreditEntitlements(ctx context.Context, customerID string, opts ...option.RequestOption) (res *CustomerListCreditEntitlementsResponse, err error)

List all credit entitlements for a customer with their current balances

func (*CustomerService) ListEntitlementGrants added in v1.107.0

List all of a customer's entitlement grants across every entitlement. One row per grant.

func (*CustomerService) ListEntitlementGrantsAutoPaging added in v1.107.0

List all of a customer's entitlement grants across every entitlement. One row per grant.

func (*CustomerService) ListEntitlements added in v1.97.0

func (r *CustomerService) ListEntitlements(ctx context.Context, customerID string, opts ...option.RequestOption) (res *CustomerListEntitlementsResponse, err error)

List all entitlement grants delivered (or in flight) to a customer.

func (*CustomerService) New added in v0.12.0

func (r *CustomerService) New(ctx context.Context, body CustomerNewParams, opts ...option.RequestOption) (res *Customer, err error)

func (*CustomerService) Update added in v0.12.0

func (r *CustomerService) Update(ctx context.Context, customerID string, body CustomerUpdateParams, opts ...option.RequestOption) (res *Customer, err error)

type CustomerUpdateParams added in v0.12.0

type CustomerUpdateParams struct {
	Email param.Field[string] `json:"email"`
	// Additional metadata for the customer
	Metadata    param.Field[MetadataParam] `json:"metadata"`
	Name        param.Field[string]        `json:"name"`
	PhoneNumber param.Field[string]        `json:"phone_number"`
}

func (CustomerUpdateParams) MarshalJSON added in v0.12.0

func (r CustomerUpdateParams) MarshalJSON() (data []byte, err error)

type CustomerWallet added in v1.53.2

type CustomerWallet struct {
	Balance    int64              `json:"balance" api:"required"`
	CreatedAt  time.Time          `json:"created_at" api:"required" format:"date-time"`
	Currency   Currency           `json:"currency" api:"required"`
	CustomerID string             `json:"customer_id" api:"required"`
	UpdatedAt  time.Time          `json:"updated_at" api:"required" format:"date-time"`
	JSON       customerWalletJSON `json:"-"`
}

func (*CustomerWallet) UnmarshalJSON added in v1.53.2

func (r *CustomerWallet) UnmarshalJSON(data []byte) (err error)

type CustomerWalletLedgerEntryListParams added in v1.53.2

type CustomerWalletLedgerEntryListParams struct {
	// Optional currency filter
	Currency   param.Field[Currency] `query:"currency"`
	PageNumber param.Field[int64]    `query:"page_number"`
	PageSize   param.Field[int64]    `query:"page_size"`
}

func (CustomerWalletLedgerEntryListParams) URLQuery added in v1.53.2

URLQuery serializes CustomerWalletLedgerEntryListParams's query parameters as `url.Values`.

type CustomerWalletLedgerEntryNewParams added in v1.53.2

type CustomerWalletLedgerEntryNewParams struct {
	Amount param.Field[int64] `json:"amount" api:"required"`
	// Currency of the wallet to adjust
	Currency param.Field[Currency] `json:"currency" api:"required"`
	// Type of ledger entry - credit or debit
	EntryType param.Field[CustomerWalletLedgerEntryNewParamsEntryType] `json:"entry_type" api:"required"`
	// Optional idempotency key to prevent duplicate entries
	IdempotencyKey param.Field[string] `json:"idempotency_key"`
	Reason         param.Field[string] `json:"reason"`
}

func (CustomerWalletLedgerEntryNewParams) MarshalJSON added in v1.53.2

func (r CustomerWalletLedgerEntryNewParams) MarshalJSON() (data []byte, err error)

type CustomerWalletLedgerEntryNewParamsEntryType added in v1.53.2

type CustomerWalletLedgerEntryNewParamsEntryType string

Type of ledger entry - credit or debit

const (
	CustomerWalletLedgerEntryNewParamsEntryTypeCredit CustomerWalletLedgerEntryNewParamsEntryType = "credit"
	CustomerWalletLedgerEntryNewParamsEntryTypeDebit  CustomerWalletLedgerEntryNewParamsEntryType = "debit"
)

func (CustomerWalletLedgerEntryNewParamsEntryType) IsKnown added in v1.53.2

type CustomerWalletLedgerEntryService added in v1.53.2

type CustomerWalletLedgerEntryService struct {
	Options []option.RequestOption
}

CustomerWalletLedgerEntryService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewCustomerWalletLedgerEntryService method instead.

func NewCustomerWalletLedgerEntryService added in v1.53.2

func NewCustomerWalletLedgerEntryService(opts ...option.RequestOption) (r *CustomerWalletLedgerEntryService)

NewCustomerWalletLedgerEntryService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*CustomerWalletLedgerEntryService) List added in v1.53.2

func (*CustomerWalletLedgerEntryService) ListAutoPaging added in v1.53.2

func (*CustomerWalletLedgerEntryService) New added in v1.53.2

type CustomerWalletListResponse added in v1.53.2

type CustomerWalletListResponse struct {
	Items []CustomerWallet `json:"items" api:"required"`
	// Sum of all wallet balances converted to USD (in smallest unit)
	TotalBalanceUsd int64                          `json:"total_balance_usd" api:"required"`
	JSON            customerWalletListResponseJSON `json:"-"`
}

func (*CustomerWalletListResponse) UnmarshalJSON added in v1.53.2

func (r *CustomerWalletListResponse) UnmarshalJSON(data []byte) (err error)

type CustomerWalletService added in v1.53.2

type CustomerWalletService struct {
	Options       []option.RequestOption
	LedgerEntries *CustomerWalletLedgerEntryService
}

CustomerWalletService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewCustomerWalletService method instead.

func NewCustomerWalletService added in v1.53.2

func NewCustomerWalletService(opts ...option.RequestOption) (r *CustomerWalletService)

NewCustomerWalletService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*CustomerWalletService) List added in v1.53.2

func (r *CustomerWalletService) List(ctx context.Context, customerID string, opts ...option.RequestOption) (res *CustomerWalletListResponse, err error)

type CustomerWalletTransaction added in v1.53.2

type CustomerWalletTransaction struct {
	ID                string                             `json:"id" api:"required"`
	AfterBalance      int64                              `json:"after_balance" api:"required"`
	Amount            int64                              `json:"amount" api:"required"`
	BeforeBalance     int64                              `json:"before_balance" api:"required"`
	BusinessID        string                             `json:"business_id" api:"required"`
	CreatedAt         time.Time                          `json:"created_at" api:"required" format:"date-time"`
	Currency          Currency                           `json:"currency" api:"required"`
	CustomerID        string                             `json:"customer_id" api:"required"`
	EventType         CustomerWalletTransactionEventType `json:"event_type" api:"required"`
	IsCredit          bool                               `json:"is_credit" api:"required"`
	Reason            string                             `json:"reason" api:"nullable"`
	ReferenceObjectID string                             `json:"reference_object_id" api:"nullable"`
	JSON              customerWalletTransactionJSON      `json:"-"`
}

func (*CustomerWalletTransaction) UnmarshalJSON added in v1.53.2

func (r *CustomerWalletTransaction) UnmarshalJSON(data []byte) (err error)

type CustomerWalletTransactionEventType added in v1.53.2

type CustomerWalletTransactionEventType string
const (
	CustomerWalletTransactionEventTypePayment            CustomerWalletTransactionEventType = "payment"
	CustomerWalletTransactionEventTypePaymentReversal    CustomerWalletTransactionEventType = "payment_reversal"
	CustomerWalletTransactionEventTypeRefund             CustomerWalletTransactionEventType = "refund"
	CustomerWalletTransactionEventTypeRefundReversal     CustomerWalletTransactionEventType = "refund_reversal"
	CustomerWalletTransactionEventTypeDispute            CustomerWalletTransactionEventType = "dispute"
	CustomerWalletTransactionEventTypeDisputeReversal    CustomerWalletTransactionEventType = "dispute_reversal"
	CustomerWalletTransactionEventTypeMerchantAdjustment CustomerWalletTransactionEventType = "merchant_adjustment"
)

func (CustomerWalletTransactionEventType) IsKnown added in v1.53.2

type DigitalProductDelivery added in v1.86.0

type DigitalProductDelivery struct {
	// One entry per attached file.
	Files []DigitalProductDeliveryFile `json:"files" api:"required"`
	// Optional external URL, passed through from the entitlement configuration.
	ExternalURL string `json:"external_url" api:"nullable"`
	// Optional human-readable delivery instructions, passed through from the
	// entitlement configuration.
	Instructions string                     `json:"instructions" api:"nullable"`
	JSON         digitalProductDeliveryJSON `json:"-"`
}

Digital-product-delivery payload, present on grants for `digital_files` entitlements. Each file carries a short-lived presigned download URL.

func (*DigitalProductDelivery) UnmarshalJSON added in v1.86.0

func (r *DigitalProductDelivery) UnmarshalJSON(data []byte) (err error)

type DigitalProductDeliveryFile added in v1.86.0

type DigitalProductDeliveryFile struct {
	// Short-lived presigned URL for downloading the file.
	DownloadURL string `json:"download_url" api:"required"`
	// Seconds until `download_url` expires.
	ExpiresIn int64 `json:"expires_in" api:"required"`
	// Identifier of the attached file.
	FileID string `json:"file_id" api:"required"`
	// Original filename of the attached file.
	Filename string `json:"filename" api:"required"`
	// Optional content-type declared at upload.
	ContentType string `json:"content_type" api:"nullable"`
	// Optional size of the file in bytes.
	FileSize int64                          `json:"file_size" api:"nullable"`
	JSON     digitalProductDeliveryFileJSON `json:"-"`
}

One file in a digital-product delivery payload.

func (*DigitalProductDeliveryFile) UnmarshalJSON added in v1.86.0

func (r *DigitalProductDeliveryFile) UnmarshalJSON(data []byte) (err error)

type Discount added in v0.24.0

type Discount struct {
	// The discount amount in **basis points** (e.g., 540 => 5.4%).
	Amount int64 `json:"amount" api:"required"`
	// The business this discount belongs to.
	BusinessID string `json:"business_id" api:"required"`
	// The discount code (up to 16 chars).
	Code string `json:"code" api:"required"`
	// Timestamp when the discount is created
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Who may redeem this discount code.
	CustomerEligibility DiscountCustomerEligibility `json:"customer_eligibility" api:"required"`
	// The unique discount ID
	DiscountID string `json:"discount_id" api:"required"`
	// Arbitrary key-value metadata. Values can be string, integer, number, or boolean.
	Metadata Metadata `json:"metadata" api:"required"`
	// Whether this discount should be preserved when a subscription changes plans.
	// Default: false (discount is removed on plan change)
	PreserveOnPlanChange bool `json:"preserve_on_plan_change" api:"required"`
	// List of product IDs to which this discount is restricted.
	RestrictedTo []string `json:"restricted_to" api:"required"`
	// How many times this discount has been used.
	TimesUsed int64 `json:"times_used" api:"required"`
	// The type of discount (`percentage` or `flat`).
	Type DiscountType `json:"type" api:"required"`
	// Per-currency options (flat deduction / percentage cap + minimum subtotal). Empty
	// for discounts without any configured currency options.
	CurrencyOptions []DiscountCurrencyOption `json:"currency_options"`
	// Optional date/time after which discount is expired.
	ExpiresAt time.Time `json:"expires_at" api:"nullable" format:"date-time"`
	// Name for the Discount
	Name string `json:"name" api:"nullable"`
	// Maximum number of times a single customer may redeem this discount, if any.
	PerCustomerUsageLimit int64 `json:"per_customer_usage_limit" api:"nullable"`
	// Optional date/time before which the discount is not yet active. NULL = active
	// immediately.
	StartsAt time.Time `json:"starts_at" api:"nullable" format:"date-time"`
	// Number of subscription billing cycles this discount is valid for. If not
	// provided, the discount will be applied indefinitely to all recurring payments
	// related to the subscription.
	SubscriptionCycles int64 `json:"subscription_cycles" api:"nullable"`
	// Usage limit for this discount, if any.
	UsageLimit int64        `json:"usage_limit" api:"nullable"`
	JSON       discountJSON `json:"-"`
}

func (*Discount) UnmarshalJSON added in v0.24.0

func (r *Discount) UnmarshalJSON(data []byte) (err error)

type DiscountCurrencyOption added in v1.109.0

type DiscountCurrencyOption struct {
	// The currency this option applies to.
	Currency Currency `json:"currency" api:"required"`
	// Whether this is the default row FX conversions pivot from.
	IsDefault bool `json:"is_default" api:"required"`
	// Eligible-cart threshold in this currency's subunits (0 = no minimum).
	MinimumSubtotal int64 `json:"minimum_subtotal" api:"required"`
	// The most this code discounts in this currency's subunits (flat deduction or
	// percentage cap).
	MaxAmountPossible int64                      `json:"max_amount_possible" api:"nullable"`
	JSON              discountCurrencyOptionJSON `json:"-"`
}

A per-currency discount option (response shape). `max_amount_possible` mirrors the DB column of the same name.

func (*DiscountCurrencyOption) UnmarshalJSON added in v1.109.0

func (r *DiscountCurrencyOption) UnmarshalJSON(data []byte) (err error)

type DiscountCustomerEligibility added in v1.109.0

type DiscountCustomerEligibility string

Who may redeem this discount code.

const (
	DiscountCustomerEligibilityAny       DiscountCustomerEligibility = "any"
	DiscountCustomerEligibilityFirstTime DiscountCustomerEligibility = "first_time"
	DiscountCustomerEligibilityExisting  DiscountCustomerEligibility = "existing"
	DiscountCustomerEligibilitySpecific  DiscountCustomerEligibility = "specific"
)

func (DiscountCustomerEligibility) IsKnown added in v1.109.0

func (r DiscountCustomerEligibility) IsKnown() bool

type DiscountDetail added in v1.99.0

type DiscountDetail struct {
	// The discount amount in **basis points** (e.g., 540 => 5.4%).
	Amount int64 `json:"amount" api:"required"`
	// The business this discount belongs to
	BusinessID string `json:"business_id" api:"required"`
	// The discount code
	Code string `json:"code" api:"required"`
	// Timestamp when the discount was created
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// The unique discount ID
	DiscountID string `json:"discount_id" api:"required"`
	// Additional metadata
	Metadata Metadata `json:"metadata" api:"required"`
	// Position of this discount in the stack (0-based)
	Position int64 `json:"position" api:"required"`
	// Whether this discount should be preserved when a subscription changes plans
	PreserveOnPlanChange bool `json:"preserve_on_plan_change" api:"required"`
	// List of product IDs to which this discount is restricted
	RestrictedTo []string `json:"restricted_to" api:"required"`
	// How many times this discount has been used
	TimesUsed int64 `json:"times_used" api:"required"`
	// The type of discount
	Type DiscountType `json:"type" api:"required"`
	// Remaining billing cycles for this discount on this subscription (None for
	// one-time payments)
	CyclesRemaining int64 `json:"cycles_remaining" api:"nullable"`
	// Optional date/time after which discount is expired
	ExpiresAt time.Time `json:"expires_at" api:"nullable" format:"date-time"`
	// Name for the Discount
	Name string `json:"name" api:"nullable"`
	// Number of subscription billing cycles this discount is valid for
	SubscriptionCycles int64 `json:"subscription_cycles" api:"nullable"`
	// Usage limit for this discount, if any
	UsageLimit int64              `json:"usage_limit" api:"nullable"`
	JSON       discountDetailJSON `json:"-"`
}

Response struct for a discount with its position in a stack and optional cycle-tracking information (for subscriptions).

func (*DiscountDetail) UnmarshalJSON added in v1.99.0

func (r *DiscountDetail) UnmarshalJSON(data []byte) (err error)

type DiscountListParams added in v0.24.0

type DiscountListParams struct {
	// Filter by active status. `true` = currently redeemable (started, not expired,
	// not usage-exhausted). `false` = not currently redeemable (expired,
	// usage-exhausted, or pending a future `starts_at`).
	Active param.Field[bool] `query:"active"`
	// Filter by discount code (partial match, case-insensitive)
	Code param.Field[string] `query:"code"`
	// Filter by discount type
	DiscountType param.Field[DiscountType] `query:"discount_type"`
	// Page number (default = 0).
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size (default = 10, max = 100).
	PageSize param.Field[int64] `query:"page_size"`
	// Filter by product restriction (only discounts that apply to this product)
	ProductID param.Field[string] `query:"product_id"`
}

func (DiscountListParams) URLQuery added in v0.24.0

func (r DiscountListParams) URLQuery() (v url.Values)

URLQuery serializes DiscountListParams's query parameters as `url.Values`.

type DiscountNewParams added in v0.24.0

type DiscountNewParams struct {
	// The discount amount in **basis points** (e.g. `540` means `5.4%`, `10000` means
	// `100%`).
	//
	// Must be at least 1.
	Amount param.Field[int64] `json:"amount" api:"required"`
	// The discount type: `percentage` or `flat` (`flat_per_unit` stays blocked).
	Type param.Field[DiscountType] `json:"type" api:"required"`
	// Optionally supply a code (will be uppercased).
	//
	// - Must be at least 3 characters if provided.
	// - If omitted, a random 16-character code is generated.
	Code param.Field[string] `json:"code"`
	// Per-currency options (flat deduction / percentage cap + minimum subtotal).
	// Required for `flat` codes (must include a resolvable default); optional
	// per-currency caps for `percentage` codes. Per-row invariants are checked in
	// `normalize_currency_options`, not via `#[validate(nested)]`.
	CurrencyOptions param.Field[[]DiscountNewParamsCurrencyOption] `json:"currency_options"`
	// Who may redeem this discount code. Defaults to `any` (unrestricted). `specific`
	// starts with zero attached customers (fails closed) until customers are attached
	// via `POST /discounts/{id}/customers`.
	CustomerEligibility param.Field[DiscountNewParamsCustomerEligibility] `json:"customer_eligibility"`
	// When the discount expires, if ever.
	ExpiresAt param.Field[time.Time] `json:"expires_at" format:"date-time"`
	// Additional metadata for the discount
	Metadata param.Field[MetadataParam] `json:"metadata"`
	Name     param.Field[string]        `json:"name"`
	// Maximum number of times a single customer may redeem this discount. Must be
	// `<= usage_limit` when both are set.
	PerCustomerUsageLimit param.Field[int64] `json:"per_customer_usage_limit"`
	// Whether this discount should be preserved when a subscription changes plans.
	// Default: false (discount is removed on plan change)
	PreserveOnPlanChange param.Field[bool] `json:"preserve_on_plan_change"`
	// List of product IDs to restrict usage (if any).
	RestrictedTo param.Field[[]string] `json:"restricted_to"`
	// When the discount becomes active, if scheduled for the future. NULL = active
	// immediately. Must be strictly before `expires_at` when both are set.
	StartsAt param.Field[time.Time] `json:"starts_at" format:"date-time"`
	// Number of subscription billing cycles this discount is valid for. If not
	// provided, the discount will be applied indefinitely to all recurring payments
	// related to the subscription.
	SubscriptionCycles param.Field[int64] `json:"subscription_cycles"`
	// How many times this discount can be used (if any). Must be >= 1 if provided.
	UsageLimit param.Field[int64] `json:"usage_limit"`
}

func (DiscountNewParams) MarshalJSON added in v0.24.0

func (r DiscountNewParams) MarshalJSON() (data []byte, err error)

type DiscountNewParamsCurrencyOption added in v1.109.0

type DiscountNewParamsCurrencyOption struct {
	// The currency this option applies to.
	Currency param.Field[Currency] `json:"currency" api:"required"`
	// Whether this row is the default to convert from for unconfigured currencies. At
	// most one row per discount may be default.
	IsDefault param.Field[bool] `json:"is_default"`
	// The most this code discounts in this currency's subunits. For `flat` codes this
	// is the deduction; for `percentage` codes it is the max-discount cap. Must be > 0
	// if provided.
	MaxAmountPossible param.Field[int64] `json:"max_amount_possible"`
	// Eligible-cart threshold in this currency's subunits (0 = no minimum).
	MinimumSubtotal param.Field[int64] `json:"minimum_subtotal"`
}

A per-currency discount option (request shape).

`max_amount_possible` is the most this code discounts in this currency — the flat deduction for `flat` codes, or the max-discount cap for `percentage` codes. Maps to the DB column of the same name.

func (DiscountNewParamsCurrencyOption) MarshalJSON added in v1.109.0

func (r DiscountNewParamsCurrencyOption) MarshalJSON() (data []byte, err error)

type DiscountNewParamsCustomerEligibility added in v1.109.0

type DiscountNewParamsCustomerEligibility string

Who may redeem this discount code. Defaults to `any` (unrestricted). `specific` starts with zero attached customers (fails closed) until customers are attached via `POST /discounts/{id}/customers`.

const (
	DiscountNewParamsCustomerEligibilityAny       DiscountNewParamsCustomerEligibility = "any"
	DiscountNewParamsCustomerEligibilityFirstTime DiscountNewParamsCustomerEligibility = "first_time"
	DiscountNewParamsCustomerEligibilityExisting  DiscountNewParamsCustomerEligibility = "existing"
	DiscountNewParamsCustomerEligibilitySpecific  DiscountNewParamsCustomerEligibility = "specific"
)

func (DiscountNewParamsCustomerEligibility) IsKnown added in v1.109.0

type DiscountService added in v0.24.0

type DiscountService struct {
	Options []option.RequestOption
}

DiscountService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewDiscountService method instead.

func NewDiscountService added in v0.24.0

func NewDiscountService(opts ...option.RequestOption) (r *DiscountService)

NewDiscountService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*DiscountService) Delete added in v0.24.0

func (r *DiscountService) Delete(ctx context.Context, discountID string, opts ...option.RequestOption) (err error)

DELETE /discounts/{discount_id}

func (*DiscountService) Get added in v0.24.0

func (r *DiscountService) Get(ctx context.Context, discountID string, opts ...option.RequestOption) (res *Discount, err error)

GET /discounts/{discount_id}

func (*DiscountService) GetByCode added in v1.73.0

func (r *DiscountService) GetByCode(ctx context.Context, code string, opts ...option.RequestOption) (res *Discount, err error)

Validate and fetch a discount by its code name (e.g., "SAVE20"). This allows real-time validation directly against the API using the human-readable discount code instead of requiring the internal discount_id.

func (*DiscountService) List added in v0.24.0

GET /discounts

func (*DiscountService) ListAutoPaging added in v0.24.0

GET /discounts

func (*DiscountService) New added in v0.24.0

func (r *DiscountService) New(ctx context.Context, body DiscountNewParams, opts ...option.RequestOption) (res *Discount, err error)

POST /discounts If `code` is omitted or empty, a random 16-char uppercase code is generated.

func (*DiscountService) Update added in v0.24.0

func (r *DiscountService) Update(ctx context.Context, discountID string, body DiscountUpdateParams, opts ...option.RequestOption) (res *Discount, err error)

PATCH /discounts/{discount_id}

type DiscountType added in v0.24.0

type DiscountType string
const (
	DiscountTypeFlat       DiscountType = "flat"
	DiscountTypePercentage DiscountType = "percentage"
)

func (DiscountType) IsKnown added in v0.24.0

func (r DiscountType) IsKnown() bool

type DiscountUpdateParams added in v0.24.0

type DiscountUpdateParams struct {
	// If present, update the discount amount in **basis points** (e.g., `540` =
	// `5.4%`, `10000` = `100%`).
	//
	// Must be at least 1 if provided.
	Amount param.Field[int64] `json:"amount"`
	// If present, update the discount code (uppercase).
	Code param.Field[string] `json:"code"`
	// If present, fully replaces the discount's currency options (replace-set
	// semantics, like `restricted_to`). Send an empty array to clear them.
	CurrencyOptions param.Field[[]DiscountUpdateParamsCurrencyOption] `json:"currency_options"`
	// If present, update who may redeem this discount. Plain field (not
	// double-option): the DB column is `NOT NULL`, so it can never be cleared back to
	// unset, only changed to another `CustomerEligibility` value.
	CustomerEligibility param.Field[DiscountUpdateParamsCustomerEligibility] `json:"customer_eligibility"`
	ExpiresAt           param.Field[time.Time]                               `json:"expires_at" format:"date-time"`
	// Additional metadata for the discount
	Metadata param.Field[MetadataParam] `json:"metadata"`
	Name     param.Field[string]        `json:"name"`
	// If present, update the per-customer usage limit (double-option: send `null` to
	// clear it back to unlimited). Must be `<= usage_limit` (the value in effect after
	// this patch) when both are set.
	PerCustomerUsageLimit param.Field[int64] `json:"per_customer_usage_limit"`
	// Whether this discount should be preserved when a subscription changes plans. If
	// not provided, the existing value is kept.
	PreserveOnPlanChange param.Field[bool] `json:"preserve_on_plan_change"`
	// If present, replaces all restricted product IDs with this new set. To remove all
	// restrictions, send empty array
	RestrictedTo param.Field[[]string] `json:"restricted_to"`
	// If present, update `starts_at` (double-option: send `null` to clear it).
	StartsAt param.Field[time.Time] `json:"starts_at" format:"date-time"`
	// Number of subscription billing cycles this discount is valid for. If not
	// provided, the discount will be applied indefinitely to all recurring payments
	// related to the subscription.
	SubscriptionCycles param.Field[int64] `json:"subscription_cycles"`
	// If present, update the discount type (`percentage` or `flat`).
	Type       param.Field[DiscountType] `json:"type"`
	UsageLimit param.Field[int64]        `json:"usage_limit"`
}

func (DiscountUpdateParams) MarshalJSON added in v0.24.0

func (r DiscountUpdateParams) MarshalJSON() (data []byte, err error)

type DiscountUpdateParamsCurrencyOption added in v1.109.0

type DiscountUpdateParamsCurrencyOption struct {
	// The currency this option applies to.
	Currency param.Field[Currency] `json:"currency" api:"required"`
	// Whether this row is the default to convert from for unconfigured currencies. At
	// most one row per discount may be default.
	IsDefault param.Field[bool] `json:"is_default"`
	// The most this code discounts in this currency's subunits. For `flat` codes this
	// is the deduction; for `percentage` codes it is the max-discount cap. Must be > 0
	// if provided.
	MaxAmountPossible param.Field[int64] `json:"max_amount_possible"`
	// Eligible-cart threshold in this currency's subunits (0 = no minimum).
	MinimumSubtotal param.Field[int64] `json:"minimum_subtotal"`
}

A per-currency discount option (request shape).

`max_amount_possible` is the most this code discounts in this currency — the flat deduction for `flat` codes, or the max-discount cap for `percentage` codes. Maps to the DB column of the same name.

func (DiscountUpdateParamsCurrencyOption) MarshalJSON added in v1.109.0

func (r DiscountUpdateParamsCurrencyOption) MarshalJSON() (data []byte, err error)

type DiscountUpdateParamsCustomerEligibility added in v1.109.0

type DiscountUpdateParamsCustomerEligibility string

If present, update who may redeem this discount. Plain field (not double-option): the DB column is `NOT NULL`, so it can never be cleared back to unset, only changed to another `CustomerEligibility` value.

const (
	DiscountUpdateParamsCustomerEligibilityAny       DiscountUpdateParamsCustomerEligibility = "any"
	DiscountUpdateParamsCustomerEligibilityFirstTime DiscountUpdateParamsCustomerEligibility = "first_time"
	DiscountUpdateParamsCustomerEligibilityExisting  DiscountUpdateParamsCustomerEligibility = "existing"
	DiscountUpdateParamsCustomerEligibilitySpecific  DiscountUpdateParamsCustomerEligibility = "specific"
)

func (DiscountUpdateParamsCustomerEligibility) IsKnown added in v1.109.0

type Dispute

type Dispute struct {
	// The amount involved in the dispute, represented as a string to accommodate
	// precision.
	Amount string `json:"amount" api:"required"`
	// The unique identifier of the business involved in the dispute.
	BusinessID string `json:"business_id" api:"required"`
	// The timestamp of when the dispute was created, in UTC.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// The currency of the disputed amount, represented as an ISO 4217 currency code.
	Currency string `json:"currency" api:"required"`
	// The unique identifier of the dispute.
	DisputeID string `json:"dispute_id" api:"required"`
	// The current stage of the dispute process.
	DisputeStage DisputeStage `json:"dispute_stage" api:"required"`
	// The current status of the dispute.
	DisputeStatus DisputeStatus `json:"dispute_status" api:"required"`
	// The unique identifier of the payment associated with the dispute.
	PaymentID string `json:"payment_id" api:"required"`
	// Whether the dispute was resolved by Rapid Dispute Resolution
	IsResolvedByRdr bool `json:"is_resolved_by_rdr" api:"nullable"`
	// Remarks
	Remarks string      `json:"remarks" api:"nullable"`
	JSON    disputeJSON `json:"-"`
}

func (*Dispute) UnmarshalJSON

func (r *Dispute) UnmarshalJSON(data []byte) (err error)

type DisputeAcceptedWebhookEvent added in v1.56.0

type DisputeAcceptedWebhookEvent struct {
	// The business identifier
	BusinessID string  `json:"business_id" api:"required"`
	Data       Dispute `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type DisputeAcceptedWebhookEventType `json:"type" api:"required"`
	JSON disputeAcceptedWebhookEventJSON `json:"-"`
}

func (*DisputeAcceptedWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *DisputeAcceptedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type DisputeAcceptedWebhookEventType added in v1.56.0

type DisputeAcceptedWebhookEventType string

The event type

const (
	DisputeAcceptedWebhookEventTypeDisputeAccepted DisputeAcceptedWebhookEventType = "dispute.accepted"
)

func (DisputeAcceptedWebhookEventType) IsKnown added in v1.56.0

type DisputeCancelledWebhookEvent added in v1.56.0

type DisputeCancelledWebhookEvent struct {
	// The business identifier
	BusinessID string  `json:"business_id" api:"required"`
	Data       Dispute `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type DisputeCancelledWebhookEventType `json:"type" api:"required"`
	JSON disputeCancelledWebhookEventJSON `json:"-"`
}

func (*DisputeCancelledWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *DisputeCancelledWebhookEvent) UnmarshalJSON(data []byte) (err error)

type DisputeCancelledWebhookEventType added in v1.56.0

type DisputeCancelledWebhookEventType string

The event type

const (
	DisputeCancelledWebhookEventTypeDisputeCancelled DisputeCancelledWebhookEventType = "dispute.cancelled"
)

func (DisputeCancelledWebhookEventType) IsKnown added in v1.56.0

type DisputeChallengedWebhookEvent added in v1.56.0

type DisputeChallengedWebhookEvent struct {
	// The business identifier
	BusinessID string  `json:"business_id" api:"required"`
	Data       Dispute `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type DisputeChallengedWebhookEventType `json:"type" api:"required"`
	JSON disputeChallengedWebhookEventJSON `json:"-"`
}

func (*DisputeChallengedWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *DisputeChallengedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type DisputeChallengedWebhookEventType added in v1.56.0

type DisputeChallengedWebhookEventType string

The event type

const (
	DisputeChallengedWebhookEventTypeDisputeChallenged DisputeChallengedWebhookEventType = "dispute.challenged"
)

func (DisputeChallengedWebhookEventType) IsKnown added in v1.56.0

type DisputeExpiredWebhookEvent added in v1.56.0

type DisputeExpiredWebhookEvent struct {
	// The business identifier
	BusinessID string  `json:"business_id" api:"required"`
	Data       Dispute `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type DisputeExpiredWebhookEventType `json:"type" api:"required"`
	JSON disputeExpiredWebhookEventJSON `json:"-"`
}

func (*DisputeExpiredWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *DisputeExpiredWebhookEvent) UnmarshalJSON(data []byte) (err error)

type DisputeExpiredWebhookEventType added in v1.56.0

type DisputeExpiredWebhookEventType string

The event type

const (
	DisputeExpiredWebhookEventTypeDisputeExpired DisputeExpiredWebhookEventType = "dispute.expired"
)

func (DisputeExpiredWebhookEventType) IsKnown added in v1.56.0

type DisputeListParams

type DisputeListParams struct {
	// Get events after this created time
	CreatedAtGte param.Field[time.Time] `query:"created_at_gte" format:"date-time"`
	// Get events created before this time
	CreatedAtLte param.Field[time.Time] `query:"created_at_lte" format:"date-time"`
	// Filter by customer_id
	CustomerID param.Field[string] `query:"customer_id"`
	// Filter by dispute stage
	DisputeStage param.Field[DisputeListParamsDisputeStage] `query:"dispute_stage"`
	// Filter by dispute status
	DisputeStatus param.Field[DisputeListParamsDisputeStatus] `query:"dispute_status"`
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
}

func (DisputeListParams) URLQuery

func (r DisputeListParams) URLQuery() (v url.Values)

URLQuery serializes DisputeListParams's query parameters as `url.Values`.

type DisputeListParamsDisputeStage added in v0.17.0

type DisputeListParamsDisputeStage string

Filter by dispute stage

const (
	DisputeListParamsDisputeStagePreDispute     DisputeListParamsDisputeStage = "pre_dispute"
	DisputeListParamsDisputeStageDispute        DisputeListParamsDisputeStage = "dispute"
	DisputeListParamsDisputeStagePreArbitration DisputeListParamsDisputeStage = "pre_arbitration"
)

func (DisputeListParamsDisputeStage) IsKnown added in v0.17.0

func (r DisputeListParamsDisputeStage) IsKnown() bool

type DisputeListParamsDisputeStatus added in v0.17.0

type DisputeListParamsDisputeStatus string

Filter by dispute status

const (
	DisputeListParamsDisputeStatusDisputeOpened     DisputeListParamsDisputeStatus = "dispute_opened"
	DisputeListParamsDisputeStatusDisputeExpired    DisputeListParamsDisputeStatus = "dispute_expired"
	DisputeListParamsDisputeStatusDisputeAccepted   DisputeListParamsDisputeStatus = "dispute_accepted"
	DisputeListParamsDisputeStatusDisputeCancelled  DisputeListParamsDisputeStatus = "dispute_cancelled"
	DisputeListParamsDisputeStatusDisputeChallenged DisputeListParamsDisputeStatus = "dispute_challenged"
	DisputeListParamsDisputeStatusDisputeWon        DisputeListParamsDisputeStatus = "dispute_won"
	DisputeListParamsDisputeStatusDisputeLost       DisputeListParamsDisputeStatus = "dispute_lost"
)

func (DisputeListParamsDisputeStatus) IsKnown added in v0.17.0

type DisputeListResponse added in v1.22.0

type DisputeListResponse struct {
	// The amount involved in the dispute, represented as a string to accommodate
	// precision.
	Amount string `json:"amount" api:"required"`
	// The unique identifier of the business involved in the dispute.
	BusinessID string `json:"business_id" api:"required"`
	// The timestamp of when the dispute was created, in UTC.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// The currency of the disputed amount, represented as an ISO 4217 currency code.
	Currency string `json:"currency" api:"required"`
	// The unique identifier of the dispute.
	DisputeID string `json:"dispute_id" api:"required"`
	// The current stage of the dispute process.
	DisputeStage DisputeStage `json:"dispute_stage" api:"required"`
	// The current status of the dispute.
	DisputeStatus DisputeStatus `json:"dispute_status" api:"required"`
	// The unique identifier of the payment associated with the dispute.
	PaymentID string `json:"payment_id" api:"required"`
	// Which processor handled the underlying payment. `stripe` / `adyen` for BYOP
	// routes (the merchant's own payment connector); `dodo` for everything Dodo
	// processed itself.
	PaymentProvider DisputeListResponsePaymentProvider `json:"payment_provider" api:"required"`
	// Whether the dispute was resolved by Rapid Dispute Resolution
	IsResolvedByRdr bool                    `json:"is_resolved_by_rdr" api:"nullable"`
	JSON            disputeListResponseJSON `json:"-"`
}

func (*DisputeListResponse) UnmarshalJSON added in v1.22.0

func (r *DisputeListResponse) UnmarshalJSON(data []byte) (err error)

type DisputeListResponsePaymentProvider added in v1.102.1

type DisputeListResponsePaymentProvider string

Which processor handled the underlying payment. `stripe` / `adyen` for BYOP routes (the merchant's own payment connector); `dodo` for everything Dodo processed itself.

const (
	DisputeListResponsePaymentProviderStripe DisputeListResponsePaymentProvider = "stripe"
	DisputeListResponsePaymentProviderAdyen  DisputeListResponsePaymentProvider = "adyen"
	DisputeListResponsePaymentProviderDodo   DisputeListResponsePaymentProvider = "dodo"
)

func (DisputeListResponsePaymentProvider) IsKnown added in v1.102.1

type DisputeLostWebhookEvent added in v1.56.0

type DisputeLostWebhookEvent struct {
	// The business identifier
	BusinessID string  `json:"business_id" api:"required"`
	Data       Dispute `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type DisputeLostWebhookEventType `json:"type" api:"required"`
	JSON disputeLostWebhookEventJSON `json:"-"`
}

func (*DisputeLostWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *DisputeLostWebhookEvent) UnmarshalJSON(data []byte) (err error)

type DisputeLostWebhookEventType added in v1.56.0

type DisputeLostWebhookEventType string

The event type

const (
	DisputeLostWebhookEventTypeDisputeLost DisputeLostWebhookEventType = "dispute.lost"
)

func (DisputeLostWebhookEventType) IsKnown added in v1.56.0

func (r DisputeLostWebhookEventType) IsKnown() bool

type DisputeOpenedWebhookEvent added in v1.56.0

type DisputeOpenedWebhookEvent struct {
	// The business identifier
	BusinessID string  `json:"business_id" api:"required"`
	Data       Dispute `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type DisputeOpenedWebhookEventType `json:"type" api:"required"`
	JSON disputeOpenedWebhookEventJSON `json:"-"`
}

func (*DisputeOpenedWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *DisputeOpenedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type DisputeOpenedWebhookEventType added in v1.56.0

type DisputeOpenedWebhookEventType string

The event type

const (
	DisputeOpenedWebhookEventTypeDisputeOpened DisputeOpenedWebhookEventType = "dispute.opened"
)

func (DisputeOpenedWebhookEventType) IsKnown added in v1.56.0

func (r DisputeOpenedWebhookEventType) IsKnown() bool

type DisputeService

type DisputeService struct {
	Options []option.RequestOption
}

DisputeService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewDisputeService method instead.

func NewDisputeService

func NewDisputeService(opts ...option.RequestOption) (r *DisputeService)

NewDisputeService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*DisputeService) Get

func (r *DisputeService) Get(ctx context.Context, disputeID string, opts ...option.RequestOption) (res *GetDispute, err error)

type DisputeStage added in v1.6.3

type DisputeStage string
const (
	DisputeStagePreDispute     DisputeStage = "pre_dispute"
	DisputeStageDispute        DisputeStage = "dispute"
	DisputeStagePreArbitration DisputeStage = "pre_arbitration"
)

func (DisputeStage) IsKnown added in v1.6.3

func (r DisputeStage) IsKnown() bool

type DisputeStatus added in v1.6.3

type DisputeStatus string
const (
	DisputeStatusDisputeOpened     DisputeStatus = "dispute_opened"
	DisputeStatusDisputeExpired    DisputeStatus = "dispute_expired"
	DisputeStatusDisputeAccepted   DisputeStatus = "dispute_accepted"
	DisputeStatusDisputeCancelled  DisputeStatus = "dispute_cancelled"
	DisputeStatusDisputeChallenged DisputeStatus = "dispute_challenged"
	DisputeStatusDisputeWon        DisputeStatus = "dispute_won"
	DisputeStatusDisputeLost       DisputeStatus = "dispute_lost"
)

func (DisputeStatus) IsKnown added in v1.6.3

func (r DisputeStatus) IsKnown() bool

type DisputeWonWebhookEvent added in v1.56.0

type DisputeWonWebhookEvent struct {
	// The business identifier
	BusinessID string  `json:"business_id" api:"required"`
	Data       Dispute `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type DisputeWonWebhookEventType `json:"type" api:"required"`
	JSON disputeWonWebhookEventJSON `json:"-"`
}

func (*DisputeWonWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *DisputeWonWebhookEvent) UnmarshalJSON(data []byte) (err error)

type DisputeWonWebhookEventType added in v1.56.0

type DisputeWonWebhookEventType string

The event type

const (
	DisputeWonWebhookEventTypeDisputeWon DisputeWonWebhookEventType = "dispute.won"
)

func (DisputeWonWebhookEventType) IsKnown added in v1.56.0

func (r DisputeWonWebhookEventType) IsKnown() bool

type DunningRecoveredWebhookEvent added in v1.93.0

type DunningRecoveredWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Webhook payload for dunning.started and dunning.recovered events
	Data DunningRecoveredWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type DunningRecoveredWebhookEventType `json:"type" api:"required"`
	JSON dunningRecoveredWebhookEventJSON `json:"-"`
}

func (*DunningRecoveredWebhookEvent) UnmarshalJSON added in v1.93.0

func (r *DunningRecoveredWebhookEvent) UnmarshalJSON(data []byte) (err error)

type DunningRecoveredWebhookEventData added in v1.93.0

type DunningRecoveredWebhookEventData struct {
	// Brand id this dunning attempt belongs to
	BrandID        string                                       `json:"brand_id" api:"required"`
	CreatedAt      time.Time                                    `json:"created_at" api:"required" format:"date-time"`
	CustomerID     string                                       `json:"customer_id" api:"required"`
	Status         DunningRecoveredWebhookEventDataStatus       `json:"status" api:"required"`
	SubscriptionID string                                       `json:"subscription_id" api:"required"`
	TriggerState   DunningRecoveredWebhookEventDataTriggerState `json:"trigger_state" api:"required"`
	PaymentID      string                                       `json:"payment_id" api:"nullable"`
	JSON           dunningRecoveredWebhookEventDataJSON         `json:"-"`
}

Webhook payload for dunning.started and dunning.recovered events

func (*DunningRecoveredWebhookEventData) UnmarshalJSON added in v1.93.0

func (r *DunningRecoveredWebhookEventData) UnmarshalJSON(data []byte) (err error)

type DunningRecoveredWebhookEventDataStatus added in v1.93.0

type DunningRecoveredWebhookEventDataStatus string
const (
	DunningRecoveredWebhookEventDataStatusRecovering DunningRecoveredWebhookEventDataStatus = "recovering"
	DunningRecoveredWebhookEventDataStatusRecovered  DunningRecoveredWebhookEventDataStatus = "recovered"
	DunningRecoveredWebhookEventDataStatusExhausted  DunningRecoveredWebhookEventDataStatus = "exhausted"
)

func (DunningRecoveredWebhookEventDataStatus) IsKnown added in v1.93.0

type DunningRecoveredWebhookEventDataTriggerState added in v1.93.0

type DunningRecoveredWebhookEventDataTriggerState string
const (
	DunningRecoveredWebhookEventDataTriggerStateOnHold    DunningRecoveredWebhookEventDataTriggerState = "on_hold"
	DunningRecoveredWebhookEventDataTriggerStateCancelled DunningRecoveredWebhookEventDataTriggerState = "cancelled"
	DunningRecoveredWebhookEventDataTriggerStatePastDue   DunningRecoveredWebhookEventDataTriggerState = "past_due"
)

func (DunningRecoveredWebhookEventDataTriggerState) IsKnown added in v1.93.0

type DunningRecoveredWebhookEventType added in v1.93.0

type DunningRecoveredWebhookEventType string

The event type

const (
	DunningRecoveredWebhookEventTypeDunningRecovered DunningRecoveredWebhookEventType = "dunning.recovered"
)

func (DunningRecoveredWebhookEventType) IsKnown added in v1.93.0

type DunningStartedWebhookEvent added in v1.93.0

type DunningStartedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Webhook payload for dunning.started and dunning.recovered events
	Data DunningStartedWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type DunningStartedWebhookEventType `json:"type" api:"required"`
	JSON dunningStartedWebhookEventJSON `json:"-"`
}

func (*DunningStartedWebhookEvent) UnmarshalJSON added in v1.93.0

func (r *DunningStartedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type DunningStartedWebhookEventData added in v1.93.0

type DunningStartedWebhookEventData struct {
	// Brand id this dunning attempt belongs to
	BrandID        string                                     `json:"brand_id" api:"required"`
	CreatedAt      time.Time                                  `json:"created_at" api:"required" format:"date-time"`
	CustomerID     string                                     `json:"customer_id" api:"required"`
	Status         DunningStartedWebhookEventDataStatus       `json:"status" api:"required"`
	SubscriptionID string                                     `json:"subscription_id" api:"required"`
	TriggerState   DunningStartedWebhookEventDataTriggerState `json:"trigger_state" api:"required"`
	PaymentID      string                                     `json:"payment_id" api:"nullable"`
	JSON           dunningStartedWebhookEventDataJSON         `json:"-"`
}

Webhook payload for dunning.started and dunning.recovered events

func (*DunningStartedWebhookEventData) UnmarshalJSON added in v1.93.0

func (r *DunningStartedWebhookEventData) UnmarshalJSON(data []byte) (err error)

type DunningStartedWebhookEventDataStatus added in v1.93.0

type DunningStartedWebhookEventDataStatus string
const (
	DunningStartedWebhookEventDataStatusRecovering DunningStartedWebhookEventDataStatus = "recovering"
	DunningStartedWebhookEventDataStatusRecovered  DunningStartedWebhookEventDataStatus = "recovered"
	DunningStartedWebhookEventDataStatusExhausted  DunningStartedWebhookEventDataStatus = "exhausted"
)

func (DunningStartedWebhookEventDataStatus) IsKnown added in v1.93.0

type DunningStartedWebhookEventDataTriggerState added in v1.93.0

type DunningStartedWebhookEventDataTriggerState string
const (
	DunningStartedWebhookEventDataTriggerStateOnHold    DunningStartedWebhookEventDataTriggerState = "on_hold"
	DunningStartedWebhookEventDataTriggerStateCancelled DunningStartedWebhookEventDataTriggerState = "cancelled"
	DunningStartedWebhookEventDataTriggerStatePastDue   DunningStartedWebhookEventDataTriggerState = "past_due"
)

func (DunningStartedWebhookEventDataTriggerState) IsKnown added in v1.93.0

type DunningStartedWebhookEventType added in v1.93.0

type DunningStartedWebhookEventType string

The event type

const (
	DunningStartedWebhookEventTypeDunningStarted DunningStartedWebhookEventType = "dunning.started"
)

func (DunningStartedWebhookEventType) IsKnown added in v1.93.0

type EmailBody added in v1.116.0

type EmailBody struct {
	// Whether the merchant wrote this content. It is true for the recovery and dunning
	// emails, which the merchant writes.
	//
	// The content is email HTML. Render it in a sandbox, whatever this value is.
	MerchantAuthored bool `json:"merchant_authored" api:"required"`
	// Why the email did not arrive. It is null unless the email failed.
	FailureCode EmailFailureCode `json:"failure_code" api:"nullable"`
	// A sentence that explains `failure_code`. It is null unless the email failed.
	FailureReason string `json:"failure_reason" api:"nullable"`
	// The stored HTML. It is null on a text-only email.
	HTML string `json:"html" api:"nullable"`
	// The stored plain text.
	Text string        `json:"text" api:"nullable"`
	JSON emailBodyJSON `json:"-"`
}

func (*EmailBody) UnmarshalJSON added in v1.116.0

func (r *EmailBody) UnmarshalJSON(data []byte) (err error)

type EmailFailureCode added in v1.116.0

type EmailFailureCode string

Why an email did not reach the recipient.

The code is stable. `send_failed` is the catch-all: it covers every failure that the other codes do not name.

const (
	EmailFailureCodeMailboxNotFound   EmailFailureCode = "mailbox_not_found"
	EmailFailureCodeAddressRejected   EmailFailureCode = "address_rejected"
	EmailFailureCodeAddressSuppressed EmailFailureCode = "address_suppressed"
	EmailFailureCodeMailboxFull       EmailFailureCode = "mailbox_full"
	EmailFailureCodeTemporaryFailure  EmailFailureCode = "temporary_failure"
	EmailFailureCodeMessageTooLarge   EmailFailureCode = "message_too_large"
	EmailFailureCodeMarkedAsSpam      EmailFailureCode = "marked_as_spam"
	EmailFailureCodeSendFailed        EmailFailureCode = "send_failed"
)

func (EmailFailureCode) IsKnown added in v1.116.0

func (r EmailFailureCode) IsKnown() bool

type EmailLogItem added in v1.116.0

type EmailLogItem struct {
	// The group this email belongs to: payments, refunds, subscriptions,
	// dunning_recovery, entitlements or auth.
	Category string `json:"category" api:"required"`
	// When this email was sent.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Identifies this email. Use it to read the body or to send it again.
	EmailLogID string `json:"email_log_id" api:"required"`
	// What kind of email this is, for example `payment_successful`.
	EmailType string `json:"email_type" api:"required"`
	// Whether this email has content to show. The content endpoint can still refuse,
	// because the content is removed after 180 days.
	HasPreview bool `json:"has_preview" api:"required"`
	// What you may do with this email.
	Policies EmailPolicies `json:"policies" api:"required"`
	// Where the email got to: sent, delivered, failed, complained or blocked.
	Status EmailLogStatus `json:"status" api:"required"`
	// Why the email did not arrive. It is null unless the email failed.
	FailureCode EmailFailureCode `json:"failure_code" api:"nullable"`
	// A sentence that explains `failure_code`. It is null unless the email failed.
	FailureReason string `json:"failure_reason" api:"nullable"`
	// The address the email was sent from.
	From string `json:"from" api:"nullable"`
	// What the merchant typed, when test mode redirected the send to the business
	// owner.
	IntendedRecipient string `json:"intended_recipient" api:"nullable"`
	// The address the email reached.
	Recipient string `json:"recipient" api:"nullable"`
	// The subject line as it was sent. Empty until the provider replicates.
	Subject string           `json:"subject" api:"nullable"`
	JSON    emailLogItemJSON `json:"-"`
}

func (*EmailLogItem) UnmarshalJSON added in v1.116.0

func (r *EmailLogItem) UnmarshalJSON(data []byte) (err error)

type EmailLogStatus added in v1.116.0

type EmailLogStatus string

The delivery status of one email.

`sent` also covers an email that is still on its way. A status only becomes `delivered`, `failed` or `complained` when the mail server answers.

const (
	EmailLogStatusSent       EmailLogStatus = "sent"
	EmailLogStatusDelivered  EmailLogStatus = "delivered"
	EmailLogStatusFailed     EmailLogStatus = "failed"
	EmailLogStatusComplained EmailLogStatus = "complained"
	EmailLogStatusBlocked    EmailLogStatus = "blocked"
)

func (EmailLogStatus) IsKnown added in v1.116.0

func (r EmailLogStatus) IsKnown() bool

type EmailPolicies added in v1.116.0

type EmailPolicies struct {
	// A permanent failure was recorded, so the same address would be a no-op.
	RequiresDifferentAddress bool `json:"requires_different_address" api:"required"`
	// The row was delivered and may be sent again.
	ResendAllowed bool `json:"resend_allowed" api:"required"`
	// How many sends are left in this email's chain.
	ResendsRemaining int64 `json:"resends_remaining" api:"required"`
	// The row failed and may be sent again.
	RetryAllowed bool              `json:"retry_allowed" api:"required"`
	JSON         emailPoliciesJSON `json:"-"`
}

What the merchant may do with one row. The server decides; the client never derives eligibility itself.

func (*EmailPolicies) UnmarshalJSON added in v1.116.0

func (r *EmailPolicies) UnmarshalJSON(data []byte) (err error)

type Entitlement added in v1.97.0

type Entitlement struct {
	// Unique identifier of the entitlement.
	ID string `json:"id" api:"required"`
	// Identifier of the business that owns this entitlement.
	BusinessID string `json:"business_id" api:"required"`
	// Timestamp when the entitlement was created.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Integration-specific configuration. For `digital_files` entitlements this
	// includes presigned download URLs for each attached file.
	IntegrationConfig IntegrationConfigResponse `json:"integration_config" api:"required"`
	// Platform integration this entitlement uses.
	IntegrationType EntitlementIntegrationType `json:"integration_type" api:"required"`
	// Always `true` for entitlements returned by the public API; soft-deleted
	// entitlements are not returned.
	IsActive bool `json:"is_active" api:"required"`
	// Arbitrary key-value metadata supplied at creation or via PATCH.
	Metadata Metadata `json:"metadata" api:"required"`
	// Display name supplied at creation.
	Name string `json:"name" api:"required"`
	// Timestamp when the entitlement was last modified.
	UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
	// Optional description supplied at creation.
	Description string          `json:"description" api:"nullable"`
	JSON        entitlementJSON `json:"-"`
}

Detailed view of a single entitlement: identity, integration type, integration-specific configuration, and metadata.

func (*Entitlement) UnmarshalJSON added in v1.97.0

func (r *Entitlement) UnmarshalJSON(data []byte) (err error)

type EntitlementFileService added in v1.97.0

type EntitlementFileService struct {
	Options []option.RequestOption
}

EntitlementFileService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewEntitlementFileService method instead.

func NewEntitlementFileService added in v1.97.0

func NewEntitlementFileService(opts ...option.RequestOption) (r *EntitlementFileService)

NewEntitlementFileService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*EntitlementFileService) Delete added in v1.97.0

func (r *EntitlementFileService) Delete(ctx context.Context, id string, fileID string, opts ...option.RequestOption) (err error)

Detach a previously-attached file from a `digital_files` entitlement.

func (*EntitlementFileService) Upload added in v1.97.0

Attach a file to a `digital_files` entitlement. Per-file size cap: 500 MiB.

type EntitlementFileUploadResponse added in v1.97.0

type EntitlementFileUploadResponse struct {
	// Identifier of the attached file. Pass it to
	// `DELETE /entitlements/{id}/files/{file_id}` to detach the file later.
	FileID string                            `json:"file_id" api:"required"`
	JSON   entitlementFileUploadResponseJSON `json:"-"`
}

func (*EntitlementFileUploadResponse) UnmarshalJSON added in v1.97.0

func (r *EntitlementFileUploadResponse) UnmarshalJSON(data []byte) (err error)

type EntitlementGrant added in v1.97.0

type EntitlementGrant struct {
	// Unique identifier of the grant.
	ID string `json:"id" api:"required"`
	// Brand id this grant belongs to.
	BrandID string `json:"brand_id" api:"required"`
	// Identifier of the business that owns the grant.
	BusinessID string `json:"business_id" api:"required"`
	// Timestamp when the grant was created.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Identifier of the customer the grant was issued to.
	CustomerID string `json:"customer_id" api:"required"`
	// Identifier of the entitlement this grant was issued from.
	EntitlementID string `json:"entitlement_id" api:"required"`
	// The integration type of the grant's entitlement (e.g. `license_key`).
	IntegrationType EntitlementIntegrationType `json:"integration_type" api:"required"`
	// Arbitrary key-value metadata recorded on the grant.
	Metadata Metadata `json:"metadata" api:"required"`
	// Lifecycle status of the grant.
	Status EntitlementGrantStatus `json:"status" api:"required"`
	// Timestamp when the grant was last modified.
	UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
	// Timestamp when the grant transitioned to `delivered`, when applicable.
	DeliveredAt time.Time `json:"delivered_at" api:"nullable" format:"date-time"`
	// Digital-product-delivery payload, present when the entitlement integration is
	// `digital_files`.
	DigitalProductDelivery DigitalProductDelivery `json:"digital_product_delivery" api:"nullable"`
	// Machine-readable code reported when delivery failed, when applicable.
	ErrorCode string `json:"error_code" api:"nullable"`
	// Human-readable message reported when delivery failed, when applicable.
	ErrorMessage string `json:"error_message" api:"nullable"`
	// Typed feature payload, present only when the entitlement integration is
	// `feature_flag`; `null` for every other integration type.
	Feature Feature `json:"feature" api:"nullable"`
	// License-key delivery payload, present when the entitlement integration is
	// `license_key`.
	LicenseKey LicenseKeyGrant `json:"license_key" api:"nullable"`
	// Timestamp when `oauth_url` stops being valid, when applicable.
	OAuthExpiresAt time.Time `json:"oauth_expires_at" api:"nullable" format:"date-time"`
	// Customer-facing OAuth URL for OAuth-style integrations. Populated during the
	// customer-portal accept flow; `null` until the customer completes that step, and
	// on grants for non-OAuth integrations.
	OAuthURL string `json:"oauth_url" api:"nullable"`
	// Identifier of the payment that triggered this grant, when applicable.
	PaymentID string `json:"payment_id" api:"nullable"`
	// Reason recorded when the grant was revoked, when applicable.
	RevocationReason string `json:"revocation_reason" api:"nullable"`
	// Timestamp when the grant transitioned to `revoked`, when applicable.
	RevokedAt time.Time `json:"revoked_at" api:"nullable" format:"date-time"`
	// Identifier of the subscription that triggered this grant, when applicable.
	SubscriptionID string               `json:"subscription_id" api:"nullable"`
	JSON           entitlementGrantJSON `json:"-"`
}

Detailed view of a single entitlement grant: who it's for, its lifecycle state, and any integration-specific delivery payload.

func (*EntitlementGrant) UnmarshalJSON added in v1.97.0

func (r *EntitlementGrant) UnmarshalJSON(data []byte) (err error)

type EntitlementGrantCreatedWebhookEvent added in v1.97.0

type EntitlementGrantCreatedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Detailed view of a single entitlement grant: who it's for, its lifecycle state,
	// and any integration-specific delivery payload.
	Data EntitlementGrant `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type EntitlementGrantCreatedWebhookEventType `json:"type" api:"required"`
	JSON entitlementGrantCreatedWebhookEventJSON `json:"-"`
}

func (*EntitlementGrantCreatedWebhookEvent) UnmarshalJSON added in v1.97.0

func (r *EntitlementGrantCreatedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type EntitlementGrantCreatedWebhookEventType added in v1.97.0

type EntitlementGrantCreatedWebhookEventType string

The event type

const (
	EntitlementGrantCreatedWebhookEventTypeEntitlementGrantCreated EntitlementGrantCreatedWebhookEventType = "entitlement_grant.created"
)

func (EntitlementGrantCreatedWebhookEventType) IsKnown added in v1.97.0

type EntitlementGrantDeliveredWebhookEvent added in v1.97.0

type EntitlementGrantDeliveredWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Detailed view of a single entitlement grant: who it's for, its lifecycle state,
	// and any integration-specific delivery payload.
	Data EntitlementGrant `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type EntitlementGrantDeliveredWebhookEventType `json:"type" api:"required"`
	JSON entitlementGrantDeliveredWebhookEventJSON `json:"-"`
}

func (*EntitlementGrantDeliveredWebhookEvent) UnmarshalJSON added in v1.97.0

func (r *EntitlementGrantDeliveredWebhookEvent) UnmarshalJSON(data []byte) (err error)

type EntitlementGrantDeliveredWebhookEventType added in v1.97.0

type EntitlementGrantDeliveredWebhookEventType string

The event type

const (
	EntitlementGrantDeliveredWebhookEventTypeEntitlementGrantDelivered EntitlementGrantDeliveredWebhookEventType = "entitlement_grant.delivered"
)

func (EntitlementGrantDeliveredWebhookEventType) IsKnown added in v1.97.0

type EntitlementGrantFailedWebhookEvent added in v1.97.0

type EntitlementGrantFailedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Detailed view of a single entitlement grant: who it's for, its lifecycle state,
	// and any integration-specific delivery payload.
	Data EntitlementGrant `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type EntitlementGrantFailedWebhookEventType `json:"type" api:"required"`
	JSON entitlementGrantFailedWebhookEventJSON `json:"-"`
}

func (*EntitlementGrantFailedWebhookEvent) UnmarshalJSON added in v1.97.0

func (r *EntitlementGrantFailedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type EntitlementGrantFailedWebhookEventType added in v1.97.0

type EntitlementGrantFailedWebhookEventType string

The event type

const (
	EntitlementGrantFailedWebhookEventTypeEntitlementGrantFailed EntitlementGrantFailedWebhookEventType = "entitlement_grant.failed"
)

func (EntitlementGrantFailedWebhookEventType) IsKnown added in v1.97.0

type EntitlementGrantFulfillLicenseKeyParams added in v1.106.0

type EntitlementGrantFulfillLicenseKeyParams struct {
	// The license key value to deliver to the customer.
	Key param.Field[string] `json:"key" api:"required"`
	// Per-key activation limit. Defaults to the entitlement's license-key
	// configuration.
	ActivationsLimit param.Field[int64] `json:"activations_limit"`
	// When the key expires. Defaults to the duration in the entitlement's license-key
	// configuration.
	ExpiresAt param.Field[time.Time] `json:"expires_at" format:"date-time"`
}

func (EntitlementGrantFulfillLicenseKeyParams) MarshalJSON added in v1.106.0

func (r EntitlementGrantFulfillLicenseKeyParams) MarshalJSON() (data []byte, err error)

type EntitlementGrantListParams added in v1.97.0

type EntitlementGrantListParams struct {
	// Filter by customer ID
	CustomerID param.Field[string] `query:"customer_id"`
	// Page number (default 0)
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size (default 10, max 100)
	PageSize param.Field[int64] `query:"page_size"`
	// Filter by grant status
	Status param.Field[EntitlementGrantListParamsStatus] `query:"status"`
}

func (EntitlementGrantListParams) URLQuery added in v1.97.0

func (r EntitlementGrantListParams) URLQuery() (v url.Values)

URLQuery serializes EntitlementGrantListParams's query parameters as `url.Values`.

type EntitlementGrantListParamsStatus added in v1.97.0

type EntitlementGrantListParamsStatus string

Filter by grant status

const (
	EntitlementGrantListParamsStatusPending   EntitlementGrantListParamsStatus = "Pending"
	EntitlementGrantListParamsStatusDelivered EntitlementGrantListParamsStatus = "Delivered"
	EntitlementGrantListParamsStatusFailed    EntitlementGrantListParamsStatus = "Failed"
	EntitlementGrantListParamsStatusRevoked   EntitlementGrantListParamsStatus = "Revoked"
)

func (EntitlementGrantListParamsStatus) IsKnown added in v1.97.0

type EntitlementGrantRevokedWebhookEvent added in v1.97.0

type EntitlementGrantRevokedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Detailed view of a single entitlement grant: who it's for, its lifecycle state,
	// and any integration-specific delivery payload.
	Data EntitlementGrant `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type EntitlementGrantRevokedWebhookEventType `json:"type" api:"required"`
	JSON entitlementGrantRevokedWebhookEventJSON `json:"-"`
}

func (*EntitlementGrantRevokedWebhookEvent) UnmarshalJSON added in v1.97.0

func (r *EntitlementGrantRevokedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type EntitlementGrantRevokedWebhookEventType added in v1.97.0

type EntitlementGrantRevokedWebhookEventType string

The event type

const (
	EntitlementGrantRevokedWebhookEventTypeEntitlementGrantRevoked EntitlementGrantRevokedWebhookEventType = "entitlement_grant.revoked"
)

func (EntitlementGrantRevokedWebhookEventType) IsKnown added in v1.97.0

type EntitlementGrantService added in v1.97.0

type EntitlementGrantService struct {
	Options []option.RequestOption
}

EntitlementGrantService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewEntitlementGrantService method instead.

func NewEntitlementGrantService added in v1.97.0

func NewEntitlementGrantService(opts ...option.RequestOption) (r *EntitlementGrantService)

NewEntitlementGrantService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*EntitlementGrantService) FulfillLicenseKey added in v1.106.0

For entitlements whose license-key config uses `manual` fulfillment, grants are created in the `pending` state without a key. Call this endpoint to deliver the key: the grant moves to `delivered`, the customer is emailed the key, and the `license_key.created` and `entitlement_grant.delivered` webhook events are sent.

func (*EntitlementGrantService) List added in v1.97.0

GET /entitlements/{id}/grants (public API)

func (*EntitlementGrantService) ListAutoPaging added in v1.97.0

GET /entitlements/{id}/grants (public API)

func (*EntitlementGrantService) Revoke added in v1.97.0

func (r *EntitlementGrantService) Revoke(ctx context.Context, id string, grantID string, opts ...option.RequestOption) (res *EntitlementGrant, err error)

Revoke a single grant. Idempotent: re-revoking an already-revoked grant returns the grant in its current state.

type EntitlementGrantStatus added in v1.97.0

type EntitlementGrantStatus string

Lifecycle status of the grant.

const (
	EntitlementGrantStatusPending   EntitlementGrantStatus = "Pending"
	EntitlementGrantStatusDelivered EntitlementGrantStatus = "Delivered"
	EntitlementGrantStatusFailed    EntitlementGrantStatus = "Failed"
	EntitlementGrantStatusRevoked   EntitlementGrantStatus = "Revoked"
)

func (EntitlementGrantStatus) IsKnown added in v1.97.0

func (r EntitlementGrantStatus) IsKnown() bool

type EntitlementIntegrationType added in v1.97.0

type EntitlementIntegrationType string
const (
	EntitlementIntegrationTypeDiscord      EntitlementIntegrationType = "discord"
	EntitlementIntegrationTypeTelegram     EntitlementIntegrationType = "telegram"
	EntitlementIntegrationTypeGitHub       EntitlementIntegrationType = "github"
	EntitlementIntegrationTypeFigma        EntitlementIntegrationType = "figma"
	EntitlementIntegrationTypeFramer       EntitlementIntegrationType = "framer"
	EntitlementIntegrationTypeNotion       EntitlementIntegrationType = "notion"
	EntitlementIntegrationTypeDigitalFiles EntitlementIntegrationType = "digital_files"
	EntitlementIntegrationTypeLicenseKey   EntitlementIntegrationType = "license_key"
	EntitlementIntegrationTypeFeatureFlag  EntitlementIntegrationType = "feature_flag"
)

func (EntitlementIntegrationType) IsKnown added in v1.97.0

func (r EntitlementIntegrationType) IsKnown() bool

type EntitlementListParams added in v1.97.0

type EntitlementListParams struct {
	// Filter by integration type
	IntegrationType param.Field[EntitlementListParamsIntegrationType] `query:"integration_type"`
	// Page number (default 0)
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size (default 10, max 100)
	PageSize param.Field[int64] `query:"page_size"`
}

func (EntitlementListParams) URLQuery added in v1.97.0

func (r EntitlementListParams) URLQuery() (v url.Values)

URLQuery serializes EntitlementListParams's query parameters as `url.Values`.

type EntitlementListParamsIntegrationType added in v1.97.0

type EntitlementListParamsIntegrationType string

Filter by integration type

const (
	EntitlementListParamsIntegrationTypeDiscord      EntitlementListParamsIntegrationType = "discord"
	EntitlementListParamsIntegrationTypeTelegram     EntitlementListParamsIntegrationType = "telegram"
	EntitlementListParamsIntegrationTypeGitHub       EntitlementListParamsIntegrationType = "github"
	EntitlementListParamsIntegrationTypeFigma        EntitlementListParamsIntegrationType = "figma"
	EntitlementListParamsIntegrationTypeFramer       EntitlementListParamsIntegrationType = "framer"
	EntitlementListParamsIntegrationTypeNotion       EntitlementListParamsIntegrationType = "notion"
	EntitlementListParamsIntegrationTypeDigitalFiles EntitlementListParamsIntegrationType = "digital_files"
	EntitlementListParamsIntegrationTypeLicenseKey   EntitlementListParamsIntegrationType = "license_key"
	EntitlementListParamsIntegrationTypeFeatureFlag  EntitlementListParamsIntegrationType = "feature_flag"
)

func (EntitlementListParamsIntegrationType) IsKnown added in v1.97.0

type EntitlementNewParams added in v1.97.0

type EntitlementNewParams struct {
	// Platform-specific configuration (validated per integration_type)
	IntegrationConfig param.Field[IntegrationConfigUnionParam] `json:"integration_config" api:"required"`
	// Which platform integration this entitlement uses
	IntegrationType param.Field[EntitlementIntegrationType] `json:"integration_type" api:"required"`
	// Display name for this entitlement
	Name param.Field[string] `json:"name" api:"required"`
	// Optional description
	Description param.Field[string] `json:"description"`
	// Additional metadata for the entitlement
	Metadata param.Field[MetadataParam] `json:"metadata"`
}

func (EntitlementNewParams) MarshalJSON added in v1.97.0

func (r EntitlementNewParams) MarshalJSON() (data []byte, err error)

type EntitlementService added in v1.97.0

type EntitlementService struct {
	Options []option.RequestOption
	Files   *EntitlementFileService
	Grants  *EntitlementGrantService
}

EntitlementService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewEntitlementService method instead.

func NewEntitlementService added in v1.97.0

func NewEntitlementService(opts ...option.RequestOption) (r *EntitlementService)

NewEntitlementService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*EntitlementService) Delete added in v1.97.0

func (r *EntitlementService) Delete(ctx context.Context, id string, opts ...option.RequestOption) (err error)

DELETE /entitlements/{id} (soft-delete)

func (*EntitlementService) Get added in v1.97.0

func (r *EntitlementService) Get(ctx context.Context, id string, opts ...option.RequestOption) (res *Entitlement, err error)

GET /entitlements/{id}

func (*EntitlementService) List added in v1.97.0

GET /entitlements

func (*EntitlementService) ListAutoPaging added in v1.97.0

GET /entitlements

func (*EntitlementService) New added in v1.97.0

POST /entitlements

func (*EntitlementService) Update added in v1.97.0

PATCH /entitlements/{id}

type EntitlementUpdateParams added in v1.97.0

type EntitlementUpdateParams struct {
	Description param.Field[string] `json:"description"`
	// Integration-specific configuration supplied when creating or updating an
	// entitlement. The shape required matches the entitlement's `integration_type`.
	//
	// Untagged enum: variants are matched in order. `FeatureFlag` must precede
	// `LicenseKey`, whose fields are all optional and would otherwise match a
	// `feature_flag` config.
	IntegrationConfig param.Field[IntegrationConfigUnionParam] `json:"integration_config"`
	// Arbitrary key-value metadata. Values can be string, integer, number, or boolean.
	Metadata param.Field[MetadataParam] `json:"metadata"`
	Name     param.Field[string]        `json:"name"`
}

func (EntitlementUpdateParams) MarshalJSON added in v1.97.0

func (r EntitlementUpdateParams) MarshalJSON() (data []byte, err error)

type Error

type Error = apierror.Error

type Event added in v1.52.4

type Event struct {
	BusinessID string    `json:"business_id" api:"required"`
	CustomerID string    `json:"customer_id" api:"required"`
	EventID    string    `json:"event_id" api:"required"`
	EventName  string    `json:"event_name" api:"required"`
	Timestamp  time.Time `json:"timestamp" api:"required" format:"date-time"`
	// Arbitrary key-value metadata. Values can be string, integer, number, or boolean.
	Metadata map[string]EventMetadataUnion `json:"metadata" api:"nullable"`
	JSON     eventJSON                     `json:"-"`
}

func (*Event) UnmarshalJSON added in v1.52.4

func (r *Event) UnmarshalJSON(data []byte) (err error)

type EventInputMetadataUnionParam added in v1.52.4

type EventInputMetadataUnionParam interface {
	ImplementsEventInputMetadataUnionParam()
}

Metadata value can be a string, integer, number, or boolean

Satisfied by shared.UnionString, shared.UnionFloat, shared.UnionBool.

type EventInputParam added in v1.52.4

type EventInputParam struct {
	// customer_id of the customer whose usage needs to be tracked
	CustomerID param.Field[string] `json:"customer_id" api:"required"`
	// Event Id acts as an idempotency key. Any subsequent requests with the same
	// event_id will be ignored
	EventID param.Field[string] `json:"event_id" api:"required"`
	// Name of the event
	EventName param.Field[string] `json:"event_name" api:"required"`
	// Custom metadata. Only key value pairs are accepted, objects or arrays submitted
	// will be rejected.
	Metadata param.Field[map[string]EventInputMetadataUnionParam] `json:"metadata"`
	// Custom Timestamp. Defaults to current timestamp in UTC. Timestamps that are
	// older that 1 hour or after 5 mins, from current timestamp, will be rejected.
	Timestamp param.Field[time.Time] `json:"timestamp" format:"date-time"`
}

func (EventInputParam) MarshalJSON added in v1.52.4

func (r EventInputParam) MarshalJSON() (data []byte, err error)

type EventMetadataUnion added in v1.52.4

type EventMetadataUnion interface {
	ImplementsEventMetadataUnion()
}

Metadata value can be a string, integer, number, or boolean

Union satisfied by shared.UnionString, shared.UnionFloat or shared.UnionBool.

type Feature added in v1.107.0

type Feature struct {
	// Identifier of the capability this grant confers.
	FeatureID string `json:"feature_id" api:"required"`
	// Type of capability conferred.
	FeatureType FeatureType `json:"feature_type" api:"required"`
	JSON        featureJSON `json:"-"`
}

Capability conferred by a `feature_flag` grant.

func (*Feature) UnmarshalJSON added in v1.107.0

func (r *Feature) UnmarshalJSON(data []byte) (err error)

type FeatureType added in v1.107.0

type FeatureType string

Type of capability a `feature_flag` entitlement confers.

const (
	FeatureTypeBoolean FeatureType = "boolean"
)

func (FeatureType) IsKnown added in v1.107.0

func (r FeatureType) IsKnown() bool

type FilterOperator added in v1.86.0

type FilterOperator string
const (
	FilterOperatorEquals              FilterOperator = "equals"
	FilterOperatorNotEquals           FilterOperator = "not_equals"
	FilterOperatorGreaterThan         FilterOperator = "greater_than"
	FilterOperatorGreaterThanOrEquals FilterOperator = "greater_than_or_equals"
	FilterOperatorLessThan            FilterOperator = "less_than"
	FilterOperatorLessThanOrEquals    FilterOperator = "less_than_or_equals"
	FilterOperatorContains            FilterOperator = "contains"
	FilterOperatorDoesNotContain      FilterOperator = "does_not_contain"
)

func (FilterOperator) IsKnown added in v1.86.0

func (r FilterOperator) IsKnown() bool

type FilterTypeMeterFilterConditionList added in v1.99.0

type FilterTypeMeterFilterConditionList []FilterTypeMeterFilterConditionListItem

type FilterTypeMeterFilterConditionListItem added in v1.99.0

type FilterTypeMeterFilterConditionListItem struct {
	// Filter key to apply
	Key string `json:"key" api:"required"`
	// Filter operator
	Operator FilterOperator `json:"operator" api:"required"`
	// Filter value - can be string, number, or boolean
	Value FilterTypeMeterFilterConditionListValueUnion `json:"value" api:"required"`
	JSON  filterTypeMeterFilterConditionListItemJSON   `json:"-"`
}

func (*FilterTypeMeterFilterConditionListItem) UnmarshalJSON added in v1.99.0

func (r *FilterTypeMeterFilterConditionListItem) UnmarshalJSON(data []byte) (err error)

type FilterTypeMeterFilterConditionListItemParam added in v1.99.0

type FilterTypeMeterFilterConditionListItemParam struct {
	// Filter key to apply
	Key param.Field[string] `json:"key" api:"required"`
	// Filter operator
	Operator param.Field[FilterOperator] `json:"operator" api:"required"`
	// Filter value - can be string, number, or boolean
	Value param.Field[FilterTypeMeterFilterConditionListValueUnionParam] `json:"value" api:"required"`
}

func (FilterTypeMeterFilterConditionListItemParam) MarshalJSON added in v1.99.0

func (r FilterTypeMeterFilterConditionListItemParam) MarshalJSON() (data []byte, err error)

type FilterTypeMeterFilterConditionListParam added in v1.99.0

type FilterTypeMeterFilterConditionListParam []FilterTypeMeterFilterConditionListItemParam

type FilterTypeMeterFilterConditionListValueUnion added in v1.99.0

type FilterTypeMeterFilterConditionListValueUnion interface {
	ImplementsFilterTypeMeterFilterConditionListValueUnion()
}

Filter value - can be string, number, or boolean

Union satisfied by shared.UnionString, shared.UnionFloat or shared.UnionBool.

type FilterTypeMeterFilterConditionListValueUnionParam added in v1.99.0

type FilterTypeMeterFilterConditionListValueUnionParam interface {
	ImplementsFilterTypeMeterFilterConditionListValueUnionParam()
}

Filter value - can be string, number, or boolean

Satisfied by shared.UnionString, shared.UnionFloat, shared.UnionBool.

type FilterTypeNestedMeterFilterList added in v1.99.0

type FilterTypeNestedMeterFilterList []MeterFilter

type FilterTypeNestedMeterFilterListParam added in v1.99.0

type FilterTypeNestedMeterFilterListParam []MeterFilterParam

type FilterTypeUnion added in v1.99.0

type FilterTypeUnion interface {
	// contains filtered or unexported methods
}

Filter clauses — either a flat list of `MeterFilterCondition`s or a list of nested `MeterFilter`s. Up to 3 levels of nesting are accepted; the limit is enforced at runtime.

Union satisfied by FilterTypeMeterFilterConditionList or FilterTypeNestedMeterFilterList.

type FilterTypeUnionParam added in v1.99.0

type FilterTypeUnionParam interface {
	// contains filtered or unexported methods
}

Filter clauses — either a flat list of `MeterFilterCondition`s or a list of nested `MeterFilter`s. Up to 3 levels of nesting are accepted; the limit is enforced at runtime.

Satisfied by FilterTypeMeterFilterConditionListParam, FilterTypeNestedMeterFilterListParam.

type GetDispute added in v1.43.0

type GetDispute struct {
	// The amount involved in the dispute, represented as a string to accommodate
	// precision.
	Amount string `json:"amount" api:"required"`
	// Brand id this dispute belongs to
	BrandID string `json:"brand_id" api:"required"`
	// The unique identifier of the business involved in the dispute.
	BusinessID string `json:"business_id" api:"required"`
	// The timestamp of when the dispute was created, in UTC.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// The currency of the disputed amount, represented as an ISO 4217 currency code.
	Currency string `json:"currency" api:"required"`
	// The customer who filed the dispute
	Customer CustomerLimitedDetails `json:"customer" api:"required"`
	// The unique identifier of the dispute.
	DisputeID string `json:"dispute_id" api:"required"`
	// The current stage of the dispute process.
	DisputeStage DisputeStage `json:"dispute_stage" api:"required"`
	// The current status of the dispute.
	DisputeStatus DisputeStatus `json:"dispute_status" api:"required"`
	// The unique identifier of the payment associated with the dispute.
	PaymentID string `json:"payment_id" api:"required"`
	// Which processor handled the underlying payment. `stripe` / `adyen` for BYOP
	// routes (the merchant's own payment connector); `dodo` for everything Dodo
	// processed itself.
	PaymentProvider GetDisputePaymentProvider `json:"payment_provider" api:"required"`
	// Whether the dispute was resolved by Rapid Dispute Resolution
	IsResolvedByRdr bool `json:"is_resolved_by_rdr" api:"nullable"`
	// Reason for the dispute
	Reason string `json:"reason" api:"nullable"`
	// Remarks
	Remarks string         `json:"remarks" api:"nullable"`
	JSON    getDisputeJSON `json:"-"`
}

func (*GetDispute) UnmarshalJSON added in v1.43.0

func (r *GetDispute) UnmarshalJSON(data []byte) (err error)

type GetDisputePaymentProvider added in v1.103.0

type GetDisputePaymentProvider string

Which processor handled the underlying payment. `stripe` / `adyen` for BYOP routes (the merchant's own payment connector); `dodo` for everything Dodo processed itself.

const (
	GetDisputePaymentProviderStripe GetDisputePaymentProvider = "stripe"
	GetDisputePaymentProviderAdyen  GetDisputePaymentProvider = "adyen"
	GetDisputePaymentProviderDodo   GetDisputePaymentProvider = "dodo"
)

func (GetDisputePaymentProvider) IsKnown added in v1.103.0

func (r GetDisputePaymentProvider) IsKnown() bool

type GitHubPermission added in v1.99.0

type GitHubPermission string

Repository permission to grant on a `github` entitlement.

const (
	GitHubPermissionPull     GitHubPermission = "pull"
	GitHubPermissionPush     GitHubPermission = "push"
	GitHubPermissionAdmin    GitHubPermission = "admin"
	GitHubPermissionMaintain GitHubPermission = "maintain"
	GitHubPermissionTriage   GitHubPermission = "triage"
)

func (GitHubPermission) IsKnown added in v1.99.0

func (r GitHubPermission) IsKnown() bool

type GroupProductParam added in v1.99.0

type GroupProductParam struct {
	// Product ID to include in the group
	ProductID param.Field[string] `json:"product_id" api:"required"`
	// Status of the product in this group (defaults to true if not provided)
	Status param.Field[bool] `json:"status"`
}

func (GroupProductParam) MarshalJSON added in v1.99.0

func (r GroupProductParam) MarshalJSON() (data []byte, err error)

type IntegrationConfigDigitalFilesConfigParam added in v1.97.0

type IntegrationConfigDigitalFilesConfigParam struct {
	// Files attached to this entitlement. Add files via
	// `POST /entitlements/{id}/files` and remove them via
	// `DELETE /entitlements/{id}/files/{file_id}`.
	DigitalFileIDs param.Field[[]string] `json:"digital_file_ids" api:"required"`
	// Optional external URL shown to the customer alongside the files.
	ExternalURL param.Field[string] `json:"external_url"`
	// Optional human-readable delivery instructions shown to the customer alongside
	// the files.
	Instructions param.Field[string] `json:"instructions"`
	// Three-way patchable list of legacy file identifiers:
	//
	// - omitted → preserve the current value
	// - `null` → clear
	// - `[...]` → replace
	//
	// On create, an omitted field, an explicit `null`, or an empty array all result in
	// no legacy files attached.
	LegacyFileIDs param.Field[[]string] `json:"legacy_file_ids"`
}

func (IntegrationConfigDigitalFilesConfigParam) MarshalJSON added in v1.97.0

func (r IntegrationConfigDigitalFilesConfigParam) MarshalJSON() (data []byte, err error)

type IntegrationConfigDiscordConfigParam added in v1.97.0

type IntegrationConfigDiscordConfigParam struct {
	// Discord guild (server) ID.
	GuildID param.Field[string] `json:"guild_id" api:"required"`
	// Optional Discord role to assign within the guild.
	RoleID param.Field[string] `json:"role_id"`
}

func (IntegrationConfigDiscordConfigParam) MarshalJSON added in v1.97.0

func (r IntegrationConfigDiscordConfigParam) MarshalJSON() (data []byte, err error)

type IntegrationConfigFeatureFlagConfigParam added in v1.107.0

type IntegrationConfigFeatureFlagConfigParam struct {
	// Merchant-chosen identifier for the capability this entitlement unlocks. Not
	// unique across entitlements.
	FeatureID param.Field[string] `json:"feature_id" api:"required"`
	// Type of capability conferred.
	FeatureType param.Field[FeatureType] `json:"feature_type" api:"required"`
}

func (IntegrationConfigFeatureFlagConfigParam) MarshalJSON added in v1.107.0

func (r IntegrationConfigFeatureFlagConfigParam) MarshalJSON() (data []byte, err error)

type IntegrationConfigFigmaConfigParam added in v1.97.0

type IntegrationConfigFigmaConfigParam struct {
	// Figma file identifier to grant access to.
	FigmaFileID param.Field[string] `json:"figma_file_id" api:"required"`
}

func (IntegrationConfigFigmaConfigParam) MarshalJSON added in v1.97.0

func (r IntegrationConfigFigmaConfigParam) MarshalJSON() (data []byte, err error)

type IntegrationConfigFramerConfigParam added in v1.97.0

type IntegrationConfigFramerConfigParam struct {
	// Framer template identifier to grant access to.
	FramerTemplateID param.Field[string] `json:"framer_template_id" api:"required"`
}

func (IntegrationConfigFramerConfigParam) MarshalJSON added in v1.97.0

func (r IntegrationConfigFramerConfigParam) MarshalJSON() (data []byte, err error)

type IntegrationConfigFulfillmentMode added in v1.102.1

type IntegrationConfigFulfillmentMode string

How license keys are fulfilled. `auto` (default) generates and delivers keys to customers automatically; `manual` creates pending grants that you fulfill with the supplied key via `POST /grants/{grant_id}/license-key`.

const (
	IntegrationConfigFulfillmentModeAuto   IntegrationConfigFulfillmentMode = "auto"
	IntegrationConfigFulfillmentModeManual IntegrationConfigFulfillmentMode = "manual"
)

func (IntegrationConfigFulfillmentMode) IsKnown added in v1.102.1

type IntegrationConfigGitHubConfigParam added in v1.97.0

type IntegrationConfigGitHubConfigParam struct {
	// Permission to grant on the repository.
	Permission param.Field[GitHubPermission] `json:"permission" api:"required"`
	// Repository or organisation slug to grant access to.
	TargetID param.Field[string] `json:"target_id" api:"required"`
}

func (IntegrationConfigGitHubConfigParam) MarshalJSON added in v1.97.0

func (r IntegrationConfigGitHubConfigParam) MarshalJSON() (data []byte, err error)

type IntegrationConfigLicenseKeyConfigFulfillmentMode added in v1.102.1

type IntegrationConfigLicenseKeyConfigFulfillmentMode string

How license keys are fulfilled. `auto` (default) generates and delivers keys to customers automatically; `manual` creates pending grants that you fulfill with the supplied key via `POST /grants/{grant_id}/license-key`.

const (
	IntegrationConfigLicenseKeyConfigFulfillmentModeAuto   IntegrationConfigLicenseKeyConfigFulfillmentMode = "auto"
	IntegrationConfigLicenseKeyConfigFulfillmentModeManual IntegrationConfigLicenseKeyConfigFulfillmentMode = "manual"
)

func (IntegrationConfigLicenseKeyConfigFulfillmentMode) IsKnown added in v1.102.1

type IntegrationConfigLicenseKeyConfigParam added in v1.97.0

type IntegrationConfigLicenseKeyConfigParam struct {
	// Optional message displayed when a customer activates the license key (≤ 2500
	// characters).
	ActivationMessage param.Field[string] `json:"activation_message"`
	// Maximum activations allowed per issued license key. Omit for unlimited.
	ActivationsLimit param.Field[int64] `json:"activations_limit"`
	// Validity duration of issued license keys. Provide both `duration_count` and
	// `duration_interval` together for a fixed duration; omit both for non-expiring
	// keys.
	DurationCount param.Field[int64] `json:"duration_count"`
	// Unit of `duration_count`.
	DurationInterval param.Field[TimeInterval] `json:"duration_interval"`
	// How license keys are fulfilled. `auto` (default) generates and delivers keys to
	// customers automatically; `manual` creates pending grants that you fulfill with
	// the supplied key via `POST /grants/{grant_id}/license-key`.
	FulfillmentMode param.Field[IntegrationConfigLicenseKeyConfigFulfillmentMode] `json:"fulfillment_mode"`
}

func (IntegrationConfigLicenseKeyConfigParam) MarshalJSON added in v1.97.0

func (r IntegrationConfigLicenseKeyConfigParam) MarshalJSON() (data []byte, err error)

type IntegrationConfigNotionConfigParam added in v1.97.0

type IntegrationConfigNotionConfigParam struct {
	// Notion template identifier to grant access to.
	NotionTemplateID param.Field[string] `json:"notion_template_id" api:"required"`
}

func (IntegrationConfigNotionConfigParam) MarshalJSON added in v1.97.0

func (r IntegrationConfigNotionConfigParam) MarshalJSON() (data []byte, err error)

type IntegrationConfigParam added in v1.97.0

type IntegrationConfigParam struct {
	// Optional message displayed when a customer activates the license key (≤ 2500
	// characters).
	ActivationMessage param.Field[string] `json:"activation_message"`
	// Maximum activations allowed per issued license key. Omit for unlimited.
	ActivationsLimit param.Field[int64] `json:"activations_limit"`
	// Telegram chat ID. For groups this is typically a negative integer.
	ChatID         param.Field[string]      `json:"chat_id"`
	DigitalFileIDs param.Field[interface{}] `json:"digital_file_ids"`
	// Validity duration of issued license keys. Provide both `duration_count` and
	// `duration_interval` together for a fixed duration; omit both for non-expiring
	// keys.
	DurationCount param.Field[int64] `json:"duration_count"`
	// Unit of `duration_count`.
	DurationInterval param.Field[TimeInterval] `json:"duration_interval"`
	// Optional external URL shown to the customer alongside the files.
	ExternalURL param.Field[string] `json:"external_url"`
	// Merchant-chosen identifier for the capability this entitlement unlocks. Not
	// unique across entitlements.
	FeatureID param.Field[string] `json:"feature_id"`
	// Type of capability conferred.
	FeatureType param.Field[FeatureType] `json:"feature_type"`
	// Figma file identifier to grant access to.
	FigmaFileID param.Field[string] `json:"figma_file_id"`
	// Framer template identifier to grant access to.
	FramerTemplateID param.Field[string] `json:"framer_template_id"`
	// How license keys are fulfilled. `auto` (default) generates and delivers keys to
	// customers automatically; `manual` creates pending grants that you fulfill with
	// the supplied key via `POST /grants/{grant_id}/license-key`.
	FulfillmentMode param.Field[IntegrationConfigFulfillmentMode] `json:"fulfillment_mode"`
	// Discord guild (server) ID.
	GuildID param.Field[string] `json:"guild_id"`
	// Optional human-readable delivery instructions shown to the customer alongside
	// the files.
	Instructions  param.Field[string]      `json:"instructions"`
	LegacyFileIDs param.Field[interface{}] `json:"legacy_file_ids"`
	// Notion template identifier to grant access to.
	NotionTemplateID param.Field[string] `json:"notion_template_id"`
	// Permission to grant on the repository.
	Permission param.Field[GitHubPermission] `json:"permission"`
	// Optional Discord role to assign within the guild.
	RoleID param.Field[string] `json:"role_id"`
	// Repository or organisation slug to grant access to.
	TargetID param.Field[string] `json:"target_id"`
}

Integration-specific configuration supplied when creating or updating an entitlement. The shape required matches the entitlement's `integration_type`.

Untagged enum: variants are matched in order. `FeatureFlag` must precede `LicenseKey`, whose fields are all optional and would otherwise match a `feature_flag` config.

func (IntegrationConfigParam) MarshalJSON added in v1.97.0

func (r IntegrationConfigParam) MarshalJSON() (data []byte, err error)

type IntegrationConfigResponse added in v1.97.0

type IntegrationConfigResponse struct {
	// Optional message displayed when a customer activates the license key (≤ 2500
	// characters).
	ActivationMessage string `json:"activation_message" api:"nullable"`
	// Maximum activations allowed per issued license key. Omit for unlimited.
	ActivationsLimit int64 `json:"activations_limit" api:"nullable"`
	// Telegram chat ID. For groups this is typically a negative integer.
	ChatID string `json:"chat_id"`
	// This field can have the runtime type of
	// [IntegrationConfigResponseDigitalFilesConfigDigitalFiles].
	DigitalFiles interface{} `json:"digital_files"`
	// Validity duration of issued license keys. Provide both `duration_count` and
	// `duration_interval` together for a fixed duration; omit both for non-expiring
	// keys.
	DurationCount int64 `json:"duration_count" api:"nullable"`
	// Unit of `duration_count`.
	DurationInterval TimeInterval `json:"duration_interval" api:"nullable"`
	// Merchant-chosen identifier for the capability this entitlement unlocks.
	FeatureID string `json:"feature_id"`
	// Type of capability conferred. Only `boolean` is supported today.
	FeatureType FeatureType `json:"feature_type"`
	// Figma file identifier to grant access to.
	FigmaFileID string `json:"figma_file_id"`
	// Framer template identifier to grant access to.
	FramerTemplateID string `json:"framer_template_id"`
	// How license keys are fulfilled. `auto` (default) generates and delivers keys to
	// customers automatically; `manual` creates pending grants that you fulfill with
	// the supplied key via `POST /grants/{grant_id}/license-key`.
	FulfillmentMode IntegrationConfigResponseFulfillmentMode `json:"fulfillment_mode" api:"nullable"`
	// Discord guild (server) ID.
	GuildID string `json:"guild_id"`
	// Notion template identifier to grant access to.
	NotionTemplateID string `json:"notion_template_id"`
	// Permission to grant on the repository.
	Permission GitHubPermission `json:"permission"`
	// Optional Discord role to assign within the guild.
	RoleID string `json:"role_id" api:"nullable"`
	// Repository or organisation slug to grant access to.
	TargetID string                        `json:"target_id"`
	JSON     integrationConfigResponseJSON `json:"-"`
	// contains filtered or unexported fields
}

Integration-specific configuration on an entitlement read response.

For `digital_files` entitlements the response includes presigned download URLs for each attached file; other integrations match the shape supplied at creation.

func (*IntegrationConfigResponse) UnmarshalJSON added in v1.97.0

func (r *IntegrationConfigResponse) UnmarshalJSON(data []byte) (err error)

type IntegrationConfigResponseDigitalFilesConfig added in v1.97.0

type IntegrationConfigResponseDigitalFilesConfig struct {
	// Populated digital-files payload with each file's metadata and a short-lived
	// presigned download URL.
	DigitalFiles IntegrationConfigResponseDigitalFilesConfigDigitalFiles `json:"digital_files" api:"required"`
	JSON         integrationConfigResponseDigitalFilesConfigJSON         `json:"-"`
}

func (*IntegrationConfigResponseDigitalFilesConfig) UnmarshalJSON added in v1.97.0

func (r *IntegrationConfigResponseDigitalFilesConfig) UnmarshalJSON(data []byte) (err error)

type IntegrationConfigResponseDigitalFilesConfigDigitalFiles added in v1.97.0

type IntegrationConfigResponseDigitalFilesConfigDigitalFiles struct {
	// One entry per attached file.
	Files []IntegrationConfigResponseDigitalFilesConfigDigitalFilesFile `json:"files" api:"required"`
	// Optional external URL, passed through from the entitlement configuration.
	ExternalURL string `json:"external_url" api:"nullable"`
	// Optional human-readable delivery instructions, passed through from the
	// entitlement configuration.
	Instructions string                                                      `json:"instructions" api:"nullable"`
	JSON         integrationConfigResponseDigitalFilesConfigDigitalFilesJSON `json:"-"`
}

Populated digital-files payload with each file's metadata and a short-lived presigned download URL.

func (*IntegrationConfigResponseDigitalFilesConfigDigitalFiles) UnmarshalJSON added in v1.97.0

type IntegrationConfigResponseDigitalFilesConfigDigitalFilesFile added in v1.97.0

type IntegrationConfigResponseDigitalFilesConfigDigitalFilesFile struct {
	// Short-lived presigned URL for downloading the file.
	DownloadURL string `json:"download_url" api:"required"`
	// Seconds until `download_url` expires.
	ExpiresIn int64 `json:"expires_in" api:"required"`
	// Identifier of the attached file.
	FileID string `json:"file_id" api:"required"`
	// Original filename of the attached file.
	Filename string `json:"filename" api:"required"`
	// Optional content-type declared at upload.
	ContentType string `json:"content_type" api:"nullable"`
	// Optional size of the file in bytes.
	FileSize int64                                                           `json:"file_size" api:"nullable"`
	JSON     integrationConfigResponseDigitalFilesConfigDigitalFilesFileJSON `json:"-"`
}

One file in a resolved digital-files payload.

func (*IntegrationConfigResponseDigitalFilesConfigDigitalFilesFile) UnmarshalJSON added in v1.97.0

type IntegrationConfigResponseDiscordConfig added in v1.97.0

type IntegrationConfigResponseDiscordConfig struct {
	// Discord guild (server) ID.
	GuildID string `json:"guild_id" api:"required"`
	// Optional Discord role to assign within the guild.
	RoleID string                                     `json:"role_id" api:"nullable"`
	JSON   integrationConfigResponseDiscordConfigJSON `json:"-"`
}

func (*IntegrationConfigResponseDiscordConfig) UnmarshalJSON added in v1.97.0

func (r *IntegrationConfigResponseDiscordConfig) UnmarshalJSON(data []byte) (err error)

type IntegrationConfigResponseFeatureFlagConfig added in v1.107.0

type IntegrationConfigResponseFeatureFlagConfig struct {
	// Merchant-chosen identifier for the capability this entitlement unlocks.
	FeatureID string `json:"feature_id" api:"required"`
	// Type of capability conferred. Only `boolean` is supported today.
	FeatureType FeatureType                                    `json:"feature_type" api:"required"`
	JSON        integrationConfigResponseFeatureFlagConfigJSON `json:"-"`
}

func (*IntegrationConfigResponseFeatureFlagConfig) UnmarshalJSON added in v1.107.0

func (r *IntegrationConfigResponseFeatureFlagConfig) UnmarshalJSON(data []byte) (err error)

type IntegrationConfigResponseFigmaConfig added in v1.97.0

type IntegrationConfigResponseFigmaConfig struct {
	// Figma file identifier to grant access to.
	FigmaFileID string                                   `json:"figma_file_id" api:"required"`
	JSON        integrationConfigResponseFigmaConfigJSON `json:"-"`
}

func (*IntegrationConfigResponseFigmaConfig) UnmarshalJSON added in v1.97.0

func (r *IntegrationConfigResponseFigmaConfig) UnmarshalJSON(data []byte) (err error)

type IntegrationConfigResponseFramerConfig added in v1.97.0

type IntegrationConfigResponseFramerConfig struct {
	// Framer template identifier to grant access to.
	FramerTemplateID string                                    `json:"framer_template_id" api:"required"`
	JSON             integrationConfigResponseFramerConfigJSON `json:"-"`
}

func (*IntegrationConfigResponseFramerConfig) UnmarshalJSON added in v1.97.0

func (r *IntegrationConfigResponseFramerConfig) UnmarshalJSON(data []byte) (err error)

type IntegrationConfigResponseFulfillmentMode added in v1.102.1

type IntegrationConfigResponseFulfillmentMode string

How license keys are fulfilled. `auto` (default) generates and delivers keys to customers automatically; `manual` creates pending grants that you fulfill with the supplied key via `POST /grants/{grant_id}/license-key`.

const (
	IntegrationConfigResponseFulfillmentModeAuto   IntegrationConfigResponseFulfillmentMode = "auto"
	IntegrationConfigResponseFulfillmentModeManual IntegrationConfigResponseFulfillmentMode = "manual"
)

func (IntegrationConfigResponseFulfillmentMode) IsKnown added in v1.102.1

type IntegrationConfigResponseGitHubConfig added in v1.97.0

type IntegrationConfigResponseGitHubConfig struct {
	// Permission to grant on the repository.
	Permission GitHubPermission `json:"permission" api:"required"`
	// Repository or organisation slug to grant access to.
	TargetID string                                    `json:"target_id" api:"required"`
	JSON     integrationConfigResponseGitHubConfigJSON `json:"-"`
}

func (*IntegrationConfigResponseGitHubConfig) UnmarshalJSON added in v1.97.0

func (r *IntegrationConfigResponseGitHubConfig) UnmarshalJSON(data []byte) (err error)

type IntegrationConfigResponseLicenseKeyConfig added in v1.97.0

type IntegrationConfigResponseLicenseKeyConfig struct {
	// Optional message displayed when a customer activates the license key (≤ 2500
	// characters).
	ActivationMessage string `json:"activation_message" api:"nullable"`
	// Maximum activations allowed per issued license key. Omit for unlimited.
	ActivationsLimit int64 `json:"activations_limit" api:"nullable"`
	// Validity duration of issued license keys. Provide both `duration_count` and
	// `duration_interval` together for a fixed duration; omit both for non-expiring
	// keys.
	DurationCount int64 `json:"duration_count" api:"nullable"`
	// Unit of `duration_count`.
	DurationInterval TimeInterval `json:"duration_interval" api:"nullable"`
	// How license keys are fulfilled. `auto` (default) generates and delivers keys to
	// customers automatically; `manual` creates pending grants that you fulfill with
	// the supplied key via `POST /grants/{grant_id}/license-key`.
	FulfillmentMode IntegrationConfigResponseLicenseKeyConfigFulfillmentMode `json:"fulfillment_mode" api:"nullable"`
	JSON            integrationConfigResponseLicenseKeyConfigJSON            `json:"-"`
}

func (*IntegrationConfigResponseLicenseKeyConfig) UnmarshalJSON added in v1.97.0

func (r *IntegrationConfigResponseLicenseKeyConfig) UnmarshalJSON(data []byte) (err error)

type IntegrationConfigResponseLicenseKeyConfigFulfillmentMode added in v1.102.1

type IntegrationConfigResponseLicenseKeyConfigFulfillmentMode string

How license keys are fulfilled. `auto` (default) generates and delivers keys to customers automatically; `manual` creates pending grants that you fulfill with the supplied key via `POST /grants/{grant_id}/license-key`.

const (
	IntegrationConfigResponseLicenseKeyConfigFulfillmentModeAuto   IntegrationConfigResponseLicenseKeyConfigFulfillmentMode = "auto"
	IntegrationConfigResponseLicenseKeyConfigFulfillmentModeManual IntegrationConfigResponseLicenseKeyConfigFulfillmentMode = "manual"
)

func (IntegrationConfigResponseLicenseKeyConfigFulfillmentMode) IsKnown added in v1.102.1

type IntegrationConfigResponseNotionConfig added in v1.97.0

type IntegrationConfigResponseNotionConfig struct {
	// Notion template identifier to grant access to.
	NotionTemplateID string                                    `json:"notion_template_id" api:"required"`
	JSON             integrationConfigResponseNotionConfigJSON `json:"-"`
}

func (*IntegrationConfigResponseNotionConfig) UnmarshalJSON added in v1.97.0

func (r *IntegrationConfigResponseNotionConfig) UnmarshalJSON(data []byte) (err error)

type IntegrationConfigResponseTelegramConfig added in v1.97.0

type IntegrationConfigResponseTelegramConfig struct {
	// Telegram chat ID. For groups this is typically a negative integer.
	ChatID string                                      `json:"chat_id" api:"required"`
	JSON   integrationConfigResponseTelegramConfigJSON `json:"-"`
}

func (*IntegrationConfigResponseTelegramConfig) UnmarshalJSON added in v1.97.0

func (r *IntegrationConfigResponseTelegramConfig) UnmarshalJSON(data []byte) (err error)

type IntegrationConfigResponseUnion added in v1.97.0

type IntegrationConfigResponseUnion interface {
	// contains filtered or unexported methods
}

Integration-specific configuration on an entitlement read response.

For `digital_files` entitlements the response includes presigned download URLs for each attached file; other integrations match the shape supplied at creation.

Union satisfied by IntegrationConfigResponseFeatureFlagConfig, IntegrationConfigResponseGitHubConfig, IntegrationConfigResponseDiscordConfig, IntegrationConfigResponseTelegramConfig, IntegrationConfigResponseFigmaConfig, IntegrationConfigResponseFramerConfig, IntegrationConfigResponseNotionConfig, IntegrationConfigResponseDigitalFilesConfig or IntegrationConfigResponseLicenseKeyConfig.

type IntegrationConfigTelegramConfigParam added in v1.97.0

type IntegrationConfigTelegramConfigParam struct {
	// Telegram chat ID. For groups this is typically a negative integer.
	ChatID param.Field[string] `json:"chat_id" api:"required"`
}

func (IntegrationConfigTelegramConfigParam) MarshalJSON added in v1.97.0

func (r IntegrationConfigTelegramConfigParam) MarshalJSON() (data []byte, err error)

type IntegrationConfigUnionParam added in v1.97.0

type IntegrationConfigUnionParam interface {
	// contains filtered or unexported methods
}

Integration-specific configuration supplied when creating or updating an entitlement. The shape required matches the entitlement's `integration_type`.

Untagged enum: variants are matched in order. `FeatureFlag` must precede `LicenseKey`, whose fields are all optional and would otherwise match a `feature_flag` config.

Satisfied by IntegrationConfigFeatureFlagConfigParam, IntegrationConfigGitHubConfigParam, IntegrationConfigDiscordConfigParam, IntegrationConfigTelegramConfigParam, IntegrationConfigFigmaConfigParam, IntegrationConfigFramerConfigParam, IntegrationConfigNotionConfigParam, IntegrationConfigDigitalFilesConfigParam, IntegrationConfigLicenseKeyConfigParam, IntegrationConfigParam.

type IntentStatus added in v1.6.3

type IntentStatus string
const (
	IntentStatusSucceeded                      IntentStatus = "succeeded"
	IntentStatusFailed                         IntentStatus = "failed"
	IntentStatusCancelled                      IntentStatus = "cancelled"
	IntentStatusProcessing                     IntentStatus = "processing"
	IntentStatusRequiresCustomerAction         IntentStatus = "requires_customer_action"
	IntentStatusRequiresMerchantAction         IntentStatus = "requires_merchant_action"
	IntentStatusRequiresPaymentMethod          IntentStatus = "requires_payment_method"
	IntentStatusRequiresConfirmation           IntentStatus = "requires_confirmation"
	IntentStatusRequiresCapture                IntentStatus = "requires_capture"
	IntentStatusPartiallyCaptured              IntentStatus = "partially_captured"
	IntentStatusPartiallyCapturedAndCapturable IntentStatus = "partially_captured_and_capturable"
)

func (IntentStatus) IsKnown added in v1.6.3

func (r IntentStatus) IsKnown() bool

type InvoicePaymentService added in v0.15.1

type InvoicePaymentService struct {
	Options []option.RequestOption
}

InvoicePaymentService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewInvoicePaymentService method instead.

func NewInvoicePaymentService added in v0.15.1

func NewInvoicePaymentService(opts ...option.RequestOption) (r *InvoicePaymentService)

NewInvoicePaymentService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*InvoicePaymentService) Get added in v0.15.1

func (r *InvoicePaymentService) Get(ctx context.Context, paymentID string, opts ...option.RequestOption) (res *http.Response, err error)

func (*InvoicePaymentService) GetPayout added in v1.88.0

func (r *InvoicePaymentService) GetPayout(ctx context.Context, payoutID string, opts ...option.RequestOption) (res *http.Response, err error)

func (*InvoicePaymentService) GetRefund added in v1.52.4

func (r *InvoicePaymentService) GetRefund(ctx context.Context, refundID string, opts ...option.RequestOption) (res *http.Response, err error)

type InvoiceService added in v0.15.1

type InvoiceService struct {
	Options  []option.RequestOption
	Payments *InvoicePaymentService
}

InvoiceService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewInvoiceService method instead.

func NewInvoiceService added in v0.15.1

func NewInvoiceService(opts ...option.RequestOption) (r *InvoiceService)

NewInvoiceService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

type LedgerEntryType added in v1.86.0

type LedgerEntryType string
const (
	LedgerEntryTypeCredit LedgerEntryType = "credit"
	LedgerEntryTypeDebit  LedgerEntryType = "debit"
)

func (LedgerEntryType) IsKnown added in v1.86.0

func (r LedgerEntryType) IsKnown() bool

type LicenseActivateParams added in v0.14.0

type LicenseActivateParams struct {
	LicenseKey param.Field[string] `json:"license_key" api:"required"`
	Name       param.Field[string] `json:"name" api:"required"`
}

func (LicenseActivateParams) MarshalJSON added in v0.14.0

func (r LicenseActivateParams) MarshalJSON() (data []byte, err error)

type LicenseActivateResponse added in v1.53.2

type LicenseActivateResponse struct {
	// License key instance ID
	ID string `json:"id" api:"required"`
	// Business ID
	BusinessID string `json:"business_id" api:"required"`
	// Creation timestamp
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Limited customer details associated with the license key.
	Customer CustomerLimitedDetails `json:"customer" api:"required"`
	// Associated license key ID
	LicenseKeyID string `json:"license_key_id" api:"required"`
	// Instance name
	Name string `json:"name" api:"required"`
	// Related product info. Present if the license key is tied to a product.
	Product LicenseActivateResponseProduct `json:"product" api:"required"`
	JSON    licenseActivateResponseJSON    `json:"-"`
}

func (*LicenseActivateResponse) UnmarshalJSON added in v1.53.2

func (r *LicenseActivateResponse) UnmarshalJSON(data []byte) (err error)

type LicenseActivateResponseProduct added in v1.53.2

type LicenseActivateResponseProduct struct {
	// Unique identifier for the product.
	ProductID string `json:"product_id" api:"required"`
	// Name of the product, if set by the merchant.
	Name string                             `json:"name" api:"nullable"`
	JSON licenseActivateResponseProductJSON `json:"-"`
}

Related product info. Present if the license key is tied to a product.

func (*LicenseActivateResponseProduct) UnmarshalJSON added in v1.53.2

func (r *LicenseActivateResponseProduct) UnmarshalJSON(data []byte) (err error)

type LicenseDeactivateParams added in v0.14.0

type LicenseDeactivateParams struct {
	LicenseKey           param.Field[string] `json:"license_key" api:"required"`
	LicenseKeyInstanceID param.Field[string] `json:"license_key_instance_id" api:"required"`
}

func (LicenseDeactivateParams) MarshalJSON added in v0.14.0

func (r LicenseDeactivateParams) MarshalJSON() (data []byte, err error)

type LicenseKey added in v0.14.0

type LicenseKey struct {
	// The unique identifier of the license key.
	ID string `json:"id" api:"required"`
	// Brand id this license key belongs to
	BrandID string `json:"brand_id" api:"required"`
	// The unique identifier of the business associated with the license key.
	BusinessID string `json:"business_id" api:"required"`
	// The timestamp indicating when the license key was created, in UTC.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// The unique identifier of the customer associated with the license key.
	CustomerID string `json:"customer_id" api:"required"`
	// The current number of instances activated for this license key.
	InstancesCount int64 `json:"instances_count" api:"required"`
	// The license key string.
	Key string `json:"key" api:"required"`
	// The unique identifier of the product associated with the license key.
	ProductID string `json:"product_id" api:"required"`
	// The source of the license key - 'auto' for keys generated by
	// payment/subscription flows, 'import' for merchant-imported keys.
	Source LicenseKeySource `json:"source" api:"required"`
	// The current status of the license key (e.g., active, inactive, expired).
	Status LicenseKeyStatus `json:"status" api:"required"`
	// The maximum number of activations allowed for this license key.
	ActivationsLimit int64 `json:"activations_limit" api:"nullable"`
	// The timestamp indicating when the license key expires, in UTC.
	ExpiresAt time.Time `json:"expires_at" api:"nullable" format:"date-time"`
	// The unique identifier of the payment associated with the license key, if any.
	PaymentID string `json:"payment_id" api:"nullable"`
	// The unique identifier of the subscription associated with the license key, if
	// any.
	SubscriptionID string         `json:"subscription_id" api:"nullable"`
	JSON           licenseKeyJSON `json:"-"`
}

func (*LicenseKey) UnmarshalJSON added in v0.14.0

func (r *LicenseKey) UnmarshalJSON(data []byte) (err error)

type LicenseKeyCreatedWebhookEvent added in v1.56.0

type LicenseKeyCreatedWebhookEvent struct {
	// The business identifier
	BusinessID string     `json:"business_id" api:"required"`
	Data       LicenseKey `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type LicenseKeyCreatedWebhookEventType `json:"type" api:"required"`
	JSON licenseKeyCreatedWebhookEventJSON `json:"-"`
}

func (*LicenseKeyCreatedWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *LicenseKeyCreatedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type LicenseKeyCreatedWebhookEventType added in v1.56.0

type LicenseKeyCreatedWebhookEventType string

The event type

const (
	LicenseKeyCreatedWebhookEventTypeLicenseKeyCreated LicenseKeyCreatedWebhookEventType = "license_key.created"
)

func (LicenseKeyCreatedWebhookEventType) IsKnown added in v1.56.0

type LicenseKeyDuration added in v1.6.3

type LicenseKeyDuration struct {
	Count int64 `json:"count" api:"required"`
	// Unit of a duration count (e.g. license-key validity period).
	Interval TimeInterval           `json:"interval" api:"required"`
	JSON     licenseKeyDurationJSON `json:"-"`
}

func (*LicenseKeyDuration) UnmarshalJSON added in v1.6.3

func (r *LicenseKeyDuration) UnmarshalJSON(data []byte) (err error)

type LicenseKeyDurationParam added in v1.6.3

type LicenseKeyDurationParam struct {
	Count param.Field[int64] `json:"count" api:"required"`
	// Unit of a duration count (e.g. license-key validity period).
	Interval param.Field[TimeInterval] `json:"interval" api:"required"`
}

func (LicenseKeyDurationParam) MarshalJSON added in v1.6.3

func (r LicenseKeyDurationParam) MarshalJSON() (data []byte, err error)

type LicenseKeyGrant added in v1.97.0

type LicenseKeyGrant struct {
	// Identifier of the issued license key.
	ID string `json:"id" api:"required"`
	// Number of instances currently active. Activation increments it and deactivation
	// decrements it, so it is a live count and not a total.
	ActivationsUsed int64 `json:"activations_used" api:"required"`
	// Issued license key.
	Key string `json:"key" api:"required"`
	// Current status of the license key. Activation fails unless it is `active`, so a
	// client can warn before the customer tries.
	Status LicenseKeyStatus `json:"status" api:"required"`
	// Maximum activations allowed by the entitlement, when set.
	ActivationsLimit int64 `json:"activations_limit" api:"nullable"`
	// When the license key expires, when applicable.
	ExpiresAt time.Time           `json:"expires_at" api:"nullable" format:"date-time"`
	JSON      licenseKeyGrantJSON `json:"-"`
}

License-key delivery payload, present on grants for `license_key` entitlements. The grant's top-level `status` is the source of truth for the grant's lifecycle.

func (*LicenseKeyGrant) UnmarshalJSON added in v1.97.0

func (r *LicenseKeyGrant) UnmarshalJSON(data []byte) (err error)

type LicenseKeyInstance added in v0.14.0

type LicenseKeyInstance struct {
	ID           string                 `json:"id" api:"required"`
	BusinessID   string                 `json:"business_id" api:"required"`
	CreatedAt    time.Time              `json:"created_at" api:"required" format:"date-time"`
	LicenseKeyID string                 `json:"license_key_id" api:"required"`
	Name         string                 `json:"name" api:"required"`
	JSON         licenseKeyInstanceJSON `json:"-"`
}

func (*LicenseKeyInstance) UnmarshalJSON added in v0.14.0

func (r *LicenseKeyInstance) UnmarshalJSON(data []byte) (err error)

type LicenseKeyInstanceListParams added in v0.14.0

type LicenseKeyInstanceListParams struct {
	// Filter instances by entitlement grant ID
	GrantID param.Field[string] `query:"grant_id"`
	// Filter by license key ID
	LicenseKeyID param.Field[string] `query:"license_key_id"`
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
}

func (LicenseKeyInstanceListParams) URLQuery added in v0.14.0

func (r LicenseKeyInstanceListParams) URLQuery() (v url.Values)

URLQuery serializes LicenseKeyInstanceListParams's query parameters as `url.Values`.

type LicenseKeyInstanceService added in v0.14.0

type LicenseKeyInstanceService struct {
	Options []option.RequestOption
}

LicenseKeyInstanceService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewLicenseKeyInstanceService method instead.

func NewLicenseKeyInstanceService added in v0.14.0

func NewLicenseKeyInstanceService(opts ...option.RequestOption) (r *LicenseKeyInstanceService)

NewLicenseKeyInstanceService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*LicenseKeyInstanceService) Get added in v0.14.0

func (*LicenseKeyInstanceService) List added in v0.14.0

func (*LicenseKeyInstanceService) Update added in v0.14.0

type LicenseKeyInstanceUpdateParams added in v0.14.0

type LicenseKeyInstanceUpdateParams struct {
	Name param.Field[string] `json:"name" api:"required"`
}

func (LicenseKeyInstanceUpdateParams) MarshalJSON added in v0.14.0

func (r LicenseKeyInstanceUpdateParams) MarshalJSON() (data []byte, err error)

type LicenseKeyListParams added in v0.14.0

type LicenseKeyListParams struct {
	// Filter license keys created on or after this timestamp
	CreatedAtGte param.Field[time.Time] `query:"created_at_gte" format:"date-time"`
	// Filter license keys created on or before this timestamp
	CreatedAtLte param.Field[time.Time] `query:"created_at_lte" format:"date-time"`
	// Filter by customer ID
	CustomerID param.Field[string] `query:"customer_id"`
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
	// Filter by product ID
	ProductID param.Field[string] `query:"product_id"`
	// Filter by license key source
	Source param.Field[LicenseKeyListParamsSource] `query:"source"`
	// Filter by license key status
	Status param.Field[LicenseKeyListParamsStatus] `query:"status"`
}

func (LicenseKeyListParams) URLQuery added in v0.14.0

func (r LicenseKeyListParams) URLQuery() (v url.Values)

URLQuery serializes LicenseKeyListParams's query parameters as `url.Values`.

type LicenseKeyListParamsSource added in v1.95.0

type LicenseKeyListParamsSource string

Filter by license key source

const (
	LicenseKeyListParamsSourceAuto   LicenseKeyListParamsSource = "auto"
	LicenseKeyListParamsSourceImport LicenseKeyListParamsSource = "import"
	LicenseKeyListParamsSourceManual LicenseKeyListParamsSource = "manual"
)

func (LicenseKeyListParamsSource) IsKnown added in v1.95.0

func (r LicenseKeyListParamsSource) IsKnown() bool

type LicenseKeyListParamsStatus added in v0.14.0

type LicenseKeyListParamsStatus string

Filter by license key status

const (
	LicenseKeyListParamsStatusActive   LicenseKeyListParamsStatus = "active"
	LicenseKeyListParamsStatusExpired  LicenseKeyListParamsStatus = "expired"
	LicenseKeyListParamsStatusDisabled LicenseKeyListParamsStatus = "disabled"
)

func (LicenseKeyListParamsStatus) IsKnown added in v0.14.0

func (r LicenseKeyListParamsStatus) IsKnown() bool

type LicenseKeyNewParams added in v1.95.0

type LicenseKeyNewParams struct {
	// The customer this license key belongs to.
	CustomerID param.Field[string] `json:"customer_id" api:"required"`
	// The license key string to import.
	Key param.Field[string] `json:"key" api:"required"`
	// The product this license key is for.
	ProductID param.Field[string] `json:"product_id" api:"required"`
	// Maximum number of activations allowed. Null means unlimited.
	ActivationsLimit param.Field[int64] `json:"activations_limit"`
	// Expiration timestamp. Null means the key never expires.
	ExpiresAt param.Field[time.Time] `json:"expires_at" format:"date-time"`
}

func (LicenseKeyNewParams) MarshalJSON added in v1.95.0

func (r LicenseKeyNewParams) MarshalJSON() (data []byte, err error)

type LicenseKeyService added in v0.14.0

type LicenseKeyService struct {
	Options []option.RequestOption
}

LicenseKeyService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewLicenseKeyService method instead.

func NewLicenseKeyService added in v0.14.0

func NewLicenseKeyService(opts ...option.RequestOption) (r *LicenseKeyService)

NewLicenseKeyService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*LicenseKeyService) Get deprecated added in v0.14.0

func (r *LicenseKeyService) Get(ctx context.Context, id string, opts ...option.RequestOption) (res *LicenseKey, err error)

Deprecated: deprecated

func (*LicenseKeyService) List deprecated added in v0.14.0

Deprecated: deprecated

func (*LicenseKeyService) ListAutoPaging deprecated added in v1.7.0

func (*LicenseKeyService) New added in v1.95.0

func (*LicenseKeyService) Update deprecated added in v0.14.0

func (r *LicenseKeyService) Update(ctx context.Context, id string, body LicenseKeyUpdateParams, opts ...option.RequestOption) (res *LicenseKey, err error)

Deprecated: deprecated

type LicenseKeySource added in v1.95.0

type LicenseKeySource string

The source of the license key - 'auto' for keys generated by payment/subscription flows, 'import' for merchant-imported keys.

const (
	LicenseKeySourceAuto   LicenseKeySource = "auto"
	LicenseKeySourceImport LicenseKeySource = "import"
	LicenseKeySourceManual LicenseKeySource = "manual"
)

func (LicenseKeySource) IsKnown added in v1.95.0

func (r LicenseKeySource) IsKnown() bool

type LicenseKeyStatus added in v0.14.0

type LicenseKeyStatus string
const (
	LicenseKeyStatusActive   LicenseKeyStatus = "active"
	LicenseKeyStatusExpired  LicenseKeyStatus = "expired"
	LicenseKeyStatusDisabled LicenseKeyStatus = "disabled"
)

func (LicenseKeyStatus) IsKnown added in v0.14.0

func (r LicenseKeyStatus) IsKnown() bool

type LicenseKeyUpdateParams added in v0.14.0

type LicenseKeyUpdateParams struct {
	// The updated activation limit for the license key. Use `null` to remove the
	// limit, or omit this field to leave it unchanged.
	ActivationsLimit param.Field[int64] `json:"activations_limit"`
	// Indicates whether the license key should be disabled. A value of `true` disables
	// the key, while `false` enables it. Omit this field to leave it unchanged.
	Disabled param.Field[bool] `json:"disabled"`
	// The updated expiration timestamp for the license key in UTC. Use `null` to
	// remove the expiration date, or omit this field to leave it unchanged.
	ExpiresAt param.Field[time.Time] `json:"expires_at" format:"date-time"`
}

func (LicenseKeyUpdateParams) MarshalJSON added in v0.14.0

func (r LicenseKeyUpdateParams) MarshalJSON() (data []byte, err error)

type LicenseService added in v0.14.0

type LicenseService struct {
	Options []option.RequestOption
}

LicenseService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewLicenseService method instead.

func NewLicenseService added in v0.14.0

func NewLicenseService(opts ...option.RequestOption) (r *LicenseService)

NewLicenseService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*LicenseService) Activate added in v0.14.0

func (*LicenseService) Deactivate added in v0.14.0

func (r *LicenseService) Deactivate(ctx context.Context, body LicenseDeactivateParams, opts ...option.RequestOption) (err error)

func (*LicenseService) Validate added in v0.14.0

type LicenseValidateParams added in v0.14.0

type LicenseValidateParams struct {
	LicenseKey           param.Field[string] `json:"license_key" api:"required"`
	LicenseKeyInstanceID param.Field[string] `json:"license_key_instance_id"`
}

func (LicenseValidateParams) MarshalJSON added in v0.14.0

func (r LicenseValidateParams) MarshalJSON() (data []byte, err error)

type LicenseValidateResponse added in v0.14.0

type LicenseValidateResponse struct {
	Valid bool                        `json:"valid" api:"required"`
	JSON  licenseValidateResponseJSON `json:"-"`
}

func (*LicenseValidateResponse) UnmarshalJSON added in v0.14.0

func (r *LicenseValidateResponse) UnmarshalJSON(data []byte) (err error)

type ListLocalizedPricesResponse added in v1.106.0

type ListLocalizedPricesResponse struct {
	Items []LocalizedPrice                `json:"items" api:"required"`
	JSON  listLocalizedPricesResponseJSON `json:"-"`
}

func (*ListLocalizedPricesResponse) UnmarshalJSON added in v1.106.0

func (r *ListLocalizedPricesResponse) UnmarshalJSON(data []byte) (err error)

type LocalizedPrice added in v1.106.0

type LocalizedPrice struct {
	// Unique identifier for the localized price.
	ID string `json:"id" api:"required"`
	// Amount in the smallest currency unit (e.g., cents).
	Amount int64 `json:"amount" api:"required"`
	// Timestamp when the localized price was created.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Currency to charge in.
	Currency Currency `json:"currency" api:"required"`
	// Pricing mode of the rule: by_currency or by_country.
	Mode PricingMode `json:"mode" api:"required"`
	// Product this localized price belongs to.
	ProductID string `json:"product_id" api:"required"`
	// Timestamp when the localized price was last updated.
	UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
	// Country the rule applies to. Only set when mode is by_country.
	CountryCode CountryCode        `json:"country_code" api:"nullable"`
	JSON        localizedPriceJSON `json:"-"`
}

func (*LocalizedPrice) UnmarshalJSON added in v1.106.0

func (r *LocalizedPrice) UnmarshalJSON(data []byte) (err error)

type ManualRetry added in v1.115.0

type ManualRetry struct {
	// The invoice the send charged.
	InvoiceID string `json:"invoice_id" api:"required"`
	// Always true on this route. Tells the row apart from an automatic attempt.
	IsManualRetry bool `json:"is_manual_retry" api:"required"`
	// The payment row this send created.
	PaymentID string `json:"payment_id" api:"required"`
	// Which attempt this send is, counting manual sends on the invoice.
	RetryAttempt int64 `json:"retry_attempt" api:"required"`
	SendsAllowed int64 `json:"sends_allowed" api:"required"`
	// Manual sends spent on this invoice, including this one.
	SendsUsed int64 `json:"sends_used" api:"required"`
	// When the next send becomes available. Null when no send is left.
	RetryAvailableAt time.Time `json:"retry_available_at" api:"nullable" format:"date-time"`
	// Outcome of the charge. `processing` means the processor has not settled it yet,
	// and the payment webhooks report the result.
	Status IntentStatus    `json:"status" api:"nullable"`
	JSON   manualRetryJSON `json:"-"`
}

func (*ManualRetry) UnmarshalJSON added in v1.115.0

func (r *ManualRetry) UnmarshalJSON(data []byte) (err error)

type ManualRetryState added in v1.115.0

type ManualRetryState struct {
	CanRetry     bool  `json:"can_retry" api:"required"`
	SendsAllowed int64 `json:"sends_allowed" api:"required"`
	SendsUsed    int64 `json:"sends_used" api:"required"`
	// The code `POST` would fail with. Null when `can_retry` is true.
	Reason string `json:"reason" api:"nullable"`
	// When the next send becomes available. Null when no send is left, or when the
	// block has nothing to do with the cooldown.
	RetryAvailableAt time.Time            `json:"retry_available_at" api:"nullable" format:"date-time"`
	JSON             manualRetryStateJSON `json:"-"`
}

func (*ManualRetryState) UnmarshalJSON added in v1.115.0

func (r *ManualRetryState) UnmarshalJSON(data []byte) (err error)

type Metadata added in v1.106.0

type Metadata map[string]MetadataItemUnion

type MetadataItemUnion added in v1.107.0

type MetadataItemUnion interface {
	ImplementsMetadataItemUnion()
}

Metadata value can be a string, integer, number, or boolean

Union satisfied by shared.UnionString, shared.UnionFloat or shared.UnionBool.

type MetadataItemUnionParam added in v1.107.0

type MetadataItemUnionParam interface {
	ImplementsMetadataItemUnionParam()
}

Metadata value can be a string, integer, number, or boolean

Satisfied by shared.UnionString, shared.UnionFloat, shared.UnionBool.

type MetadataParam added in v1.106.0

type MetadataParam map[string]MetadataItemUnionParam

type Meter added in v1.52.4

type Meter struct {
	ID              string           `json:"id" api:"required"`
	Aggregation     MeterAggregation `json:"aggregation" api:"required"`
	BusinessID      string           `json:"business_id" api:"required"`
	CreatedAt       time.Time        `json:"created_at" api:"required" format:"date-time"`
	EventName       string           `json:"event_name" api:"required"`
	MeasurementUnit string           `json:"measurement_unit" api:"required"`
	Name            string           `json:"name" api:"required"`
	UpdatedAt       time.Time        `json:"updated_at" api:"required" format:"date-time"`
	Description     string           `json:"description" api:"nullable"`
	// A filter structure that combines multiple conditions with logical conjunctions
	// (AND/OR).
	//
	// Supports up to 3 levels of nesting to create complex filter expressions. Each
	// filter has a conjunction (and/or) and clauses that can be either direct
	// conditions or nested filters.
	Filter MeterFilter `json:"filter" api:"nullable"`
	JSON   meterJSON   `json:"-"`
}

func (*Meter) UnmarshalJSON added in v1.52.4

func (r *Meter) UnmarshalJSON(data []byte) (err error)

type MeterAggregation added in v1.52.4

type MeterAggregation struct {
	// Aggregation type for the meter
	Type MeterAggregationType `json:"type" api:"required"`
	// Required when type is not COUNT
	Key  string               `json:"key" api:"nullable"`
	JSON meterAggregationJSON `json:"-"`
}

func (*MeterAggregation) UnmarshalJSON added in v1.52.4

func (r *MeterAggregation) UnmarshalJSON(data []byte) (err error)

type MeterAggregationParam added in v1.52.4

type MeterAggregationParam struct {
	// Aggregation type for the meter
	Type param.Field[MeterAggregationType] `json:"type" api:"required"`
	// Required when type is not COUNT
	Key param.Field[string] `json:"key"`
}

func (MeterAggregationParam) MarshalJSON added in v1.52.4

func (r MeterAggregationParam) MarshalJSON() (data []byte, err error)

type MeterAggregationType added in v1.52.4

type MeterAggregationType string

Aggregation type for the meter

const (
	MeterAggregationTypeCount MeterAggregationType = "count"
	MeterAggregationTypeSum   MeterAggregationType = "sum"
	MeterAggregationTypeMax   MeterAggregationType = "max"
	MeterAggregationTypeLast  MeterAggregationType = "last"
)

func (MeterAggregationType) IsKnown added in v1.52.4

func (r MeterAggregationType) IsKnown() bool

type MeterCartResponseItem added in v1.86.0

type MeterCartResponseItem struct {
	Currency        Currency                  `json:"currency" api:"required"`
	FreeThreshold   int64                     `json:"free_threshold" api:"required"`
	MeasurementUnit string                    `json:"measurement_unit" api:"required"`
	MeterID         string                    `json:"meter_id" api:"required"`
	Name            string                    `json:"name" api:"required"`
	Description     string                    `json:"description" api:"nullable"`
	PricePerUnit    string                    `json:"price_per_unit" api:"nullable"`
	JSON            meterCartResponseItemJSON `json:"-"`
}

Response struct representing usage-based meter cart details for a subscription

func (*MeterCartResponseItem) UnmarshalJSON added in v1.86.0

func (r *MeterCartResponseItem) UnmarshalJSON(data []byte) (err error)

type MeterCreditEntitlementCartResponse added in v1.86.0

type MeterCreditEntitlementCartResponse struct {
	CreditEntitlementID string                                 `json:"credit_entitlement_id" api:"required"`
	MeterID             string                                 `json:"meter_id" api:"required"`
	MeterName           string                                 `json:"meter_name" api:"required"`
	MeterUnitsPerCredit string                                 `json:"meter_units_per_credit" api:"required"`
	ProductID           string                                 `json:"product_id" api:"required"`
	JSON                meterCreditEntitlementCartResponseJSON `json:"-"`
}

Response struct representing meter-credit entitlement mapping cart details for a subscription

func (*MeterCreditEntitlementCartResponse) UnmarshalJSON added in v1.86.0

func (r *MeterCreditEntitlementCartResponse) UnmarshalJSON(data []byte) (err error)

type MeterFilter added in v1.52.4

type MeterFilter struct {
	// Filter clauses - can be direct conditions or nested filters (up to 3 levels
	// deep)
	Clauses FilterTypeUnion `json:"clauses" api:"required"`
	// Logical conjunction to apply between clauses (and/or)
	Conjunction Conjunction     `json:"conjunction" api:"required"`
	JSON        meterFilterJSON `json:"-"`
}

A filter structure that combines multiple conditions with logical conjunctions (AND/OR).

Supports up to 3 levels of nesting to create complex filter expressions. Each filter has a conjunction (and/or) and clauses that can be either direct conditions or nested filters.

func (*MeterFilter) UnmarshalJSON added in v1.52.4

func (r *MeterFilter) UnmarshalJSON(data []byte) (err error)

type MeterFilterParam added in v1.52.4

type MeterFilterParam struct {
	// Filter clauses - can be direct conditions or nested filters (up to 3 levels
	// deep)
	Clauses param.Field[FilterTypeUnionParam] `json:"clauses" api:"required"`
	// Logical conjunction to apply between clauses (and/or)
	Conjunction param.Field[Conjunction] `json:"conjunction" api:"required"`
}

A filter structure that combines multiple conditions with logical conjunctions (AND/OR).

Supports up to 3 levels of nesting to create complex filter expressions. Each filter has a conjunction (and/or) and clauses that can be either direct conditions or nested filters.

func (MeterFilterParam) MarshalJSON added in v1.52.4

func (r MeterFilterParam) MarshalJSON() (data []byte, err error)

type MeterListParams added in v1.52.4

type MeterListParams struct {
	// List archived meters
	Archived param.Field[bool] `query:"archived"`
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
}

func (MeterListParams) URLQuery added in v1.52.4

func (r MeterListParams) URLQuery() (v url.Values)

URLQuery serializes MeterListParams's query parameters as `url.Values`.

type MeterNewParams added in v1.52.4

type MeterNewParams struct {
	// Aggregation configuration for the meter
	Aggregation param.Field[MeterAggregationParam] `json:"aggregation" api:"required"`
	// Event name to track
	EventName param.Field[string] `json:"event_name" api:"required"`
	// measurement unit
	MeasurementUnit param.Field[string] `json:"measurement_unit" api:"required"`
	// Name of the meter
	Name param.Field[string] `json:"name" api:"required"`
	// Optional description of the meter
	Description param.Field[string] `json:"description"`
	// Optional filter to apply to the meter
	Filter param.Field[MeterFilterParam] `json:"filter"`
}

func (MeterNewParams) MarshalJSON added in v1.52.4

func (r MeterNewParams) MarshalJSON() (data []byte, err error)

type MeterService added in v1.52.4

type MeterService struct {
	Options []option.RequestOption
}

MeterService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewMeterService method instead.

func NewMeterService added in v1.52.4

func NewMeterService(opts ...option.RequestOption) (r *MeterService)

NewMeterService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*MeterService) Archive added in v1.52.4

func (r *MeterService) Archive(ctx context.Context, id string, opts ...option.RequestOption) (err error)

func (*MeterService) Get added in v1.52.4

func (r *MeterService) Get(ctx context.Context, id string, opts ...option.RequestOption) (res *Meter, err error)

func (*MeterService) List added in v1.52.4

func (*MeterService) ListAutoPaging added in v1.52.4

func (*MeterService) New added in v1.52.4

func (r *MeterService) New(ctx context.Context, body MeterNewParams, opts ...option.RequestOption) (res *Meter, err error)

func (*MeterService) Unarchive added in v1.52.4

func (r *MeterService) Unarchive(ctx context.Context, id string, opts ...option.RequestOption) (err error)

type MiscService

type MiscService struct {
	Options []option.RequestOption
}

MiscService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewMiscService method instead.

func NewMiscService

func NewMiscService(opts ...option.RequestOption) (r *MiscService)

NewMiscService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*MiscService) ListSupportedCountries added in v1.6.3

func (r *MiscService) ListSupportedCountries(ctx context.Context, opts ...option.RequestOption) (res *[]CountryCode, err error)

type NewCustomerParam added in v1.47.0

type NewCustomerParam struct {
	// Email is required for creating a new customer
	Email param.Field[string] `json:"email" api:"required"`
	// Optional full name of the customer. If provided during session creation, it is
	// persisted and becomes immutable for the session. If omitted here, it can be
	// provided later via the confirm API.
	Name        param.Field[string] `json:"name"`
	PhoneNumber param.Field[string] `json:"phone_number"`
}

func (NewCustomerParam) MarshalJSON added in v1.47.0

func (r NewCustomerParam) MarshalJSON() (data []byte, err error)

type NoteRequestParam added in v1.115.0

type NoteRequestParam struct {
	Note param.Field[string] `json:"note" api:"required"`
}

func (NoteRequestParam) MarshalJSON added in v1.115.0

func (r NoteRequestParam) MarshalJSON() (data []byte, err error)

type OnDemandSubscriptionParam added in v1.51.0

type OnDemandSubscriptionParam struct {
	// If set as True, does not perform any charge and only authorizes payment method
	// details for future use.
	MandateOnly param.Field[bool] `json:"mandate_only" api:"required"`
	// Whether adaptive currency fees should be included in the product_price (true) or
	// added on top (false). This field is ignored if adaptive pricing is not enabled
	// for the business.
	AdaptiveCurrencyFeesInclusive param.Field[bool] `json:"adaptive_currency_fees_inclusive"`
	// Optional currency of the product price. If not specified, defaults to the
	// currency of the product.
	ProductCurrency param.Field[Currency] `json:"product_currency"`
	// Optional product description override for billing and line items. If not
	// specified, the stored description of the product will be used.
	ProductDescription param.Field[string] `json:"product_description"`
	// Product price for the initial charge to customer If not specified the stored
	// price of the product will be used Represented in the lowest denomination of the
	// currency (e.g., cents for USD). For example, to charge $1.00, pass `100`.
	ProductPrice param.Field[int64] `json:"product_price"`
}

func (OnDemandSubscriptionParam) MarshalJSON added in v1.51.0

func (r OnDemandSubscriptionParam) MarshalJSON() (data []byte, err error)

type OneTimeProductCartItem added in v1.6.3

type OneTimeProductCartItem struct {
	ProductID string `json:"product_id" api:"required"`
	Quantity  int64  `json:"quantity" api:"required"`
	// Amount the customer pays if pay_what_you_want is enabled. If disabled then
	// amount will be ignored Represented in the lowest denomination of the currency
	// (e.g., cents for USD). For example, to charge $1.00, pass `100`.
	Amount int64                      `json:"amount" api:"nullable"`
	JSON   oneTimeProductCartItemJSON `json:"-"`
}

func (*OneTimeProductCartItem) UnmarshalJSON added in v1.6.3

func (r *OneTimeProductCartItem) UnmarshalJSON(data []byte) (err error)

type OneTimeProductCartItemParam added in v1.6.3

type OneTimeProductCartItemParam struct {
	ProductID param.Field[string] `json:"product_id" api:"required"`
	Quantity  param.Field[int64]  `json:"quantity" api:"required"`
	// Amount the customer pays if pay_what_you_want is enabled. If disabled then
	// amount will be ignored Represented in the lowest denomination of the currency
	// (e.g., cents for USD). For example, to charge $1.00, pass `100`.
	Amount param.Field[int64] `json:"amount"`
}

func (OneTimeProductCartItemParam) MarshalJSON added in v1.6.3

func (r OneTimeProductCartItemParam) MarshalJSON() (data []byte, err error)

type Payment

type Payment struct {
	// Billing address details for payments
	Billing BillingAddress `json:"billing" api:"required"`
	// brand id this payment belongs to
	BrandID string `json:"brand_id" api:"required"`
	// Identifier of the business associated with the payment
	BusinessID string `json:"business_id" api:"required"`
	// Timestamp when the payment was created
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Currency used for the payment
	Currency Currency `json:"currency" api:"required"`
	// Details about the customer who made the payment
	Customer CustomerLimitedDetails `json:"customer" api:"required"`
	// Whether the digital products purchased in this payment have been delivered.
	DigitalProductsDelivered bool `json:"digital_products_delivered" api:"required"`
	// List of disputes associated with this payment
	Disputes []Dispute `json:"disputes" api:"required"`
	// Whether this payment was created solely to update a subscription's payment
	// method (a zero-/setup-amount charge). `false` for normal charges.
	IsUpdatePaymentMethod bool `json:"is_update_payment_method" api:"required"`
	// Additional custom data associated with the payment
	Metadata Metadata `json:"metadata" api:"required"`
	// Unique identifier for the payment
	PaymentID string `json:"payment_id" api:"required"`
	// Which processor handled this payment. `stripe` / `adyen` for BYOP routes (the
	// merchant's own payment connector); `dodo` for everything Dodo processed itself.
	PaymentProvider PaymentPaymentProvider `json:"payment_provider" api:"required"`
	// List of refunds issued for this payment
	Refunds []RefundListItem `json:"refunds" api:"required"`
	// Retry attempt number for subscription renewal payments. `0` for the original
	// payment, `1`+ for each scheduled off-session retry after a failed renewal.
	// Always `0` for non-subscription payments.
	RetryAttempt int64 `json:"retry_attempt" api:"required"`
	// The amount that will be credited to your Dodo balance after currency conversion
	// and processing. Especially relevant for adaptive pricing where the customer's
	// payment currency differs from your settlement currency.
	SettlementAmount int64 `json:"settlement_amount" api:"required"`
	// The currency in which the settlement_amount will be credited to your Dodo
	// balance. This may differ from the customer's payment currency in adaptive
	// pricing scenarios.
	SettlementCurrency Currency `json:"settlement_currency" api:"required"`
	// Total amount charged to the customer including tax, in the currency's smallest
	// unit (e.g. cents for USD, yen for JPY, fils for KWD — see the currency's decimal
	// places)
	TotalAmount int64 `json:"total_amount" api:"required"`
	// Cardholder name
	CardHolderName string `json:"card_holder_name" api:"nullable"`
	// ISO2 country code of the card
	CardIssuingCountry CountryCode `json:"card_issuing_country" api:"nullable"`
	// The last four digits of the card
	CardLastFour string `json:"card_last_four" api:"nullable"`
	// Card network like VISA, MASTERCARD etc.
	CardNetwork string `json:"card_network" api:"nullable"`
	// The type of card DEBIT or CREDIT
	CardType string `json:"card_type" api:"nullable"`
	// If payment is made using a checkout session, this field is set to the id of the
	// session.
	CheckoutSessionID string `json:"checkout_session_id" api:"nullable"`
	// Customer's responses to custom fields collected during checkout
	CustomFieldResponses []CustomFieldResponse `json:"custom_field_responses" api:"nullable"`
	// DEPRECATED: Use discounts instead. Returns the first discount's ID if present.
	//
	// Deprecated: Use `discounts` instead.
	DiscountID string `json:"discount_id" api:"nullable"`
	// All stacked discounts applied, ordered by position
	Discounts []DiscountDetail `json:"discounts" api:"nullable"`
	// An error code if the payment failed
	ErrorCode string `json:"error_code" api:"nullable"`
	// An error message if the payment failed. When `error_code` is a recognised
	// unified code, this is the merchant-facing headline + recommended action (Payment
	// Details copy) rather than the raw connector text.
	ErrorMessage string `json:"error_message" api:"nullable"`
	// Invoice ID for this payment. Uses India-specific invoice ID if available.
	InvoiceID string `json:"invoice_id" api:"nullable"`
	// URL to download the invoice PDF for this payment.
	InvoiceURL string `json:"invoice_url" api:"nullable"`
	// Checkout URL
	PaymentLink string `json:"payment_link" api:"nullable"`
	// Payment method used by customer (e.g. "card", "bank_transfer")
	PaymentMethod string `json:"payment_method" api:"nullable"`
	// Identifier of the saved payment method used for this payment, if any.
	PaymentMethodID string `json:"payment_method_id" api:"nullable"`
	// Specific type of payment method (e.g. "visa", "mastercard")
	PaymentMethodType string `json:"payment_method_type" api:"nullable"`
	// List of products purchased in a one-time payment
	ProductCart []PaymentProductCart `json:"product_cart" api:"nullable"`
	// Summary of the refund status for this payment. None if no succeeded refunds
	// exist.
	RefundStatus PaymentRefundStatus `json:"refund_status" api:"nullable"`
	// This represents the portion of settlement_amount that corresponds to taxes
	// collected. Especially relevant for adaptive pricing where the tax component must
	// be tracked separately in your Dodo balance.
	SettlementTax int64 `json:"settlement_tax" api:"nullable"`
	// Current status of the payment intent
	Status IntentStatus `json:"status" api:"nullable"`
	// Identifier of the subscription if payment is part of a subscription
	SubscriptionID string `json:"subscription_id" api:"nullable"`
	// Amount of tax collected in the currency's smallest unit (e.g. cents for USD, yen
	// for JPY, fils for KWD)
	Tax int64 `json:"tax" api:"nullable"`
	// Timestamp when the payment was last updated
	UpdatedAt time.Time   `json:"updated_at" api:"nullable" format:"date-time"`
	JSON      paymentJSON `json:"-"`
}

func (*Payment) UnmarshalJSON

func (r *Payment) UnmarshalJSON(data []byte) (err error)

type PaymentCancelledWebhookEvent added in v1.56.0

type PaymentCancelledWebhookEvent struct {
	// The business identifier
	BusinessID string  `json:"business_id" api:"required"`
	Data       Payment `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type PaymentCancelledWebhookEventType `json:"type" api:"required"`
	JSON paymentCancelledWebhookEventJSON `json:"-"`
}

func (*PaymentCancelledWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *PaymentCancelledWebhookEvent) UnmarshalJSON(data []byte) (err error)

type PaymentCancelledWebhookEventType added in v1.56.0

type PaymentCancelledWebhookEventType string

The event type

const (
	PaymentCancelledWebhookEventTypePaymentCancelled PaymentCancelledWebhookEventType = "payment.cancelled"
)

func (PaymentCancelledWebhookEventType) IsKnown added in v1.56.0

type PaymentFailedWebhookEvent added in v1.56.0

type PaymentFailedWebhookEvent struct {
	// The business identifier
	BusinessID string  `json:"business_id" api:"required"`
	Data       Payment `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type PaymentFailedWebhookEventType `json:"type" api:"required"`
	JSON paymentFailedWebhookEventJSON `json:"-"`
}

func (*PaymentFailedWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *PaymentFailedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type PaymentFailedWebhookEventType added in v1.56.0

type PaymentFailedWebhookEventType string

The event type

const (
	PaymentFailedWebhookEventTypePaymentFailed PaymentFailedWebhookEventType = "payment.failed"
)

func (PaymentFailedWebhookEventType) IsKnown added in v1.56.0

func (r PaymentFailedWebhookEventType) IsKnown() bool

type PaymentGetLineItemsResponse added in v1.27.0

type PaymentGetLineItemsResponse struct {
	Currency Currency                          `json:"currency" api:"required"`
	Items    []PaymentGetLineItemsResponseItem `json:"items" api:"required"`
	JSON     paymentGetLineItemsResponseJSON   `json:"-"`
}

func (*PaymentGetLineItemsResponse) UnmarshalJSON added in v1.27.0

func (r *PaymentGetLineItemsResponse) UnmarshalJSON(data []byte) (err error)

type PaymentGetLineItemsResponseItem added in v1.27.0

type PaymentGetLineItemsResponseItem struct {
	Amount           int64                               `json:"amount" api:"required"`
	ItemsID          string                              `json:"items_id" api:"required"`
	RefundableAmount int64                               `json:"refundable_amount" api:"required"`
	Tax              int64                               `json:"tax" api:"required"`
	Description      string                              `json:"description" api:"nullable"`
	Name             string                              `json:"name" api:"nullable"`
	JSON             paymentGetLineItemsResponseItemJSON `json:"-"`
}

func (*PaymentGetLineItemsResponseItem) UnmarshalJSON added in v1.27.0

func (r *PaymentGetLineItemsResponseItem) UnmarshalJSON(data []byte) (err error)

type PaymentListParams

type PaymentListParams struct {
	// filter by Brand id
	BrandID param.Field[string] `query:"brand_id"`
	// Get events after this created time
	CreatedAtGte param.Field[time.Time] `query:"created_at_gte" format:"date-time"`
	// Get events created before this time
	CreatedAtLte param.Field[time.Time] `query:"created_at_lte" format:"date-time"`
	// Filter by currency
	Currency param.Field[PaymentListParamsCurrency] `query:"currency"`
	// Filter by customer id
	CustomerID param.Field[string] `query:"customer_id"`
	// Page number default is 0. Capped to bound OFFSET-based deep pagination, which
	// forces Postgres to scan and discard every preceding row.
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
	// Filter by product id
	ProductID param.Field[string] `query:"product_id"`
	// Filter by status
	Status param.Field[PaymentListParamsStatus] `query:"status"`
	// Filter by subscription id
	SubscriptionID param.Field[string] `query:"subscription_id"`
}

func (PaymentListParams) URLQuery

func (r PaymentListParams) URLQuery() (v url.Values)

URLQuery serializes PaymentListParams's query parameters as `url.Values`.

type PaymentListParamsCurrency added in v1.109.0

type PaymentListParamsCurrency string

Filter by currency

const (
	PaymentListParamsCurrencyAed PaymentListParamsCurrency = "AED"
	PaymentListParamsCurrencyAll PaymentListParamsCurrency = "ALL"
	PaymentListParamsCurrencyAmd PaymentListParamsCurrency = "AMD"
	PaymentListParamsCurrencyAng PaymentListParamsCurrency = "ANG"
	PaymentListParamsCurrencyAoa PaymentListParamsCurrency = "AOA"
	PaymentListParamsCurrencyArs PaymentListParamsCurrency = "ARS"
	PaymentListParamsCurrencyAud PaymentListParamsCurrency = "AUD"
	PaymentListParamsCurrencyAwg PaymentListParamsCurrency = "AWG"
	PaymentListParamsCurrencyAzn PaymentListParamsCurrency = "AZN"
	PaymentListParamsCurrencyBam PaymentListParamsCurrency = "BAM"
	PaymentListParamsCurrencyBbd PaymentListParamsCurrency = "BBD"
	PaymentListParamsCurrencyBdt PaymentListParamsCurrency = "BDT"
	PaymentListParamsCurrencyBgn PaymentListParamsCurrency = "BGN"
	PaymentListParamsCurrencyBhd PaymentListParamsCurrency = "BHD"
	PaymentListParamsCurrencyBif PaymentListParamsCurrency = "BIF"
	PaymentListParamsCurrencyBmd PaymentListParamsCurrency = "BMD"
	PaymentListParamsCurrencyBnd PaymentListParamsCurrency = "BND"
	PaymentListParamsCurrencyBob PaymentListParamsCurrency = "BOB"
	PaymentListParamsCurrencyBrl PaymentListParamsCurrency = "BRL"
	PaymentListParamsCurrencyBsd PaymentListParamsCurrency = "BSD"
	PaymentListParamsCurrencyBwp PaymentListParamsCurrency = "BWP"
	PaymentListParamsCurrencyByn PaymentListParamsCurrency = "BYN"
	PaymentListParamsCurrencyBzd PaymentListParamsCurrency = "BZD"
	PaymentListParamsCurrencyCad PaymentListParamsCurrency = "CAD"
	PaymentListParamsCurrencyChf PaymentListParamsCurrency = "CHF"
	PaymentListParamsCurrencyClp PaymentListParamsCurrency = "CLP"
	PaymentListParamsCurrencyCny PaymentListParamsCurrency = "CNY"
	PaymentListParamsCurrencyCop PaymentListParamsCurrency = "COP"
	PaymentListParamsCurrencyCrc PaymentListParamsCurrency = "CRC"
	PaymentListParamsCurrencyCup PaymentListParamsCurrency = "CUP"
	PaymentListParamsCurrencyCve PaymentListParamsCurrency = "CVE"
	PaymentListParamsCurrencyCzk PaymentListParamsCurrency = "CZK"
	PaymentListParamsCurrencyDjf PaymentListParamsCurrency = "DJF"
	PaymentListParamsCurrencyDkk PaymentListParamsCurrency = "DKK"
	PaymentListParamsCurrencyDop PaymentListParamsCurrency = "DOP"
	PaymentListParamsCurrencyDzd PaymentListParamsCurrency = "DZD"
	PaymentListParamsCurrencyEgp PaymentListParamsCurrency = "EGP"
	PaymentListParamsCurrencyEtb PaymentListParamsCurrency = "ETB"
	PaymentListParamsCurrencyEur PaymentListParamsCurrency = "EUR"
	PaymentListParamsCurrencyFjd PaymentListParamsCurrency = "FJD"
	PaymentListParamsCurrencyFkp PaymentListParamsCurrency = "FKP"
	PaymentListParamsCurrencyGbp PaymentListParamsCurrency = "GBP"
	PaymentListParamsCurrencyGel PaymentListParamsCurrency = "GEL"
	PaymentListParamsCurrencyGhs PaymentListParamsCurrency = "GHS"
	PaymentListParamsCurrencyGip PaymentListParamsCurrency = "GIP"
	PaymentListParamsCurrencyGmd PaymentListParamsCurrency = "GMD"
	PaymentListParamsCurrencyGnf PaymentListParamsCurrency = "GNF"
	PaymentListParamsCurrencyGtq PaymentListParamsCurrency = "GTQ"
	PaymentListParamsCurrencyGyd PaymentListParamsCurrency = "GYD"
	PaymentListParamsCurrencyHkd PaymentListParamsCurrency = "HKD"
	PaymentListParamsCurrencyHnl PaymentListParamsCurrency = "HNL"
	PaymentListParamsCurrencyHrk PaymentListParamsCurrency = "HRK"
	PaymentListParamsCurrencyHtg PaymentListParamsCurrency = "HTG"
	PaymentListParamsCurrencyHuf PaymentListParamsCurrency = "HUF"
	PaymentListParamsCurrencyIdr PaymentListParamsCurrency = "IDR"
	PaymentListParamsCurrencyIls PaymentListParamsCurrency = "ILS"
	PaymentListParamsCurrencyInr PaymentListParamsCurrency = "INR"
	PaymentListParamsCurrencyIqd PaymentListParamsCurrency = "IQD"
	PaymentListParamsCurrencyJmd PaymentListParamsCurrency = "JMD"
	PaymentListParamsCurrencyJod PaymentListParamsCurrency = "JOD"
	PaymentListParamsCurrencyJpy PaymentListParamsCurrency = "JPY"
	PaymentListParamsCurrencyKes PaymentListParamsCurrency = "KES"
	PaymentListParamsCurrencyKgs PaymentListParamsCurrency = "KGS"
	PaymentListParamsCurrencyKhr PaymentListParamsCurrency = "KHR"
	PaymentListParamsCurrencyKmf PaymentListParamsCurrency = "KMF"
	PaymentListParamsCurrencyKrw PaymentListParamsCurrency = "KRW"
	PaymentListParamsCurrencyKwd PaymentListParamsCurrency = "KWD"
	PaymentListParamsCurrencyKyd PaymentListParamsCurrency = "KYD"
	PaymentListParamsCurrencyKzt PaymentListParamsCurrency = "KZT"
	PaymentListParamsCurrencyLak PaymentListParamsCurrency = "LAK"
	PaymentListParamsCurrencyLbp PaymentListParamsCurrency = "LBP"
	PaymentListParamsCurrencyLkr PaymentListParamsCurrency = "LKR"
	PaymentListParamsCurrencyLrd PaymentListParamsCurrency = "LRD"
	PaymentListParamsCurrencyLsl PaymentListParamsCurrency = "LSL"
	PaymentListParamsCurrencyLyd PaymentListParamsCurrency = "LYD"
	PaymentListParamsCurrencyMad PaymentListParamsCurrency = "MAD"
	PaymentListParamsCurrencyMdl PaymentListParamsCurrency = "MDL"
	PaymentListParamsCurrencyMga PaymentListParamsCurrency = "MGA"
	PaymentListParamsCurrencyMkd PaymentListParamsCurrency = "MKD"
	PaymentListParamsCurrencyMmk PaymentListParamsCurrency = "MMK"
	PaymentListParamsCurrencyMnt PaymentListParamsCurrency = "MNT"
	PaymentListParamsCurrencyMop PaymentListParamsCurrency = "MOP"
	PaymentListParamsCurrencyMru PaymentListParamsCurrency = "MRU"
	PaymentListParamsCurrencyMur PaymentListParamsCurrency = "MUR"
	PaymentListParamsCurrencyMvr PaymentListParamsCurrency = "MVR"
	PaymentListParamsCurrencyMwk PaymentListParamsCurrency = "MWK"
	PaymentListParamsCurrencyMxn PaymentListParamsCurrency = "MXN"
	PaymentListParamsCurrencyMyr PaymentListParamsCurrency = "MYR"
	PaymentListParamsCurrencyMzn PaymentListParamsCurrency = "MZN"
	PaymentListParamsCurrencyNad PaymentListParamsCurrency = "NAD"
	PaymentListParamsCurrencyNgn PaymentListParamsCurrency = "NGN"
	PaymentListParamsCurrencyNio PaymentListParamsCurrency = "NIO"
	PaymentListParamsCurrencyNok PaymentListParamsCurrency = "NOK"
	PaymentListParamsCurrencyNpr PaymentListParamsCurrency = "NPR"
	PaymentListParamsCurrencyNzd PaymentListParamsCurrency = "NZD"
	PaymentListParamsCurrencyOmr PaymentListParamsCurrency = "OMR"
	PaymentListParamsCurrencyPab PaymentListParamsCurrency = "PAB"
	PaymentListParamsCurrencyPen PaymentListParamsCurrency = "PEN"
	PaymentListParamsCurrencyPgk PaymentListParamsCurrency = "PGK"
	PaymentListParamsCurrencyPhp PaymentListParamsCurrency = "PHP"
	PaymentListParamsCurrencyPkr PaymentListParamsCurrency = "PKR"
	PaymentListParamsCurrencyPln PaymentListParamsCurrency = "PLN"
	PaymentListParamsCurrencyPyg PaymentListParamsCurrency = "PYG"
	PaymentListParamsCurrencyQar PaymentListParamsCurrency = "QAR"
	PaymentListParamsCurrencyRon PaymentListParamsCurrency = "RON"
	PaymentListParamsCurrencyRsd PaymentListParamsCurrency = "RSD"
	PaymentListParamsCurrencyRub PaymentListParamsCurrency = "RUB"
	PaymentListParamsCurrencyRwf PaymentListParamsCurrency = "RWF"
	PaymentListParamsCurrencySar PaymentListParamsCurrency = "SAR"
	PaymentListParamsCurrencySbd PaymentListParamsCurrency = "SBD"
	PaymentListParamsCurrencyScr PaymentListParamsCurrency = "SCR"
	PaymentListParamsCurrencySek PaymentListParamsCurrency = "SEK"
	PaymentListParamsCurrencySgd PaymentListParamsCurrency = "SGD"
	PaymentListParamsCurrencyShp PaymentListParamsCurrency = "SHP"
	PaymentListParamsCurrencySle PaymentListParamsCurrency = "SLE"
	PaymentListParamsCurrencySll PaymentListParamsCurrency = "SLL"
	PaymentListParamsCurrencySos PaymentListParamsCurrency = "SOS"
	PaymentListParamsCurrencySrd PaymentListParamsCurrency = "SRD"
	PaymentListParamsCurrencySsp PaymentListParamsCurrency = "SSP"
	PaymentListParamsCurrencyStn PaymentListParamsCurrency = "STN"
	PaymentListParamsCurrencySvc PaymentListParamsCurrency = "SVC"
	PaymentListParamsCurrencySzl PaymentListParamsCurrency = "SZL"
	PaymentListParamsCurrencyThb PaymentListParamsCurrency = "THB"
	PaymentListParamsCurrencyTnd PaymentListParamsCurrency = "TND"
	PaymentListParamsCurrencyTop PaymentListParamsCurrency = "TOP"
	PaymentListParamsCurrencyTry PaymentListParamsCurrency = "TRY"
	PaymentListParamsCurrencyTtd PaymentListParamsCurrency = "TTD"
	PaymentListParamsCurrencyTwd PaymentListParamsCurrency = "TWD"
	PaymentListParamsCurrencyTzs PaymentListParamsCurrency = "TZS"
	PaymentListParamsCurrencyUah PaymentListParamsCurrency = "UAH"
	PaymentListParamsCurrencyUgx PaymentListParamsCurrency = "UGX"
	PaymentListParamsCurrencyUsd PaymentListParamsCurrency = "USD"
	PaymentListParamsCurrencyUyu PaymentListParamsCurrency = "UYU"
	PaymentListParamsCurrencyUzs PaymentListParamsCurrency = "UZS"
	PaymentListParamsCurrencyVes PaymentListParamsCurrency = "VES"
	PaymentListParamsCurrencyVnd PaymentListParamsCurrency = "VND"
	PaymentListParamsCurrencyVuv PaymentListParamsCurrency = "VUV"
	PaymentListParamsCurrencyWst PaymentListParamsCurrency = "WST"
	PaymentListParamsCurrencyXaf PaymentListParamsCurrency = "XAF"
	PaymentListParamsCurrencyXcd PaymentListParamsCurrency = "XCD"
	PaymentListParamsCurrencyXof PaymentListParamsCurrency = "XOF"
	PaymentListParamsCurrencyXpf PaymentListParamsCurrency = "XPF"
	PaymentListParamsCurrencyYer PaymentListParamsCurrency = "YER"
	PaymentListParamsCurrencyZar PaymentListParamsCurrency = "ZAR"
	PaymentListParamsCurrencyZmw PaymentListParamsCurrency = "ZMW"
)

func (PaymentListParamsCurrency) IsKnown added in v1.109.0

func (r PaymentListParamsCurrency) IsKnown() bool

type PaymentListParamsStatus added in v0.17.0

type PaymentListParamsStatus string

Filter by status

const (
	PaymentListParamsStatusSucceeded                      PaymentListParamsStatus = "succeeded"
	PaymentListParamsStatusFailed                         PaymentListParamsStatus = "failed"
	PaymentListParamsStatusCancelled                      PaymentListParamsStatus = "cancelled"
	PaymentListParamsStatusProcessing                     PaymentListParamsStatus = "processing"
	PaymentListParamsStatusRequiresCustomerAction         PaymentListParamsStatus = "requires_customer_action"
	PaymentListParamsStatusRequiresMerchantAction         PaymentListParamsStatus = "requires_merchant_action"
	PaymentListParamsStatusRequiresPaymentMethod          PaymentListParamsStatus = "requires_payment_method"
	PaymentListParamsStatusRequiresConfirmation           PaymentListParamsStatus = "requires_confirmation"
	PaymentListParamsStatusRequiresCapture                PaymentListParamsStatus = "requires_capture"
	PaymentListParamsStatusPartiallyCaptured              PaymentListParamsStatus = "partially_captured"
	PaymentListParamsStatusPartiallyCapturedAndCapturable PaymentListParamsStatus = "partially_captured_and_capturable"
)

func (PaymentListParamsStatus) IsKnown added in v0.17.0

func (r PaymentListParamsStatus) IsKnown() bool

type PaymentListResponse

type PaymentListResponse struct {
	BrandID                  string                 `json:"brand_id" api:"required"`
	CreatedAt                time.Time              `json:"created_at" api:"required" format:"date-time"`
	Currency                 Currency               `json:"currency" api:"required"`
	Customer                 CustomerLimitedDetails `json:"customer" api:"required"`
	DigitalProductsDelivered bool                   `json:"digital_products_delivered" api:"required"`
	HasLicenseKey            bool                   `json:"has_license_key" api:"required"`
	// Arbitrary key-value metadata. Values can be string, integer, number, or boolean.
	Metadata  Metadata `json:"metadata" api:"required"`
	PaymentID string   `json:"payment_id" api:"required"`
	// Which processor handled this payment. `stripe` / `adyen` for BYOP routes (the
	// merchant's own payment connector); `dodo` for everything Dodo processed itself.
	PaymentProvider PaymentListResponsePaymentProvider `json:"payment_provider" api:"required"`
	TotalAmount     int64                              `json:"total_amount" api:"required"`
	// The last four digits of the card
	CardLastFour string `json:"card_last_four" api:"nullable"`
	// Card network like VISA, MASTERCARD etc.
	CardNetwork string `json:"card_network" api:"nullable"`
	// The most recent dispute status for this payment. None if no disputes exist.
	DisputeStatus DisputeStatus `json:"dispute_status" api:"nullable"`
	// Invoice ID for this payment. Uses India-specific invoice ID if available.
	InvoiceID string `json:"invoice_id" api:"nullable"`
	// URL to download the invoice PDF for this payment.
	InvoiceURL        string `json:"invoice_url" api:"nullable"`
	PaymentMethod     string `json:"payment_method" api:"nullable"`
	PaymentMethodType string `json:"payment_method_type" api:"nullable"`
	// Summary of the refund status for this payment. None if no succeeded refunds
	// exist.
	RefundStatus   PaymentRefundStatus     `json:"refund_status" api:"nullable"`
	Status         IntentStatus            `json:"status" api:"nullable"`
	SubscriptionID string                  `json:"subscription_id" api:"nullable"`
	JSON           paymentListResponseJSON `json:"-"`
}

func (*PaymentListResponse) UnmarshalJSON

func (r *PaymentListResponse) UnmarshalJSON(data []byte) (err error)

type PaymentListResponsePaymentProvider added in v1.102.1

type PaymentListResponsePaymentProvider string

Which processor handled this payment. `stripe` / `adyen` for BYOP routes (the merchant's own payment connector); `dodo` for everything Dodo processed itself.

const (
	PaymentListResponsePaymentProviderStripe PaymentListResponsePaymentProvider = "stripe"
	PaymentListResponsePaymentProviderAdyen  PaymentListResponsePaymentProvider = "adyen"
	PaymentListResponsePaymentProviderDodo   PaymentListResponsePaymentProvider = "dodo"
)

func (PaymentListResponsePaymentProvider) IsKnown added in v1.102.1

type PaymentMethodTypes added in v1.43.0

type PaymentMethodTypes string

All supported payment method types.

Used for disabled-payment-methods filtering and validation.

const (
	PaymentMethodTypesACH                        PaymentMethodTypes = "ach"
	PaymentMethodTypesAffirm                     PaymentMethodTypes = "affirm"
	PaymentMethodTypesAfterpayClearpay           PaymentMethodTypes = "afterpay_clearpay"
	PaymentMethodTypesAlfamart                   PaymentMethodTypes = "alfamart"
	PaymentMethodTypesAliPay                     PaymentMethodTypes = "ali_pay"
	PaymentMethodTypesAliPayHk                   PaymentMethodTypes = "ali_pay_hk"
	PaymentMethodTypesAlma                       PaymentMethodTypes = "alma"
	PaymentMethodTypesAmazonPay                  PaymentMethodTypes = "amazon_pay"
	PaymentMethodTypesApplePay                   PaymentMethodTypes = "apple_pay"
	PaymentMethodTypesAtome                      PaymentMethodTypes = "atome"
	PaymentMethodTypesBacs                       PaymentMethodTypes = "bacs"
	PaymentMethodTypesBancontactCard             PaymentMethodTypes = "bancontact_card"
	PaymentMethodTypesBecs                       PaymentMethodTypes = "becs"
	PaymentMethodTypesBenefit                    PaymentMethodTypes = "benefit"
	PaymentMethodTypesBizum                      PaymentMethodTypes = "bizum"
	PaymentMethodTypesBlik                       PaymentMethodTypes = "blik"
	PaymentMethodTypesBoleto                     PaymentMethodTypes = "boleto"
	PaymentMethodTypesBcaBankTransfer            PaymentMethodTypes = "bca_bank_transfer"
	PaymentMethodTypesBniVa                      PaymentMethodTypes = "bni_va"
	PaymentMethodTypesBriVa                      PaymentMethodTypes = "bri_va"
	PaymentMethodTypesCardRedirect               PaymentMethodTypes = "card_redirect"
	PaymentMethodTypesCimbVa                     PaymentMethodTypes = "cimb_va"
	PaymentMethodTypesClassic                    PaymentMethodTypes = "classic"
	PaymentMethodTypesCredit                     PaymentMethodTypes = "credit"
	PaymentMethodTypesCryptoCurrency             PaymentMethodTypes = "crypto_currency"
	PaymentMethodTypesCashapp                    PaymentMethodTypes = "cashapp"
	PaymentMethodTypesDana                       PaymentMethodTypes = "dana"
	PaymentMethodTypesDanamonVa                  PaymentMethodTypes = "danamon_va"
	PaymentMethodTypesDebit                      PaymentMethodTypes = "debit"
	PaymentMethodTypesDuitNow                    PaymentMethodTypes = "duit_now"
	PaymentMethodTypesEfecty                     PaymentMethodTypes = "efecty"
	PaymentMethodTypesEft                        PaymentMethodTypes = "eft"
	PaymentMethodTypesEps                        PaymentMethodTypes = "eps"
	PaymentMethodTypesFps                        PaymentMethodTypes = "fps"
	PaymentMethodTypesEvoucher                   PaymentMethodTypes = "evoucher"
	PaymentMethodTypesGiropay                    PaymentMethodTypes = "giropay"
	PaymentMethodTypesGivex                      PaymentMethodTypes = "givex"
	PaymentMethodTypesGooglePay                  PaymentMethodTypes = "google_pay"
	PaymentMethodTypesGoPay                      PaymentMethodTypes = "go_pay"
	PaymentMethodTypesGcash                      PaymentMethodTypes = "gcash"
	PaymentMethodTypesIdeal                      PaymentMethodTypes = "ideal"
	PaymentMethodTypesInterac                    PaymentMethodTypes = "interac"
	PaymentMethodTypesIndomaret                  PaymentMethodTypes = "indomaret"
	PaymentMethodTypesKlarna                     PaymentMethodTypes = "klarna"
	PaymentMethodTypesKakaoPay                   PaymentMethodTypes = "kakao_pay"
	PaymentMethodTypesLocalBankRedirect          PaymentMethodTypes = "local_bank_redirect"
	PaymentMethodTypesMandiriVa                  PaymentMethodTypes = "mandiri_va"
	PaymentMethodTypesKnet                       PaymentMethodTypes = "knet"
	PaymentMethodTypesMBWay                      PaymentMethodTypes = "mb_way"
	PaymentMethodTypesMobilePay                  PaymentMethodTypes = "mobile_pay"
	PaymentMethodTypesMomo                       PaymentMethodTypes = "momo"
	PaymentMethodTypesMomoAtm                    PaymentMethodTypes = "momo_atm"
	PaymentMethodTypesMultibanco                 PaymentMethodTypes = "multibanco"
	PaymentMethodTypesOnlineBankingThailand      PaymentMethodTypes = "online_banking_thailand"
	PaymentMethodTypesOnlineBankingCzechRepublic PaymentMethodTypes = "online_banking_czech_republic"
	PaymentMethodTypesOnlineBankingFinland       PaymentMethodTypes = "online_banking_finland"
	PaymentMethodTypesOnlineBankingFpx           PaymentMethodTypes = "online_banking_fpx"
	PaymentMethodTypesOnlineBankingPoland        PaymentMethodTypes = "online_banking_poland"
	PaymentMethodTypesOnlineBankingSlovakia      PaymentMethodTypes = "online_banking_slovakia"
	PaymentMethodTypesOxxo                       PaymentMethodTypes = "oxxo"
	PaymentMethodTypesPagoEfectivo               PaymentMethodTypes = "pago_efectivo"
	PaymentMethodTypesPermataBankTransfer        PaymentMethodTypes = "permata_bank_transfer"
	PaymentMethodTypesOpenBankingUk              PaymentMethodTypes = "open_banking_uk"
	PaymentMethodTypesPayBright                  PaymentMethodTypes = "pay_bright"
	PaymentMethodTypesPaypal                     PaymentMethodTypes = "paypal"
	PaymentMethodTypesPaze                       PaymentMethodTypes = "paze"
	PaymentMethodTypesPix                        PaymentMethodTypes = "pix"
	PaymentMethodTypesPaySafeCard                PaymentMethodTypes = "pay_safe_card"
	PaymentMethodTypesPrzelewy24                 PaymentMethodTypes = "przelewy24"
	PaymentMethodTypesPromptPay                  PaymentMethodTypes = "prompt_pay"
	PaymentMethodTypesPse                        PaymentMethodTypes = "pse"
	PaymentMethodTypesRedCompra                  PaymentMethodTypes = "red_compra"
	PaymentMethodTypesRedPagos                   PaymentMethodTypes = "red_pagos"
	PaymentMethodTypesSamsungPay                 PaymentMethodTypes = "samsung_pay"
	PaymentMethodTypesSepa                       PaymentMethodTypes = "sepa"
	PaymentMethodTypesSepaBankTransfer           PaymentMethodTypes = "sepa_bank_transfer"
	PaymentMethodTypesSofort                     PaymentMethodTypes = "sofort"
	PaymentMethodTypesSwish                      PaymentMethodTypes = "swish"
	PaymentMethodTypesTouchNGo                   PaymentMethodTypes = "touch_n_go"
	PaymentMethodTypesTrustly                    PaymentMethodTypes = "trustly"
	PaymentMethodTypesTwint                      PaymentMethodTypes = "twint"
	PaymentMethodTypesUpiCollect                 PaymentMethodTypes = "upi_collect"
	PaymentMethodTypesUpiIntent                  PaymentMethodTypes = "upi_intent"
	PaymentMethodTypesVipps                      PaymentMethodTypes = "vipps"
	PaymentMethodTypesVietQr                     PaymentMethodTypes = "viet_qr"
	PaymentMethodTypesVenmo                      PaymentMethodTypes = "venmo"
	PaymentMethodTypesWalley                     PaymentMethodTypes = "walley"
	PaymentMethodTypesWeChatPay                  PaymentMethodTypes = "we_chat_pay"
	PaymentMethodTypesSevenEleven                PaymentMethodTypes = "seven_eleven"
	PaymentMethodTypesLawson                     PaymentMethodTypes = "lawson"
	PaymentMethodTypesMiniStop                   PaymentMethodTypes = "mini_stop"
	PaymentMethodTypesFamilyMart                 PaymentMethodTypes = "family_mart"
	PaymentMethodTypesSeicomart                  PaymentMethodTypes = "seicomart"
	PaymentMethodTypesPayEasy                    PaymentMethodTypes = "pay_easy"
	PaymentMethodTypesLocalBankTransfer          PaymentMethodTypes = "local_bank_transfer"
	PaymentMethodTypesMifinity                   PaymentMethodTypes = "mifinity"
	PaymentMethodTypesOpenBankingPis             PaymentMethodTypes = "open_banking_pis"
	PaymentMethodTypesDirectCarrierBilling       PaymentMethodTypes = "direct_carrier_billing"
	PaymentMethodTypesInstantBankTransfer        PaymentMethodTypes = "instant_bank_transfer"
	PaymentMethodTypesBillie                     PaymentMethodTypes = "billie"
	PaymentMethodTypesZip                        PaymentMethodTypes = "zip"
	PaymentMethodTypesRevolutPay                 PaymentMethodTypes = "revolut_pay"
	PaymentMethodTypesNaverPay                   PaymentMethodTypes = "naver_pay"
	PaymentMethodTypesPayco                      PaymentMethodTypes = "payco"
	PaymentMethodTypesSatispay                   PaymentMethodTypes = "satispay"
)

func (PaymentMethodTypes) IsKnown added in v1.43.0

func (r PaymentMethodTypes) IsKnown() bool

type PaymentNewParams

type PaymentNewParams struct {
	// Billing address details for the payment
	Billing param.Field[BillingAddressParam] `json:"billing" api:"required"`
	// Customer information for the payment
	Customer param.Field[CustomerRequestUnionParam] `json:"customer" api:"required"`
	// List of products in the cart. Must contain at least 1 and at most 100 items.
	ProductCart param.Field[[]OneTimeProductCartItemParam] `json:"product_cart" api:"required"`
	// Whether adaptive currency fees should be included in the price (true) or added
	// on top (false). If not specified, defaults to the business-level setting.
	AdaptiveCurrencyFeesInclusive param.Field[bool] `json:"adaptive_currency_fees_inclusive"`
	// List of payment methods allowed during checkout.
	//
	// Customers will **never** see payment methods that are **not** in this list.
	// However, adding a method here **does not guarantee** customers will see it.
	// Availability still depends on other factors (e.g., customer location, merchant
	// settings).
	AllowedPaymentMethodTypes param.Field[[]PaymentMethodTypes] `json:"allowed_payment_method_types"`
	// Fix the currency in which the end customer is billed. If Dodo Payments cannot
	// support that currency for this transaction, it will not proceed
	BillingCurrency param.Field[Currency] `json:"billing_currency"`
	// Optional business / legal name associated with the tax id. When provided
	// together with a valid tax id for a B2B purchase, this name is rendered on the
	// invoice instead of the customer's personal name.
	CustomerBusinessName param.Field[string] `json:"customer_business_name"`
	// DEPRECATED: Use discount_codes instead. Cannot be used together with
	// discount_codes.
	DiscountCode param.Field[string] `json:"discount_code"`
	// Stacked discount codes to apply, in order of application. Max 20. Cannot be used
	// together with discount_code.
	DiscountCodes param.Field[[]string] `json:"discount_codes"`
	// Override merchant default 3DS behaviour for this payment
	Force3DS param.Field[bool] `json:"force_3ds"`
	// Additional metadata associated with the payment. Defaults to empty if not
	// provided.
	Metadata param.Field[MetadataParam] `json:"metadata"`
	// Whether to generate a payment link. Defaults to false if not specified.
	PaymentLink param.Field[bool] `json:"payment_link"`
	// Optional payment method ID to use for this payment. If provided, customer_id
	// must also be provided. The payment method will be validated for eligibility with
	// the payment's currency.
	PaymentMethodID param.Field[string] `json:"payment_method_id"`
	// If true, redirects the customer immediately after payment completion False by
	// default
	RedirectImmediately param.Field[bool] `json:"redirect_immediately"`
	// If true, the customer's phone number is required to create this payment.
	// Typically set alongside `payment_link=true` so merchants can enforce phone
	// collection on the hosted payment page. Defaults to false.
	RequirePhoneNumber param.Field[bool] `json:"require_phone_number"`
	// Optional URL to redirect the customer after payment. Must be a valid URL if
	// provided.
	ReturnURL param.Field[string] `json:"return_url"`
	// If true, returns a shortened payment link. Defaults to false if not specified.
	ShortLink param.Field[bool] `json:"short_link"`
	// Display saved payment methods of a returning customer False by default
	ShowSavedPaymentMethods param.Field[bool] `json:"show_saved_payment_methods"`
	// Tax ID in case the payment is B2B. If tax id validation fails the payment
	// creation will fail
	TaxID param.Field[string] `json:"tax_id"`
}

func (PaymentNewParams) MarshalJSON

func (r PaymentNewParams) MarshalJSON() (data []byte, err error)

type PaymentNewResponse

type PaymentNewResponse struct {
	// Client secret used to load Dodo checkout SDK NOTE : Dodo checkout SDK will be
	// coming soon
	ClientSecret string `json:"client_secret" api:"required"`
	// Limited details about the customer making the payment
	Customer CustomerLimitedDetails `json:"customer" api:"required"`
	// Additional metadata associated with the payment
	Metadata Metadata `json:"metadata" api:"required"`
	// Unique identifier for the payment
	PaymentID string `json:"payment_id" api:"required"`
	// Total amount of the payment in the currency's smallest unit (cents for USD, yen
	// for JPY, fils for KWD)
	TotalAmount int64 `json:"total_amount" api:"required"`
	// DEPRECATED: Use discount_ids instead. Returns the first discount's ID if
	// present.
	//
	// Deprecated: Use `discounts` instead.
	DiscountID string `json:"discount_id" api:"nullable"`
	// All stacked discount IDs applied, in order of application
	DiscountIDs []string `json:"discount_ids" api:"nullable"`
	// Expiry timestamp of the payment link
	ExpiresOn time.Time `json:"expires_on" api:"nullable" format:"date-time"`
	// Optional URL to a hosted payment page
	PaymentLink string `json:"payment_link" api:"nullable"`
	// Optional list of products included in the payment
	ProductCart []OneTimeProductCartItem `json:"product_cart" api:"nullable"`
	JSON        paymentNewResponseJSON   `json:"-"`
}

func (*PaymentNewResponse) UnmarshalJSON

func (r *PaymentNewResponse) UnmarshalJSON(data []byte) (err error)

type PaymentPaymentProvider added in v1.102.1

type PaymentPaymentProvider string

Which processor handled this payment. `stripe` / `adyen` for BYOP routes (the merchant's own payment connector); `dodo` for everything Dodo processed itself.

const (
	PaymentPaymentProviderStripe PaymentPaymentProvider = "stripe"
	PaymentPaymentProviderAdyen  PaymentPaymentProvider = "adyen"
	PaymentPaymentProviderDodo   PaymentPaymentProvider = "dodo"
)

func (PaymentPaymentProvider) IsKnown added in v1.102.1

func (r PaymentPaymentProvider) IsKnown() bool

type PaymentProcessingWebhookEvent added in v1.56.0

type PaymentProcessingWebhookEvent struct {
	// The business identifier
	BusinessID string  `json:"business_id" api:"required"`
	Data       Payment `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type PaymentProcessingWebhookEventType `json:"type" api:"required"`
	JSON paymentProcessingWebhookEventJSON `json:"-"`
}

func (*PaymentProcessingWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *PaymentProcessingWebhookEvent) UnmarshalJSON(data []byte) (err error)

type PaymentProcessingWebhookEventType added in v1.56.0

type PaymentProcessingWebhookEventType string

The event type

const (
	PaymentProcessingWebhookEventTypePaymentProcessing PaymentProcessingWebhookEventType = "payment.processing"
)

func (PaymentProcessingWebhookEventType) IsKnown added in v1.56.0

type PaymentProductCart

type PaymentProductCart struct {
	ProductID string                 `json:"product_id" api:"required"`
	Quantity  int64                  `json:"quantity" api:"required"`
	JSON      paymentProductCartJSON `json:"-"`
}

func (*PaymentProductCart) UnmarshalJSON

func (r *PaymentProductCart) UnmarshalJSON(data []byte) (err error)

type PaymentRefundStatus added in v1.81.0

type PaymentRefundStatus string
const (
	PaymentRefundStatusPartial PaymentRefundStatus = "partial"
	PaymentRefundStatusFull    PaymentRefundStatus = "full"
)

func (PaymentRefundStatus) IsKnown added in v1.81.0

func (r PaymentRefundStatus) IsKnown() bool

type PaymentService

type PaymentService struct {
	Options []option.RequestOption
}

PaymentService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewPaymentService method instead.

func NewPaymentService

func NewPaymentService(opts ...option.RequestOption) (r *PaymentService)

NewPaymentService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*PaymentService) Get

func (r *PaymentService) Get(ctx context.Context, paymentID string, opts ...option.RequestOption) (res *Payment, err error)

func (*PaymentService) GetLineItems added in v1.27.0

func (r *PaymentService) GetLineItems(ctx context.Context, paymentID string, opts ...option.RequestOption) (res *PaymentGetLineItemsResponse, err error)

func (*PaymentService) GetRetryState added in v1.115.0

func (r *PaymentService) GetRetryState(ctx context.Context, paymentID string, opts ...option.RequestOption) (res *ManualRetryState, err error)

func (*PaymentService) New deprecated

Deprecated: deprecated

func (*PaymentService) Retry added in v1.115.0

func (r *PaymentService) Retry(ctx context.Context, paymentID string, opts ...option.RequestOption) (res *ManualRetry, err error)

type PaymentSucceededWebhookEvent added in v1.56.0

type PaymentSucceededWebhookEvent struct {
	// The business identifier
	BusinessID string  `json:"business_id" api:"required"`
	Data       Payment `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type PaymentSucceededWebhookEventType `json:"type" api:"required"`
	JSON paymentSucceededWebhookEventJSON `json:"-"`
}

func (*PaymentSucceededWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *PaymentSucceededWebhookEvent) UnmarshalJSON(data []byte) (err error)

type PaymentSucceededWebhookEventType added in v1.56.0

type PaymentSucceededWebhookEventType string

The event type

const (
	PaymentSucceededWebhookEventTypePaymentSucceeded PaymentSucceededWebhookEventType = "payment.succeeded"
)

func (PaymentSucceededWebhookEventType) IsKnown added in v1.56.0

type PayoutBreakupDetailListParams added in v1.93.0

type PayoutBreakupDetailListParams struct {
	// Page number (0-indexed). Default: 0.
	PageNumber param.Field[int64] `query:"page_number"`
	// Number of items per page. Default: 10, Max: 100.
	PageSize param.Field[int64] `query:"page_size"`
}

func (PayoutBreakupDetailListParams) URLQuery added in v1.93.0

func (r PayoutBreakupDetailListParams) URLQuery() (v url.Values)

URLQuery serializes PayoutBreakupDetailListParams's query parameters as `url.Values`.

type PayoutBreakupDetailListResponse added in v1.93.0

type PayoutBreakupDetailListResponse struct {
	// Unique identifier of the balance ledger entry.
	ID string `json:"id" api:"required"`
	// Timestamp when this entry was created.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// The type of balance ledger event (e.g., "payment", "refund", "dispute",
	// "payment_fees").
	EventType string `json:"event_type" api:"required"`
	// Original amount in the original currency, in that currency's smallest unit
	// (cents for USD, yen for JPY, fils for KWD).
	OriginalAmount int64 `json:"original_amount" api:"required"`
	// Original currency as ISO 4217 code (e.g., "USD", "EUR").
	OriginalCurrency string `json:"original_currency" api:"required"`
	// Amount in the payout's currency, in that currency's smallest unit (cents for
	// USD, yen for JPY, fils for KWD). Uses cumulative rounding to ensure sum matches
	// payout total exactly.
	PayoutCurrencyAmount int64 `json:"payout_currency_amount" api:"required"`
	// USD equivalent of the original amount (in cents).
	UsdEquivalentAmount int64 `json:"usd_equivalent_amount" api:"required"`
	// Human-readable description of the transaction.
	Description string `json:"description" api:"nullable"`
	// ID of the related object (e.g., payment ID, refund ID) if applicable.
	ReferenceObjectID string                              `json:"reference_object_id" api:"nullable"`
	JSON              payoutBreakupDetailListResponseJSON `json:"-"`
}

Individual balance ledger entry for a payout, with amounts pro-rated into the payout's currency.

func (*PayoutBreakupDetailListResponse) UnmarshalJSON added in v1.93.0

func (r *PayoutBreakupDetailListResponse) UnmarshalJSON(data []byte) (err error)

type PayoutBreakupDetailService added in v1.93.0

type PayoutBreakupDetailService struct {
	Options []option.RequestOption
}

PayoutBreakupDetailService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewPayoutBreakupDetailService method instead.

func NewPayoutBreakupDetailService added in v1.93.0

func NewPayoutBreakupDetailService(opts ...option.RequestOption) (r *PayoutBreakupDetailService)

NewPayoutBreakupDetailService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*PayoutBreakupDetailService) DownloadCsv added in v1.93.0

func (r *PayoutBreakupDetailService) DownloadCsv(ctx context.Context, payoutID string, opts ...option.RequestOption) (err error)

Downloads the complete payout breakup as a CSV file. Each row represents a balance ledger entry with columns: Ledger ID, Event Type, Original Amount, Original Currency, Reference Object ID, Description, Created At, USD Equivalent Amount, and Payout Currency Amount.

func (*PayoutBreakupDetailService) List added in v1.93.0

Returns paginated individual balance ledger entries for a payout, with each entry's amount pro-rated into the payout's currency. Supports pagination via `page_size` (default 10, max 100) and `page_number` (default 0) query parameters.

func (*PayoutBreakupDetailService) ListAutoPaging added in v1.93.0

Returns paginated individual balance ledger entries for a payout, with each entry's amount pro-rated into the payout's currency. Supports pagination via `page_size` (default 10, max 100) and `page_number` (default 0) query parameters.

type PayoutBreakupGetResponse added in v1.93.0

type PayoutBreakupGetResponse struct {
	// The type of balance ledger event (e.g., "payment", "refund", "dispute",
	// "payment_fees").
	EventType string `json:"event_type" api:"required"`
	// Total amount for this event type in the payout's currency, in that currency's
	// smallest unit (cents for USD, yen for JPY, fils for KWD).
	Total int64                        `json:"total" api:"required"`
	JSON  payoutBreakupGetResponseJSON `json:"-"`
}

Payout breakup aggregated by event type, with amounts in the payout's currency.

func (*PayoutBreakupGetResponse) UnmarshalJSON added in v1.93.0

func (r *PayoutBreakupGetResponse) UnmarshalJSON(data []byte) (err error)

type PayoutBreakupService added in v1.93.0

type PayoutBreakupService struct {
	Options []option.RequestOption
	Details *PayoutBreakupDetailService
}

PayoutBreakupService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewPayoutBreakupService method instead.

func NewPayoutBreakupService added in v1.93.0

func NewPayoutBreakupService(opts ...option.RequestOption) (r *PayoutBreakupService)

NewPayoutBreakupService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*PayoutBreakupService) Get added in v1.93.0

func (r *PayoutBreakupService) Get(ctx context.Context, payoutID string, opts ...option.RequestOption) (res *[]PayoutBreakupGetResponse, err error)

Returns the breakdown of a payout by event type (payments, refunds, disputes, fees, etc.) in the payout's currency. Each amount is proportionally allocated based on USD equivalent values, ensuring the total sums exactly to the payout amount.

type PayoutCreatedWebhookEvent added in v1.110.0

type PayoutCreatedWebhookEvent struct {
	// The business identifier
	BusinessID string                        `json:"business_id" api:"required"`
	Data       PayoutCreatedWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type PayoutCreatedWebhookEventType `json:"type" api:"required"`
	JSON payoutCreatedWebhookEventJSON `json:"-"`
}

func (*PayoutCreatedWebhookEvent) UnmarshalJSON added in v1.110.0

func (r *PayoutCreatedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type PayoutCreatedWebhookEventData added in v1.110.0

type PayoutCreatedWebhookEventData struct {
	// The total amount of the payout.
	Amount int64 `json:"amount" api:"required"`
	// The unique identifier of the business associated with the payout.
	BusinessID string `json:"business_id" api:"required"`
	// The total value of chargebacks associated with the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Chargebacks int64 `json:"chargebacks" api:"required"`
	// The timestamp when the payout was created, in UTC.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// The currency of the payout, represented as an ISO 4217 currency code.
	Currency Currency `json:"currency" api:"required"`
	// The fee charged for processing the payout.
	Fee int64 `json:"fee" api:"required"`
	// The payment method used for the payout (e.g., bank transfer, card, etc.).
	PaymentMethod string `json:"payment_method" api:"required"`
	// The unique identifier of the payout.
	PayoutID string `json:"payout_id" api:"required"`
	// The total value of refunds associated with the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Refunds int64 `json:"refunds" api:"required"`
	// The current status of the payout.
	Status PayoutCreatedWebhookEventDataStatus `json:"status" api:"required"`
	// The tax applied to the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Tax int64 `json:"tax" api:"required"`
	// The timestamp when the payout was last updated, in UTC.
	UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
	// The name of the payout recipient or purpose.
	Name string `json:"name" api:"nullable"`
	// The URL of the document associated with the payout.
	PayoutDocumentURL string `json:"payout_document_url" api:"nullable"`
	// Any additional remarks or notes associated with the payout.
	Remarks string                            `json:"remarks" api:"nullable"`
	JSON    payoutCreatedWebhookEventDataJSON `json:"-"`
}

func (*PayoutCreatedWebhookEventData) UnmarshalJSON added in v1.110.0

func (r *PayoutCreatedWebhookEventData) UnmarshalJSON(data []byte) (err error)

type PayoutCreatedWebhookEventDataStatus added in v1.110.0

type PayoutCreatedWebhookEventDataStatus string

The current status of the payout.

const (
	PayoutCreatedWebhookEventDataStatusNotInitiated PayoutCreatedWebhookEventDataStatus = "not_initiated"
	PayoutCreatedWebhookEventDataStatusInProgress   PayoutCreatedWebhookEventDataStatus = "in_progress"
	PayoutCreatedWebhookEventDataStatusOnHold       PayoutCreatedWebhookEventDataStatus = "on_hold"
	PayoutCreatedWebhookEventDataStatusFailed       PayoutCreatedWebhookEventDataStatus = "failed"
	PayoutCreatedWebhookEventDataStatusSuccess      PayoutCreatedWebhookEventDataStatus = "success"
)

func (PayoutCreatedWebhookEventDataStatus) IsKnown added in v1.110.0

type PayoutCreatedWebhookEventType added in v1.110.0

type PayoutCreatedWebhookEventType string

The event type

const (
	PayoutCreatedWebhookEventTypePayoutCreated PayoutCreatedWebhookEventType = "payout.created"
)

func (PayoutCreatedWebhookEventType) IsKnown added in v1.110.0

func (r PayoutCreatedWebhookEventType) IsKnown() bool

type PayoutFailedWebhookEvent added in v1.110.0

type PayoutFailedWebhookEvent struct {
	// The business identifier
	BusinessID string                       `json:"business_id" api:"required"`
	Data       PayoutFailedWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type PayoutFailedWebhookEventType `json:"type" api:"required"`
	JSON payoutFailedWebhookEventJSON `json:"-"`
}

func (*PayoutFailedWebhookEvent) UnmarshalJSON added in v1.110.0

func (r *PayoutFailedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type PayoutFailedWebhookEventData added in v1.110.0

type PayoutFailedWebhookEventData struct {
	// The total amount of the payout.
	Amount int64 `json:"amount" api:"required"`
	// The unique identifier of the business associated with the payout.
	BusinessID string `json:"business_id" api:"required"`
	// The total value of chargebacks associated with the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Chargebacks int64 `json:"chargebacks" api:"required"`
	// The timestamp when the payout was created, in UTC.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// The currency of the payout, represented as an ISO 4217 currency code.
	Currency Currency `json:"currency" api:"required"`
	// The fee charged for processing the payout.
	Fee int64 `json:"fee" api:"required"`
	// The payment method used for the payout (e.g., bank transfer, card, etc.).
	PaymentMethod string `json:"payment_method" api:"required"`
	// The unique identifier of the payout.
	PayoutID string `json:"payout_id" api:"required"`
	// The total value of refunds associated with the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Refunds int64 `json:"refunds" api:"required"`
	// The current status of the payout.
	Status PayoutFailedWebhookEventDataStatus `json:"status" api:"required"`
	// The tax applied to the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Tax int64 `json:"tax" api:"required"`
	// The timestamp when the payout was last updated, in UTC.
	UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
	// The name of the payout recipient or purpose.
	Name string `json:"name" api:"nullable"`
	// The URL of the document associated with the payout.
	PayoutDocumentURL string `json:"payout_document_url" api:"nullable"`
	// Any additional remarks or notes associated with the payout.
	Remarks string                           `json:"remarks" api:"nullable"`
	JSON    payoutFailedWebhookEventDataJSON `json:"-"`
}

func (*PayoutFailedWebhookEventData) UnmarshalJSON added in v1.110.0

func (r *PayoutFailedWebhookEventData) UnmarshalJSON(data []byte) (err error)

type PayoutFailedWebhookEventDataStatus added in v1.110.0

type PayoutFailedWebhookEventDataStatus string

The current status of the payout.

const (
	PayoutFailedWebhookEventDataStatusNotInitiated PayoutFailedWebhookEventDataStatus = "not_initiated"
	PayoutFailedWebhookEventDataStatusInProgress   PayoutFailedWebhookEventDataStatus = "in_progress"
	PayoutFailedWebhookEventDataStatusOnHold       PayoutFailedWebhookEventDataStatus = "on_hold"
	PayoutFailedWebhookEventDataStatusFailed       PayoutFailedWebhookEventDataStatus = "failed"
	PayoutFailedWebhookEventDataStatusSuccess      PayoutFailedWebhookEventDataStatus = "success"
)

func (PayoutFailedWebhookEventDataStatus) IsKnown added in v1.110.0

type PayoutFailedWebhookEventType added in v1.110.0

type PayoutFailedWebhookEventType string

The event type

const (
	PayoutFailedWebhookEventTypePayoutFailed PayoutFailedWebhookEventType = "payout.failed"
)

func (PayoutFailedWebhookEventType) IsKnown added in v1.110.0

func (r PayoutFailedWebhookEventType) IsKnown() bool

type PayoutInProgressWebhookEvent added in v1.110.0

type PayoutInProgressWebhookEvent struct {
	// The business identifier
	BusinessID string                           `json:"business_id" api:"required"`
	Data       PayoutInProgressWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type PayoutInProgressWebhookEventType `json:"type" api:"required"`
	JSON payoutInProgressWebhookEventJSON `json:"-"`
}

func (*PayoutInProgressWebhookEvent) UnmarshalJSON added in v1.110.0

func (r *PayoutInProgressWebhookEvent) UnmarshalJSON(data []byte) (err error)

type PayoutInProgressWebhookEventData added in v1.110.0

type PayoutInProgressWebhookEventData struct {
	// The total amount of the payout.
	Amount int64 `json:"amount" api:"required"`
	// The unique identifier of the business associated with the payout.
	BusinessID string `json:"business_id" api:"required"`
	// The total value of chargebacks associated with the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Chargebacks int64 `json:"chargebacks" api:"required"`
	// The timestamp when the payout was created, in UTC.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// The currency of the payout, represented as an ISO 4217 currency code.
	Currency Currency `json:"currency" api:"required"`
	// The fee charged for processing the payout.
	Fee int64 `json:"fee" api:"required"`
	// The payment method used for the payout (e.g., bank transfer, card, etc.).
	PaymentMethod string `json:"payment_method" api:"required"`
	// The unique identifier of the payout.
	PayoutID string `json:"payout_id" api:"required"`
	// The total value of refunds associated with the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Refunds int64 `json:"refunds" api:"required"`
	// The current status of the payout.
	Status PayoutInProgressWebhookEventDataStatus `json:"status" api:"required"`
	// The tax applied to the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Tax int64 `json:"tax" api:"required"`
	// The timestamp when the payout was last updated, in UTC.
	UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
	// The name of the payout recipient or purpose.
	Name string `json:"name" api:"nullable"`
	// The URL of the document associated with the payout.
	PayoutDocumentURL string `json:"payout_document_url" api:"nullable"`
	// Any additional remarks or notes associated with the payout.
	Remarks string                               `json:"remarks" api:"nullable"`
	JSON    payoutInProgressWebhookEventDataJSON `json:"-"`
}

func (*PayoutInProgressWebhookEventData) UnmarshalJSON added in v1.110.0

func (r *PayoutInProgressWebhookEventData) UnmarshalJSON(data []byte) (err error)

type PayoutInProgressWebhookEventDataStatus added in v1.110.0

type PayoutInProgressWebhookEventDataStatus string

The current status of the payout.

const (
	PayoutInProgressWebhookEventDataStatusNotInitiated PayoutInProgressWebhookEventDataStatus = "not_initiated"
	PayoutInProgressWebhookEventDataStatusInProgress   PayoutInProgressWebhookEventDataStatus = "in_progress"
	PayoutInProgressWebhookEventDataStatusOnHold       PayoutInProgressWebhookEventDataStatus = "on_hold"
	PayoutInProgressWebhookEventDataStatusFailed       PayoutInProgressWebhookEventDataStatus = "failed"
	PayoutInProgressWebhookEventDataStatusSuccess      PayoutInProgressWebhookEventDataStatus = "success"
)

func (PayoutInProgressWebhookEventDataStatus) IsKnown added in v1.110.0

type PayoutInProgressWebhookEventType added in v1.110.0

type PayoutInProgressWebhookEventType string

The event type

const (
	PayoutInProgressWebhookEventTypePayoutInProgress PayoutInProgressWebhookEventType = "payout.in_progress"
)

func (PayoutInProgressWebhookEventType) IsKnown added in v1.110.0

type PayoutListParams

type PayoutListParams struct {
	// Get payouts created after this time (inclusive)
	CreatedAtGte param.Field[time.Time] `query:"created_at_gte" format:"date-time"`
	// Get payouts created before this time (inclusive)
	CreatedAtLte param.Field[time.Time] `query:"created_at_lte" format:"date-time"`
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
}

func (PayoutListParams) URLQuery

func (r PayoutListParams) URLQuery() (v url.Values)

URLQuery serializes PayoutListParams's query parameters as `url.Values`.

type PayoutListResponse

type PayoutListResponse struct {
	// The total amount of the payout.
	Amount int64 `json:"amount" api:"required"`
	// The unique identifier of the business associated with the payout.
	BusinessID string `json:"business_id" api:"required"`
	// The total value of chargebacks associated with the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Chargebacks int64 `json:"chargebacks" api:"required"`
	// The timestamp when the payout was created, in UTC.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// The currency of the payout, represented as an ISO 4217 currency code.
	Currency Currency `json:"currency" api:"required"`
	// The fee charged for processing the payout.
	Fee int64 `json:"fee" api:"required"`
	// The payment method used for the payout (e.g., bank transfer, card, etc.).
	PaymentMethod string `json:"payment_method" api:"required"`
	// The unique identifier of the payout.
	PayoutID string `json:"payout_id" api:"required"`
	// The total value of refunds associated with the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Refunds int64 `json:"refunds" api:"required"`
	// The current status of the payout.
	Status PayoutListResponseStatus `json:"status" api:"required"`
	// The tax applied to the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Tax int64 `json:"tax" api:"required"`
	// The timestamp when the payout was last updated, in UTC.
	UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
	// The name of the payout recipient or purpose.
	Name string `json:"name" api:"nullable"`
	// The URL of the document associated with the payout.
	PayoutDocumentURL string `json:"payout_document_url" api:"nullable"`
	// Any additional remarks or notes associated with the payout.
	Remarks string                 `json:"remarks" api:"nullable"`
	JSON    payoutListResponseJSON `json:"-"`
}

func (*PayoutListResponse) UnmarshalJSON

func (r *PayoutListResponse) UnmarshalJSON(data []byte) (err error)

type PayoutListResponseStatus

type PayoutListResponseStatus string

The current status of the payout.

const (
	PayoutListResponseStatusNotInitiated PayoutListResponseStatus = "not_initiated"
	PayoutListResponseStatusInProgress   PayoutListResponseStatus = "in_progress"
	PayoutListResponseStatusOnHold       PayoutListResponseStatus = "on_hold"
	PayoutListResponseStatusFailed       PayoutListResponseStatus = "failed"
	PayoutListResponseStatusSuccess      PayoutListResponseStatus = "success"
)

func (PayoutListResponseStatus) IsKnown

func (r PayoutListResponseStatus) IsKnown() bool

type PayoutOnHoldWebhookEvent added in v1.110.0

type PayoutOnHoldWebhookEvent struct {
	// The business identifier
	BusinessID string                       `json:"business_id" api:"required"`
	Data       PayoutOnHoldWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type PayoutOnHoldWebhookEventType `json:"type" api:"required"`
	JSON payoutOnHoldWebhookEventJSON `json:"-"`
}

func (*PayoutOnHoldWebhookEvent) UnmarshalJSON added in v1.110.0

func (r *PayoutOnHoldWebhookEvent) UnmarshalJSON(data []byte) (err error)

type PayoutOnHoldWebhookEventData added in v1.110.0

type PayoutOnHoldWebhookEventData struct {
	// The total amount of the payout.
	Amount int64 `json:"amount" api:"required"`
	// The unique identifier of the business associated with the payout.
	BusinessID string `json:"business_id" api:"required"`
	// The total value of chargebacks associated with the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Chargebacks int64 `json:"chargebacks" api:"required"`
	// The timestamp when the payout was created, in UTC.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// The currency of the payout, represented as an ISO 4217 currency code.
	Currency Currency `json:"currency" api:"required"`
	// The fee charged for processing the payout.
	Fee int64 `json:"fee" api:"required"`
	// The payment method used for the payout (e.g., bank transfer, card, etc.).
	PaymentMethod string `json:"payment_method" api:"required"`
	// The unique identifier of the payout.
	PayoutID string `json:"payout_id" api:"required"`
	// The total value of refunds associated with the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Refunds int64 `json:"refunds" api:"required"`
	// The current status of the payout.
	Status PayoutOnHoldWebhookEventDataStatus `json:"status" api:"required"`
	// The tax applied to the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Tax int64 `json:"tax" api:"required"`
	// The timestamp when the payout was last updated, in UTC.
	UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
	// The name of the payout recipient or purpose.
	Name string `json:"name" api:"nullable"`
	// The URL of the document associated with the payout.
	PayoutDocumentURL string `json:"payout_document_url" api:"nullable"`
	// Any additional remarks or notes associated with the payout.
	Remarks string                           `json:"remarks" api:"nullable"`
	JSON    payoutOnHoldWebhookEventDataJSON `json:"-"`
}

func (*PayoutOnHoldWebhookEventData) UnmarshalJSON added in v1.110.0

func (r *PayoutOnHoldWebhookEventData) UnmarshalJSON(data []byte) (err error)

type PayoutOnHoldWebhookEventDataStatus added in v1.110.0

type PayoutOnHoldWebhookEventDataStatus string

The current status of the payout.

const (
	PayoutOnHoldWebhookEventDataStatusNotInitiated PayoutOnHoldWebhookEventDataStatus = "not_initiated"
	PayoutOnHoldWebhookEventDataStatusInProgress   PayoutOnHoldWebhookEventDataStatus = "in_progress"
	PayoutOnHoldWebhookEventDataStatusOnHold       PayoutOnHoldWebhookEventDataStatus = "on_hold"
	PayoutOnHoldWebhookEventDataStatusFailed       PayoutOnHoldWebhookEventDataStatus = "failed"
	PayoutOnHoldWebhookEventDataStatusSuccess      PayoutOnHoldWebhookEventDataStatus = "success"
)

func (PayoutOnHoldWebhookEventDataStatus) IsKnown added in v1.110.0

type PayoutOnHoldWebhookEventType added in v1.110.0

type PayoutOnHoldWebhookEventType string

The event type

const (
	PayoutOnHoldWebhookEventTypePayoutOnHold PayoutOnHoldWebhookEventType = "payout.on_hold"
)

func (PayoutOnHoldWebhookEventType) IsKnown added in v1.110.0

func (r PayoutOnHoldWebhookEventType) IsKnown() bool

type PayoutService

type PayoutService struct {
	Options []option.RequestOption
	Breakup *PayoutBreakupService
}

PayoutService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewPayoutService method instead.

func NewPayoutService

func NewPayoutService(opts ...option.RequestOption) (r *PayoutService)

NewPayoutService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

type PayoutSuccessWebhookEvent added in v1.110.0

type PayoutSuccessWebhookEvent struct {
	// The business identifier
	BusinessID string                        `json:"business_id" api:"required"`
	Data       PayoutSuccessWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type PayoutSuccessWebhookEventType `json:"type" api:"required"`
	JSON payoutSuccessWebhookEventJSON `json:"-"`
}

func (*PayoutSuccessWebhookEvent) UnmarshalJSON added in v1.110.0

func (r *PayoutSuccessWebhookEvent) UnmarshalJSON(data []byte) (err error)

type PayoutSuccessWebhookEventData added in v1.110.0

type PayoutSuccessWebhookEventData struct {
	// The total amount of the payout.
	Amount int64 `json:"amount" api:"required"`
	// The unique identifier of the business associated with the payout.
	BusinessID string `json:"business_id" api:"required"`
	// The total value of chargebacks associated with the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Chargebacks int64 `json:"chargebacks" api:"required"`
	// The timestamp when the payout was created, in UTC.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// The currency of the payout, represented as an ISO 4217 currency code.
	Currency Currency `json:"currency" api:"required"`
	// The fee charged for processing the payout.
	Fee int64 `json:"fee" api:"required"`
	// The payment method used for the payout (e.g., bank transfer, card, etc.).
	PaymentMethod string `json:"payment_method" api:"required"`
	// The unique identifier of the payout.
	PayoutID string `json:"payout_id" api:"required"`
	// The total value of refunds associated with the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Refunds int64 `json:"refunds" api:"required"`
	// The current status of the payout.
	Status PayoutSuccessWebhookEventDataStatus `json:"status" api:"required"`
	// The tax applied to the payout.
	//
	// Deprecated: Use the v3 payout breakup endpoints instead. Will be removed in a
	// future release.
	Tax int64 `json:"tax" api:"required"`
	// The timestamp when the payout was last updated, in UTC.
	UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
	// The name of the payout recipient or purpose.
	Name string `json:"name" api:"nullable"`
	// The URL of the document associated with the payout.
	PayoutDocumentURL string `json:"payout_document_url" api:"nullable"`
	// Any additional remarks or notes associated with the payout.
	Remarks string                            `json:"remarks" api:"nullable"`
	JSON    payoutSuccessWebhookEventDataJSON `json:"-"`
}

func (*PayoutSuccessWebhookEventData) UnmarshalJSON added in v1.110.0

func (r *PayoutSuccessWebhookEventData) UnmarshalJSON(data []byte) (err error)

type PayoutSuccessWebhookEventDataStatus added in v1.110.0

type PayoutSuccessWebhookEventDataStatus string

The current status of the payout.

const (
	PayoutSuccessWebhookEventDataStatusNotInitiated PayoutSuccessWebhookEventDataStatus = "not_initiated"
	PayoutSuccessWebhookEventDataStatusInProgress   PayoutSuccessWebhookEventDataStatus = "in_progress"
	PayoutSuccessWebhookEventDataStatusOnHold       PayoutSuccessWebhookEventDataStatus = "on_hold"
	PayoutSuccessWebhookEventDataStatusFailed       PayoutSuccessWebhookEventDataStatus = "failed"
	PayoutSuccessWebhookEventDataStatusSuccess      PayoutSuccessWebhookEventDataStatus = "success"
)

func (PayoutSuccessWebhookEventDataStatus) IsKnown added in v1.110.0

type PayoutSuccessWebhookEventType added in v1.110.0

type PayoutSuccessWebhookEventType string

The event type

const (
	PayoutSuccessWebhookEventTypePayoutSuccess PayoutSuccessWebhookEventType = "payout.success"
)

func (PayoutSuccessWebhookEventType) IsKnown added in v1.110.0

func (r PayoutSuccessWebhookEventType) IsKnown() bool

type Price added in v1.6.3

type Price struct {
	// The currency in which the payment is made.
	Currency Currency  `json:"currency" api:"required"`
	Type     PriceType `json:"type" api:"required"`
	// Deprecated: use `discount_bps` instead.
	//
	// Discount applied to the price, represented as a percentage (0 to 100). A
	// response rounds this value to the nearest whole percent. Defaults to `0`.
	//
	// Deprecated: deprecated
	Discount int64 `json:"discount"`
	// Discount applied to the price, in basis points. 100 basis points make one
	// percent, so `1250` is a discount of 12.5%.
	//
	// Use this field for a discount with a fraction of a percent. A request that sends
	// this field ignores `discount`. A value of `0` gives no discount.
	DiscountBps int64 `json:"discount_bps" api:"nullable"`
	// The fixed payment amount. Represented in the lowest denomination of the currency
	// (e.g., cents for USD). For example, to charge $1.00, pass `100`.
	FixedPrice int64 `json:"fixed_price"`
	// This field can have the runtime type of [[]AddMeterToPrice].
	Meters interface{} `json:"meters"`
	// Indicates whether the customer can pay any amount they choose. If set to `true`,
	// the [`price`](Self::price) field is the minimum amount.
	PayWhatYouWant bool `json:"pay_what_you_want"`
	// Number of units for the payment frequency. For example, a value of `1` with a
	// `payment_frequency_interval` of `month` represents monthly payments.
	PaymentFrequencyCount int64 `json:"payment_frequency_count"`
	// The time interval for the payment frequency (e.g., day, month, year).
	PaymentFrequencyInterval TimeInterval `json:"payment_frequency_interval"`
	// The payment amount, in the smallest denomination of the currency (e.g., cents
	// for USD). For example, to charge $1.00, pass `100`.
	//
	// If [`pay_what_you_want`](Self::pay_what_you_want) is set to `true`, this field
	// represents the **minimum** amount the customer must pay.
	Price int64 `json:"price"`
	// Opts this price in to purchasing power parity. The business must also enable
	// purchasing power parity. The discount percentage per country is always
	// business-wide. Defaults to `false`.
	PurchasingPowerParity bool `json:"purchasing_power_parity"`
	// Number of units for the subscription period. For example, a value of `12` with a
	// `subscription_period_interval` of `month` represents a one-year subscription.
	SubscriptionPeriodCount int64 `json:"subscription_period_count"`
	// The time interval for the subscription period (e.g., day, month, year).
	SubscriptionPeriodInterval TimeInterval `json:"subscription_period_interval"`
	// A suggested price for the user to pay. This value is only considered if
	// [`pay_what_you_want`](Self::pay_what_you_want) is `true`. Otherwise, it is
	// ignored.
	SuggestedPrice int64 `json:"suggested_price" api:"nullable"`
	// Indicates if the price is tax inclusive.
	TaxInclusive bool `json:"tax_inclusive" api:"nullable"`
	// Amount charged today for a paid trial, in the price currency's minor units.
	// Requires `trial_period_days > 0`. Omit or null for a free trial (the default).
	TrialAmount int64 `json:"trial_amount" api:"nullable"`
	// Whether discount codes reduce the trial charge. Defaults to false. Only
	// meaningful when a paid trial is configured.
	TrialApplyDiscounts bool `json:"trial_apply_discounts" api:"nullable"`
	// Let a customer start a free trial with no card. Defaults to false.
	TrialPaymentMethodOptional bool `json:"trial_payment_method_optional"`
	// Number of days for the trial period. A value of `0` indicates no trial period.
	TrialPeriodDays int64 `json:"trial_period_days"`
	// Let a customer start a subscription with no card, when the amount due today is
	// `0` (a native `0` price, or a 100% discount). Defaults to false.
	ZeroAmountPaymentMethodOptional bool      `json:"zero_amount_payment_method_optional"`
	JSON                            priceJSON `json:"-"`
	// contains filtered or unexported fields
}

One-time price details.

func (Price) AsUnion added in v1.6.3

func (r Price) AsUnion() PriceUnion

AsUnion returns a PriceUnion interface which you can cast to the specific types for more type safety.

Possible runtime types of the union are PriceOneTimePrice, PriceRecurringPrice, PriceUsageBasedPrice.

func (*Price) UnmarshalJSON added in v1.6.3

func (r *Price) UnmarshalJSON(data []byte) (err error)

type PriceOneTimePrice added in v1.6.3

type PriceOneTimePrice struct {
	// The currency in which the payment is made.
	Currency Currency `json:"currency" api:"required"`
	// The payment amount, in the smallest denomination of the currency (e.g., cents
	// for USD). For example, to charge $1.00, pass `100`.
	//
	// If [`pay_what_you_want`](Self::pay_what_you_want) is set to `true`, this field
	// represents the **minimum** amount the customer must pay.
	Price int64                 `json:"price" api:"required"`
	Type  PriceOneTimePriceType `json:"type" api:"required"`
	// Deprecated: use `discount_bps` instead.
	//
	// Discount applied to the price, represented as a percentage (0 to 100). A
	// response rounds this value to the nearest whole percent. Defaults to `0`.
	//
	// Deprecated: deprecated
	Discount int64 `json:"discount"`
	// Discount applied to the price, in basis points. 100 basis points make one
	// percent, so `1250` is a discount of 12.5%.
	//
	// Use this field for a discount with a fraction of a percent. A request that sends
	// this field ignores `discount`. A value of `0` gives no discount.
	DiscountBps int64 `json:"discount_bps" api:"nullable"`
	// Indicates whether the customer can pay any amount they choose. If set to `true`,
	// the [`price`](Self::price) field is the minimum amount.
	PayWhatYouWant bool `json:"pay_what_you_want"`
	// Opts this price in to purchasing power parity. The business must also enable
	// purchasing power parity. The discount percentage per country is always
	// business-wide. Defaults to `false`.
	PurchasingPowerParity bool `json:"purchasing_power_parity"`
	// A suggested price for the user to pay. This value is only considered if
	// [`pay_what_you_want`](Self::pay_what_you_want) is `true`. Otherwise, it is
	// ignored.
	SuggestedPrice int64 `json:"suggested_price" api:"nullable"`
	// Indicates if the price is tax inclusive.
	TaxInclusive bool                  `json:"tax_inclusive" api:"nullable"`
	JSON         priceOneTimePriceJSON `json:"-"`
}

One-time price details.

func (*PriceOneTimePrice) UnmarshalJSON added in v1.6.3

func (r *PriceOneTimePrice) UnmarshalJSON(data []byte) (err error)

type PriceOneTimePriceParam added in v1.6.3

type PriceOneTimePriceParam struct {
	// The currency in which the payment is made.
	Currency param.Field[Currency] `json:"currency" api:"required"`
	// The payment amount, in the smallest denomination of the currency (e.g., cents
	// for USD). For example, to charge $1.00, pass `100`.
	//
	// If [`pay_what_you_want`](Self::pay_what_you_want) is set to `true`, this field
	// represents the **minimum** amount the customer must pay.
	Price param.Field[int64]                 `json:"price" api:"required"`
	Type  param.Field[PriceOneTimePriceType] `json:"type" api:"required"`
	// Deprecated: use `discount_bps` instead.
	//
	// Discount applied to the price, represented as a percentage (0 to 100). A
	// response rounds this value to the nearest whole percent. Defaults to `0`.
	//
	// Deprecated: deprecated
	Discount param.Field[int64] `json:"discount"`
	// Discount applied to the price, in basis points. 100 basis points make one
	// percent, so `1250` is a discount of 12.5%.
	//
	// Use this field for a discount with a fraction of a percent. A request that sends
	// this field ignores `discount`. A value of `0` gives no discount.
	DiscountBps param.Field[int64] `json:"discount_bps"`
	// Indicates whether the customer can pay any amount they choose. If set to `true`,
	// the [`price`](Self::price) field is the minimum amount.
	PayWhatYouWant param.Field[bool] `json:"pay_what_you_want"`
	// Opts this price in to purchasing power parity. The business must also enable
	// purchasing power parity. The discount percentage per country is always
	// business-wide. Defaults to `false`.
	PurchasingPowerParity param.Field[bool] `json:"purchasing_power_parity"`
	// A suggested price for the user to pay. This value is only considered if
	// [`pay_what_you_want`](Self::pay_what_you_want) is `true`. Otherwise, it is
	// ignored.
	SuggestedPrice param.Field[int64] `json:"suggested_price"`
	// Indicates if the price is tax inclusive.
	TaxInclusive param.Field[bool] `json:"tax_inclusive"`
}

One-time price details.

func (PriceOneTimePriceParam) MarshalJSON added in v1.6.3

func (r PriceOneTimePriceParam) MarshalJSON() (data []byte, err error)

type PriceOneTimePriceType added in v1.6.3

type PriceOneTimePriceType string
const (
	PriceOneTimePriceTypeOneTimePrice PriceOneTimePriceType = "one_time_price"
)

func (PriceOneTimePriceType) IsKnown added in v1.6.3

func (r PriceOneTimePriceType) IsKnown() bool

type PriceParam added in v1.6.3

type PriceParam struct {
	// The currency in which the payment is made.
	Currency param.Field[Currency]  `json:"currency" api:"required"`
	Type     param.Field[PriceType] `json:"type" api:"required"`
	// Deprecated: use `discount_bps` instead.
	//
	// Discount applied to the price, represented as a percentage (0 to 100). A
	// response rounds this value to the nearest whole percent. Defaults to `0`.
	//
	// Deprecated: deprecated
	Discount param.Field[int64] `json:"discount"`
	// Discount applied to the price, in basis points. 100 basis points make one
	// percent, so `1250` is a discount of 12.5%.
	//
	// Use this field for a discount with a fraction of a percent. A request that sends
	// this field ignores `discount`. A value of `0` gives no discount.
	DiscountBps param.Field[int64] `json:"discount_bps"`
	// The fixed payment amount. Represented in the lowest denomination of the currency
	// (e.g., cents for USD). For example, to charge $1.00, pass `100`.
	FixedPrice param.Field[int64]       `json:"fixed_price"`
	Meters     param.Field[interface{}] `json:"meters"`
	// Indicates whether the customer can pay any amount they choose. If set to `true`,
	// the [`price`](Self::price) field is the minimum amount.
	PayWhatYouWant param.Field[bool] `json:"pay_what_you_want"`
	// Number of units for the payment frequency. For example, a value of `1` with a
	// `payment_frequency_interval` of `month` represents monthly payments.
	PaymentFrequencyCount param.Field[int64] `json:"payment_frequency_count"`
	// The time interval for the payment frequency (e.g., day, month, year).
	PaymentFrequencyInterval param.Field[TimeInterval] `json:"payment_frequency_interval"`
	// The payment amount, in the smallest denomination of the currency (e.g., cents
	// for USD). For example, to charge $1.00, pass `100`.
	//
	// If [`pay_what_you_want`](Self::pay_what_you_want) is set to `true`, this field
	// represents the **minimum** amount the customer must pay.
	Price param.Field[int64] `json:"price"`
	// Opts this price in to purchasing power parity. The business must also enable
	// purchasing power parity. The discount percentage per country is always
	// business-wide. Defaults to `false`.
	PurchasingPowerParity param.Field[bool] `json:"purchasing_power_parity"`
	// Number of units for the subscription period. For example, a value of `12` with a
	// `subscription_period_interval` of `month` represents a one-year subscription.
	SubscriptionPeriodCount param.Field[int64] `json:"subscription_period_count"`
	// The time interval for the subscription period (e.g., day, month, year).
	SubscriptionPeriodInterval param.Field[TimeInterval] `json:"subscription_period_interval"`
	// A suggested price for the user to pay. This value is only considered if
	// [`pay_what_you_want`](Self::pay_what_you_want) is `true`. Otherwise, it is
	// ignored.
	SuggestedPrice param.Field[int64] `json:"suggested_price"`
	// Indicates if the price is tax inclusive.
	TaxInclusive param.Field[bool] `json:"tax_inclusive"`
	// Amount charged today for a paid trial, in the price currency's minor units.
	// Requires `trial_period_days > 0`. Omit or null for a free trial (the default).
	TrialAmount param.Field[int64] `json:"trial_amount"`
	// Whether discount codes reduce the trial charge. Defaults to false. Only
	// meaningful when a paid trial is configured.
	TrialApplyDiscounts param.Field[bool] `json:"trial_apply_discounts"`
	// Let a customer start a free trial with no card. Defaults to false.
	TrialPaymentMethodOptional param.Field[bool] `json:"trial_payment_method_optional"`
	// Number of days for the trial period. A value of `0` indicates no trial period.
	TrialPeriodDays param.Field[int64] `json:"trial_period_days"`
	// Let a customer start a subscription with no card, when the amount due today is
	// `0` (a native `0` price, or a 100% discount). Defaults to false.
	ZeroAmountPaymentMethodOptional param.Field[bool] `json:"zero_amount_payment_method_optional"`
}

One-time price details.

func (PriceParam) MarshalJSON added in v1.6.3

func (r PriceParam) MarshalJSON() (data []byte, err error)

type PriceRecurringPrice added in v1.6.3

type PriceRecurringPrice struct {
	// The currency in which the payment is made.
	Currency Currency `json:"currency" api:"required"`
	// Number of units for the payment frequency. For example, a value of `1` with a
	// `payment_frequency_interval` of `month` represents monthly payments.
	PaymentFrequencyCount int64 `json:"payment_frequency_count" api:"required"`
	// The time interval for the payment frequency (e.g., day, month, year).
	PaymentFrequencyInterval TimeInterval `json:"payment_frequency_interval" api:"required"`
	// The payment amount. Represented in the lowest denomination of the currency
	// (e.g., cents for USD). For example, to charge $1.00, pass `100`.
	Price int64 `json:"price" api:"required"`
	// Number of units for the subscription period. For example, a value of `12` with a
	// `subscription_period_interval` of `month` represents a one-year subscription.
	SubscriptionPeriodCount int64 `json:"subscription_period_count" api:"required"`
	// The time interval for the subscription period (e.g., day, month, year).
	SubscriptionPeriodInterval TimeInterval            `json:"subscription_period_interval" api:"required"`
	Type                       PriceRecurringPriceType `json:"type" api:"required"`
	// Deprecated: use `discount_bps` instead.
	//
	// Discount applied to the price, represented as a percentage (0 to 100). A
	// response rounds this value to the nearest whole percent. Defaults to `0`.
	//
	// Deprecated: deprecated
	Discount int64 `json:"discount"`
	// Discount applied to the price, in basis points. 100 basis points make one
	// percent, so `1250` is a discount of 12.5%.
	//
	// Use this field for a discount with a fraction of a percent. A request that sends
	// this field ignores `discount`. A value of `0` gives no discount.
	DiscountBps int64 `json:"discount_bps" api:"nullable"`
	// Opts this price in to purchasing power parity. The business must also enable
	// purchasing power parity. The discount percentage per country is always
	// business-wide. Defaults to `false`.
	PurchasingPowerParity bool `json:"purchasing_power_parity"`
	// Indicates if the price is tax inclusive
	TaxInclusive bool `json:"tax_inclusive" api:"nullable"`
	// Amount charged today for a paid trial, in the price currency's minor units.
	// Requires `trial_period_days > 0`. Omit or null for a free trial (the default).
	TrialAmount int64 `json:"trial_amount" api:"nullable"`
	// Whether discount codes reduce the trial charge. Defaults to false. Only
	// meaningful when a paid trial is configured.
	TrialApplyDiscounts bool `json:"trial_apply_discounts" api:"nullable"`
	// Let a customer start a free trial with no card. Defaults to false.
	TrialPaymentMethodOptional bool `json:"trial_payment_method_optional"`
	// Number of days for the trial period. A value of `0` indicates no trial period.
	TrialPeriodDays int64 `json:"trial_period_days"`
	// Let a customer start a subscription with no card, when the amount due today is
	// `0` (a native `0` price, or a 100% discount). Defaults to false.
	ZeroAmountPaymentMethodOptional bool                    `json:"zero_amount_payment_method_optional"`
	JSON                            priceRecurringPriceJSON `json:"-"`
}

Recurring price details.

func (*PriceRecurringPrice) UnmarshalJSON added in v1.6.3

func (r *PriceRecurringPrice) UnmarshalJSON(data []byte) (err error)

type PriceRecurringPriceParam added in v1.6.3

type PriceRecurringPriceParam struct {
	// The currency in which the payment is made.
	Currency param.Field[Currency] `json:"currency" api:"required"`
	// Number of units for the payment frequency. For example, a value of `1` with a
	// `payment_frequency_interval` of `month` represents monthly payments.
	PaymentFrequencyCount param.Field[int64] `json:"payment_frequency_count" api:"required"`
	// The time interval for the payment frequency (e.g., day, month, year).
	PaymentFrequencyInterval param.Field[TimeInterval] `json:"payment_frequency_interval" api:"required"`
	// The payment amount. Represented in the lowest denomination of the currency
	// (e.g., cents for USD). For example, to charge $1.00, pass `100`.
	Price param.Field[int64] `json:"price" api:"required"`
	// Number of units for the subscription period. For example, a value of `12` with a
	// `subscription_period_interval` of `month` represents a one-year subscription.
	SubscriptionPeriodCount param.Field[int64] `json:"subscription_period_count" api:"required"`
	// The time interval for the subscription period (e.g., day, month, year).
	SubscriptionPeriodInterval param.Field[TimeInterval]            `json:"subscription_period_interval" api:"required"`
	Type                       param.Field[PriceRecurringPriceType] `json:"type" api:"required"`
	// Deprecated: use `discount_bps` instead.
	//
	// Discount applied to the price, represented as a percentage (0 to 100). A
	// response rounds this value to the nearest whole percent. Defaults to `0`.
	//
	// Deprecated: deprecated
	Discount param.Field[int64] `json:"discount"`
	// Discount applied to the price, in basis points. 100 basis points make one
	// percent, so `1250` is a discount of 12.5%.
	//
	// Use this field for a discount with a fraction of a percent. A request that sends
	// this field ignores `discount`. A value of `0` gives no discount.
	DiscountBps param.Field[int64] `json:"discount_bps"`
	// Opts this price in to purchasing power parity. The business must also enable
	// purchasing power parity. The discount percentage per country is always
	// business-wide. Defaults to `false`.
	PurchasingPowerParity param.Field[bool] `json:"purchasing_power_parity"`
	// Indicates if the price is tax inclusive
	TaxInclusive param.Field[bool] `json:"tax_inclusive"`
	// Amount charged today for a paid trial, in the price currency's minor units.
	// Requires `trial_period_days > 0`. Omit or null for a free trial (the default).
	TrialAmount param.Field[int64] `json:"trial_amount"`
	// Whether discount codes reduce the trial charge. Defaults to false. Only
	// meaningful when a paid trial is configured.
	TrialApplyDiscounts param.Field[bool] `json:"trial_apply_discounts"`
	// Let a customer start a free trial with no card. Defaults to false.
	TrialPaymentMethodOptional param.Field[bool] `json:"trial_payment_method_optional"`
	// Number of days for the trial period. A value of `0` indicates no trial period.
	TrialPeriodDays param.Field[int64] `json:"trial_period_days"`
	// Let a customer start a subscription with no card, when the amount due today is
	// `0` (a native `0` price, or a 100% discount). Defaults to false.
	ZeroAmountPaymentMethodOptional param.Field[bool] `json:"zero_amount_payment_method_optional"`
}

Recurring price details.

func (PriceRecurringPriceParam) MarshalJSON added in v1.6.3

func (r PriceRecurringPriceParam) MarshalJSON() (data []byte, err error)

type PriceRecurringPriceType added in v1.6.3

type PriceRecurringPriceType string
const (
	PriceRecurringPriceTypeRecurringPrice PriceRecurringPriceType = "recurring_price"
)

func (PriceRecurringPriceType) IsKnown added in v1.6.3

func (r PriceRecurringPriceType) IsKnown() bool

type PriceType added in v1.6.3

type PriceType string
const (
	PriceTypeOneTimePrice    PriceType = "one_time_price"
	PriceTypeRecurringPrice  PriceType = "recurring_price"
	PriceTypeUsageBasedPrice PriceType = "usage_based_price"
)

func (PriceType) IsKnown added in v1.6.3

func (r PriceType) IsKnown() bool

type PriceUnion added in v1.6.3

type PriceUnion interface {
	// contains filtered or unexported methods
}

One-time price details.

Union satisfied by PriceOneTimePrice, PriceRecurringPrice or PriceUsageBasedPrice.

type PriceUnionParam added in v1.6.3

type PriceUnionParam interface {
	// contains filtered or unexported methods
}

One-time price details.

Satisfied by PriceOneTimePriceParam, PriceRecurringPriceParam, PriceUsageBasedPriceParam, PriceParam.

type PriceUsageBasedPrice added in v1.52.4

type PriceUsageBasedPrice struct {
	// The currency in which the payment is made.
	Currency Currency `json:"currency" api:"required"`
	// The fixed payment amount. Represented in the lowest denomination of the currency
	// (e.g., cents for USD). For example, to charge $1.00, pass `100`.
	FixedPrice int64 `json:"fixed_price" api:"required"`
	// Number of units for the payment frequency. For example, a value of `1` with a
	// `payment_frequency_interval` of `month` represents monthly payments.
	PaymentFrequencyCount int64 `json:"payment_frequency_count" api:"required"`
	// The time interval for the payment frequency (e.g., day, month, year).
	PaymentFrequencyInterval TimeInterval `json:"payment_frequency_interval" api:"required"`
	// Number of units for the subscription period. For example, a value of `12` with a
	// `subscription_period_interval` of `month` represents a one-year subscription.
	SubscriptionPeriodCount int64 `json:"subscription_period_count" api:"required"`
	// The time interval for the subscription period (e.g., day, month, year).
	SubscriptionPeriodInterval TimeInterval             `json:"subscription_period_interval" api:"required"`
	Type                       PriceUsageBasedPriceType `json:"type" api:"required"`
	// Deprecated: use `discount_bps` instead.
	//
	// Discount applied to the price, represented as a percentage (0 to 100). A
	// response rounds this value to the nearest whole percent. Defaults to `0`.
	//
	// Deprecated: deprecated
	Discount int64 `json:"discount"`
	// Discount applied to the price, in basis points. 100 basis points make one
	// percent, so `1250` is a discount of 12.5%.
	//
	// Use this field for a discount with a fraction of a percent. A request that sends
	// this field ignores `discount`. A value of `0` gives no discount.
	DiscountBps int64             `json:"discount_bps" api:"nullable"`
	Meters      []AddMeterToPrice `json:"meters" api:"nullable"`
	// Opts this price in to purchasing power parity. The business must also enable
	// purchasing power parity. The discount percentage per country is always
	// business-wide. Applies to the fixed fee only, never to metered usage. Defaults
	// to `false`.
	PurchasingPowerParity bool `json:"purchasing_power_parity"`
	// Indicates if the price is tax inclusive
	TaxInclusive bool                     `json:"tax_inclusive" api:"nullable"`
	JSON         priceUsageBasedPriceJSON `json:"-"`
}

Usage Based price details.

func (*PriceUsageBasedPrice) UnmarshalJSON added in v1.52.4

func (r *PriceUsageBasedPrice) UnmarshalJSON(data []byte) (err error)

type PriceUsageBasedPriceParam added in v1.52.4

type PriceUsageBasedPriceParam struct {
	// The currency in which the payment is made.
	Currency param.Field[Currency] `json:"currency" api:"required"`
	// The fixed payment amount. Represented in the lowest denomination of the currency
	// (e.g., cents for USD). For example, to charge $1.00, pass `100`.
	FixedPrice param.Field[int64] `json:"fixed_price" api:"required"`
	// Number of units for the payment frequency. For example, a value of `1` with a
	// `payment_frequency_interval` of `month` represents monthly payments.
	PaymentFrequencyCount param.Field[int64] `json:"payment_frequency_count" api:"required"`
	// The time interval for the payment frequency (e.g., day, month, year).
	PaymentFrequencyInterval param.Field[TimeInterval] `json:"payment_frequency_interval" api:"required"`
	// Number of units for the subscription period. For example, a value of `12` with a
	// `subscription_period_interval` of `month` represents a one-year subscription.
	SubscriptionPeriodCount param.Field[int64] `json:"subscription_period_count" api:"required"`
	// The time interval for the subscription period (e.g., day, month, year).
	SubscriptionPeriodInterval param.Field[TimeInterval]             `json:"subscription_period_interval" api:"required"`
	Type                       param.Field[PriceUsageBasedPriceType] `json:"type" api:"required"`
	// Deprecated: use `discount_bps` instead.
	//
	// Discount applied to the price, represented as a percentage (0 to 100). A
	// response rounds this value to the nearest whole percent. Defaults to `0`.
	//
	// Deprecated: deprecated
	Discount param.Field[int64] `json:"discount"`
	// Discount applied to the price, in basis points. 100 basis points make one
	// percent, so `1250` is a discount of 12.5%.
	//
	// Use this field for a discount with a fraction of a percent. A request that sends
	// this field ignores `discount`. A value of `0` gives no discount.
	DiscountBps param.Field[int64]                  `json:"discount_bps"`
	Meters      param.Field[[]AddMeterToPriceParam] `json:"meters"`
	// Opts this price in to purchasing power parity. The business must also enable
	// purchasing power parity. The discount percentage per country is always
	// business-wide. Applies to the fixed fee only, never to metered usage. Defaults
	// to `false`.
	PurchasingPowerParity param.Field[bool] `json:"purchasing_power_parity"`
	// Indicates if the price is tax inclusive
	TaxInclusive param.Field[bool] `json:"tax_inclusive"`
}

Usage Based price details.

func (PriceUsageBasedPriceParam) MarshalJSON added in v1.52.4

func (r PriceUsageBasedPriceParam) MarshalJSON() (data []byte, err error)

type PriceUsageBasedPriceType added in v1.52.4

type PriceUsageBasedPriceType string
const (
	PriceUsageBasedPriceTypeUsageBasedPrice PriceUsageBasedPriceType = "usage_based_price"
)

func (PriceUsageBasedPriceType) IsKnown added in v1.52.4

func (r PriceUsageBasedPriceType) IsKnown() bool

type PricingMode added in v1.106.0

type PricingMode string
const (
	PricingModeByCurrency PricingMode = "by_currency"
	PricingModeByCountry  PricingMode = "by_country"
)

func (PricingMode) IsKnown added in v1.106.0

func (r PricingMode) IsKnown() bool

type Product

type Product struct {
	BrandID string `json:"brand_id" api:"required"`
	// Unique identifier for the business to which the product belongs.
	BusinessID string `json:"business_id" api:"required"`
	// Timestamp when the product was created.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Attached credit entitlements with settings
	CreditEntitlements []CreditEntitlementMappingResponse `json:"credit_entitlements" api:"required"`
	// Attached entitlements (integration-based access grants)
	Entitlements []ProductEntitlementSummary `json:"entitlements" api:"required"`
	// Indicates if the product is recurring (e.g., subscriptions).
	IsRecurring bool `json:"is_recurring" api:"required"`
	// Indicates whether the product requires a license key.
	//
	// Deprecated: Use the dedicated entitlements API to configure license-key
	// delivery.
	LicenseKeyEnabled bool `json:"license_key_enabled" api:"required"`
	// Additional custom data associated with the product
	Metadata Metadata `json:"metadata" api:"required"`
	// Pricing information for the product.
	Price Price `json:"price" api:"required"`
	// Unique identifier for the product.
	ProductID string `json:"product_id" api:"required"`
	// Tax category associated with the product.
	TaxCategory TaxCategory `json:"tax_category" api:"required"`
	// Timestamp when the product was last updated.
	UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
	// Available Addons for subscription products
	Addons []string `json:"addons" api:"nullable"`
	// Description of the product, optional.
	Description string `json:"description" api:"nullable"`
	// Digital-product-delivery payload, present on grants for `digital_files`
	// entitlements. Each file carries a short-lived presigned download URL.
	DigitalProductDelivery DigitalProductDelivery `json:"digital_product_delivery" api:"nullable"`
	// URL of the product image, optional.
	Image string `json:"image" api:"nullable"`
	// Message sent upon license key activation, if applicable.
	//
	// Deprecated: Use the dedicated entitlements API to configure license-key
	// delivery.
	LicenseKeyActivationMessage string `json:"license_key_activation_message" api:"nullable"`
	// Limit on the number of activations for the license key, if enabled.
	//
	// Deprecated: Use the dedicated entitlements API to configure license-key
	// delivery.
	LicenseKeyActivationsLimit int64 `json:"license_key_activations_limit" api:"nullable"`
	// Duration of the license key validity, if enabled.
	LicenseKeyDuration LicenseKeyDuration `json:"license_key_duration" api:"nullable"`
	// Name of the product, optional.
	Name string `json:"name" api:"nullable"`
	// Pricing mode for localized pricing. NULL means base-only (no localized rules
	// apply).
	PricingMode PricingMode `json:"pricing_mode" api:"nullable"`
	// The product collection ID this product belongs to, if any
	ProductCollectionID string      `json:"product_collection_id" api:"nullable"`
	JSON                productJSON `json:"-"`
}

func (*Product) UnmarshalJSON

func (r *Product) UnmarshalJSON(data []byte) (err error)

type ProductCollection added in v1.99.0

type ProductCollection struct {
	// Unique identifier for the product collection
	ID string `json:"id" api:"required"`
	// Brand ID for the collection
	BrandID string `json:"brand_id" api:"required"`
	// Timestamp when the collection was created
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Groups in this collection
	Groups []ProductCollectionGroupResponse `json:"groups" api:"required"`
	// Name of the collection
	Name string `json:"name" api:"required"`
	// Timestamp when the collection was last updated
	UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
	// Description of the collection
	Description string `json:"description" api:"nullable"`
	// Default effective_at setting for subscription plan downgrades (null = inherit
	// from business)
	EffectiveAtOnDowngrade ProductCollectionEffectiveAtOnDowngrade `json:"effective_at_on_downgrade" api:"nullable"`
	// Default effective_at setting for subscription plan upgrades (null = inherit from
	// business)
	EffectiveAtOnUpgrade ProductCollectionEffectiveAtOnUpgrade `json:"effective_at_on_upgrade" api:"nullable"`
	// URL of the collection image
	Image string `json:"image" api:"nullable"`
	// Default behavior for subscription plan changes on payment failure (null =
	// inherit from business)
	OnPaymentFailure ProductCollectionOnPaymentFailure `json:"on_payment_failure" api:"nullable"`
	// Default proration billing mode for subscription plan downgrades (null = inherit
	// from business)
	ProrationBillingModeOnDowngrade ProductCollectionProrationBillingModeOnDowngrade `json:"proration_billing_mode_on_downgrade" api:"nullable"`
	// Default proration billing mode for subscription plan upgrades (null = inherit
	// from business)
	ProrationBillingModeOnUpgrade ProductCollectionProrationBillingModeOnUpgrade `json:"proration_billing_mode_on_upgrade" api:"nullable"`
	JSON                          productCollectionJSON                          `json:"-"`
}

func (*ProductCollection) UnmarshalJSON added in v1.99.0

func (r *ProductCollection) UnmarshalJSON(data []byte) (err error)

type ProductCollectionEffectiveAtOnDowngrade added in v1.101.0

type ProductCollectionEffectiveAtOnDowngrade string

Default effective_at setting for subscription plan downgrades (null = inherit from business)

const (
	ProductCollectionEffectiveAtOnDowngradeImmediately     ProductCollectionEffectiveAtOnDowngrade = "immediately"
	ProductCollectionEffectiveAtOnDowngradeNextBillingDate ProductCollectionEffectiveAtOnDowngrade = "next_billing_date"
)

func (ProductCollectionEffectiveAtOnDowngrade) IsKnown added in v1.101.0

type ProductCollectionEffectiveAtOnUpgrade added in v1.101.0

type ProductCollectionEffectiveAtOnUpgrade string

Default effective_at setting for subscription plan upgrades (null = inherit from business)

const (
	ProductCollectionEffectiveAtOnUpgradeImmediately     ProductCollectionEffectiveAtOnUpgrade = "immediately"
	ProductCollectionEffectiveAtOnUpgradeNextBillingDate ProductCollectionEffectiveAtOnUpgrade = "next_billing_date"
)

func (ProductCollectionEffectiveAtOnUpgrade) IsKnown added in v1.101.0

type ProductCollectionGroupDetailsParam added in v1.99.0

type ProductCollectionGroupDetailsParam struct {
	// Products in this group
	Products param.Field[[]GroupProductParam] `json:"products" api:"required"`
	// Optional group name. Multiple groups can have null names, but named groups must
	// be unique per collection
	GroupName param.Field[string] `json:"group_name"`
	// Status of the group (defaults to true if not provided)
	Status param.Field[bool] `json:"status"`
}

func (ProductCollectionGroupDetailsParam) MarshalJSON added in v1.99.0

func (r ProductCollectionGroupDetailsParam) MarshalJSON() (data []byte, err error)

type ProductCollectionGroupItemNewParams added in v1.88.0

type ProductCollectionGroupItemNewParams struct {
	// Products to add to the group
	Products param.Field[[]GroupProductParam] `json:"products" api:"required"`
}

func (ProductCollectionGroupItemNewParams) MarshalJSON added in v1.88.0

func (r ProductCollectionGroupItemNewParams) MarshalJSON() (data []byte, err error)

type ProductCollectionGroupItemService added in v1.88.0

type ProductCollectionGroupItemService struct {
	Options []option.RequestOption
}

ProductCollectionGroupItemService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewProductCollectionGroupItemService method instead.

func NewProductCollectionGroupItemService added in v1.88.0

func NewProductCollectionGroupItemService(opts ...option.RequestOption) (r *ProductCollectionGroupItemService)

NewProductCollectionGroupItemService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*ProductCollectionGroupItemService) Delete added in v1.88.0

func (r *ProductCollectionGroupItemService) Delete(ctx context.Context, id string, groupID string, itemID string, opts ...option.RequestOption) (err error)

func (*ProductCollectionGroupItemService) New added in v1.88.0

func (*ProductCollectionGroupItemService) Update added in v1.88.0

type ProductCollectionGroupItemUpdateParams added in v1.88.0

type ProductCollectionGroupItemUpdateParams struct {
	// Status of the product in the group
	Status param.Field[bool] `json:"status" api:"required"`
}

func (ProductCollectionGroupItemUpdateParams) MarshalJSON added in v1.88.0

func (r ProductCollectionGroupItemUpdateParams) MarshalJSON() (data []byte, err error)

type ProductCollectionGroupNewParams added in v1.88.0

type ProductCollectionGroupNewParams struct {
	ProductCollectionGroupDetails ProductCollectionGroupDetailsParam `json:"product_collection_group_details" api:"required"`
}

func (ProductCollectionGroupNewParams) MarshalJSON added in v1.88.0

func (r ProductCollectionGroupNewParams) MarshalJSON() (data []byte, err error)

type ProductCollectionGroupResponse added in v1.99.0

type ProductCollectionGroupResponse struct {
	GroupID   string                             `json:"group_id" api:"required"`
	Products  []ProductCollectionProduct         `json:"products" api:"required"`
	Status    bool                               `json:"status" api:"required"`
	GroupName string                             `json:"group_name" api:"nullable"`
	JSON      productCollectionGroupResponseJSON `json:"-"`
}

func (*ProductCollectionGroupResponse) UnmarshalJSON added in v1.99.0

func (r *ProductCollectionGroupResponse) UnmarshalJSON(data []byte) (err error)

type ProductCollectionGroupService added in v1.88.0

type ProductCollectionGroupService struct {
	Options []option.RequestOption
	Items   *ProductCollectionGroupItemService
}

ProductCollectionGroupService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewProductCollectionGroupService method instead.

func NewProductCollectionGroupService added in v1.88.0

func NewProductCollectionGroupService(opts ...option.RequestOption) (r *ProductCollectionGroupService)

NewProductCollectionGroupService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*ProductCollectionGroupService) Delete added in v1.88.0

func (r *ProductCollectionGroupService) Delete(ctx context.Context, id string, groupID string, opts ...option.RequestOption) (err error)

func (*ProductCollectionGroupService) New added in v1.88.0

func (*ProductCollectionGroupService) Update added in v1.88.0

type ProductCollectionGroupUpdateParams added in v1.88.0

type ProductCollectionGroupUpdateParams struct {
	// Optional group name update: Some(Some(name)) = set name, Some(None) = clear
	// name, None = no change
	GroupName param.Field[string] `json:"group_name"`
	// Optional new order for products in this group (array of
	// product_collection_group_pdts UUIDs)
	ProductOrder param.Field[[]string] `json:"product_order" format:"uuid"`
	// Optional status update
	Status param.Field[bool] `json:"status"`
}

func (ProductCollectionGroupUpdateParams) MarshalJSON added in v1.88.0

func (r ProductCollectionGroupUpdateParams) MarshalJSON() (data []byte, err error)

type ProductCollectionListParams added in v1.88.0

type ProductCollectionListParams struct {
	// List archived collections
	Archived param.Field[bool] `query:"archived"`
	// Filter by Brand id
	BrandID param.Field[string] `query:"brand_id"`
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
}

func (ProductCollectionListParams) URLQuery added in v1.88.0

func (r ProductCollectionListParams) URLQuery() (v url.Values)

URLQuery serializes ProductCollectionListParams's query parameters as `url.Values`.

type ProductCollectionListResponse added in v1.88.0

type ProductCollectionListResponse struct {
	// Collection ID
	ID string `json:"id" api:"required"`
	// Timestamp when created
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Collection name
	Name string `json:"name" api:"required"`
	// Number of products in the collection
	ProductsCount int64 `json:"products_count" api:"required"`
	// Timestamp when last updated
	UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
	// Collection description
	Description string `json:"description" api:"nullable"`
	// Collection image URL
	Image string                            `json:"image" api:"nullable"`
	JSON  productCollectionListResponseJSON `json:"-"`
}

func (*ProductCollectionListResponse) UnmarshalJSON added in v1.88.0

func (r *ProductCollectionListResponse) UnmarshalJSON(data []byte) (err error)

type ProductCollectionNewParams added in v1.88.0

type ProductCollectionNewParams struct {
	// Groups of products in this collection
	Groups param.Field[[]ProductCollectionGroupDetailsParam] `json:"groups" api:"required"`
	// Name of the product collection
	Name param.Field[string] `json:"name" api:"required"`
	// Brand id for the collection, if not provided will default to primary brand
	BrandID param.Field[string] `json:"brand_id"`
	// Optional description of the product collection
	Description param.Field[string] `json:"description"`
	// Default effective_at setting for subscription plan downgrades (NULL = inherit
	// from business)
	EffectiveAtOnDowngrade param.Field[ProductCollectionNewParamsEffectiveAtOnDowngrade] `json:"effective_at_on_downgrade"`
	// Default effective_at setting for subscription plan upgrades (NULL = inherit from
	// business)
	EffectiveAtOnUpgrade param.Field[ProductCollectionNewParamsEffectiveAtOnUpgrade] `json:"effective_at_on_upgrade"`
	// Default behavior for subscription plan changes on payment failure (NULL =
	// inherit from business)
	OnPaymentFailure param.Field[ProductCollectionNewParamsOnPaymentFailure] `json:"on_payment_failure"`
	// Default proration billing mode for subscription plan downgrades (NULL = inherit
	// from business)
	ProrationBillingModeOnDowngrade param.Field[ProductCollectionNewParamsProrationBillingModeOnDowngrade] `json:"proration_billing_mode_on_downgrade"`
	// Default proration billing mode for subscription plan upgrades (NULL = inherit
	// from business)
	ProrationBillingModeOnUpgrade param.Field[ProductCollectionNewParamsProrationBillingModeOnUpgrade] `json:"proration_billing_mode_on_upgrade"`
}

func (ProductCollectionNewParams) MarshalJSON added in v1.88.0

func (r ProductCollectionNewParams) MarshalJSON() (data []byte, err error)

type ProductCollectionNewParamsEffectiveAtOnDowngrade added in v1.101.0

type ProductCollectionNewParamsEffectiveAtOnDowngrade string

Default effective_at setting for subscription plan downgrades (NULL = inherit from business)

const (
	ProductCollectionNewParamsEffectiveAtOnDowngradeImmediately     ProductCollectionNewParamsEffectiveAtOnDowngrade = "immediately"
	ProductCollectionNewParamsEffectiveAtOnDowngradeNextBillingDate ProductCollectionNewParamsEffectiveAtOnDowngrade = "next_billing_date"
)

func (ProductCollectionNewParamsEffectiveAtOnDowngrade) IsKnown added in v1.101.0

type ProductCollectionNewParamsEffectiveAtOnUpgrade added in v1.101.0

type ProductCollectionNewParamsEffectiveAtOnUpgrade string

Default effective_at setting for subscription plan upgrades (NULL = inherit from business)

const (
	ProductCollectionNewParamsEffectiveAtOnUpgradeImmediately     ProductCollectionNewParamsEffectiveAtOnUpgrade = "immediately"
	ProductCollectionNewParamsEffectiveAtOnUpgradeNextBillingDate ProductCollectionNewParamsEffectiveAtOnUpgrade = "next_billing_date"
)

func (ProductCollectionNewParamsEffectiveAtOnUpgrade) IsKnown added in v1.101.0

type ProductCollectionNewParamsOnPaymentFailure added in v1.101.0

type ProductCollectionNewParamsOnPaymentFailure string

Default behavior for subscription plan changes on payment failure (NULL = inherit from business)

const (
	ProductCollectionNewParamsOnPaymentFailurePreventChange ProductCollectionNewParamsOnPaymentFailure = "prevent_change"
	ProductCollectionNewParamsOnPaymentFailureApplyChange   ProductCollectionNewParamsOnPaymentFailure = "apply_change"
)

func (ProductCollectionNewParamsOnPaymentFailure) IsKnown added in v1.101.0

type ProductCollectionNewParamsProrationBillingModeOnDowngrade added in v1.101.0

type ProductCollectionNewParamsProrationBillingModeOnDowngrade string

Default proration billing mode for subscription plan downgrades (NULL = inherit from business)

const (
	ProductCollectionNewParamsProrationBillingModeOnDowngradeProratedImmediately   ProductCollectionNewParamsProrationBillingModeOnDowngrade = "prorated_immediately"
	ProductCollectionNewParamsProrationBillingModeOnDowngradeFullImmediately       ProductCollectionNewParamsProrationBillingModeOnDowngrade = "full_immediately"
	ProductCollectionNewParamsProrationBillingModeOnDowngradeDifferenceImmediately ProductCollectionNewParamsProrationBillingModeOnDowngrade = "difference_immediately"
	ProductCollectionNewParamsProrationBillingModeOnDowngradeDoNotBill             ProductCollectionNewParamsProrationBillingModeOnDowngrade = "do_not_bill"
)

func (ProductCollectionNewParamsProrationBillingModeOnDowngrade) IsKnown added in v1.101.0

type ProductCollectionNewParamsProrationBillingModeOnUpgrade added in v1.101.0

type ProductCollectionNewParamsProrationBillingModeOnUpgrade string

Default proration billing mode for subscription plan upgrades (NULL = inherit from business)

const (
	ProductCollectionNewParamsProrationBillingModeOnUpgradeProratedImmediately   ProductCollectionNewParamsProrationBillingModeOnUpgrade = "prorated_immediately"
	ProductCollectionNewParamsProrationBillingModeOnUpgradeFullImmediately       ProductCollectionNewParamsProrationBillingModeOnUpgrade = "full_immediately"
	ProductCollectionNewParamsProrationBillingModeOnUpgradeDifferenceImmediately ProductCollectionNewParamsProrationBillingModeOnUpgrade = "difference_immediately"
	ProductCollectionNewParamsProrationBillingModeOnUpgradeDoNotBill             ProductCollectionNewParamsProrationBillingModeOnUpgrade = "do_not_bill"
)

func (ProductCollectionNewParamsProrationBillingModeOnUpgrade) IsKnown added in v1.101.0

type ProductCollectionOnPaymentFailure added in v1.101.0

type ProductCollectionOnPaymentFailure string

Default behavior for subscription plan changes on payment failure (null = inherit from business)

const (
	ProductCollectionOnPaymentFailurePreventChange ProductCollectionOnPaymentFailure = "prevent_change"
	ProductCollectionOnPaymentFailureApplyChange   ProductCollectionOnPaymentFailure = "apply_change"
)

func (ProductCollectionOnPaymentFailure) IsKnown added in v1.101.0

type ProductCollectionProduct added in v1.99.0

type ProductCollectionProduct struct {
	ID          string `json:"id" api:"required"`
	AddonsCount int64  `json:"addons_count" api:"required"`
	FilesCount  int64  `json:"files_count" api:"required"`
	// Whether this product has any credit entitlements attached
	HasCreditEntitlements bool     `json:"has_credit_entitlements" api:"required"`
	IsRecurring           bool     `json:"is_recurring" api:"required"`
	LicenseKeyEnabled     bool     `json:"license_key_enabled" api:"required"`
	MetersCount           int64    `json:"meters_count" api:"required"`
	ProductID             string   `json:"product_id" api:"required"`
	Status                bool     `json:"status" api:"required"`
	Currency              Currency `json:"currency" api:"nullable"`
	Description           string   `json:"description" api:"nullable"`
	Name                  string   `json:"name" api:"nullable"`
	Price                 int64    `json:"price" api:"nullable"`
	// One-time price details.
	PriceDetail Price `json:"price_detail" api:"nullable"`
	// Represents the different categories of taxation applicable to various products
	// and services.
	TaxCategory  TaxCategory                  `json:"tax_category" api:"nullable"`
	TaxInclusive bool                         `json:"tax_inclusive" api:"nullable"`
	JSON         productCollectionProductJSON `json:"-"`
}

func (*ProductCollectionProduct) UnmarshalJSON added in v1.99.0

func (r *ProductCollectionProduct) UnmarshalJSON(data []byte) (err error)

type ProductCollectionProrationBillingModeOnDowngrade added in v1.101.0

type ProductCollectionProrationBillingModeOnDowngrade string

Default proration billing mode for subscription plan downgrades (null = inherit from business)

const (
	ProductCollectionProrationBillingModeOnDowngradeProratedImmediately   ProductCollectionProrationBillingModeOnDowngrade = "prorated_immediately"
	ProductCollectionProrationBillingModeOnDowngradeFullImmediately       ProductCollectionProrationBillingModeOnDowngrade = "full_immediately"
	ProductCollectionProrationBillingModeOnDowngradeDifferenceImmediately ProductCollectionProrationBillingModeOnDowngrade = "difference_immediately"
	ProductCollectionProrationBillingModeOnDowngradeDoNotBill             ProductCollectionProrationBillingModeOnDowngrade = "do_not_bill"
)

func (ProductCollectionProrationBillingModeOnDowngrade) IsKnown added in v1.101.0

type ProductCollectionProrationBillingModeOnUpgrade added in v1.101.0

type ProductCollectionProrationBillingModeOnUpgrade string

Default proration billing mode for subscription plan upgrades (null = inherit from business)

const (
	ProductCollectionProrationBillingModeOnUpgradeProratedImmediately   ProductCollectionProrationBillingModeOnUpgrade = "prorated_immediately"
	ProductCollectionProrationBillingModeOnUpgradeFullImmediately       ProductCollectionProrationBillingModeOnUpgrade = "full_immediately"
	ProductCollectionProrationBillingModeOnUpgradeDifferenceImmediately ProductCollectionProrationBillingModeOnUpgrade = "difference_immediately"
	ProductCollectionProrationBillingModeOnUpgradeDoNotBill             ProductCollectionProrationBillingModeOnUpgrade = "do_not_bill"
)

func (ProductCollectionProrationBillingModeOnUpgrade) IsKnown added in v1.101.0

type ProductCollectionService added in v1.88.0

type ProductCollectionService struct {
	Options []option.RequestOption
	Groups  *ProductCollectionGroupService
}

ProductCollectionService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewProductCollectionService method instead.

func NewProductCollectionService added in v1.88.0

func NewProductCollectionService(opts ...option.RequestOption) (r *ProductCollectionService)

NewProductCollectionService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*ProductCollectionService) Delete added in v1.88.0

func (r *ProductCollectionService) Delete(ctx context.Context, id string, opts ...option.RequestOption) (err error)

func (*ProductCollectionService) Get added in v1.88.0

func (*ProductCollectionService) List added in v1.88.0

func (*ProductCollectionService) New added in v1.88.0

func (*ProductCollectionService) Unarchive added in v1.88.0

func (*ProductCollectionService) Update added in v1.88.0

func (*ProductCollectionService) UpdateImages added in v1.88.0

type ProductCollectionUnarchiveResponse added in v1.88.0

type ProductCollectionUnarchiveResponse struct {
	// Collection ID that was unarchived
	CollectionID string `json:"collection_id" api:"required"`
	// Product IDs that were excluded because they are archived
	ExcludedProductIDs []string `json:"excluded_product_ids" api:"required"`
	// Success message
	Message string                                 `json:"message" api:"required"`
	JSON    productCollectionUnarchiveResponseJSON `json:"-"`
}

func (*ProductCollectionUnarchiveResponse) UnmarshalJSON added in v1.88.0

func (r *ProductCollectionUnarchiveResponse) UnmarshalJSON(data []byte) (err error)

type ProductCollectionUpdateImagesParams added in v1.88.0

type ProductCollectionUpdateImagesParams struct {
	// If true, generates a new image ID to force cache invalidation
	ForceUpdate param.Field[bool] `query:"force_update"`
}

func (ProductCollectionUpdateImagesParams) URLQuery added in v1.88.0

URLQuery serializes ProductCollectionUpdateImagesParams's query parameters as `url.Values`.

type ProductCollectionUpdateImagesResponse added in v1.88.0

type ProductCollectionUpdateImagesResponse struct {
	// Presigned S3 URL for uploading the image
	URL string `json:"url" api:"required"`
	// Optional image ID (present when force_update is true)
	ImageID string                                    `json:"image_id" api:"nullable" format:"uuid"`
	JSON    productCollectionUpdateImagesResponseJSON `json:"-"`
}

func (*ProductCollectionUpdateImagesResponse) UnmarshalJSON added in v1.88.0

func (r *ProductCollectionUpdateImagesResponse) UnmarshalJSON(data []byte) (err error)

type ProductCollectionUpdateParams added in v1.88.0

type ProductCollectionUpdateParams struct {
	// Optional brand_id update
	BrandID param.Field[string] `json:"brand_id"`
	// Optional description update - pass null to remove, omit to keep unchanged
	Description param.Field[string] `json:"description"`
	// Effective_at setting for downgrades: Some(Some(val)) = set, Some(None) = clear
	// (inherit), None = no change
	EffectiveAtOnDowngrade param.Field[ProductCollectionUpdateParamsEffectiveAtOnDowngrade] `json:"effective_at_on_downgrade"`
	// Effective_at setting for upgrades: Some(Some(val)) = set, Some(None) = clear
	// (inherit), None = no change
	EffectiveAtOnUpgrade param.Field[ProductCollectionUpdateParamsEffectiveAtOnUpgrade] `json:"effective_at_on_upgrade"`
	// Optional new order for groups (array of group UUIDs in desired order)
	GroupOrder param.Field[[]string] `json:"group_order" format:"uuid"`
	// Optional image update - pass null to remove, omit to keep unchanged
	ImageID param.Field[string] `json:"image_id" format:"uuid"`
	// Optional new name for the collection
	Name param.Field[string] `json:"name"`
	// On payment failure behavior: Some(Some(val)) = set, Some(None) = clear
	// (inherit), None = no change
	OnPaymentFailure param.Field[ProductCollectionUpdateParamsOnPaymentFailure] `json:"on_payment_failure"`
	// Proration billing mode for downgrades: Some(Some(val)) = set, Some(None) = clear
	// (inherit), None = no change
	ProrationBillingModeOnDowngrade param.Field[ProductCollectionUpdateParamsProrationBillingModeOnDowngrade] `json:"proration_billing_mode_on_downgrade"`
	// Proration billing mode for upgrades: Some(Some(val)) = set, Some(None) = clear
	// (inherit), None = no change
	ProrationBillingModeOnUpgrade param.Field[ProductCollectionUpdateParamsProrationBillingModeOnUpgrade] `json:"proration_billing_mode_on_upgrade"`
}

func (ProductCollectionUpdateParams) MarshalJSON added in v1.88.0

func (r ProductCollectionUpdateParams) MarshalJSON() (data []byte, err error)

type ProductCollectionUpdateParamsEffectiveAtOnDowngrade added in v1.101.0

type ProductCollectionUpdateParamsEffectiveAtOnDowngrade string

Effective_at setting for downgrades: Some(Some(val)) = set, Some(None) = clear (inherit), None = no change

const (
	ProductCollectionUpdateParamsEffectiveAtOnDowngradeImmediately     ProductCollectionUpdateParamsEffectiveAtOnDowngrade = "immediately"
	ProductCollectionUpdateParamsEffectiveAtOnDowngradeNextBillingDate ProductCollectionUpdateParamsEffectiveAtOnDowngrade = "next_billing_date"
)

func (ProductCollectionUpdateParamsEffectiveAtOnDowngrade) IsKnown added in v1.101.0

type ProductCollectionUpdateParamsEffectiveAtOnUpgrade added in v1.101.0

type ProductCollectionUpdateParamsEffectiveAtOnUpgrade string

Effective_at setting for upgrades: Some(Some(val)) = set, Some(None) = clear (inherit), None = no change

const (
	ProductCollectionUpdateParamsEffectiveAtOnUpgradeImmediately     ProductCollectionUpdateParamsEffectiveAtOnUpgrade = "immediately"
	ProductCollectionUpdateParamsEffectiveAtOnUpgradeNextBillingDate ProductCollectionUpdateParamsEffectiveAtOnUpgrade = "next_billing_date"
)

func (ProductCollectionUpdateParamsEffectiveAtOnUpgrade) IsKnown added in v1.101.0

type ProductCollectionUpdateParamsOnPaymentFailure added in v1.101.0

type ProductCollectionUpdateParamsOnPaymentFailure string

On payment failure behavior: Some(Some(val)) = set, Some(None) = clear (inherit), None = no change

const (
	ProductCollectionUpdateParamsOnPaymentFailurePreventChange ProductCollectionUpdateParamsOnPaymentFailure = "prevent_change"
	ProductCollectionUpdateParamsOnPaymentFailureApplyChange   ProductCollectionUpdateParamsOnPaymentFailure = "apply_change"
)

func (ProductCollectionUpdateParamsOnPaymentFailure) IsKnown added in v1.101.0

type ProductCollectionUpdateParamsProrationBillingModeOnDowngrade added in v1.101.0

type ProductCollectionUpdateParamsProrationBillingModeOnDowngrade string

Proration billing mode for downgrades: Some(Some(val)) = set, Some(None) = clear (inherit), None = no change

const (
	ProductCollectionUpdateParamsProrationBillingModeOnDowngradeProratedImmediately   ProductCollectionUpdateParamsProrationBillingModeOnDowngrade = "prorated_immediately"
	ProductCollectionUpdateParamsProrationBillingModeOnDowngradeFullImmediately       ProductCollectionUpdateParamsProrationBillingModeOnDowngrade = "full_immediately"
	ProductCollectionUpdateParamsProrationBillingModeOnDowngradeDifferenceImmediately ProductCollectionUpdateParamsProrationBillingModeOnDowngrade = "difference_immediately"
	ProductCollectionUpdateParamsProrationBillingModeOnDowngradeDoNotBill             ProductCollectionUpdateParamsProrationBillingModeOnDowngrade = "do_not_bill"
)

func (ProductCollectionUpdateParamsProrationBillingModeOnDowngrade) IsKnown added in v1.101.0

type ProductCollectionUpdateParamsProrationBillingModeOnUpgrade added in v1.101.0

type ProductCollectionUpdateParamsProrationBillingModeOnUpgrade string

Proration billing mode for upgrades: Some(Some(val)) = set, Some(None) = clear (inherit), None = no change

const (
	ProductCollectionUpdateParamsProrationBillingModeOnUpgradeProratedImmediately   ProductCollectionUpdateParamsProrationBillingModeOnUpgrade = "prorated_immediately"
	ProductCollectionUpdateParamsProrationBillingModeOnUpgradeFullImmediately       ProductCollectionUpdateParamsProrationBillingModeOnUpgrade = "full_immediately"
	ProductCollectionUpdateParamsProrationBillingModeOnUpgradeDifferenceImmediately ProductCollectionUpdateParamsProrationBillingModeOnUpgrade = "difference_immediately"
	ProductCollectionUpdateParamsProrationBillingModeOnUpgradeDoNotBill             ProductCollectionUpdateParamsProrationBillingModeOnUpgrade = "do_not_bill"
)

func (ProductCollectionUpdateParamsProrationBillingModeOnUpgrade) IsKnown added in v1.101.0

type ProductEntitlementSummary added in v1.97.0

type ProductEntitlementSummary struct {
	ID string `json:"id" api:"required"`
	// Integration-specific configuration on an entitlement read response.
	//
	// For `digital_files` entitlements the response includes presigned download URLs
	// for each attached file; other integrations match the shape supplied at creation.
	IntegrationConfig IntegrationConfigResponse     `json:"integration_config" api:"required"`
	IntegrationType   EntitlementIntegrationType    `json:"integration_type" api:"required"`
	Name              string                        `json:"name" api:"required"`
	Description       string                        `json:"description" api:"nullable"`
	JSON              productEntitlementSummaryJSON `json:"-"`
}

Summary of an entitlement attached to a product.

`integration_config` uses [`IntegrationConfigResponse`] (NOT the persisted [`IntegrationConfig`]) so digital_files entitlements embed the resolved `digital_files` object — matching what `GET /entitlements/{id}` returns. All other variants pass through unchanged via `#[serde(untagged)]`.

func (*ProductEntitlementSummary) UnmarshalJSON added in v1.97.0

func (r *ProductEntitlementSummary) UnmarshalJSON(data []byte) (err error)

type ProductImageService

type ProductImageService struct {
	Options []option.RequestOption
}

ProductImageService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewProductImageService method instead.

func NewProductImageService

func NewProductImageService(opts ...option.RequestOption) (r *ProductImageService)

NewProductImageService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*ProductImageService) Update

type ProductImageUpdateParams added in v0.22.0

type ProductImageUpdateParams struct {
	ForceUpdate param.Field[bool] `query:"force_update"`
}

func (ProductImageUpdateParams) URLQuery added in v0.22.0

func (r ProductImageUpdateParams) URLQuery() (v url.Values)

URLQuery serializes ProductImageUpdateParams's query parameters as `url.Values`.

type ProductImageUpdateResponse

type ProductImageUpdateResponse struct {
	URL     string                         `json:"url" api:"required"`
	ImageID string                         `json:"image_id" api:"nullable" format:"uuid"`
	JSON    productImageUpdateResponseJSON `json:"-"`
}

func (*ProductImageUpdateResponse) UnmarshalJSON

func (r *ProductImageUpdateResponse) UnmarshalJSON(data []byte) (err error)

type ProductItemReqCreditEntitlementParam added in v1.97.3

type ProductItemReqCreditEntitlementParam struct {
	// ID of the credit entitlement to override. Must already be attached to the
	// product.
	CreditEntitlementID param.Field[string] `json:"credit_entitlement_id" api:"required"`
	// Number of credits to grant for this checkout session, overriding the
	// product-level `credits_amount` set on the credit entitlement mapping. Must be
	// greater than zero.
	CreditsAmount param.Field[string] `json:"credits_amount" api:"required"`
}

Per-checkout-session override for a single credit entitlement attached to a product.

func (ProductItemReqCreditEntitlementParam) MarshalJSON added in v1.97.3

func (r ProductItemReqCreditEntitlementParam) MarshalJSON() (data []byte, err error)

type ProductItemReqParam added in v1.81.0

type ProductItemReqParam struct {
	// unique id of the product
	ProductID param.Field[string] `json:"product_id" api:"required"`
	Quantity  param.Field[int64]  `json:"quantity" api:"required"`
	// only valid if product is a subscription
	Addons param.Field[[]AttachAddonParam] `json:"addons"`
	// Amount the customer pays if pay_what_you_want is enabled. If disabled then
	// amount will be ignored Represented in the lowest denomination of the currency
	// (e.g., cents for USD). For example, to charge $1.00, pass `100`. Only applicable
	// for one time payments
	//
	// If amount is not set for pay_what_you_want product, customer is allowed to
	// select the amount.
	Amount param.Field[int64] `json:"amount"`
	// Per-checkout-session overrides for credit entitlements already attached to this
	// product. Each entry overrides the `credits_amount` granted by the referenced
	// credit entitlement when this checkout session is fulfilled. The
	// credit_entitlement_id must already be attached to the product.
	CreditEntitlements param.Field[[]ProductItemReqCreditEntitlementParam] `json:"credit_entitlements"`
}

func (ProductItemReqParam) MarshalJSON added in v1.81.0

func (r ProductItemReqParam) MarshalJSON() (data []byte, err error)

type ProductListParams

type ProductListParams struct {
	// List archived products
	Archived param.Field[bool] `query:"archived"`
	// filter by Brand id
	BrandID param.Field[string] `query:"brand_id"`
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
	// Filter products by pricing type:
	//
	// - `true`: Show only recurring pricing products (e.g. subscriptions)
	// - `false`: Show only one-time price products
	// - `null` or absent: Show both types of products
	Recurring param.Field[bool] `query:"recurring"`
}

func (ProductListParams) URLQuery

func (r ProductListParams) URLQuery() (v url.Values)

URLQuery serializes ProductListParams's query parameters as `url.Values`.

type ProductListResponse

type ProductListResponse struct {
	// Unique identifier for the business to which the product belongs.
	BusinessID string `json:"business_id" api:"required"`
	// Timestamp when the product was created.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Entitlements linked to this product
	Entitlements []ProductEntitlementSummary `json:"entitlements" api:"required"`
	// Indicates if the product is recurring (e.g., subscriptions).
	IsRecurring bool `json:"is_recurring" api:"required"`
	// Additional custom data associated with the product
	Metadata Metadata `json:"metadata" api:"required"`
	// Unique identifier for the product.
	ProductID string `json:"product_id" api:"required"`
	// Tax category associated with the product.
	TaxCategory TaxCategory `json:"tax_category" api:"required"`
	// Timestamp when the product was last updated.
	UpdatedAt time.Time `json:"updated_at" api:"required" format:"date-time"`
	// Currency of the price
	Currency Currency `json:"currency" api:"nullable"`
	// Description of the product, optional.
	Description string `json:"description" api:"nullable"`
	// URL of the product image, optional.
	Image string `json:"image" api:"nullable"`
	// Name of the product, optional.
	Name string `json:"name" api:"nullable"`
	// Price of the product, optional.
	//
	// The price is represented in the lowest denomination of the currency. For
	// example:
	//
	// - In USD, a price of `$12.34` would be represented as `1234` (cents).
	// - In JPY, a price of `¥1500` would be represented as `1500` (yen).
	// - In INR, a price of `₹1234.56` would be represented as `123456` (paise).
	//
	// This ensures precision and avoids floating-point rounding errors.
	Price int64 `json:"price" api:"nullable"`
	// Details of the price
	PriceDetail Price `json:"price_detail" api:"nullable"`
	// Pricing mode for localized pricing. NULL means base-only (no localized rules
	// apply).
	PricingMode PricingMode `json:"pricing_mode" api:"nullable"`
	// Indicates if the price is tax inclusive
	TaxInclusive bool                    `json:"tax_inclusive" api:"nullable"`
	JSON         productListResponseJSON `json:"-"`
}

func (*ProductListResponse) UnmarshalJSON

func (r *ProductListResponse) UnmarshalJSON(data []byte) (err error)

type ProductLocalizedPriceNewParams added in v1.106.0

type ProductLocalizedPriceNewParams struct {
	// Amount in the smallest currency unit (e.g., cents). Must be greater than zero.
	Amount param.Field[int64] `json:"amount" api:"required"`
	// Currency to charge in. Must be a supported currency.
	Currency param.Field[Currency] `json:"currency" api:"required"`
	// Required when the product's pricing_mode is by_country; forbidden when
	// by_currency.
	CountryCode param.Field[CountryCode] `json:"country_code"`
}

func (ProductLocalizedPriceNewParams) MarshalJSON added in v1.106.0

func (r ProductLocalizedPriceNewParams) MarshalJSON() (data []byte, err error)

type ProductLocalizedPriceService added in v1.106.0

type ProductLocalizedPriceService struct {
	Options []option.RequestOption
}

ProductLocalizedPriceService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewProductLocalizedPriceService method instead.

func NewProductLocalizedPriceService added in v1.106.0

func NewProductLocalizedPriceService(opts ...option.RequestOption) (r *ProductLocalizedPriceService)

NewProductLocalizedPriceService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*ProductLocalizedPriceService) Archive added in v1.106.0

func (r *ProductLocalizedPriceService) Archive(ctx context.Context, productID string, id string, opts ...option.RequestOption) (err error)

func (*ProductLocalizedPriceService) Get added in v1.106.0

func (r *ProductLocalizedPriceService) Get(ctx context.Context, productID string, id string, opts ...option.RequestOption) (res *LocalizedPrice, err error)

func (*ProductLocalizedPriceService) List added in v1.106.0

func (*ProductLocalizedPriceService) New added in v1.106.0

func (*ProductLocalizedPriceService) Update added in v1.106.0

type ProductLocalizedPriceUpdateParams added in v1.106.0

type ProductLocalizedPriceUpdateParams struct {
	// New amount in the smallest currency unit (e.g., cents). Must be greater than
	// zero. The currency and country_code of an existing rule cannot be changed.
	Amount param.Field[int64] `json:"amount"`
}

func (ProductLocalizedPriceUpdateParams) MarshalJSON added in v1.106.0

func (r ProductLocalizedPriceUpdateParams) MarshalJSON() (data []byte, err error)

type ProductNewParams

type ProductNewParams struct {
	// Name of the product
	Name param.Field[string] `json:"name" api:"required"`
	// Price configuration for the product
	Price param.Field[PriceUnionParam] `json:"price" api:"required"`
	// Tax category applied to this product
	TaxCategory param.Field[TaxCategory] `json:"tax_category" api:"required"`
	// Addons available for subscription product
	Addons param.Field[[]string] `json:"addons"`
	// Brand id for the product, if not provided will default to primary brand
	BrandID param.Field[string] `json:"brand_id"`
	// Optional credit entitlements to attach (max 5)
	CreditEntitlements param.Field[[]AttachCreditEntitlementParam] `json:"credit_entitlements"`
	// Optional description of the product
	Description param.Field[string] `json:"description"`
	// Choose how you would like you digital product delivered
	//
	// deprecated: use entitlements instead
	DigitalProductDelivery param.Field[ProductNewParamsDigitalProductDelivery] `json:"digital_product_delivery"`
	// Optional entitlements to attach to this product (max 50)
	Entitlements param.Field[[]AttachProductEntitlementParam] `json:"entitlements"`
	// Optional message displayed during license key activation
	//
	// deprecated: use entitlements instead. Ignored when a `license_key` entitlement
	// is attached via the `entitlements` field.
	LicenseKeyActivationMessage param.Field[string] `json:"license_key_activation_message"`
	// The number of times the license key can be activated. Must be 0 or greater
	//
	// deprecated: use entitlements instead. Ignored when a `license_key` entitlement
	// is attached via the `entitlements` field.
	LicenseKeyActivationsLimit param.Field[int64] `json:"license_key_activations_limit"`
	// Duration configuration for the license key. Set to null if you don't want the
	// license key to expire. For subscriptions, the lifetime of the license key is
	// tied to the subscription period
	//
	// deprecated: use entitlements instead. Ignored when a `license_key` entitlement
	// is attached via the `entitlements` field.
	LicenseKeyDuration param.Field[LicenseKeyDurationParam] `json:"license_key_duration"`
	// When true, generates and sends a license key to your customer. Defaults to false
	//
	// deprecated: use entitlements instead. If a `license_key` entitlement is also
	// attached via the `entitlements` field, the `license_key_*` config fields below
	// are ignored — the attached entitlement's config is the source of truth.
	LicenseKeyEnabled param.Field[bool] `json:"license_key_enabled"`
	// Additional metadata for the product
	Metadata param.Field[MetadataParam] `json:"metadata"`
	// Pricing mode for localized pricing. When set, rules from
	// /products/{id}/localized-prices apply at checkout. NULL means base-only
	// (existing behavior).
	PricingMode param.Field[PricingMode] `json:"pricing_mode"`
}

func (ProductNewParams) MarshalJSON

func (r ProductNewParams) MarshalJSON() (data []byte, err error)

type ProductNewParamsDigitalProductDelivery added in v1.34.0

type ProductNewParamsDigitalProductDelivery struct {
	// External URL to digital product
	ExternalURL param.Field[string] `json:"external_url"`
	// Instructions to download and use the digital product
	Instructions param.Field[string] `json:"instructions"`
}

Choose how you would like you digital product delivered

deprecated: use entitlements instead

func (ProductNewParamsDigitalProductDelivery) MarshalJSON added in v1.34.0

func (r ProductNewParamsDigitalProductDelivery) MarshalJSON() (data []byte, err error)

type ProductService

type ProductService struct {
	Options         []option.RequestOption
	Images          *ProductImageService
	ShortLinks      *ProductShortLinkService
	LocalizedPrices *ProductLocalizedPriceService
}

ProductService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewProductService method instead.

func NewProductService

func NewProductService(opts ...option.RequestOption) (r *ProductService)

NewProductService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*ProductService) Archive added in v1.52.4

func (r *ProductService) Archive(ctx context.Context, id string, opts ...option.RequestOption) (err error)

func (*ProductService) Get

func (r *ProductService) Get(ctx context.Context, id string, opts ...option.RequestOption) (res *Product, err error)

func (*ProductService) New

func (r *ProductService) New(ctx context.Context, body ProductNewParams, opts ...option.RequestOption) (res *Product, err error)

func (*ProductService) Unarchive added in v0.19.0

func (r *ProductService) Unarchive(ctx context.Context, id string, opts ...option.RequestOption) (err error)

func (*ProductService) Update

func (r *ProductService) Update(ctx context.Context, id string, body ProductUpdateParams, opts ...option.RequestOption) (err error)

func (*ProductService) UpdateFiles added in v1.34.0

type ProductShortLinkListParams added in v1.69.0

type ProductShortLinkListParams struct {
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
	// Filter by product ID
	ProductID param.Field[string] `query:"product_id"`
}

func (ProductShortLinkListParams) URLQuery added in v1.69.0

func (r ProductShortLinkListParams) URLQuery() (v url.Values)

URLQuery serializes ProductShortLinkListParams's query parameters as `url.Values`.

type ProductShortLinkListResponse added in v1.69.0

type ProductShortLinkListResponse struct {
	// When the short url was created
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Full URL the short url redirects to
	FullURL string `json:"full_url" api:"required"`
	// Product ID associated with the short link
	ProductID string `json:"product_id" api:"required"`
	// Short URL
	ShortURL string                           `json:"short_url" api:"required"`
	JSON     productShortLinkListResponseJSON `json:"-"`
}

func (*ProductShortLinkListResponse) UnmarshalJSON added in v1.69.0

func (r *ProductShortLinkListResponse) UnmarshalJSON(data []byte) (err error)

type ProductShortLinkNewParams added in v1.69.0

type ProductShortLinkNewParams struct {
	// Slug for the short link.
	Slug param.Field[string] `json:"slug" api:"required"`
	// Static Checkout URL parameters to apply to the resulting short URL.
	StaticCheckoutParams param.Field[map[string]string] `json:"static_checkout_params"`
}

func (ProductShortLinkNewParams) MarshalJSON added in v1.69.0

func (r ProductShortLinkNewParams) MarshalJSON() (data []byte, err error)

type ProductShortLinkNewResponse added in v1.69.0

type ProductShortLinkNewResponse struct {
	// Full URL.
	FullURL string `json:"full_url" api:"required"`
	// Short URL.
	ShortURL string                          `json:"short_url" api:"required"`
	JSON     productShortLinkNewResponseJSON `json:"-"`
}

func (*ProductShortLinkNewResponse) UnmarshalJSON added in v1.69.0

func (r *ProductShortLinkNewResponse) UnmarshalJSON(data []byte) (err error)

type ProductShortLinkService added in v1.69.0

type ProductShortLinkService struct {
	Options []option.RequestOption
}

ProductShortLinkService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewProductShortLinkService method instead.

func NewProductShortLinkService added in v1.69.0

func NewProductShortLinkService(opts ...option.RequestOption) (r *ProductShortLinkService)

NewProductShortLinkService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*ProductShortLinkService) List added in v1.69.0

Lists all short links created by the business.

func (*ProductShortLinkService) ListAutoPaging added in v1.69.0

Lists all short links created by the business.

func (*ProductShortLinkService) New added in v1.69.0

Gives a Short Checkout URL with custom slug for a product. Uses a Static Checkout URL under the hood.

type ProductUpdateFilesParams added in v1.34.0

type ProductUpdateFilesParams struct {
	FileName param.Field[string] `json:"file_name" api:"required"`
}

func (ProductUpdateFilesParams) MarshalJSON added in v1.34.0

func (r ProductUpdateFilesParams) MarshalJSON() (data []byte, err error)

type ProductUpdateFilesResponse added in v1.34.0

type ProductUpdateFilesResponse struct {
	FileID string                         `json:"file_id" api:"required" format:"uuid"`
	URL    string                         `json:"url" api:"required"`
	JSON   productUpdateFilesResponseJSON `json:"-"`
}

func (*ProductUpdateFilesResponse) UnmarshalJSON added in v1.34.0

func (r *ProductUpdateFilesResponse) UnmarshalJSON(data []byte) (err error)

type ProductUpdateParams

type ProductUpdateParams struct {
	// Available Addons for subscription products
	Addons  param.Field[[]string] `json:"addons"`
	BrandID param.Field[string]   `json:"brand_id"`
	// Credit entitlements to update (replaces all existing when present) Send empty
	// array to remove all, omit field to leave unchanged
	CreditEntitlements param.Field[[]AttachCreditEntitlementParam] `json:"credit_entitlements"`
	// Description of the product, optional and must be at most 1000 characters.
	Description param.Field[string] `json:"description"`
	// Choose how you would like you digital product delivered
	//
	// deprecated: use entitlements instead
	DigitalProductDelivery param.Field[ProductUpdateParamsDigitalProductDelivery] `json:"digital_product_delivery"`
	// Entitlements to attach (replaces all existing when present) Send empty array to
	// remove all, omit field to leave unchanged
	Entitlements param.Field[[]AttachProductEntitlementParam] `json:"entitlements"`
	// Product image id after its uploaded to S3
	ImageID param.Field[string] `json:"image_id" format:"uuid"`
	// Message sent to the customer upon license key activation.
	//
	// Only applicable if `license_key_enabled` is `true`. This message contains
	// instructions for activating the license key.
	//
	// deprecated: use entitlements instead
	LicenseKeyActivationMessage param.Field[string] `json:"license_key_activation_message"`
	// Limit for the number of activations for the license key.
	//
	// Only applicable if `license_key_enabled` is `true`. Represents the maximum
	// number of times the license key can be activated.
	//
	// deprecated: use entitlements instead
	LicenseKeyActivationsLimit param.Field[int64] `json:"license_key_activations_limit"`
	// Duration of the license key if enabled.
	//
	// Only applicable if `license_key_enabled` is `true`. Represents the duration in
	// days for which the license key is valid.
	//
	// deprecated: use entitlements instead
	LicenseKeyDuration param.Field[LicenseKeyDurationParam] `json:"license_key_duration"`
	// Whether the product requires a license key.
	//
	// If `true`, additional fields related to license key (duration, activations
	// limit, activation message) become applicable.
	//
	// deprecated: use entitlements instead
	LicenseKeyEnabled param.Field[bool] `json:"license_key_enabled"`
	// Additional metadata for the product
	Metadata param.Field[MetadataParam] `json:"metadata"`
	// Name of the product, optional and must be at most 100 characters.
	Name param.Field[string] `json:"name"`
	// Price details of the product.
	Price param.Field[PriceUnionParam] `json:"price"`
	// Update the pricing mode. Omit to leave unchanged; set to null to clear (which
	// archives all active localized rules for this product). Changing to a different
	// non-null mode also archives any rules whose mode doesn't match the new mode.
	PricingMode param.Field[PricingMode] `json:"pricing_mode"`
	// Tax category of the product.
	TaxCategory param.Field[TaxCategory] `json:"tax_category"`
}

func (ProductUpdateParams) MarshalJSON

func (r ProductUpdateParams) MarshalJSON() (data []byte, err error)

type ProductUpdateParamsDigitalProductDelivery added in v1.34.0

type ProductUpdateParamsDigitalProductDelivery struct {
	// External URL to digital product
	ExternalURL param.Field[string] `json:"external_url"`
	// Uploaded files ids of digital product
	Files param.Field[[]string] `json:"files" format:"uuid"`
	// Instructions to download and use the digital product
	Instructions param.Field[string] `json:"instructions"`
}

Choose how you would like you digital product delivered

deprecated: use entitlements instead

func (ProductUpdateParamsDigitalProductDelivery) MarshalJSON added in v1.34.0

func (r ProductUpdateParamsDigitalProductDelivery) MarshalJSON() (data []byte, err error)

type Refund

type Refund struct {
	// Brand id this refund belongs to
	BrandID string `json:"brand_id" api:"required"`
	// The unique identifier of the business issuing the refund.
	BusinessID string `json:"business_id" api:"required"`
	// The timestamp of when the refund was created in UTC.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Details about the customer for this refund (from the associated payment)
	Customer CustomerLimitedDetails `json:"customer" api:"required"`
	// If true the refund is a partial refund
	IsPartial bool `json:"is_partial" api:"required"`
	// Additional metadata stored with the refund.
	Metadata Metadata `json:"metadata" api:"required"`
	// The unique identifier of the payment associated with the refund.
	PaymentID string `json:"payment_id" api:"required"`
	// The unique identifier of the refund.
	RefundID string `json:"refund_id" api:"required"`
	// The current status of the refund.
	Status RefundStatus `json:"status" api:"required"`
	// The refunded amount.
	Amount int64 `json:"amount" api:"nullable"`
	// The currency of the refund, represented as an ISO 4217 currency code.
	Currency Currency `json:"currency" api:"nullable"`
	// The reason provided for the refund, if any. Optional.
	Reason string     `json:"reason" api:"nullable"`
	JSON   refundJSON `json:"-"`
}

func (*Refund) UnmarshalJSON

func (r *Refund) UnmarshalJSON(data []byte) (err error)

type RefundFailedWebhookEvent added in v1.56.0

type RefundFailedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	Data       Refund `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type RefundFailedWebhookEventType `json:"type" api:"required"`
	JSON refundFailedWebhookEventJSON `json:"-"`
}

func (*RefundFailedWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *RefundFailedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type RefundFailedWebhookEventType added in v1.56.0

type RefundFailedWebhookEventType string

The event type

const (
	RefundFailedWebhookEventTypeRefundFailed RefundFailedWebhookEventType = "refund.failed"
)

func (RefundFailedWebhookEventType) IsKnown added in v1.56.0

func (r RefundFailedWebhookEventType) IsKnown() bool

type RefundListItem added in v1.86.0

type RefundListItem struct {
	// The unique identifier of the business issuing the refund.
	BusinessID string `json:"business_id" api:"required"`
	// The timestamp of when the refund was created in UTC.
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// If true the refund is a partial refund
	IsPartial bool `json:"is_partial" api:"required"`
	// The unique identifier of the payment associated with the refund.
	PaymentID string `json:"payment_id" api:"required"`
	// The unique identifier of the refund.
	RefundID string `json:"refund_id" api:"required"`
	// The current status of the refund.
	Status RefundStatus `json:"status" api:"required"`
	// The refunded amount.
	Amount int64 `json:"amount" api:"nullable"`
	// The currency of the refund, represented as an ISO 4217 currency code.
	Currency Currency `json:"currency" api:"nullable"`
	// The reason provided for the refund, if any. Optional.
	Reason string             `json:"reason" api:"nullable"`
	JSON   refundListItemJSON `json:"-"`
}

func (*RefundListItem) UnmarshalJSON added in v1.86.0

func (r *RefundListItem) UnmarshalJSON(data []byte) (err error)

type RefundListParams

type RefundListParams struct {
	// Get events after this created time
	CreatedAtGte param.Field[time.Time] `query:"created_at_gte" format:"date-time"`
	// Get events created before this time
	CreatedAtLte param.Field[time.Time] `query:"created_at_lte" format:"date-time"`
	// Filter by customer_id
	CustomerID param.Field[string] `query:"customer_id"`
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
	// Filter by status
	Status param.Field[RefundListParamsStatus] `query:"status"`
	// Filter by subscription id
	SubscriptionID param.Field[string] `query:"subscription_id"`
}

func (RefundListParams) URLQuery

func (r RefundListParams) URLQuery() (v url.Values)

URLQuery serializes RefundListParams's query parameters as `url.Values`.

type RefundListParamsStatus added in v0.17.0

type RefundListParamsStatus string

Filter by status

const (
	RefundListParamsStatusSucceeded RefundListParamsStatus = "succeeded"
	RefundListParamsStatusFailed    RefundListParamsStatus = "failed"
	RefundListParamsStatusPending   RefundListParamsStatus = "pending"
	RefundListParamsStatusReview    RefundListParamsStatus = "review"
)

func (RefundListParamsStatus) IsKnown added in v0.17.0

func (r RefundListParamsStatus) IsKnown() bool

type RefundNewParams

type RefundNewParams struct {
	// The unique identifier of the payment to be refunded.
	PaymentID param.Field[string] `json:"payment_id" api:"required"`
	// Partially Refund an Individual Item
	Items param.Field[[]RefundNewParamsItem] `json:"items"`
	// Additional metadata associated with the refund.
	Metadata param.Field[MetadataParam] `json:"metadata"`
	// The reason for the refund, if any. Maximum length is 3000 characters. Optional.
	Reason param.Field[string] `json:"reason"`
}

func (RefundNewParams) MarshalJSON

func (r RefundNewParams) MarshalJSON() (data []byte, err error)

type RefundNewParamsItem added in v1.27.0

type RefundNewParamsItem struct {
	// The id of the item (i.e. `product_id` or `addon_id`)
	ItemID param.Field[string] `json:"item_id" api:"required"`
	// The amount to refund. if None the whole item is refunded
	Amount param.Field[int64] `json:"amount"`
	// Specify if tax is inclusive of the refund. Default true.
	TaxInclusive param.Field[bool] `json:"tax_inclusive"`
}

func (RefundNewParamsItem) MarshalJSON added in v1.27.0

func (r RefundNewParamsItem) MarshalJSON() (data []byte, err error)

type RefundService

type RefundService struct {
	Options []option.RequestOption
}

RefundService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewRefundService method instead.

func NewRefundService

func NewRefundService(opts ...option.RequestOption) (r *RefundService)

NewRefundService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*RefundService) Get

func (r *RefundService) Get(ctx context.Context, refundID string, opts ...option.RequestOption) (res *Refund, err error)

func (*RefundService) List

func (*RefundService) New

func (r *RefundService) New(ctx context.Context, body RefundNewParams, opts ...option.RequestOption) (res *Refund, err error)

type RefundStatus

type RefundStatus string
const (
	RefundStatusSucceeded RefundStatus = "succeeded"
	RefundStatusFailed    RefundStatus = "failed"
	RefundStatusPending   RefundStatus = "pending"
	RefundStatusReview    RefundStatus = "review"
)

func (RefundStatus) IsKnown

func (r RefundStatus) IsKnown() bool

type RefundSucceededWebhookEvent added in v1.56.0

type RefundSucceededWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	Data       Refund `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type RefundSucceededWebhookEventType `json:"type" api:"required"`
	JSON refundSucceededWebhookEventJSON `json:"-"`
}

func (*RefundSucceededWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *RefundSucceededWebhookEvent) UnmarshalJSON(data []byte) (err error)

type RefundSucceededWebhookEventType added in v1.56.0

type RefundSucceededWebhookEventType string

The event type

const (
	RefundSucceededWebhookEventTypeRefundSucceeded RefundSucceededWebhookEventType = "refund.succeeded"
)

func (RefundSucceededWebhookEventType) IsKnown added in v1.56.0

type ScheduledPlanChange added in v1.97.0

type ScheduledPlanChange struct {
	// The scheduled plan change ID
	ID string `json:"id" api:"required"`
	// Addons included in the scheduled change
	Addons []ScheduledPlanChangeAddon `json:"addons" api:"required"`
	// When this scheduled change was created
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// When the change will be applied
	EffectiveAt time.Time `json:"effective_at" api:"required" format:"date-time"`
	// The product ID the subscription will change to
	ProductID string `json:"product_id" api:"required"`
	// Quantity for the new plan
	Quantity int64 `json:"quantity" api:"required"`
	// Description of the product being changed to
	ProductDescription string `json:"product_description" api:"nullable"`
	// Name of the product being changed to
	ProductName string                  `json:"product_name" api:"nullable"`
	JSON        scheduledPlanChangeJSON `json:"-"`
}

func (*ScheduledPlanChange) UnmarshalJSON added in v1.97.0

func (r *ScheduledPlanChange) UnmarshalJSON(data []byte) (err error)

type ScheduledPlanChangeAddon added in v1.97.0

type ScheduledPlanChangeAddon struct {
	// The addon ID
	AddonID string `json:"addon_id" api:"required"`
	// Name of the addon
	Name string `json:"name" api:"required"`
	// Quantity of the addon
	Quantity int64                        `json:"quantity" api:"required"`
	JSON     scheduledPlanChangeAddonJSON `json:"-"`
}

func (*ScheduledPlanChangeAddon) UnmarshalJSON added in v1.97.0

func (r *ScheduledPlanChangeAddon) UnmarshalJSON(data []byte) (err error)

type Subscription

type Subscription struct {
	// Addons associated with this subscription
	Addons []AddonCartResponseItem `json:"addons" api:"required"`
	// Billing address details for payments
	Billing BillingAddress `json:"billing" api:"required"`
	// Brand id this subscription belongs to
	BrandID string `json:"brand_id" api:"required"`
	// Indicates if the subscription will cancel at the next billing date
	CancelAtNextBillingDate bool `json:"cancel_at_next_billing_date" api:"required"`
	// Timestamp when the subscription was created
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Credit entitlement cart settings for this subscription
	CreditEntitlementCart []CreditEntitlementCartResponse `json:"credit_entitlement_cart" api:"required"`
	// Currency used for the subscription payments
	Currency Currency `json:"currency" api:"required"`
	// Customer details associated with the subscription
	Customer CustomerLimitedDetails `json:"customer" api:"required"`
	// Whether a payment method is on file. False while a card-optional subscription
	// waits for the customer to add one.
	HasPaymentMethod bool `json:"has_payment_method" api:"required"`
	// Additional custom data associated with the subscription
	Metadata Metadata `json:"metadata" api:"required"`
	// Meter credit entitlement cart settings for this subscription
	MeterCreditEntitlementCart []MeterCreditEntitlementCartResponse `json:"meter_credit_entitlement_cart" api:"required"`
	// Meters associated with this subscription (for usage-based billing)
	Meters []MeterCartResponseItem `json:"meters" api:"required"`
	// Timestamp of the next scheduled billing. Indicates the end of current billing
	// period
	NextBillingDate time.Time `json:"next_billing_date" api:"required" format:"date-time"`
	// Wether the subscription is on-demand or not
	OnDemand bool `json:"on_demand" api:"required"`
	// Number of payment frequency intervals
	PaymentFrequencyCount int64 `json:"payment_frequency_count" api:"required"`
	// Time interval for payment frequency (e.g. month, year)
	PaymentFrequencyInterval TimeInterval `json:"payment_frequency_interval" api:"required"`
	// Timestamp of the last payment. Indicates the start of current billing period
	PreviousBillingDate time.Time `json:"previous_billing_date" api:"required" format:"date-time"`
	// Identifier of the product associated with this subscription
	ProductID string `json:"product_id" api:"required"`
	// Number of units/items included in the subscription
	Quantity int64 `json:"quantity" api:"required"`
	// Amount charged before tax for each recurring payment in the currency's smallest
	// unit (cents for USD, yen for JPY, fils for KWD)
	RecurringPreTaxAmount int64 `json:"recurring_pre_tax_amount" api:"required"`
	// Current status of the subscription
	Status SubscriptionStatus `json:"status" api:"required"`
	// Unique identifier for the subscription
	SubscriptionID string `json:"subscription_id" api:"required"`
	// Number of subscription period intervals
	SubscriptionPeriodCount int64 `json:"subscription_period_count" api:"required"`
	// Time interval for the subscription period (e.g. month, year)
	SubscriptionPeriodInterval TimeInterval `json:"subscription_period_interval" api:"required"`
	// Indicates if the recurring_pre_tax_amount is tax inclusive
	TaxInclusive bool `json:"tax_inclusive" api:"required"`
	// Number of days in the trial period (0 if no trial)
	TrialPeriodDays int64 `json:"trial_period_days" api:"required"`
	// Free-text cancellation comment, if any
	CancellationComment string `json:"cancellation_comment" api:"nullable"`
	// Customer-supplied churn reason, if any
	CancellationFeedback CancellationFeedback `json:"cancellation_feedback" api:"nullable"`
	// Cancelled timestamp if the subscription is cancelled
	CancelledAt time.Time `json:"cancelled_at" api:"nullable" format:"date-time"`
	// Customer's responses to custom fields collected during checkout
	CustomFieldResponses []CustomFieldResponse `json:"custom_field_responses" api:"nullable"`
	// Business / legal name associated with the tax id (B2B). When set this is used on
	// the invoice in place of the customer's personal name.
	CustomerBusinessName string `json:"customer_business_name" api:"nullable"`
	// DEPRECATED: Use discounts[].cycles_remaining instead.
	DiscountCyclesRemaining int64 `json:"discount_cycles_remaining" api:"nullable"`
	// DEPRECATED: Use discounts instead. Returns the first discount's ID if present.
	DiscountID string `json:"discount_id" api:"nullable"`
	// All stacked discounts applied, ordered by position
	Discounts []DiscountDetail `json:"discounts" api:"nullable"`
	// Timestamp when the subscription will expire
	ExpiresAt time.Time `json:"expires_at" api:"nullable" format:"date-time"`
	// Timestamp when the subscription was paused, if it currently is (or is `OnHold`
	// due to an unresolved pause settlement). `null` otherwise.
	PausedAt time.Time `json:"paused_at" api:"nullable" format:"date-time"`
	// Saved payment method id used for recurring charges
	PaymentMethodID string `json:"payment_method_id" api:"nullable"`
	// Scheduled plan change details, if any
	ScheduledChange ScheduledPlanChange `json:"scheduled_change" api:"nullable"`
	// Tax identifier provided for this subscription (if applicable)
	TaxID string `json:"tax_id" api:"nullable"`
	// Per-unit trial amount after discounts, snapshotted at subscription creation
	// (price currency minor units, pre-quantity, pre-tax). Null for a free trial or no
	// trial.
	TrialAmount int64            `json:"trial_amount" api:"nullable"`
	JSON        subscriptionJSON `json:"-"`
}

Response struct representing subscription details

func (*Subscription) UnmarshalJSON

func (r *Subscription) UnmarshalJSON(data []byte) (err error)

type SubscriptionActiveWebhookEvent added in v1.56.0

type SubscriptionActiveWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Subscription payload sent on a webhook. It carries every field of
	// `SubscriptionResponse`, plus the grace-period deadline.
	Data SubscriptionActiveWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type SubscriptionActiveWebhookEventType `json:"type" api:"required"`
	JSON subscriptionActiveWebhookEventJSON `json:"-"`
}

func (*SubscriptionActiveWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *SubscriptionActiveWebhookEvent) UnmarshalJSON(data []byte) (err error)

type SubscriptionActiveWebhookEventData added in v1.56.0

type SubscriptionActiveWebhookEventData struct {
	// Time when the grace period ends. The subscription moves to `on_hold` or to
	// `cancelled` at this time.
	//
	// Read in the same query as the rest of the payload, so it always comes from the
	// row snapshot that produced `status`. It is set whenever the subscription sits in
	// a window at that moment. A delayed event of another type therefore carries the
	// deadline too, next to a `past_due` status.
	PastDueEndsAt time.Time                              `json:"past_due_ends_at" api:"nullable" format:"date-time"`
	JSON          subscriptionActiveWebhookEventDataJSON `json:"-"`
	Subscription
}

Subscription payload sent on a webhook. It carries every field of `SubscriptionResponse`, plus the grace-period deadline.

func (*SubscriptionActiveWebhookEventData) UnmarshalJSON added in v1.56.0

func (r *SubscriptionActiveWebhookEventData) UnmarshalJSON(data []byte) (err error)

type SubscriptionActiveWebhookEventType added in v1.56.0

type SubscriptionActiveWebhookEventType string

The event type

const (
	SubscriptionActiveWebhookEventTypeSubscriptionActive SubscriptionActiveWebhookEventType = "subscription.active"
)

func (SubscriptionActiveWebhookEventType) IsKnown added in v1.56.0

type SubscriptionCancelledWebhookEvent added in v1.56.0

type SubscriptionCancelledWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Subscription payload sent on a webhook. It carries every field of
	// `SubscriptionResponse`, plus the grace-period deadline.
	Data SubscriptionCancelledWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type SubscriptionCancelledWebhookEventType `json:"type" api:"required"`
	JSON subscriptionCancelledWebhookEventJSON `json:"-"`
}

func (*SubscriptionCancelledWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *SubscriptionCancelledWebhookEvent) UnmarshalJSON(data []byte) (err error)

type SubscriptionCancelledWebhookEventData added in v1.56.0

type SubscriptionCancelledWebhookEventData struct {
	// Time when the grace period ends. The subscription moves to `on_hold` or to
	// `cancelled` at this time.
	//
	// Read in the same query as the rest of the payload, so it always comes from the
	// row snapshot that produced `status`. It is set whenever the subscription sits in
	// a window at that moment. A delayed event of another type therefore carries the
	// deadline too, next to a `past_due` status.
	PastDueEndsAt time.Time                                 `json:"past_due_ends_at" api:"nullable" format:"date-time"`
	JSON          subscriptionCancelledWebhookEventDataJSON `json:"-"`
	Subscription
}

Subscription payload sent on a webhook. It carries every field of `SubscriptionResponse`, plus the grace-period deadline.

func (*SubscriptionCancelledWebhookEventData) UnmarshalJSON added in v1.56.0

func (r *SubscriptionCancelledWebhookEventData) UnmarshalJSON(data []byte) (err error)

type SubscriptionCancelledWebhookEventType added in v1.56.0

type SubscriptionCancelledWebhookEventType string

The event type

const (
	SubscriptionCancelledWebhookEventTypeSubscriptionCancelled SubscriptionCancelledWebhookEventType = "subscription.cancelled"
)

func (SubscriptionCancelledWebhookEventType) IsKnown added in v1.56.0

type SubscriptionChangePlanParams added in v1.18.0

type SubscriptionChangePlanParams struct {
	UpdateSubscriptionPlanReq UpdateSubscriptionPlanReqParam `json:"update_subscription_plan_req" api:"required"`
}

func (SubscriptionChangePlanParams) MarshalJSON added in v1.18.0

func (r SubscriptionChangePlanParams) MarshalJSON() (data []byte, err error)

type SubscriptionChangePlanResponse added in v1.114.0

type SubscriptionChangePlanResponse struct {
	// Client secret for an embedded checkout.
	ClientSecret string `json:"client_secret" api:"nullable"`
	// When the link stops working.
	ExpiresOn time.Time `json:"expires_on" api:"nullable" format:"date-time"`
	// Id of the payment that settles the plan change.
	PaymentID string `json:"payment_id" api:"nullable"`
	// Checkout page URL. Give this to the customer.
	PaymentLink string                             `json:"payment_link" api:"nullable"`
	JSON        subscriptionChangePlanResponseJSON `json:"-"`
}

Handles for a hosted checkout page that settles a plan change.

The four fields repeat `UpdatePaymentMethodResponse` and a subset of `CreateSubscriptionResponse`. A shared type would rename the generated SDK types for all three routes, so each route keeps its own.

func (*SubscriptionChangePlanResponse) UnmarshalJSON added in v1.114.0

func (r *SubscriptionChangePlanResponse) UnmarshalJSON(data []byte) (err error)

type SubscriptionChargeParams added in v1.10.1

type SubscriptionChargeParams struct {
	// The product price. Represented in the lowest denomination of the currency (e.g.,
	// cents for USD). For example, to charge $1.00, pass `100`.
	ProductPrice param.Field[int64] `json:"product_price" api:"required"`
	// Whether adaptive currency fees should be included in the product_price (true) or
	// added on top (false). This field is ignored if adaptive pricing is not enabled
	// for the business.
	AdaptiveCurrencyFeesInclusive param.Field[bool] `json:"adaptive_currency_fees_inclusive"`
	// Specify how customer balance is used for the payment
	CustomerBalanceConfig param.Field[SubscriptionChargeParamsCustomerBalanceConfig] `json:"customer_balance_config"`
	// Metadata for the payment. If not passed, the metadata of the subscription will
	// be taken
	Metadata param.Field[MetadataParam] `json:"metadata"`
	// Optional currency of the product price. If not specified, defaults to the
	// currency of the product.
	ProductCurrency param.Field[Currency] `json:"product_currency"`
	// Optional product description override for billing and line items. If not
	// specified, the stored description of the product will be used.
	ProductDescription param.Field[string] `json:"product_description"`
}

func (SubscriptionChargeParams) MarshalJSON added in v1.10.1

func (r SubscriptionChargeParams) MarshalJSON() (data []byte, err error)

type SubscriptionChargeParamsCustomerBalanceConfig added in v1.53.2

type SubscriptionChargeParamsCustomerBalanceConfig struct {
	// Allows Customer Credit to be purchased to settle payments
	AllowCustomerCreditsPurchase param.Field[bool] `json:"allow_customer_credits_purchase"`
	// Allows Customer Credit Balance to be used to settle payments
	AllowCustomerCreditsUsage param.Field[bool] `json:"allow_customer_credits_usage"`
}

Specify how customer balance is used for the payment

func (SubscriptionChargeParamsCustomerBalanceConfig) MarshalJSON added in v1.53.2

func (r SubscriptionChargeParamsCustomerBalanceConfig) MarshalJSON() (data []byte, err error)

type SubscriptionChargeResponse added in v1.10.1

type SubscriptionChargeResponse struct {
	PaymentID string                         `json:"payment_id" api:"required"`
	JSON      subscriptionChargeResponseJSON `json:"-"`
}

func (*SubscriptionChargeResponse) UnmarshalJSON added in v1.10.1

func (r *SubscriptionChargeResponse) UnmarshalJSON(data []byte) (err error)

type SubscriptionDataParam added in v1.81.0

type SubscriptionDataParam struct {
	OnDemand param.Field[OnDemandSubscriptionParam] `json:"on_demand"`
	// Optional trial period in days If specified, this value overrides the trial
	// period set in the product's price Must be between 0 and 10000 days
	TrialPeriodDays param.Field[int64] `json:"trial_period_days"`
}

func (SubscriptionDataParam) MarshalJSON added in v1.81.0

func (r SubscriptionDataParam) MarshalJSON() (data []byte, err error)

type SubscriptionExpiredWebhookEvent added in v1.56.0

type SubscriptionExpiredWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Subscription payload sent on a webhook. It carries every field of
	// `SubscriptionResponse`, plus the grace-period deadline.
	Data SubscriptionExpiredWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type SubscriptionExpiredWebhookEventType `json:"type" api:"required"`
	JSON subscriptionExpiredWebhookEventJSON `json:"-"`
}

func (*SubscriptionExpiredWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *SubscriptionExpiredWebhookEvent) UnmarshalJSON(data []byte) (err error)

type SubscriptionExpiredWebhookEventData added in v1.56.0

type SubscriptionExpiredWebhookEventData struct {
	// Time when the grace period ends. The subscription moves to `on_hold` or to
	// `cancelled` at this time.
	//
	// Read in the same query as the rest of the payload, so it always comes from the
	// row snapshot that produced `status`. It is set whenever the subscription sits in
	// a window at that moment. A delayed event of another type therefore carries the
	// deadline too, next to a `past_due` status.
	PastDueEndsAt time.Time                               `json:"past_due_ends_at" api:"nullable" format:"date-time"`
	JSON          subscriptionExpiredWebhookEventDataJSON `json:"-"`
	Subscription
}

Subscription payload sent on a webhook. It carries every field of `SubscriptionResponse`, plus the grace-period deadline.

func (*SubscriptionExpiredWebhookEventData) UnmarshalJSON added in v1.56.0

func (r *SubscriptionExpiredWebhookEventData) UnmarshalJSON(data []byte) (err error)

type SubscriptionExpiredWebhookEventType added in v1.56.0

type SubscriptionExpiredWebhookEventType string

The event type

const (
	SubscriptionExpiredWebhookEventTypeSubscriptionExpired SubscriptionExpiredWebhookEventType = "subscription.expired"
)

func (SubscriptionExpiredWebhookEventType) IsKnown added in v1.56.0

type SubscriptionFailedWebhookEvent added in v1.56.0

type SubscriptionFailedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Subscription payload sent on a webhook. It carries every field of
	// `SubscriptionResponse`, plus the grace-period deadline.
	Data SubscriptionFailedWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type SubscriptionFailedWebhookEventType `json:"type" api:"required"`
	JSON subscriptionFailedWebhookEventJSON `json:"-"`
}

func (*SubscriptionFailedWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *SubscriptionFailedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type SubscriptionFailedWebhookEventData added in v1.56.0

type SubscriptionFailedWebhookEventData struct {
	// Time when the grace period ends. The subscription moves to `on_hold` or to
	// `cancelled` at this time.
	//
	// Read in the same query as the rest of the payload, so it always comes from the
	// row snapshot that produced `status`. It is set whenever the subscription sits in
	// a window at that moment. A delayed event of another type therefore carries the
	// deadline too, next to a `past_due` status.
	PastDueEndsAt time.Time                              `json:"past_due_ends_at" api:"nullable" format:"date-time"`
	JSON          subscriptionFailedWebhookEventDataJSON `json:"-"`
	Subscription
}

Subscription payload sent on a webhook. It carries every field of `SubscriptionResponse`, plus the grace-period deadline.

func (*SubscriptionFailedWebhookEventData) UnmarshalJSON added in v1.56.0

func (r *SubscriptionFailedWebhookEventData) UnmarshalJSON(data []byte) (err error)

type SubscriptionFailedWebhookEventType added in v1.56.0

type SubscriptionFailedWebhookEventType string

The event type

const (
	SubscriptionFailedWebhookEventTypeSubscriptionFailed SubscriptionFailedWebhookEventType = "subscription.failed"
)

func (SubscriptionFailedWebhookEventType) IsKnown added in v1.56.0

type SubscriptionGetCreditUsageResponse added in v1.86.0

type SubscriptionGetCreditUsageResponse struct {
	Items          []SubscriptionGetCreditUsageResponseItem `json:"items" api:"required"`
	SubscriptionID string                                   `json:"subscription_id" api:"required"`
	JSON           subscriptionGetCreditUsageResponseJSON   `json:"-"`
}

Credit usage status for all entitlements linked to a subscription

func (*SubscriptionGetCreditUsageResponse) UnmarshalJSON added in v1.86.0

func (r *SubscriptionGetCreditUsageResponse) UnmarshalJSON(data []byte) (err error)

type SubscriptionGetCreditUsageResponseItem added in v1.86.0

type SubscriptionGetCreditUsageResponseItem struct {
	// Customer's current credit balance for this entitlement (customer-wide)
	Balance               string `json:"balance" api:"required"`
	CreditEntitlementID   string `json:"credit_entitlement_id" api:"required"`
	CreditEntitlementName string `json:"credit_entitlement_name" api:"required"`
	// True if overage has reached or exceeded the limit. When true, further deductions
	// that would increase overage will fail.
	LimitReached bool `json:"limit_reached" api:"required"`
	// Current overage amount accrued (customer-wide)
	Overage string `json:"overage" api:"required"`
	// Whether overage is enabled for this entitlement on this subscription
	OverageEnabled bool `json:"overage_enabled" api:"required"`
	// Unit label for the credit entitlement (e.g. "API Calls", "Tokens")
	Unit string `json:"unit" api:"required"`
	// Maximum allowed overage before deductions are blocked. None means unlimited
	// overage (when overage_enabled is true).
	OverageLimit string `json:"overage_limit" api:"nullable"`
	// How much more overage can accumulate before being blocked. None if overage is
	// not enabled or there is no limit (unlimited). A value of 0 means the next
	// deduction that increases overage will be blocked.
	RemainingHeadroom string                                     `json:"remaining_headroom" api:"nullable"`
	JSON              subscriptionGetCreditUsageResponseItemJSON `json:"-"`
}

Per-entitlement credit usage status for a subscription

func (*SubscriptionGetCreditUsageResponseItem) UnmarshalJSON added in v1.86.0

func (r *SubscriptionGetCreditUsageResponseItem) UnmarshalJSON(data []byte) (err error)

type SubscriptionGetUsageHistoryParams added in v1.52.4

type SubscriptionGetUsageHistoryParams struct {
	// Filter by end date (inclusive)
	EndDate param.Field[time.Time] `query:"end_date" format:"date-time"`
	// Filter by specific meter ID
	MeterID param.Field[string] `query:"meter_id"`
	// Page number (default: 0)
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size (default: 10, max: 100)
	PageSize param.Field[int64] `query:"page_size"`
	// Filter by start date (inclusive)
	StartDate param.Field[time.Time] `query:"start_date" format:"date-time"`
}

func (SubscriptionGetUsageHistoryParams) URLQuery added in v1.52.4

func (r SubscriptionGetUsageHistoryParams) URLQuery() (v url.Values)

URLQuery serializes SubscriptionGetUsageHistoryParams's query parameters as `url.Values`.

type SubscriptionGetUsageHistoryResponse added in v1.52.4

type SubscriptionGetUsageHistoryResponse struct {
	// End date of the billing period
	EndDate time.Time `json:"end_date" api:"required" format:"date-time"`
	// List of meters and their usage for this billing period
	Meters []SubscriptionGetUsageHistoryResponseMeter `json:"meters" api:"required"`
	// Start date of the billing period
	StartDate time.Time                               `json:"start_date" api:"required" format:"date-time"`
	JSON      subscriptionGetUsageHistoryResponseJSON `json:"-"`
}

func (*SubscriptionGetUsageHistoryResponse) UnmarshalJSON added in v1.52.4

func (r *SubscriptionGetUsageHistoryResponse) UnmarshalJSON(data []byte) (err error)

type SubscriptionGetUsageHistoryResponseMeter added in v1.52.4

type SubscriptionGetUsageHistoryResponseMeter struct {
	// Meter identifier
	ID string `json:"id" api:"required"`
	// Chargeable units (after free threshold) as string for precision
	ChargeableUnits string `json:"chargeable_units" api:"required"`
	// Total units consumed as string for precision
	ConsumedUnits string `json:"consumed_units" api:"required"`
	// Currency for the price per unit
	Currency Currency `json:"currency" api:"required"`
	// Free threshold units for this meter
	FreeThreshold int64 `json:"free_threshold" api:"required"`
	// Meter name
	Name string `json:"name" api:"required"`
	// Price per unit in string format for precision
	PricePerUnit string `json:"price_per_unit" api:"required"`
	// Total price charged for this meter in the currency's smallest unit (cents for
	// USD, yen for JPY, fils for KWD)
	TotalPrice int64                                        `json:"total_price" api:"required"`
	JSON       subscriptionGetUsageHistoryResponseMeterJSON `json:"-"`
}

func (*SubscriptionGetUsageHistoryResponseMeter) UnmarshalJSON added in v1.52.4

func (r *SubscriptionGetUsageHistoryResponseMeter) UnmarshalJSON(data []byte) (err error)

type SubscriptionListParams

type SubscriptionListParams struct {
	// filter by Brand id
	BrandID param.Field[string] `query:"brand_id"`
	// Filter by cancel_at_next_billing_date (subscriptions scheduled for cancellation)
	CancelAtNextBillingDate param.Field[bool] `query:"cancel_at_next_billing_date"`
	// Get events after this created time
	CreatedAtGte param.Field[time.Time] `query:"created_at_gte" format:"date-time"`
	// Get events created before this time
	CreatedAtLte param.Field[time.Time] `query:"created_at_lte" format:"date-time"`
	// Filter by customer id
	CustomerID param.Field[string] `query:"customer_id"`
	// Page number default is 0
	PageNumber param.Field[int64] `query:"page_number"`
	// Page size default is 10 max is 100
	PageSize param.Field[int64] `query:"page_size"`
	// Filter by product id
	ProductID param.Field[string] `query:"product_id"`
	// Filter by status
	Status param.Field[SubscriptionListParamsStatus] `query:"status"`
}

func (SubscriptionListParams) URLQuery

func (r SubscriptionListParams) URLQuery() (v url.Values)

URLQuery serializes SubscriptionListParams's query parameters as `url.Values`.

type SubscriptionListParamsStatus added in v0.17.0

type SubscriptionListParamsStatus string

Filter by status

const (
	SubscriptionListParamsStatusPending   SubscriptionListParamsStatus = "pending"
	SubscriptionListParamsStatusActive    SubscriptionListParamsStatus = "active"
	SubscriptionListParamsStatusOnHold    SubscriptionListParamsStatus = "on_hold"
	SubscriptionListParamsStatusPaused    SubscriptionListParamsStatus = "paused"
	SubscriptionListParamsStatusCancelled SubscriptionListParamsStatus = "cancelled"
	SubscriptionListParamsStatusFailed    SubscriptionListParamsStatus = "failed"
	SubscriptionListParamsStatusExpired   SubscriptionListParamsStatus = "expired"
	SubscriptionListParamsStatusPastDue   SubscriptionListParamsStatus = "past_due"
)

func (SubscriptionListParamsStatus) IsKnown added in v0.17.0

func (r SubscriptionListParamsStatus) IsKnown() bool

type SubscriptionListResponse added in v1.20.0

type SubscriptionListResponse struct {
	// Billing address details for payments
	Billing BillingAddress `json:"billing" api:"required"`
	// Indicates if the subscription will cancel at the next billing date
	CancelAtNextBillingDate bool `json:"cancel_at_next_billing_date" api:"required"`
	// Timestamp when the subscription was created
	CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
	// Currency used for the subscription payments
	Currency Currency `json:"currency" api:"required"`
	// Customer details associated with the subscription
	Customer CustomerLimitedDetails `json:"customer" api:"required"`
	// All stacked discounts applied, in order of application
	Discounts []SubscriptionListResponseDiscount `json:"discounts" api:"required"`
	// Whether a payment method is on file. False while a card-optional subscription
	// waits for the customer to add one.
	HasPaymentMethod bool `json:"has_payment_method" api:"required"`
	// Additional custom data associated with the subscription
	Metadata Metadata `json:"metadata" api:"required"`
	// Timestamp of the next scheduled billing. Indicates the end of current billing
	// period
	NextBillingDate time.Time `json:"next_billing_date" api:"required" format:"date-time"`
	// Wether the subscription is on-demand or not
	OnDemand bool `json:"on_demand" api:"required"`
	// Number of payment frequency intervals
	PaymentFrequencyCount int64 `json:"payment_frequency_count" api:"required"`
	// Time interval for payment frequency (e.g. month, year)
	PaymentFrequencyInterval TimeInterval `json:"payment_frequency_interval" api:"required"`
	// Timestamp of the last payment. Indicates the start of current billing period
	PreviousBillingDate time.Time `json:"previous_billing_date" api:"required" format:"date-time"`
	// Identifier of the product associated with this subscription
	ProductID string `json:"product_id" api:"required"`
	// Number of units/items included in the subscription
	Quantity int64 `json:"quantity" api:"required"`
	// Amount charged before tax for each recurring payment in the currency's smallest
	// unit (cents for USD, yen for JPY, fils for KWD)
	RecurringPreTaxAmount int64 `json:"recurring_pre_tax_amount" api:"required"`
	// Current status of the subscription
	Status SubscriptionStatus `json:"status" api:"required"`
	// Unique identifier for the subscription
	SubscriptionID string `json:"subscription_id" api:"required"`
	// Number of subscription period intervals
	SubscriptionPeriodCount int64 `json:"subscription_period_count" api:"required"`
	// Time interval for the subscription period (e.g. month, year)
	SubscriptionPeriodInterval TimeInterval `json:"subscription_period_interval" api:"required"`
	// Indicates if the recurring_pre_tax_amount is tax inclusive
	TaxInclusive bool `json:"tax_inclusive" api:"required"`
	// Number of days in the trial period (0 if no trial)
	TrialPeriodDays int64 `json:"trial_period_days" api:"required"`
	// Cancelled timestamp if the subscription is cancelled
	CancelledAt time.Time `json:"cancelled_at" api:"nullable" format:"date-time"`
	// Business / legal name associated with the tax id (B2B). When set this is used on
	// the invoice in place of the customer's personal name.
	CustomerBusinessName string `json:"customer_business_name" api:"nullable"`
	// DEPRECATED: Use discounts[].cycles_remaining instead.
	DiscountCyclesRemaining int64 `json:"discount_cycles_remaining" api:"nullable"`
	// DEPRECATED: Use discounts instead.
	DiscountID string `json:"discount_id" api:"nullable"`
	// Timestamp when the subscription was paused, if it currently is (or is `OnHold`
	// due to an unresolved pause settlement). `null` otherwise.
	PausedAt time.Time `json:"paused_at" api:"nullable" format:"date-time"`
	// Saved payment method id used for recurring charges
	PaymentMethodID string `json:"payment_method_id" api:"nullable"`
	// Name of the product associated with this subscription
	ProductName string `json:"product_name" api:"nullable"`
	// Scheduled plan change details, if any
	ScheduledChange ScheduledPlanChange `json:"scheduled_change" api:"nullable"`
	// Tax identifier provided for this subscription (if applicable)
	TaxID string `json:"tax_id" api:"nullable"`
	// Per-unit trial amount after discounts, snapshotted at subscription creation
	// (price currency minor units, pre-quantity, pre-tax). Null for a free trial or no
	// trial.
	TrialAmount int64                        `json:"trial_amount" api:"nullable"`
	JSON        subscriptionListResponseJSON `json:"-"`
}

Response struct representing subscription details

func (*SubscriptionListResponse) UnmarshalJSON added in v1.20.0

func (r *SubscriptionListResponse) UnmarshalJSON(data []byte) (err error)

type SubscriptionListResponseDiscount added in v1.97.3

type SubscriptionListResponseDiscount struct {
	// The unique discount ID
	DiscountID string `json:"discount_id" api:"required"`
	// Remaining billing cycles for this discount on this subscription
	DiscountCyclesRemaining int64                                `json:"discount_cycles_remaining" api:"nullable"`
	JSON                    subscriptionListResponseDiscountJSON `json:"-"`
}

Lightweight discount info for list endpoints. Array order represents position (no explicit position field).

func (*SubscriptionListResponseDiscount) UnmarshalJSON added in v1.97.3

func (r *SubscriptionListResponseDiscount) UnmarshalJSON(data []byte) (err error)

type SubscriptionNewParams

type SubscriptionNewParams struct {
	// Billing address information for the subscription
	Billing param.Field[BillingAddressParam] `json:"billing" api:"required"`
	// Customer details for the subscription
	Customer param.Field[CustomerRequestUnionParam] `json:"customer" api:"required"`
	// Unique identifier of the product to subscribe to
	ProductID param.Field[string] `json:"product_id" api:"required"`
	// Number of units to subscribe for. Must be at least 1.
	Quantity param.Field[int64] `json:"quantity" api:"required"`
	// Attach addons to this subscription
	Addons param.Field[[]AttachAddonParam] `json:"addons"`
	// List of payment methods allowed during checkout.
	//
	// Customers will **never** see payment methods that are **not** in this list.
	// However, adding a method here **does not guarantee** customers will see it.
	// Availability still depends on other factors (e.g., customer location, merchant
	// settings).
	AllowedPaymentMethodTypes param.Field[[]PaymentMethodTypes] `json:"allowed_payment_method_types"`
	// Fix the currency in which the end customer is billed. If Dodo Payments cannot
	// support that currency for this transaction, it will not proceed
	BillingCurrency param.Field[Currency] `json:"billing_currency"`
	// Optional business / legal name associated with the tax id. When provided
	// together with a valid tax id for a B2B purchase, this name is rendered on the
	// invoice instead of the customer's personal name.
	CustomerBusinessName param.Field[string] `json:"customer_business_name"`
	// DEPRECATED: Use discount_codes instead. Cannot be used together with
	// discount_codes.
	DiscountCode param.Field[string] `json:"discount_code"`
	// Stacked discount codes to apply, in order of application. Max 20. Cannot be used
	// together with discount_code.
	DiscountCodes param.Field[[]string] `json:"discount_codes"`
	// Override merchant default 3DS behaviour for this subscription
	Force3DS param.Field[bool] `json:"force_3ds"`
	// Override the merchant-level mandate floor (in INR paise) for INR e-mandates on
	// Indian-card recurring payments. The mandate amount sent to the processor is
	// `max(this_floor, actual_billing_amount)`, so this is effectively the
	// customer-facing authorization ceiling whenever billing is lower. When unset, the
	// merchant setting applies; when that's also unset, the system default of ₹15,000
	// applies.
	MandateMinAmountInrPaise param.Field[int64] `json:"mandate_min_amount_inr_paise"`
	// Additional metadata for the subscription Defaults to empty if not specified
	Metadata param.Field[MetadataParam]             `json:"metadata"`
	OnDemand param.Field[OnDemandSubscriptionParam] `json:"on_demand"`
	// List of one time products that will be bundled with the first payment for this
	// subscription
	OneTimeProductCart param.Field[[]OneTimeProductCartItemParam] `json:"one_time_product_cart"`
	// If true, generates a payment link. Defaults to false if not specified.
	PaymentLink param.Field[bool] `json:"payment_link"`
	// Optional payment method ID to use for this subscription. If provided,
	// customer_id must also be provided (via AttachExistingCustomer). The payment
	// method will be validated for eligibility with the subscription's currency.
	PaymentMethodID param.Field[string] `json:"payment_method_id"`
	// If true, redirects the customer immediately after payment completion False by
	// default
	RedirectImmediately param.Field[bool] `json:"redirect_immediately"`
	// If true, the customer's phone number is required to create this subscription.
	// Typically set alongside `payment_link=true` so merchants can enforce phone
	// collection on the hosted payment page. Defaults to false.
	RequirePhoneNumber param.Field[bool] `json:"require_phone_number"`
	// Optional URL to redirect after successful subscription creation
	ReturnURL param.Field[string] `json:"return_url"`
	// If true, returns a shortened payment link. Defaults to false if not specified.
	ShortLink param.Field[bool] `json:"short_link"`
	// Display saved payment methods of a returning customer False by default
	ShowSavedPaymentMethods param.Field[bool] `json:"show_saved_payment_methods"`
	// Tax ID in case the payment is B2B. If tax id validation fails the payment
	// creation will fail
	TaxID param.Field[string] `json:"tax_id"`
	// Optional trial period in days If specified, this value overrides the trial
	// period set in the product's price Must be between 0 and 10000 days
	TrialPeriodDays param.Field[int64] `json:"trial_period_days"`
}

func (SubscriptionNewParams) MarshalJSON

func (r SubscriptionNewParams) MarshalJSON() (data []byte, err error)

type SubscriptionNewResponse

type SubscriptionNewResponse struct {
	// Addons associated with this subscription
	Addons []AddonCartResponseItem `json:"addons" api:"required"`
	// Customer details associated with this subscription
	Customer CustomerLimitedDetails `json:"customer" api:"required"`
	// Additional metadata associated with the subscription
	Metadata Metadata `json:"metadata" api:"required"`
	// First payment id for the subscription
	PaymentID string `json:"payment_id" api:"required"`
	// False when the customer can start this subscription with no card. True for every
	// other subscription.
	PaymentMethodRequired bool `json:"payment_method_required" api:"required"`
	// Tax will be added to the amount and charged to the customer on each billing
	// cycle
	RecurringPreTaxAmount int64 `json:"recurring_pre_tax_amount" api:"required"`
	// Unique identifier for the subscription
	SubscriptionID string `json:"subscription_id" api:"required"`
	// Client secret used to load Dodo checkout SDK NOTE : Dodo checkout SDK will be
	// coming soon
	ClientSecret string `json:"client_secret" api:"nullable"`
	// DEPRECATED: Use discount_ids instead. Returns the first discount's ID if
	// present.
	//
	// Deprecated: Use `discounts` instead.
	DiscountID string `json:"discount_id" api:"nullable"`
	// All stacked discount IDs applied, in order of application
	DiscountIDs []string `json:"discount_ids" api:"nullable"`
	// Expiry timestamp of the payment link
	ExpiresOn time.Time `json:"expires_on" api:"nullable" format:"date-time"`
	// One time products associated with the purchase of subscription
	OneTimeProductCart []SubscriptionNewResponseOneTimeProductCart `json:"one_time_product_cart" api:"nullable"`
	// URL to checkout page
	PaymentLink string `json:"payment_link" api:"nullable"`
	// Per-unit trial amount after discounts, in the price currency's minor units
	// (pre-quantity, pre-tax). Null for a free trial or no trial.
	TrialAmount int64                       `json:"trial_amount" api:"nullable"`
	JSON        subscriptionNewResponseJSON `json:"-"`
}

func (*SubscriptionNewResponse) UnmarshalJSON

func (r *SubscriptionNewResponse) UnmarshalJSON(data []byte) (err error)

type SubscriptionNewResponseOneTimeProductCart added in v1.66.2

type SubscriptionNewResponseOneTimeProductCart struct {
	ProductID string                                        `json:"product_id" api:"required"`
	Quantity  int64                                         `json:"quantity" api:"required"`
	JSON      subscriptionNewResponseOneTimeProductCartJSON `json:"-"`
}

func (*SubscriptionNewResponseOneTimeProductCart) UnmarshalJSON added in v1.66.2

func (r *SubscriptionNewResponseOneTimeProductCart) UnmarshalJSON(data []byte) (err error)

type SubscriptionOnHoldWebhookEvent added in v1.56.0

type SubscriptionOnHoldWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Subscription payload sent on a webhook. It carries every field of
	// `SubscriptionResponse`, plus the grace-period deadline.
	Data SubscriptionOnHoldWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type SubscriptionOnHoldWebhookEventType `json:"type" api:"required"`
	JSON subscriptionOnHoldWebhookEventJSON `json:"-"`
}

func (*SubscriptionOnHoldWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *SubscriptionOnHoldWebhookEvent) UnmarshalJSON(data []byte) (err error)

type SubscriptionOnHoldWebhookEventData added in v1.56.0

type SubscriptionOnHoldWebhookEventData struct {
	// Time when the grace period ends. The subscription moves to `on_hold` or to
	// `cancelled` at this time.
	//
	// Read in the same query as the rest of the payload, so it always comes from the
	// row snapshot that produced `status`. It is set whenever the subscription sits in
	// a window at that moment. A delayed event of another type therefore carries the
	// deadline too, next to a `past_due` status.
	PastDueEndsAt time.Time                              `json:"past_due_ends_at" api:"nullable" format:"date-time"`
	JSON          subscriptionOnHoldWebhookEventDataJSON `json:"-"`
	Subscription
}

Subscription payload sent on a webhook. It carries every field of `SubscriptionResponse`, plus the grace-period deadline.

func (*SubscriptionOnHoldWebhookEventData) UnmarshalJSON added in v1.56.0

func (r *SubscriptionOnHoldWebhookEventData) UnmarshalJSON(data []byte) (err error)

type SubscriptionOnHoldWebhookEventType added in v1.56.0

type SubscriptionOnHoldWebhookEventType string

The event type

const (
	SubscriptionOnHoldWebhookEventTypeSubscriptionOnHold SubscriptionOnHoldWebhookEventType = "subscription.on_hold"
)

func (SubscriptionOnHoldWebhookEventType) IsKnown added in v1.56.0

type SubscriptionPastDueWebhookEvent added in v1.115.0

type SubscriptionPastDueWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Subscription payload sent on a webhook. It carries every field of
	// `SubscriptionResponse`, plus the grace-period deadline.
	Data SubscriptionPastDueWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type SubscriptionPastDueWebhookEventType `json:"type" api:"required"`
	JSON subscriptionPastDueWebhookEventJSON `json:"-"`
}

func (*SubscriptionPastDueWebhookEvent) UnmarshalJSON added in v1.115.0

func (r *SubscriptionPastDueWebhookEvent) UnmarshalJSON(data []byte) (err error)

type SubscriptionPastDueWebhookEventData added in v1.115.0

type SubscriptionPastDueWebhookEventData struct {
	// Time when the grace period ends. The subscription moves to `on_hold` or to
	// `cancelled` at this time.
	//
	// Read in the same query as the rest of the payload, so it always comes from the
	// row snapshot that produced `status`. It is set whenever the subscription sits in
	// a window at that moment. A delayed event of another type therefore carries the
	// deadline too, next to a `past_due` status.
	PastDueEndsAt time.Time                               `json:"past_due_ends_at" api:"nullable" format:"date-time"`
	JSON          subscriptionPastDueWebhookEventDataJSON `json:"-"`
	Subscription
}

Subscription payload sent on a webhook. It carries every field of `SubscriptionResponse`, plus the grace-period deadline.

func (*SubscriptionPastDueWebhookEventData) UnmarshalJSON added in v1.115.0

func (r *SubscriptionPastDueWebhookEventData) UnmarshalJSON(data []byte) (err error)

type SubscriptionPastDueWebhookEventType added in v1.115.0

type SubscriptionPastDueWebhookEventType string

The event type

const (
	SubscriptionPastDueWebhookEventTypeSubscriptionPastDue SubscriptionPastDueWebhookEventType = "subscription.past_due"
)

func (SubscriptionPastDueWebhookEventType) IsKnown added in v1.115.0

type SubscriptionPausedWebhookEvent added in v1.112.0

type SubscriptionPausedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Subscription payload sent on a webhook. It carries every field of
	// `SubscriptionResponse`, plus the grace-period deadline.
	Data SubscriptionPausedWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type SubscriptionPausedWebhookEventType `json:"type" api:"required"`
	JSON subscriptionPausedWebhookEventJSON `json:"-"`
}

func (*SubscriptionPausedWebhookEvent) UnmarshalJSON added in v1.112.0

func (r *SubscriptionPausedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type SubscriptionPausedWebhookEventData added in v1.115.0

type SubscriptionPausedWebhookEventData struct {
	// Time when the grace period ends. The subscription moves to `on_hold` or to
	// `cancelled` at this time.
	//
	// Read in the same query as the rest of the payload, so it always comes from the
	// row snapshot that produced `status`. It is set whenever the subscription sits in
	// a window at that moment. A delayed event of another type therefore carries the
	// deadline too, next to a `past_due` status.
	PastDueEndsAt time.Time                              `json:"past_due_ends_at" api:"nullable" format:"date-time"`
	JSON          subscriptionPausedWebhookEventDataJSON `json:"-"`
	Subscription
}

Subscription payload sent on a webhook. It carries every field of `SubscriptionResponse`, plus the grace-period deadline.

func (*SubscriptionPausedWebhookEventData) UnmarshalJSON added in v1.115.0

func (r *SubscriptionPausedWebhookEventData) UnmarshalJSON(data []byte) (err error)

type SubscriptionPausedWebhookEventType added in v1.112.0

type SubscriptionPausedWebhookEventType string

The event type

const (
	SubscriptionPausedWebhookEventTypeSubscriptionPaused SubscriptionPausedWebhookEventType = "subscription.paused"
)

func (SubscriptionPausedWebhookEventType) IsKnown added in v1.112.0

type SubscriptionPlanChangedWebhookEvent added in v1.56.0

type SubscriptionPlanChangedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Subscription payload sent on a webhook. It carries every field of
	// `SubscriptionResponse`, plus the grace-period deadline.
	Data SubscriptionPlanChangedWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type SubscriptionPlanChangedWebhookEventType `json:"type" api:"required"`
	JSON subscriptionPlanChangedWebhookEventJSON `json:"-"`
}

func (*SubscriptionPlanChangedWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *SubscriptionPlanChangedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type SubscriptionPlanChangedWebhookEventData added in v1.56.0

type SubscriptionPlanChangedWebhookEventData struct {
	// Time when the grace period ends. The subscription moves to `on_hold` or to
	// `cancelled` at this time.
	//
	// Read in the same query as the rest of the payload, so it always comes from the
	// row snapshot that produced `status`. It is set whenever the subscription sits in
	// a window at that moment. A delayed event of another type therefore carries the
	// deadline too, next to a `past_due` status.
	PastDueEndsAt time.Time                                   `json:"past_due_ends_at" api:"nullable" format:"date-time"`
	JSON          subscriptionPlanChangedWebhookEventDataJSON `json:"-"`
	Subscription
}

Subscription payload sent on a webhook. It carries every field of `SubscriptionResponse`, plus the grace-period deadline.

func (*SubscriptionPlanChangedWebhookEventData) UnmarshalJSON added in v1.56.0

func (r *SubscriptionPlanChangedWebhookEventData) UnmarshalJSON(data []byte) (err error)

type SubscriptionPlanChangedWebhookEventType added in v1.56.0

type SubscriptionPlanChangedWebhookEventType string

The event type

const (
	SubscriptionPlanChangedWebhookEventTypeSubscriptionPlanChanged SubscriptionPlanChangedWebhookEventType = "subscription.plan_changed"
)

func (SubscriptionPlanChangedWebhookEventType) IsKnown added in v1.56.0

type SubscriptionPreviewChangePlanParams added in v1.66.0

type SubscriptionPreviewChangePlanParams struct {
	UpdateSubscriptionPlanReq UpdateSubscriptionPlanReqParam `json:"update_subscription_plan_req" api:"required"`
}

func (SubscriptionPreviewChangePlanParams) MarshalJSON added in v1.66.0

func (r SubscriptionPreviewChangePlanParams) MarshalJSON() (data []byte, err error)

type SubscriptionPreviewChangePlanResponse added in v1.66.0

type SubscriptionPreviewChangePlanResponse struct {
	ImmediateCharge SubscriptionPreviewChangePlanResponseImmediateCharge `json:"immediate_charge" api:"required"`
	// Response struct representing subscription details
	NewPlan Subscription                              `json:"new_plan" api:"required"`
	JSON    subscriptionPreviewChangePlanResponseJSON `json:"-"`
}

func (*SubscriptionPreviewChangePlanResponse) UnmarshalJSON added in v1.66.0

func (r *SubscriptionPreviewChangePlanResponse) UnmarshalJSON(data []byte) (err error)

type SubscriptionPreviewChangePlanResponseImmediateCharge added in v1.66.0

type SubscriptionPreviewChangePlanResponseImmediateCharge struct {
	// When the plan change will be effective
	EffectiveAt time.Time                                                      `json:"effective_at" api:"required" format:"date-time"`
	LineItems   []SubscriptionPreviewChangePlanResponseImmediateChargeLineItem `json:"line_items" api:"required"`
	Summary     SubscriptionPreviewChangePlanResponseImmediateChargeSummary    `json:"summary" api:"required"`
	JSON        subscriptionPreviewChangePlanResponseImmediateChargeJSON       `json:"-"`
}

func (*SubscriptionPreviewChangePlanResponseImmediateCharge) UnmarshalJSON added in v1.66.0

func (r *SubscriptionPreviewChangePlanResponseImmediateCharge) UnmarshalJSON(data []byte) (err error)

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItem added in v1.66.0

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItem struct {
	ID              string                                                            `json:"id" api:"required"`
	Currency        Currency                                                          `json:"currency" api:"required"`
	TaxInclusive    bool                                                              `json:"tax_inclusive" api:"required"`
	Type            SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsType `json:"type" api:"required"`
	ChargeableUnits string                                                            `json:"chargeable_units"`
	Description     string                                                            `json:"description" api:"nullable"`
	FreeThreshold   int64                                                             `json:"free_threshold"`
	Name            string                                                            `json:"name" api:"nullable"`
	PricePerUnit    string                                                            `json:"price_per_unit"`
	ProductID       string                                                            `json:"product_id"`
	ProrationFactor float64                                                           `json:"proration_factor"`
	Quantity        int64                                                             `json:"quantity"`
	Subtotal        int64                                                             `json:"subtotal"`
	Tax             int64                                                             `json:"tax" api:"nullable"`
	// Represents the different categories of taxation applicable to various products
	// and services.
	TaxCategory   TaxCategory                                                      `json:"tax_category"`
	TaxRate       float64                                                          `json:"tax_rate" api:"nullable"`
	UnitPrice     int64                                                            `json:"unit_price"`
	UnitsConsumed string                                                           `json:"units_consumed"`
	JSON          subscriptionPreviewChangePlanResponseImmediateChargeLineItemJSON `json:"-"`
	// contains filtered or unexported fields
}

func (*SubscriptionPreviewChangePlanResponseImmediateChargeLineItem) UnmarshalJSON added in v1.66.0

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsAddon added in v1.66.2

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsAddon struct {
	ID              string   `json:"id" api:"required"`
	Currency        Currency `json:"currency" api:"required"`
	Name            string   `json:"name" api:"required"`
	ProrationFactor float64  `json:"proration_factor" api:"required"`
	Quantity        int64    `json:"quantity" api:"required"`
	// Represents the different categories of taxation applicable to various products
	// and services.
	TaxCategory  TaxCategory                                                            `json:"tax_category" api:"required"`
	TaxInclusive bool                                                                   `json:"tax_inclusive" api:"required"`
	TaxRate      float64                                                                `json:"tax_rate" api:"required"`
	Type         SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsAddonType `json:"type" api:"required"`
	UnitPrice    int64                                                                  `json:"unit_price" api:"required"`
	Description  string                                                                 `json:"description" api:"nullable"`
	Tax          int64                                                                  `json:"tax" api:"nullable"`
	JSON         subscriptionPreviewChangePlanResponseImmediateChargeLineItemsAddonJSON `json:"-"`
}

func (*SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsAddon) UnmarshalJSON added in v1.66.2

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsAddonType added in v1.66.2

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsAddonType string
const (
	SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsAddonTypeAddon SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsAddonType = "addon"
)

func (SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsAddonType) IsKnown added in v1.66.2

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsMeter added in v1.66.2

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsMeter struct {
	ID              string                                                                 `json:"id" api:"required"`
	ChargeableUnits string                                                                 `json:"chargeable_units" api:"required"`
	Currency        Currency                                                               `json:"currency" api:"required"`
	FreeThreshold   int64                                                                  `json:"free_threshold" api:"required"`
	Name            string                                                                 `json:"name" api:"required"`
	PricePerUnit    string                                                                 `json:"price_per_unit" api:"required"`
	Subtotal        int64                                                                  `json:"subtotal" api:"required"`
	TaxInclusive    bool                                                                   `json:"tax_inclusive" api:"required"`
	TaxRate         float64                                                                `json:"tax_rate" api:"required"`
	Type            SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsMeterType `json:"type" api:"required"`
	UnitsConsumed   string                                                                 `json:"units_consumed" api:"required"`
	Description     string                                                                 `json:"description" api:"nullable"`
	Tax             int64                                                                  `json:"tax" api:"nullable"`
	JSON            subscriptionPreviewChangePlanResponseImmediateChargeLineItemsMeterJSON `json:"-"`
}

func (*SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsMeter) UnmarshalJSON added in v1.66.2

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsMeterType added in v1.66.2

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsMeterType string
const (
	SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsMeterTypeMeter SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsMeterType = "meter"
)

func (SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsMeterType) IsKnown added in v1.66.2

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsSubscription added in v1.66.2

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsSubscription struct {
	ID              string                                                                        `json:"id" api:"required"`
	Currency        Currency                                                                      `json:"currency" api:"required"`
	ProductID       string                                                                        `json:"product_id" api:"required"`
	ProrationFactor float64                                                                       `json:"proration_factor" api:"required"`
	Quantity        int64                                                                         `json:"quantity" api:"required"`
	TaxInclusive    bool                                                                          `json:"tax_inclusive" api:"required"`
	Type            SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsSubscriptionType `json:"type" api:"required"`
	UnitPrice       int64                                                                         `json:"unit_price" api:"required"`
	Description     string                                                                        `json:"description" api:"nullable"`
	Name            string                                                                        `json:"name" api:"nullable"`
	Tax             int64                                                                         `json:"tax" api:"nullable"`
	TaxRate         float64                                                                       `json:"tax_rate" api:"nullable"`
	JSON            subscriptionPreviewChangePlanResponseImmediateChargeLineItemsSubscriptionJSON `json:"-"`
}

func (*SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsSubscription) UnmarshalJSON added in v1.66.2

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsSubscriptionType added in v1.66.2

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsSubscriptionType string
const (
	SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsSubscriptionTypeSubscription SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsSubscriptionType = "subscription"
)

func (SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsSubscriptionType) IsKnown added in v1.66.2

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsType added in v1.66.0

type SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsType string
const (
	SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsTypeSubscription SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsType = "subscription"
	SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsTypeAddon        SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsType = "addon"
	SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsTypeMeter        SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsType = "meter"
)

func (SubscriptionPreviewChangePlanResponseImmediateChargeLineItemsType) IsKnown added in v1.66.0

type SubscriptionPreviewChangePlanResponseImmediateChargeSummary added in v1.66.0

type SubscriptionPreviewChangePlanResponseImmediateChargeSummary struct {
	Currency Currency `json:"currency" api:"required"`
	// Net credit movement in the smallest currency unit (e.g. cents). **Negative** –
	// credits were deducted from the customer's balance to offset the charge (typical
	// on upgrades). **Positive** – credits were added to the customer's balance,
	// either from a downgrade proration refund or from topping-up the wallet to meet a
	// gateway minimum-charge threshold. **Zero** – no credit movement occurred.
	CustomerCredits    int64                                                           `json:"customer_credits" api:"required"`
	SettlementAmount   int64                                                           `json:"settlement_amount" api:"required"`
	SettlementCurrency Currency                                                        `json:"settlement_currency" api:"required"`
	TotalAmount        int64                                                           `json:"total_amount" api:"required"`
	SettlementTax      int64                                                           `json:"settlement_tax" api:"nullable"`
	Tax                int64                                                           `json:"tax" api:"nullable"`
	JSON               subscriptionPreviewChangePlanResponseImmediateChargeSummaryJSON `json:"-"`
}

func (*SubscriptionPreviewChangePlanResponseImmediateChargeSummary) UnmarshalJSON added in v1.66.0

type SubscriptionRenewedWebhookEvent added in v1.56.0

type SubscriptionRenewedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Subscription payload sent on a webhook. It carries every field of
	// `SubscriptionResponse`, plus the grace-period deadline.
	Data SubscriptionRenewedWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type SubscriptionRenewedWebhookEventType `json:"type" api:"required"`
	JSON subscriptionRenewedWebhookEventJSON `json:"-"`
}

func (*SubscriptionRenewedWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *SubscriptionRenewedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type SubscriptionRenewedWebhookEventData added in v1.56.0

type SubscriptionRenewedWebhookEventData struct {
	// Time when the grace period ends. The subscription moves to `on_hold` or to
	// `cancelled` at this time.
	//
	// Read in the same query as the rest of the payload, so it always comes from the
	// row snapshot that produced `status`. It is set whenever the subscription sits in
	// a window at that moment. A delayed event of another type therefore carries the
	// deadline too, next to a `past_due` status.
	PastDueEndsAt time.Time                               `json:"past_due_ends_at" api:"nullable" format:"date-time"`
	JSON          subscriptionRenewedWebhookEventDataJSON `json:"-"`
	Subscription
}

Subscription payload sent on a webhook. It carries every field of `SubscriptionResponse`, plus the grace-period deadline.

func (*SubscriptionRenewedWebhookEventData) UnmarshalJSON added in v1.56.0

func (r *SubscriptionRenewedWebhookEventData) UnmarshalJSON(data []byte) (err error)

type SubscriptionRenewedWebhookEventType added in v1.56.0

type SubscriptionRenewedWebhookEventType string

The event type

const (
	SubscriptionRenewedWebhookEventTypeSubscriptionRenewed SubscriptionRenewedWebhookEventType = "subscription.renewed"
)

func (SubscriptionRenewedWebhookEventType) IsKnown added in v1.56.0

type SubscriptionService

type SubscriptionService struct {
	Options []option.RequestOption
}

SubscriptionService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewSubscriptionService method instead.

func NewSubscriptionService

func NewSubscriptionService(opts ...option.RequestOption) (r *SubscriptionService)

NewSubscriptionService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*SubscriptionService) CancelChangePlan added in v1.88.0

func (r *SubscriptionService) CancelChangePlan(ctx context.Context, subscriptionID string, opts ...option.RequestOption) (err error)

func (*SubscriptionService) ChangePlan added in v1.18.0

func (*SubscriptionService) Charge added in v1.10.1

func (*SubscriptionService) Get

func (r *SubscriptionService) Get(ctx context.Context, subscriptionID string, opts ...option.RequestOption) (res *Subscription, err error)

func (*SubscriptionService) GetCreditUsage added in v1.86.0

func (r *SubscriptionService) GetCreditUsage(ctx context.Context, subscriptionID string, opts ...option.RequestOption) (res *SubscriptionGetCreditUsageResponse, err error)

func (*SubscriptionService) GetUsageHistory added in v1.52.4

Get detailed usage history for a subscription that includes usage-based billing (metered components). This endpoint provides insights into customer usage patterns and billing calculations over time.

## What You'll Get:

  • **Billing periods**: Each item represents a billing cycle with start and end dates
  • **Meter usage**: Detailed breakdown of usage for each meter configured on the subscription
  • **Usage calculations**: Total units consumed, free threshold units, and chargeable units
  • **Historical tracking**: Complete audit trail of usage-based charges

## Use Cases:

- **Customer support**: Investigate billing questions and usage discrepancies - **Usage analytics**: Analyze customer consumption patterns over time - **Billing transparency**: Provide customers with detailed usage breakdowns - **Revenue optimization**: Identify usage trends to optimize pricing strategies

## Filtering Options:

- **Date range filtering**: Get usage history for specific time periods - **Meter-specific filtering**: Focus on usage for a particular meter - **Pagination**: Navigate through large usage histories efficiently

## Important Notes:

  • Only returns data for subscriptions with usage-based (metered) components
  • Usage history is organized by billing periods (subscription cycles)
  • Free threshold units are calculated and displayed separately from chargeable units
  • Historical data is preserved even if meter configurations change

## Example Query Patterns:

  • Get last 3 months: `?start_date=2024-01-01T00:00:00Z&end_date=2024-03-31T23:59:59Z`
  • Filter by meter: `?meter_id=mtr_api_requests`
  • Paginate results: `?page_size=20&page_number=1`
  • Recent usage: `?start_date=2024-03-01T00:00:00Z` (from March 1st to now)

func (*SubscriptionService) GetUsageHistoryAutoPaging added in v1.52.4

Get detailed usage history for a subscription that includes usage-based billing (metered components). This endpoint provides insights into customer usage patterns and billing calculations over time.

## What You'll Get:

  • **Billing periods**: Each item represents a billing cycle with start and end dates
  • **Meter usage**: Detailed breakdown of usage for each meter configured on the subscription
  • **Usage calculations**: Total units consumed, free threshold units, and chargeable units
  • **Historical tracking**: Complete audit trail of usage-based charges

## Use Cases:

- **Customer support**: Investigate billing questions and usage discrepancies - **Usage analytics**: Analyze customer consumption patterns over time - **Billing transparency**: Provide customers with detailed usage breakdowns - **Revenue optimization**: Identify usage trends to optimize pricing strategies

## Filtering Options:

- **Date range filtering**: Get usage history for specific time periods - **Meter-specific filtering**: Focus on usage for a particular meter - **Pagination**: Navigate through large usage histories efficiently

## Important Notes:

  • Only returns data for subscriptions with usage-based (metered) components
  • Usage history is organized by billing periods (subscription cycles)
  • Free threshold units are calculated and displayed separately from chargeable units
  • Historical data is preserved even if meter configurations change

## Example Query Patterns:

  • Get last 3 months: `?start_date=2024-01-01T00:00:00Z&end_date=2024-03-31T23:59:59Z`
  • Filter by meter: `?meter_id=mtr_api_requests`
  • Paginate results: `?page_size=20&page_number=1`
  • Recent usage: `?start_date=2024-03-01T00:00:00Z` (from March 1st to now)

func (*SubscriptionService) New deprecated

Deprecated: deprecated

func (*SubscriptionService) PreviewChangePlan added in v1.66.0

func (*SubscriptionService) Update

func (r *SubscriptionService) Update(ctx context.Context, subscriptionID string, body SubscriptionUpdateParams, opts ...option.RequestOption) (res *Subscription, err error)

func (*SubscriptionService) UpdatePaymentMethod added in v1.60.0

type SubscriptionStatus

type SubscriptionStatus string
const (
	SubscriptionStatusPending   SubscriptionStatus = "pending"
	SubscriptionStatusActive    SubscriptionStatus = "active"
	SubscriptionStatusOnHold    SubscriptionStatus = "on_hold"
	SubscriptionStatusPaused    SubscriptionStatus = "paused"
	SubscriptionStatusCancelled SubscriptionStatus = "cancelled"
	SubscriptionStatusFailed    SubscriptionStatus = "failed"
	SubscriptionStatusExpired   SubscriptionStatus = "expired"
	SubscriptionStatusPastDue   SubscriptionStatus = "past_due"
)

func (SubscriptionStatus) IsKnown

func (r SubscriptionStatus) IsKnown() bool

type SubscriptionUnpausedWebhookEvent added in v1.112.0

type SubscriptionUnpausedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Subscription payload sent on a webhook. It carries every field of
	// `SubscriptionResponse`, plus the grace-period deadline.
	Data SubscriptionUnpausedWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type SubscriptionUnpausedWebhookEventType `json:"type" api:"required"`
	JSON subscriptionUnpausedWebhookEventJSON `json:"-"`
}

func (*SubscriptionUnpausedWebhookEvent) UnmarshalJSON added in v1.112.0

func (r *SubscriptionUnpausedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type SubscriptionUnpausedWebhookEventData added in v1.115.0

type SubscriptionUnpausedWebhookEventData struct {
	// Time when the grace period ends. The subscription moves to `on_hold` or to
	// `cancelled` at this time.
	//
	// Read in the same query as the rest of the payload, so it always comes from the
	// row snapshot that produced `status`. It is set whenever the subscription sits in
	// a window at that moment. A delayed event of another type therefore carries the
	// deadline too, next to a `past_due` status.
	PastDueEndsAt time.Time                                `json:"past_due_ends_at" api:"nullable" format:"date-time"`
	JSON          subscriptionUnpausedWebhookEventDataJSON `json:"-"`
	Subscription
}

Subscription payload sent on a webhook. It carries every field of `SubscriptionResponse`, plus the grace-period deadline.

func (*SubscriptionUnpausedWebhookEventData) UnmarshalJSON added in v1.115.0

func (r *SubscriptionUnpausedWebhookEventData) UnmarshalJSON(data []byte) (err error)

type SubscriptionUnpausedWebhookEventType added in v1.112.0

type SubscriptionUnpausedWebhookEventType string

The event type

const (
	SubscriptionUnpausedWebhookEventTypeSubscriptionUnpaused SubscriptionUnpausedWebhookEventType = "subscription.unpaused"
)

func (SubscriptionUnpausedWebhookEventType) IsKnown added in v1.112.0

type SubscriptionUpdateParams

type SubscriptionUpdateParams struct {
	Billing param.Field[BillingAddressParam] `json:"billing"`
	// When set, the subscription will remain active until the end of billing period
	CancelAtNextBillingDate param.Field[bool]                                 `json:"cancel_at_next_billing_date"`
	CancelReason            param.Field[SubscriptionUpdateParamsCancelReason] `json:"cancel_reason"`
	// Free-text cancellation comment (only valid when cancelling or scheduling
	// cancellation).
	CancellationComment param.Field[string] `json:"cancellation_comment"`
	// Customer-supplied churn reason (only valid when cancelling or scheduling
	// cancellation).
	CancellationFeedback param.Field[CancellationFeedback] `json:"cancellation_feedback"`
	// Update credit entitlement cart settings
	CreditEntitlementCart param.Field[[]SubscriptionUpdateParamsCreditEntitlementCart] `json:"credit_entitlement_cart"`
	// Optional business / legal name associated with the tax id. When provided
	// together with a valid tax id for a B2B subscription, this name is rendered on
	// the invoice instead of the customer's personal name. Send `null` to explicitly
	// clear the business name.
	CustomerBusinessName param.Field[string]                                  `json:"customer_business_name"`
	CustomerName         param.Field[string]                                  `json:"customer_name"`
	DisableOnDemand      param.Field[SubscriptionUpdateParamsDisableOnDemand] `json:"disable_on_demand"`
	// Arbitrary key-value metadata. Values can be string, integer, number, or boolean.
	Metadata        param.Field[MetadataParam] `json:"metadata"`
	NextBillingDate param.Field[time.Time]     `json:"next_billing_date" format:"date-time"`
	// Removed. Use `status: paused` to pause and `status: active` to resume. This
	// field always fails with 422, so a caller still on it gets a loud error instead
	// of a silent no-op.
	Pause param.Field[bool] `json:"pause"`
	// Set to `cancelled` to cancel the subscription. See `cancel_reason`,
	// `cancellation_feedback`, `cancellation_comment`, and
	// `cancel_at_next_billing_date` for cancellation options.
	//
	// Set to `paused` to pause an active subscription. Set to `active` to resume a
	// `paused` subscription. `active` also resumes an `on_hold` subscription that has
	// an unpaid pause invoice. This voids that invoice.
	//
	// Send `paused` or `active` alone. A request that combines either with any other
	// field fails with 422. `cancelled` is not exclusive this way — see
	// `cancel_reason` and friends below.
	Status param.Field[SubscriptionStatus] `json:"status"`
	// New number of `subscription_period_interval` units the subscription entitlement
	// should span. Used together with `subscription_period_interval` to extend the
	// subscription period. The resulting period must not be shorter than the current
	// one (this endpoint only extends).
	SubscriptionPeriodCount param.Field[int64] `json:"subscription_period_count"`
	// New interval unit for the subscription period. When changing the period, this
	// may be supplied alongside `subscription_period_count`; if omitted the existing
	// interval is retained.
	SubscriptionPeriodInterval param.Field[TimeInterval] `json:"subscription_period_interval"`
	TaxID                      param.Field[string]       `json:"tax_id"`
}

func (SubscriptionUpdateParams) MarshalJSON

func (r SubscriptionUpdateParams) MarshalJSON() (data []byte, err error)

type SubscriptionUpdateParamsCancelReason added in v1.93.0

type SubscriptionUpdateParamsCancelReason string
const (
	SubscriptionUpdateParamsCancelReasonCancelledByCustomer                   SubscriptionUpdateParamsCancelReason = "cancelled_by_customer"
	SubscriptionUpdateParamsCancelReasonCancelledByMerchant                   SubscriptionUpdateParamsCancelReason = "cancelled_by_merchant"
	SubscriptionUpdateParamsCancelReasonCancelledByMerchantSendDunning        SubscriptionUpdateParamsCancelReason = "cancelled_by_merchant_send_dunning"
	SubscriptionUpdateParamsCancelReasonCancelledByMerchantGracePeriodExpired SubscriptionUpdateParamsCancelReason = "cancelled_by_merchant_grace_period_expired"
	SubscriptionUpdateParamsCancelReasonDodoTeam                              SubscriptionUpdateParamsCancelReason = "dodo_team"
)

func (SubscriptionUpdateParamsCancelReason) IsKnown added in v1.93.0

type SubscriptionUpdateParamsCreditEntitlementCart added in v1.84.0

type SubscriptionUpdateParamsCreditEntitlementCart struct {
	CreditEntitlementID        param.Field[string] `json:"credit_entitlement_id" api:"required"`
	CreditsAmount              param.Field[string] `json:"credits_amount"`
	ExpiresAfterDays           param.Field[int64]  `json:"expires_after_days"`
	LowBalanceThresholdPercent param.Field[int64]  `json:"low_balance_threshold_percent"`
	MaxRolloverCount           param.Field[int64]  `json:"max_rollover_count"`
	OverageEnabled             param.Field[bool]   `json:"overage_enabled"`
	OverageLimit               param.Field[string] `json:"overage_limit"`
	RolloverEnabled            param.Field[bool]   `json:"rollover_enabled"`
	RolloverPercentage         param.Field[int64]  `json:"rollover_percentage"`
	RolloverTimeframeCount     param.Field[int64]  `json:"rollover_timeframe_count"`
	// Unit of a duration count (e.g. license-key validity period).
	RolloverTimeframeInterval param.Field[TimeInterval] `json:"rollover_timeframe_interval"`
}

func (SubscriptionUpdateParamsCreditEntitlementCart) MarshalJSON added in v1.84.0

func (r SubscriptionUpdateParamsCreditEntitlementCart) MarshalJSON() (data []byte, err error)

type SubscriptionUpdateParamsDisableOnDemand added in v1.19.0

type SubscriptionUpdateParamsDisableOnDemand struct {
	NextBillingDate param.Field[time.Time] `json:"next_billing_date" api:"required" format:"date-time"`
}

func (SubscriptionUpdateParamsDisableOnDemand) MarshalJSON added in v1.19.0

func (r SubscriptionUpdateParamsDisableOnDemand) MarshalJSON() (data []byte, err error)

type SubscriptionUpdatePaymentMethodParams added in v1.60.0

type SubscriptionUpdatePaymentMethodParams struct {
	PaymentMethod SubscriptionUpdatePaymentMethodParamsPaymentMethodUnion `json:"payment_method" api:"required"`
}

func (SubscriptionUpdatePaymentMethodParams) MarshalJSON added in v1.60.0

func (r SubscriptionUpdatePaymentMethodParams) MarshalJSON() (data []byte, err error)

type SubscriptionUpdatePaymentMethodParamsPaymentMethod added in v1.99.0

type SubscriptionUpdatePaymentMethodParamsPaymentMethod struct {
	Type                      param.Field[SubscriptionUpdatePaymentMethodParamsPaymentMethodType] `json:"type" api:"required"`
	AllowedPaymentMethodTypes param.Field[interface{}]                                            `json:"allowed_payment_method_types"`
	PaymentMethodID           param.Field[string]                                                 `json:"payment_method_id"`
	ReturnURL                 param.Field[string]                                                 `json:"return_url"`
}

func (SubscriptionUpdatePaymentMethodParamsPaymentMethod) MarshalJSON added in v1.99.0

func (r SubscriptionUpdatePaymentMethodParamsPaymentMethod) MarshalJSON() (data []byte, err error)

type SubscriptionUpdatePaymentMethodParamsPaymentMethodExisting added in v1.99.0

type SubscriptionUpdatePaymentMethodParamsPaymentMethodExisting struct {
	PaymentMethodID param.Field[string]                                                         `json:"payment_method_id" api:"required"`
	Type            param.Field[SubscriptionUpdatePaymentMethodParamsPaymentMethodExistingType] `json:"type" api:"required"`
}

func (SubscriptionUpdatePaymentMethodParamsPaymentMethodExisting) MarshalJSON added in v1.99.0

type SubscriptionUpdatePaymentMethodParamsPaymentMethodExistingType added in v1.99.0

type SubscriptionUpdatePaymentMethodParamsPaymentMethodExistingType string
const (
	SubscriptionUpdatePaymentMethodParamsPaymentMethodExistingTypeExisting SubscriptionUpdatePaymentMethodParamsPaymentMethodExistingType = "existing"
)

func (SubscriptionUpdatePaymentMethodParamsPaymentMethodExistingType) IsKnown added in v1.99.0

type SubscriptionUpdatePaymentMethodParamsPaymentMethodNew added in v1.99.0

type SubscriptionUpdatePaymentMethodParamsPaymentMethodNew struct {
	Type param.Field[SubscriptionUpdatePaymentMethodParamsPaymentMethodNewType] `json:"type" api:"required"`
	// List of payment methods allowed during checkout.
	//
	// Customers will **never** see payment methods that are **not** in this list.
	// However, adding a method here **does not guarantee** customers will see it.
	// Availability still depends on other factors (e.g., customer location, merchant
	// settings).
	AllowedPaymentMethodTypes param.Field[[]PaymentMethodTypes] `json:"allowed_payment_method_types"`
	ReturnURL                 param.Field[string]               `json:"return_url"`
}

func (SubscriptionUpdatePaymentMethodParamsPaymentMethodNew) MarshalJSON added in v1.99.0

type SubscriptionUpdatePaymentMethodParamsPaymentMethodNewType added in v1.99.0

type SubscriptionUpdatePaymentMethodParamsPaymentMethodNewType string
const (
	SubscriptionUpdatePaymentMethodParamsPaymentMethodNewTypeNew SubscriptionUpdatePaymentMethodParamsPaymentMethodNewType = "new"
)

func (SubscriptionUpdatePaymentMethodParamsPaymentMethodNewType) IsKnown added in v1.99.0

type SubscriptionUpdatePaymentMethodParamsPaymentMethodType added in v1.99.0

type SubscriptionUpdatePaymentMethodParamsPaymentMethodType string
const (
	SubscriptionUpdatePaymentMethodParamsPaymentMethodTypeNew      SubscriptionUpdatePaymentMethodParamsPaymentMethodType = "new"
	SubscriptionUpdatePaymentMethodParamsPaymentMethodTypeExisting SubscriptionUpdatePaymentMethodParamsPaymentMethodType = "existing"
)

func (SubscriptionUpdatePaymentMethodParamsPaymentMethodType) IsKnown added in v1.99.0

type SubscriptionUpdatePaymentMethodParamsPaymentMethodUnion added in v1.99.0

type SubscriptionUpdatePaymentMethodParamsPaymentMethodUnion interface {
	// contains filtered or unexported methods
}

Satisfied by SubscriptionUpdatePaymentMethodParamsPaymentMethodNew, SubscriptionUpdatePaymentMethodParamsPaymentMethodExisting, SubscriptionUpdatePaymentMethodParamsPaymentMethod.

type SubscriptionUpdatePaymentMethodResponse added in v1.60.0

type SubscriptionUpdatePaymentMethodResponse struct {
	ClientSecret string                                      `json:"client_secret" api:"nullable"`
	ExpiresOn    time.Time                                   `json:"expires_on" api:"nullable" format:"date-time"`
	PaymentID    string                                      `json:"payment_id" api:"nullable"`
	PaymentLink  string                                      `json:"payment_link" api:"nullable"`
	JSON         subscriptionUpdatePaymentMethodResponseJSON `json:"-"`
}

func (*SubscriptionUpdatePaymentMethodResponse) UnmarshalJSON added in v1.60.0

func (r *SubscriptionUpdatePaymentMethodResponse) UnmarshalJSON(data []byte) (err error)

type SubscriptionUpdatePaymentMethodWebhookEvent added in v1.108.1

type SubscriptionUpdatePaymentMethodWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Subscription payload sent on a webhook. It carries every field of
	// `SubscriptionResponse`, plus the grace-period deadline.
	Data SubscriptionUpdatePaymentMethodWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type SubscriptionUpdatePaymentMethodWebhookEventType `json:"type" api:"required"`
	JSON subscriptionUpdatePaymentMethodWebhookEventJSON `json:"-"`
}

func (*SubscriptionUpdatePaymentMethodWebhookEvent) UnmarshalJSON added in v1.108.1

func (r *SubscriptionUpdatePaymentMethodWebhookEvent) UnmarshalJSON(data []byte) (err error)

type SubscriptionUpdatePaymentMethodWebhookEventData added in v1.115.0

type SubscriptionUpdatePaymentMethodWebhookEventData struct {
	// Time when the grace period ends. The subscription moves to `on_hold` or to
	// `cancelled` at this time.
	//
	// Read in the same query as the rest of the payload, so it always comes from the
	// row snapshot that produced `status`. It is set whenever the subscription sits in
	// a window at that moment. A delayed event of another type therefore carries the
	// deadline too, next to a `past_due` status.
	PastDueEndsAt time.Time                                           `json:"past_due_ends_at" api:"nullable" format:"date-time"`
	JSON          subscriptionUpdatePaymentMethodWebhookEventDataJSON `json:"-"`
	Subscription
}

Subscription payload sent on a webhook. It carries every field of `SubscriptionResponse`, plus the grace-period deadline.

func (*SubscriptionUpdatePaymentMethodWebhookEventData) UnmarshalJSON added in v1.115.0

func (r *SubscriptionUpdatePaymentMethodWebhookEventData) UnmarshalJSON(data []byte) (err error)

type SubscriptionUpdatePaymentMethodWebhookEventType added in v1.108.1

type SubscriptionUpdatePaymentMethodWebhookEventType string

The event type

const (
	SubscriptionUpdatePaymentMethodWebhookEventTypeSubscriptionUpdatePaymentMethod SubscriptionUpdatePaymentMethodWebhookEventType = "subscription.update_payment_method"
)

func (SubscriptionUpdatePaymentMethodWebhookEventType) IsKnown added in v1.108.1

type SubscriptionUpdatedWebhookEvent added in v1.66.0

type SubscriptionUpdatedWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// Subscription payload sent on a webhook. It carries every field of
	// `SubscriptionResponse`, plus the grace-period deadline.
	Data SubscriptionUpdatedWebhookEventData `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type SubscriptionUpdatedWebhookEventType `json:"type" api:"required"`
	JSON subscriptionUpdatedWebhookEventJSON `json:"-"`
}

func (*SubscriptionUpdatedWebhookEvent) UnmarshalJSON added in v1.66.0

func (r *SubscriptionUpdatedWebhookEvent) UnmarshalJSON(data []byte) (err error)

type SubscriptionUpdatedWebhookEventData added in v1.66.0

type SubscriptionUpdatedWebhookEventData struct {
	// Time when the grace period ends. The subscription moves to `on_hold` or to
	// `cancelled` at this time.
	//
	// Read in the same query as the rest of the payload, so it always comes from the
	// row snapshot that produced `status`. It is set whenever the subscription sits in
	// a window at that moment. A delayed event of another type therefore carries the
	// deadline too, next to a `past_due` status.
	PastDueEndsAt time.Time                               `json:"past_due_ends_at" api:"nullable" format:"date-time"`
	JSON          subscriptionUpdatedWebhookEventDataJSON `json:"-"`
	Subscription
}

Subscription payload sent on a webhook. It carries every field of `SubscriptionResponse`, plus the grace-period deadline.

func (*SubscriptionUpdatedWebhookEventData) UnmarshalJSON added in v1.66.0

func (r *SubscriptionUpdatedWebhookEventData) UnmarshalJSON(data []byte) (err error)

type SubscriptionUpdatedWebhookEventType added in v1.66.0

type SubscriptionUpdatedWebhookEventType string

The event type

const (
	SubscriptionUpdatedWebhookEventTypeSubscriptionUpdated SubscriptionUpdatedWebhookEventType = "subscription.updated"
)

func (SubscriptionUpdatedWebhookEventType) IsKnown added in v1.66.0

type TaxCategory added in v1.20.0

type TaxCategory string

Represents the different categories of taxation applicable to various products and services.

const (
	TaxCategoryDigitalProducts TaxCategory = "digital_products"
	TaxCategorySaas            TaxCategory = "saas"
	TaxCategoryEBook           TaxCategory = "e_book"
	TaxCategoryEdtech          TaxCategory = "edtech"
	TaxCategoryLiveTutoring    TaxCategory = "live_tutoring"
)

func (TaxCategory) IsKnown added in v1.20.0

func (r TaxCategory) IsKnown() bool

type ThemeConfigFontSize added in v1.81.0

type ThemeConfigFontSize string

Font size for the checkout UI

const (
	ThemeConfigFontSizeXs  ThemeConfigFontSize = "xs"
	ThemeConfigFontSizeSm  ThemeConfigFontSize = "sm"
	ThemeConfigFontSizeMd  ThemeConfigFontSize = "md"
	ThemeConfigFontSizeLg  ThemeConfigFontSize = "lg"
	ThemeConfigFontSizeXl  ThemeConfigFontSize = "xl"
	ThemeConfigFontSize2xl ThemeConfigFontSize = "2xl"
)

func (ThemeConfigFontSize) IsKnown added in v1.81.0

func (r ThemeConfigFontSize) IsKnown() bool

type ThemeConfigFontWeight added in v1.81.0

type ThemeConfigFontWeight string

Font weight for the checkout UI

const (
	ThemeConfigFontWeightNormal    ThemeConfigFontWeight = "normal"
	ThemeConfigFontWeightMedium    ThemeConfigFontWeight = "medium"
	ThemeConfigFontWeightBold      ThemeConfigFontWeight = "bold"
	ThemeConfigFontWeightExtraBold ThemeConfigFontWeight = "extraBold"
)

func (ThemeConfigFontWeight) IsKnown added in v1.81.0

func (r ThemeConfigFontWeight) IsKnown() bool

type ThemeConfigParam added in v1.81.0

type ThemeConfigParam struct {
	// Dark mode color configuration
	Dark param.Field[ThemeModeConfigParam] `json:"dark"`
	// URL for the primary font. Must be a valid https:// URL.
	FontPrimaryURL param.Field[string] `json:"font_primary_url"`
	// URL for the secondary font. Must be a valid https:// URL.
	FontSecondaryURL param.Field[string] `json:"font_secondary_url"`
	// Font size for the checkout UI
	FontSize param.Field[ThemeConfigFontSize] `json:"font_size"`
	// Font weight for the checkout UI
	FontWeight param.Field[ThemeConfigFontWeight] `json:"font_weight"`
	// Light mode color configuration
	Light param.Field[ThemeModeConfigParam] `json:"light"`
	// Custom text for the pay button (e.g., "Complete Purchase", "Subscribe Now"). Max
	// 100 characters.
	PayButtonText param.Field[string] `json:"pay_button_text"`
	// Border radius for UI elements. Must be a number followed by px, rem, or em
	// (e.g., "4px", "0.5rem", "1em")
	Radius param.Field[string] `json:"radius"`
}

Custom theme configuration with colors for light and dark modes.

func (ThemeConfigParam) MarshalJSON added in v1.81.0

func (r ThemeConfigParam) MarshalJSON() (data []byte, err error)

type ThemeModeConfigParam added in v1.81.0

type ThemeModeConfigParam struct {
	// Background primary color
	//
	// Examples: `"#ffffff"`, `"rgb(255, 255, 255)"`, `"white"`
	BgPrimary param.Field[string] `json:"bg_primary"`
	// Background secondary color
	BgSecondary param.Field[string] `json:"bg_secondary"`
	// Border primary color
	BorderPrimary param.Field[string] `json:"border_primary"`
	// Border secondary color
	BorderSecondary param.Field[string] `json:"border_secondary"`
	// Primary button background color
	ButtonPrimary param.Field[string] `json:"button_primary"`
	// Primary button hover color
	ButtonPrimaryHover param.Field[string] `json:"button_primary_hover"`
	// Secondary button background color
	ButtonSecondary param.Field[string] `json:"button_secondary"`
	// Secondary button hover color
	ButtonSecondaryHover param.Field[string] `json:"button_secondary_hover"`
	// Primary button text color
	ButtonTextPrimary param.Field[string] `json:"button_text_primary"`
	// Secondary button text color
	ButtonTextSecondary param.Field[string] `json:"button_text_secondary"`
	// Input focus border color
	InputFocusBorder param.Field[string] `json:"input_focus_border"`
	// Text error color
	TextError param.Field[string] `json:"text_error"`
	// Text placeholder color
	TextPlaceholder param.Field[string] `json:"text_placeholder"`
	// Text primary color
	TextPrimary param.Field[string] `json:"text_primary"`
	// Text secondary color
	TextSecondary param.Field[string] `json:"text_secondary"`
	// Text success color
	TextSuccess param.Field[string] `json:"text_success"`
}

Color configuration for a single theme mode (light or dark).

All color fields accept standard CSS color formats:

- Hex: `#fff`, `#ffffff`, `#ffffffff` (with or without # prefix) - RGB/RGBA: `rgb(255, 255, 255)`, `rgba(255, 255, 255, 0.5)` - HSL/HSLA: `hsl(120, 100%, 50%)`, `hsla(120, 100%, 50%, 0.5)` - Named colors: `red`, `blue`, `transparent`, etc. - Advanced: `hwb()`, `lab()`, `lch()`, `oklab()`, `oklch()`, `color()`

func (ThemeModeConfigParam) MarshalJSON added in v1.81.0

func (r ThemeModeConfigParam) MarshalJSON() (data []byte, err error)

type TimeInterval added in v1.6.3

type TimeInterval string

Unit of a duration count (e.g. license-key validity period).

const (
	TimeIntervalDay   TimeInterval = "Day"
	TimeIntervalWeek  TimeInterval = "Week"
	TimeIntervalMonth TimeInterval = "Month"
	TimeIntervalYear  TimeInterval = "Year"
)

func (TimeInterval) IsKnown added in v1.6.3

func (r TimeInterval) IsKnown() bool

type UnsafeUnwrapWebhookEvent added in v1.56.0

type UnsafeUnwrapWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// This field can have the runtime type of
	// [AbandonedCheckoutDetectedWebhookEventData],
	// [AbandonedCheckoutRecoveredWebhookEventData], [CreditLedgerEntry],
	// [CreditBalanceLowWebhookEventData], [Dispute],
	// [DunningRecoveredWebhookEventData], [DunningStartedWebhookEventData],
	// [EntitlementGrant], [LicenseKey], [Payment], [PayoutCreatedWebhookEventData],
	// [PayoutFailedWebhookEventData], [PayoutInProgressWebhookEventData],
	// [PayoutOnHoldWebhookEventData], [PayoutSuccessWebhookEventData], [Refund],
	// [SubscriptionActiveWebhookEventData], [SubscriptionCancelledWebhookEventData],
	// [SubscriptionExpiredWebhookEventData], [SubscriptionFailedWebhookEventData],
	// [SubscriptionOnHoldWebhookEventData], [SubscriptionPastDueWebhookEventData],
	// [SubscriptionPausedWebhookEventData], [SubscriptionPlanChangedWebhookEventData],
	// [SubscriptionRenewedWebhookEventData], [SubscriptionUnpausedWebhookEventData],
	// [SubscriptionUpdatePaymentMethodWebhookEventData],
	// [SubscriptionUpdatedWebhookEventData].
	Data interface{} `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type UnsafeUnwrapWebhookEventType `json:"type" api:"required"`
	JSON unsafeUnwrapWebhookEventJSON `json:"-"`
	// contains filtered or unexported fields
}

func (UnsafeUnwrapWebhookEvent) AsUnion added in v1.56.0

AsUnion returns a UnsafeUnwrapWebhookEventUnion interface which you can cast to the specific types for more type safety.

Possible runtime types of the union are AbandonedCheckoutDetectedWebhookEvent, AbandonedCheckoutRecoveredWebhookEvent, CreditAddedWebhookEvent, CreditBalanceLowWebhookEvent, CreditDeductedWebhookEvent, CreditExpiredWebhookEvent, CreditManualAdjustmentWebhookEvent, CreditOverageChargedWebhookEvent, CreditOverageResetWebhookEvent, CreditRolledOverWebhookEvent, CreditRolloverForfeitedWebhookEvent, DisputeAcceptedWebhookEvent, DisputeCancelledWebhookEvent, DisputeChallengedWebhookEvent, DisputeExpiredWebhookEvent, DisputeLostWebhookEvent, DisputeOpenedWebhookEvent, DisputeWonWebhookEvent, DunningRecoveredWebhookEvent, DunningStartedWebhookEvent, EntitlementGrantCreatedWebhookEvent, EntitlementGrantDeliveredWebhookEvent, EntitlementGrantFailedWebhookEvent, EntitlementGrantRevokedWebhookEvent, LicenseKeyCreatedWebhookEvent, PaymentCancelledWebhookEvent, PaymentFailedWebhookEvent, PaymentProcessingWebhookEvent, PaymentSucceededWebhookEvent, PayoutCreatedWebhookEvent, PayoutFailedWebhookEvent, PayoutInProgressWebhookEvent, PayoutOnHoldWebhookEvent, PayoutSuccessWebhookEvent, RefundFailedWebhookEvent, RefundSucceededWebhookEvent, SubscriptionActiveWebhookEvent, SubscriptionCancelledWebhookEvent, SubscriptionExpiredWebhookEvent, SubscriptionFailedWebhookEvent, SubscriptionOnHoldWebhookEvent, SubscriptionPastDueWebhookEvent, SubscriptionPausedWebhookEvent, SubscriptionPlanChangedWebhookEvent, SubscriptionRenewedWebhookEvent, SubscriptionUnpausedWebhookEvent, SubscriptionUpdatePaymentMethodWebhookEvent, SubscriptionUpdatedWebhookEvent.

func (*UnsafeUnwrapWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *UnsafeUnwrapWebhookEvent) UnmarshalJSON(data []byte) (err error)

type UnsafeUnwrapWebhookEventType added in v1.56.0

type UnsafeUnwrapWebhookEventType string

The event type

const (
	UnsafeUnwrapWebhookEventTypeAbandonedCheckoutDetected       UnsafeUnwrapWebhookEventType = "abandoned_checkout.detected"
	UnsafeUnwrapWebhookEventTypeAbandonedCheckoutRecovered      UnsafeUnwrapWebhookEventType = "abandoned_checkout.recovered"
	UnsafeUnwrapWebhookEventTypeCreditAdded                     UnsafeUnwrapWebhookEventType = "credit.added"
	UnsafeUnwrapWebhookEventTypeCreditBalanceLow                UnsafeUnwrapWebhookEventType = "credit.balance_low"
	UnsafeUnwrapWebhookEventTypeCreditDeducted                  UnsafeUnwrapWebhookEventType = "credit.deducted"
	UnsafeUnwrapWebhookEventTypeCreditExpired                   UnsafeUnwrapWebhookEventType = "credit.expired"
	UnsafeUnwrapWebhookEventTypeCreditManualAdjustment          UnsafeUnwrapWebhookEventType = "credit.manual_adjustment"
	UnsafeUnwrapWebhookEventTypeCreditOverageCharged            UnsafeUnwrapWebhookEventType = "credit.overage_charged"
	UnsafeUnwrapWebhookEventTypeCreditOverageReset              UnsafeUnwrapWebhookEventType = "credit.overage_reset"
	UnsafeUnwrapWebhookEventTypeCreditRolledOver                UnsafeUnwrapWebhookEventType = "credit.rolled_over"
	UnsafeUnwrapWebhookEventTypeCreditRolloverForfeited         UnsafeUnwrapWebhookEventType = "credit.rollover_forfeited"
	UnsafeUnwrapWebhookEventTypeDisputeAccepted                 UnsafeUnwrapWebhookEventType = "dispute.accepted"
	UnsafeUnwrapWebhookEventTypeDisputeCancelled                UnsafeUnwrapWebhookEventType = "dispute.cancelled"
	UnsafeUnwrapWebhookEventTypeDisputeChallenged               UnsafeUnwrapWebhookEventType = "dispute.challenged"
	UnsafeUnwrapWebhookEventTypeDisputeExpired                  UnsafeUnwrapWebhookEventType = "dispute.expired"
	UnsafeUnwrapWebhookEventTypeDisputeLost                     UnsafeUnwrapWebhookEventType = "dispute.lost"
	UnsafeUnwrapWebhookEventTypeDisputeOpened                   UnsafeUnwrapWebhookEventType = "dispute.opened"
	UnsafeUnwrapWebhookEventTypeDisputeWon                      UnsafeUnwrapWebhookEventType = "dispute.won"
	UnsafeUnwrapWebhookEventTypeDunningRecovered                UnsafeUnwrapWebhookEventType = "dunning.recovered"
	UnsafeUnwrapWebhookEventTypeDunningStarted                  UnsafeUnwrapWebhookEventType = "dunning.started"
	UnsafeUnwrapWebhookEventTypeEntitlementGrantCreated         UnsafeUnwrapWebhookEventType = "entitlement_grant.created"
	UnsafeUnwrapWebhookEventTypeEntitlementGrantDelivered       UnsafeUnwrapWebhookEventType = "entitlement_grant.delivered"
	UnsafeUnwrapWebhookEventTypeEntitlementGrantFailed          UnsafeUnwrapWebhookEventType = "entitlement_grant.failed"
	UnsafeUnwrapWebhookEventTypeEntitlementGrantRevoked         UnsafeUnwrapWebhookEventType = "entitlement_grant.revoked"
	UnsafeUnwrapWebhookEventTypeLicenseKeyCreated               UnsafeUnwrapWebhookEventType = "license_key.created"
	UnsafeUnwrapWebhookEventTypePaymentCancelled                UnsafeUnwrapWebhookEventType = "payment.cancelled"
	UnsafeUnwrapWebhookEventTypePaymentFailed                   UnsafeUnwrapWebhookEventType = "payment.failed"
	UnsafeUnwrapWebhookEventTypePaymentProcessing               UnsafeUnwrapWebhookEventType = "payment.processing"
	UnsafeUnwrapWebhookEventTypePaymentSucceeded                UnsafeUnwrapWebhookEventType = "payment.succeeded"
	UnsafeUnwrapWebhookEventTypePayoutCreated                   UnsafeUnwrapWebhookEventType = "payout.created"
	UnsafeUnwrapWebhookEventTypePayoutFailed                    UnsafeUnwrapWebhookEventType = "payout.failed"
	UnsafeUnwrapWebhookEventTypePayoutInProgress                UnsafeUnwrapWebhookEventType = "payout.in_progress"
	UnsafeUnwrapWebhookEventTypePayoutOnHold                    UnsafeUnwrapWebhookEventType = "payout.on_hold"
	UnsafeUnwrapWebhookEventTypePayoutSuccess                   UnsafeUnwrapWebhookEventType = "payout.success"
	UnsafeUnwrapWebhookEventTypeRefundFailed                    UnsafeUnwrapWebhookEventType = "refund.failed"
	UnsafeUnwrapWebhookEventTypeRefundSucceeded                 UnsafeUnwrapWebhookEventType = "refund.succeeded"
	UnsafeUnwrapWebhookEventTypeSubscriptionActive              UnsafeUnwrapWebhookEventType = "subscription.active"
	UnsafeUnwrapWebhookEventTypeSubscriptionCancelled           UnsafeUnwrapWebhookEventType = "subscription.cancelled"
	UnsafeUnwrapWebhookEventTypeSubscriptionExpired             UnsafeUnwrapWebhookEventType = "subscription.expired"
	UnsafeUnwrapWebhookEventTypeSubscriptionFailed              UnsafeUnwrapWebhookEventType = "subscription.failed"
	UnsafeUnwrapWebhookEventTypeSubscriptionOnHold              UnsafeUnwrapWebhookEventType = "subscription.on_hold"
	UnsafeUnwrapWebhookEventTypeSubscriptionPastDue             UnsafeUnwrapWebhookEventType = "subscription.past_due"
	UnsafeUnwrapWebhookEventTypeSubscriptionPaused              UnsafeUnwrapWebhookEventType = "subscription.paused"
	UnsafeUnwrapWebhookEventTypeSubscriptionPlanChanged         UnsafeUnwrapWebhookEventType = "subscription.plan_changed"
	UnsafeUnwrapWebhookEventTypeSubscriptionRenewed             UnsafeUnwrapWebhookEventType = "subscription.renewed"
	UnsafeUnwrapWebhookEventTypeSubscriptionUnpaused            UnsafeUnwrapWebhookEventType = "subscription.unpaused"
	UnsafeUnwrapWebhookEventTypeSubscriptionUpdatePaymentMethod UnsafeUnwrapWebhookEventType = "subscription.update_payment_method"
	UnsafeUnwrapWebhookEventTypeSubscriptionUpdated             UnsafeUnwrapWebhookEventType = "subscription.updated"
)

func (UnsafeUnwrapWebhookEventType) IsKnown added in v1.56.0

func (r UnsafeUnwrapWebhookEventType) IsKnown() bool

type UnsafeUnwrapWebhookEventUnion added in v1.56.0

type UnsafeUnwrapWebhookEventUnion interface {
	// contains filtered or unexported methods
}

Union satisfied by AbandonedCheckoutDetectedWebhookEvent, AbandonedCheckoutRecoveredWebhookEvent, CreditAddedWebhookEvent, CreditBalanceLowWebhookEvent, CreditDeductedWebhookEvent, CreditExpiredWebhookEvent, CreditManualAdjustmentWebhookEvent, CreditOverageChargedWebhookEvent, CreditOverageResetWebhookEvent, CreditRolledOverWebhookEvent, CreditRolloverForfeitedWebhookEvent, DisputeAcceptedWebhookEvent, DisputeCancelledWebhookEvent, DisputeChallengedWebhookEvent, DisputeExpiredWebhookEvent, DisputeLostWebhookEvent, DisputeOpenedWebhookEvent, DisputeWonWebhookEvent, DunningRecoveredWebhookEvent, DunningStartedWebhookEvent, EntitlementGrantCreatedWebhookEvent, EntitlementGrantDeliveredWebhookEvent, EntitlementGrantFailedWebhookEvent, EntitlementGrantRevokedWebhookEvent, LicenseKeyCreatedWebhookEvent, PaymentCancelledWebhookEvent, PaymentFailedWebhookEvent, PaymentProcessingWebhookEvent, PaymentSucceededWebhookEvent, PayoutCreatedWebhookEvent, PayoutFailedWebhookEvent, PayoutInProgressWebhookEvent, PayoutOnHoldWebhookEvent, PayoutSuccessWebhookEvent, RefundFailedWebhookEvent, RefundSucceededWebhookEvent, SubscriptionActiveWebhookEvent, SubscriptionCancelledWebhookEvent, SubscriptionExpiredWebhookEvent, SubscriptionFailedWebhookEvent, SubscriptionOnHoldWebhookEvent, SubscriptionPastDueWebhookEvent, SubscriptionPausedWebhookEvent, SubscriptionPlanChangedWebhookEvent, SubscriptionRenewedWebhookEvent, SubscriptionUnpausedWebhookEvent, SubscriptionUpdatePaymentMethodWebhookEvent or SubscriptionUpdatedWebhookEvent.

type UnwrapWebhookEvent added in v1.56.0

type UnwrapWebhookEvent struct {
	// The business identifier
	BusinessID string `json:"business_id" api:"required"`
	// This field can have the runtime type of
	// [AbandonedCheckoutDetectedWebhookEventData],
	// [AbandonedCheckoutRecoveredWebhookEventData], [CreditLedgerEntry],
	// [CreditBalanceLowWebhookEventData], [Dispute],
	// [DunningRecoveredWebhookEventData], [DunningStartedWebhookEventData],
	// [EntitlementGrant], [LicenseKey], [Payment], [PayoutCreatedWebhookEventData],
	// [PayoutFailedWebhookEventData], [PayoutInProgressWebhookEventData],
	// [PayoutOnHoldWebhookEventData], [PayoutSuccessWebhookEventData], [Refund],
	// [SubscriptionActiveWebhookEventData], [SubscriptionCancelledWebhookEventData],
	// [SubscriptionExpiredWebhookEventData], [SubscriptionFailedWebhookEventData],
	// [SubscriptionOnHoldWebhookEventData], [SubscriptionPastDueWebhookEventData],
	// [SubscriptionPausedWebhookEventData], [SubscriptionPlanChangedWebhookEventData],
	// [SubscriptionRenewedWebhookEventData], [SubscriptionUnpausedWebhookEventData],
	// [SubscriptionUpdatePaymentMethodWebhookEventData],
	// [SubscriptionUpdatedWebhookEventData].
	Data interface{} `json:"data" api:"required"`
	// The timestamp of when the event occurred
	Timestamp time.Time `json:"timestamp" api:"required" format:"date-time"`
	// The event type
	Type UnwrapWebhookEventType `json:"type" api:"required"`
	JSON unwrapWebhookEventJSON `json:"-"`
	// contains filtered or unexported fields
}

func (UnwrapWebhookEvent) AsUnion added in v1.56.0

AsUnion returns a UnwrapWebhookEventUnion interface which you can cast to the specific types for more type safety.

Possible runtime types of the union are AbandonedCheckoutDetectedWebhookEvent, AbandonedCheckoutRecoveredWebhookEvent, CreditAddedWebhookEvent, CreditBalanceLowWebhookEvent, CreditDeductedWebhookEvent, CreditExpiredWebhookEvent, CreditManualAdjustmentWebhookEvent, CreditOverageChargedWebhookEvent, CreditOverageResetWebhookEvent, CreditRolledOverWebhookEvent, CreditRolloverForfeitedWebhookEvent, DisputeAcceptedWebhookEvent, DisputeCancelledWebhookEvent, DisputeChallengedWebhookEvent, DisputeExpiredWebhookEvent, DisputeLostWebhookEvent, DisputeOpenedWebhookEvent, DisputeWonWebhookEvent, DunningRecoveredWebhookEvent, DunningStartedWebhookEvent, EntitlementGrantCreatedWebhookEvent, EntitlementGrantDeliveredWebhookEvent, EntitlementGrantFailedWebhookEvent, EntitlementGrantRevokedWebhookEvent, LicenseKeyCreatedWebhookEvent, PaymentCancelledWebhookEvent, PaymentFailedWebhookEvent, PaymentProcessingWebhookEvent, PaymentSucceededWebhookEvent, PayoutCreatedWebhookEvent, PayoutFailedWebhookEvent, PayoutInProgressWebhookEvent, PayoutOnHoldWebhookEvent, PayoutSuccessWebhookEvent, RefundFailedWebhookEvent, RefundSucceededWebhookEvent, SubscriptionActiveWebhookEvent, SubscriptionCancelledWebhookEvent, SubscriptionExpiredWebhookEvent, SubscriptionFailedWebhookEvent, SubscriptionOnHoldWebhookEvent, SubscriptionPastDueWebhookEvent, SubscriptionPausedWebhookEvent, SubscriptionPlanChangedWebhookEvent, SubscriptionRenewedWebhookEvent, SubscriptionUnpausedWebhookEvent, SubscriptionUpdatePaymentMethodWebhookEvent, SubscriptionUpdatedWebhookEvent.

func (*UnwrapWebhookEvent) UnmarshalJSON added in v1.56.0

func (r *UnwrapWebhookEvent) UnmarshalJSON(data []byte) (err error)

type UnwrapWebhookEventType added in v1.56.0

type UnwrapWebhookEventType string

The event type

const (
	UnwrapWebhookEventTypeAbandonedCheckoutDetected       UnwrapWebhookEventType = "abandoned_checkout.detected"
	UnwrapWebhookEventTypeAbandonedCheckoutRecovered      UnwrapWebhookEventType = "abandoned_checkout.recovered"
	UnwrapWebhookEventTypeCreditAdded                     UnwrapWebhookEventType = "credit.added"
	UnwrapWebhookEventTypeCreditBalanceLow                UnwrapWebhookEventType = "credit.balance_low"
	UnwrapWebhookEventTypeCreditDeducted                  UnwrapWebhookEventType = "credit.deducted"
	UnwrapWebhookEventTypeCreditExpired                   UnwrapWebhookEventType = "credit.expired"
	UnwrapWebhookEventTypeCreditManualAdjustment          UnwrapWebhookEventType = "credit.manual_adjustment"
	UnwrapWebhookEventTypeCreditOverageCharged            UnwrapWebhookEventType = "credit.overage_charged"
	UnwrapWebhookEventTypeCreditOverageReset              UnwrapWebhookEventType = "credit.overage_reset"
	UnwrapWebhookEventTypeCreditRolledOver                UnwrapWebhookEventType = "credit.rolled_over"
	UnwrapWebhookEventTypeCreditRolloverForfeited         UnwrapWebhookEventType = "credit.rollover_forfeited"
	UnwrapWebhookEventTypeDisputeAccepted                 UnwrapWebhookEventType = "dispute.accepted"
	UnwrapWebhookEventTypeDisputeCancelled                UnwrapWebhookEventType = "dispute.cancelled"
	UnwrapWebhookEventTypeDisputeChallenged               UnwrapWebhookEventType = "dispute.challenged"
	UnwrapWebhookEventTypeDisputeExpired                  UnwrapWebhookEventType = "dispute.expired"
	UnwrapWebhookEventTypeDisputeLost                     UnwrapWebhookEventType = "dispute.lost"
	UnwrapWebhookEventTypeDisputeOpened                   UnwrapWebhookEventType = "dispute.opened"
	UnwrapWebhookEventTypeDisputeWon                      UnwrapWebhookEventType = "dispute.won"
	UnwrapWebhookEventTypeDunningRecovered                UnwrapWebhookEventType = "dunning.recovered"
	UnwrapWebhookEventTypeDunningStarted                  UnwrapWebhookEventType = "dunning.started"
	UnwrapWebhookEventTypeEntitlementGrantCreated         UnwrapWebhookEventType = "entitlement_grant.created"
	UnwrapWebhookEventTypeEntitlementGrantDelivered       UnwrapWebhookEventType = "entitlement_grant.delivered"
	UnwrapWebhookEventTypeEntitlementGrantFailed          UnwrapWebhookEventType = "entitlement_grant.failed"
	UnwrapWebhookEventTypeEntitlementGrantRevoked         UnwrapWebhookEventType = "entitlement_grant.revoked"
	UnwrapWebhookEventTypeLicenseKeyCreated               UnwrapWebhookEventType = "license_key.created"
	UnwrapWebhookEventTypePaymentCancelled                UnwrapWebhookEventType = "payment.cancelled"
	UnwrapWebhookEventTypePaymentFailed                   UnwrapWebhookEventType = "payment.failed"
	UnwrapWebhookEventTypePaymentProcessing               UnwrapWebhookEventType = "payment.processing"
	UnwrapWebhookEventTypePaymentSucceeded                UnwrapWebhookEventType = "payment.succeeded"
	UnwrapWebhookEventTypePayoutCreated                   UnwrapWebhookEventType = "payout.created"
	UnwrapWebhookEventTypePayoutFailed                    UnwrapWebhookEventType = "payout.failed"
	UnwrapWebhookEventTypePayoutInProgress                UnwrapWebhookEventType = "payout.in_progress"
	UnwrapWebhookEventTypePayoutOnHold                    UnwrapWebhookEventType = "payout.on_hold"
	UnwrapWebhookEventTypePayoutSuccess                   UnwrapWebhookEventType = "payout.success"
	UnwrapWebhookEventTypeRefundFailed                    UnwrapWebhookEventType = "refund.failed"
	UnwrapWebhookEventTypeRefundSucceeded                 UnwrapWebhookEventType = "refund.succeeded"
	UnwrapWebhookEventTypeSubscriptionActive              UnwrapWebhookEventType = "subscription.active"
	UnwrapWebhookEventTypeSubscriptionCancelled           UnwrapWebhookEventType = "subscription.cancelled"
	UnwrapWebhookEventTypeSubscriptionExpired             UnwrapWebhookEventType = "subscription.expired"
	UnwrapWebhookEventTypeSubscriptionFailed              UnwrapWebhookEventType = "subscription.failed"
	UnwrapWebhookEventTypeSubscriptionOnHold              UnwrapWebhookEventType = "subscription.on_hold"
	UnwrapWebhookEventTypeSubscriptionPastDue             UnwrapWebhookEventType = "subscription.past_due"
	UnwrapWebhookEventTypeSubscriptionPaused              UnwrapWebhookEventType = "subscription.paused"
	UnwrapWebhookEventTypeSubscriptionPlanChanged         UnwrapWebhookEventType = "subscription.plan_changed"
	UnwrapWebhookEventTypeSubscriptionRenewed             UnwrapWebhookEventType = "subscription.renewed"
	UnwrapWebhookEventTypeSubscriptionUnpaused            UnwrapWebhookEventType = "subscription.unpaused"
	UnwrapWebhookEventTypeSubscriptionUpdatePaymentMethod UnwrapWebhookEventType = "subscription.update_payment_method"
	UnwrapWebhookEventTypeSubscriptionUpdated             UnwrapWebhookEventType = "subscription.updated"
)

func (UnwrapWebhookEventType) IsKnown added in v1.56.0

func (r UnwrapWebhookEventType) IsKnown() bool

type UnwrapWebhookEventUnion added in v1.56.0

type UnwrapWebhookEventUnion interface {
	// contains filtered or unexported methods
}

Union satisfied by AbandonedCheckoutDetectedWebhookEvent, AbandonedCheckoutRecoveredWebhookEvent, CreditAddedWebhookEvent, CreditBalanceLowWebhookEvent, CreditDeductedWebhookEvent, CreditExpiredWebhookEvent, CreditManualAdjustmentWebhookEvent, CreditOverageChargedWebhookEvent, CreditOverageResetWebhookEvent, CreditRolledOverWebhookEvent, CreditRolloverForfeitedWebhookEvent, DisputeAcceptedWebhookEvent, DisputeCancelledWebhookEvent, DisputeChallengedWebhookEvent, DisputeExpiredWebhookEvent, DisputeLostWebhookEvent, DisputeOpenedWebhookEvent, DisputeWonWebhookEvent, DunningRecoveredWebhookEvent, DunningStartedWebhookEvent, EntitlementGrantCreatedWebhookEvent, EntitlementGrantDeliveredWebhookEvent, EntitlementGrantFailedWebhookEvent, EntitlementGrantRevokedWebhookEvent, LicenseKeyCreatedWebhookEvent, PaymentCancelledWebhookEvent, PaymentFailedWebhookEvent, PaymentProcessingWebhookEvent, PaymentSucceededWebhookEvent, PayoutCreatedWebhookEvent, PayoutFailedWebhookEvent, PayoutInProgressWebhookEvent, PayoutOnHoldWebhookEvent, PayoutSuccessWebhookEvent, RefundFailedWebhookEvent, RefundSucceededWebhookEvent, SubscriptionActiveWebhookEvent, SubscriptionCancelledWebhookEvent, SubscriptionExpiredWebhookEvent, SubscriptionFailedWebhookEvent, SubscriptionOnHoldWebhookEvent, SubscriptionPastDueWebhookEvent, SubscriptionPausedWebhookEvent, SubscriptionPlanChangedWebhookEvent, SubscriptionRenewedWebhookEvent, SubscriptionUnpausedWebhookEvent, SubscriptionUpdatePaymentMethodWebhookEvent or SubscriptionUpdatedWebhookEvent.

type UpdateSubscriptionPlanReqEffectiveAt added in v1.88.0

type UpdateSubscriptionPlanReqEffectiveAt string

When to apply the plan change.

- `immediately` (default): Apply the plan change right away - `next_billing_date`: Schedule the change for the next billing date

const (
	UpdateSubscriptionPlanReqEffectiveAtImmediately     UpdateSubscriptionPlanReqEffectiveAt = "immediately"
	UpdateSubscriptionPlanReqEffectiveAtNextBillingDate UpdateSubscriptionPlanReqEffectiveAt = "next_billing_date"
)

func (UpdateSubscriptionPlanReqEffectiveAt) IsKnown added in v1.88.0

type UpdateSubscriptionPlanReqOnPaymentFailure added in v1.86.0

type UpdateSubscriptionPlanReqOnPaymentFailure string

Controls behavior when the plan change payment fails.

  • `prevent_change`: Keep subscription on current plan until payment succeeds
  • `apply_change` (default): Apply plan change immediately regardless of payment outcome

If not specified, uses the business-level default setting.

const (
	UpdateSubscriptionPlanReqOnPaymentFailurePreventChange UpdateSubscriptionPlanReqOnPaymentFailure = "prevent_change"
	UpdateSubscriptionPlanReqOnPaymentFailureApplyChange   UpdateSubscriptionPlanReqOnPaymentFailure = "apply_change"
)

func (UpdateSubscriptionPlanReqOnPaymentFailure) IsKnown added in v1.86.0

type UpdateSubscriptionPlanReqParam added in v1.86.0

type UpdateSubscriptionPlanReqParam struct {
	// Unique identifier of the product to subscribe to
	ProductID param.Field[string] `json:"product_id" api:"required"`
	// Proration Billing Mode
	ProrationBillingMode param.Field[UpdateSubscriptionPlanReqProrationBillingMode] `json:"proration_billing_mode" api:"required"`
	// Number of units to subscribe for. Must be at least 1.
	Quantity param.Field[int64] `json:"quantity" api:"required"`
	// Whether adaptive currency fees should be included in the price (true) or added
	// on top (false). If not specified, uses the subscription's stored setting.
	AdaptiveCurrencyFeesInclusive param.Field[bool] `json:"adaptive_currency_fees_inclusive"`
	// Addons for the new plan. Note : Leaving this empty would remove any existing
	// addons
	Addons param.Field[[]AttachAddonParam] `json:"addons"`
	// Replace a scheduled plan change with this one.
	//
	// The scheduled change is cancelled by the transaction that applies this change. A
	// change that never applies leaves the schedule in place.
	//
	// `effective_at: next_billing_date` is allowed. The new schedule then replaces the
	// old one in the request transaction.
	//
	// A pending plan change still gets a `409`. This field does not affect it.
	//
	// The preview route shares this request body, so a preview that sets this field
	// also passes the scheduled-change `409`.
	CancelScheduledChangePlan param.Field[bool] `json:"cancel_scheduled_change_plan"`
	// Collect the plan-change amount with a payment link. The customer then pays on a
	// checkout page.
	//
	// The business needs the `allow_plan_change_via_payment_link` capability. The
	// request needs `effective_at: immediately`. The request also needs
	// `on_payment_failure: prevent_change`.
	//
	// The preview route shares this request body and ignores this field.
	CollectViaPaymentLink param.Field[bool] `json:"collect_via_payment_link"`
	// DEPRECATED: Use discount_codes instead. Cannot be used together with
	// discount_codes.
	//
	// Deprecated: Use `discount_id` instead.
	DiscountCode param.Field[string] `json:"discount_code"`
	// Stacked discount codes to apply to the new plan. Max 20. Cannot be used together
	// with discount_code. If provided, replaces any existing discount codes. Empty
	// array removes all discounts. If not provided (None), existing discounts with
	// preserve_on_plan_change=true are preserved.
	DiscountCodes param.Field[[]string] `json:"discount_codes"`
	// When to apply the plan change.
	//
	// - `immediately` (default): Apply the plan change right away
	// - `next_billing_date`: Schedule the change for the next billing date
	EffectiveAt param.Field[UpdateSubscriptionPlanReqEffectiveAt] `json:"effective_at"`
	// Metadata for the payment. If not passed, the metadata of the subscription will
	// be taken
	Metadata param.Field[MetadataParam] `json:"metadata"`
	// Controls behavior when the plan change payment fails.
	//
	//   - `prevent_change`: Keep subscription on current plan until payment succeeds
	//   - `apply_change` (default): Apply plan change immediately regardless of payment
	//     outcome
	//
	// If not specified, uses the business-level default setting.
	OnPaymentFailure param.Field[UpdateSubscriptionPlanReqOnPaymentFailure] `json:"on_payment_failure"`
}

func (UpdateSubscriptionPlanReqParam) MarshalJSON added in v1.86.0

func (r UpdateSubscriptionPlanReqParam) MarshalJSON() (data []byte, err error)

type UpdateSubscriptionPlanReqProrationBillingMode added in v1.86.0

type UpdateSubscriptionPlanReqProrationBillingMode string

Proration Billing Mode

const (
	UpdateSubscriptionPlanReqProrationBillingModeProratedImmediately   UpdateSubscriptionPlanReqProrationBillingMode = "prorated_immediately"
	UpdateSubscriptionPlanReqProrationBillingModeFullImmediately       UpdateSubscriptionPlanReqProrationBillingMode = "full_immediately"
	UpdateSubscriptionPlanReqProrationBillingModeDifferenceImmediately UpdateSubscriptionPlanReqProrationBillingMode = "difference_immediately"
	UpdateSubscriptionPlanReqProrationBillingModeDoNotBill             UpdateSubscriptionPlanReqProrationBillingMode = "do_not_bill"
)

func (UpdateSubscriptionPlanReqProrationBillingMode) IsKnown added in v1.86.0

type UsageEventIngestParams added in v1.52.4

type UsageEventIngestParams struct {
	// List of events to be pushed
	Events param.Field[[]EventInputParam] `json:"events" api:"required"`
}

func (UsageEventIngestParams) MarshalJSON added in v1.52.4

func (r UsageEventIngestParams) MarshalJSON() (data []byte, err error)

type UsageEventIngestResponse added in v1.52.4

type UsageEventIngestResponse struct {
	IngestedCount int64                        `json:"ingested_count" api:"required"`
	JSON          usageEventIngestResponseJSON `json:"-"`
}

func (*UsageEventIngestResponse) UnmarshalJSON added in v1.52.4

func (r *UsageEventIngestResponse) UnmarshalJSON(data []byte) (err error)

type UsageEventListParams added in v1.52.4

type UsageEventListParams struct {
	// Filter events by customer ID
	CustomerID param.Field[string] `query:"customer_id"`
	// Filter events created before this timestamp
	End param.Field[time.Time] `query:"end" format:"date-time"`
	// Filter events by event name. If both event_name and meter_id are provided, they
	// must match the meter's configured event_name
	EventName param.Field[string] `query:"event_name"`
	// Filter events by meter ID. When provided, only events that match the meter's
	// event_name and filter criteria will be returned
	MeterID param.Field[string] `query:"meter_id"`
	// Page number (0-based, default: 0)
	PageNumber param.Field[int64] `query:"page_number"`
	// Number of events to return per page (default: 10)
	PageSize param.Field[int64] `query:"page_size"`
	// Filter events created after this timestamp
	Start param.Field[time.Time] `query:"start" format:"date-time"`
}

func (UsageEventListParams) URLQuery added in v1.52.4

func (r UsageEventListParams) URLQuery() (v url.Values)

URLQuery serializes UsageEventListParams's query parameters as `url.Values`.

type UsageEventService added in v1.52.4

type UsageEventService struct {
	Options []option.RequestOption
}

UsageEventService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewUsageEventService method instead.

func NewUsageEventService added in v1.52.4

func NewUsageEventService(opts ...option.RequestOption) (r *UsageEventService)

NewUsageEventService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*UsageEventService) Get added in v1.52.4

func (r *UsageEventService) Get(ctx context.Context, eventID string, opts ...option.RequestOption) (res *Event, err error)

Fetch detailed information about a single event using its unique event ID. This endpoint is useful for:

- Debugging specific event ingestion issues - Retrieving event details for customer support - Validating that events were processed correctly - Getting the complete metadata for an event

## Event ID Format:

The event ID should be the same value that was provided during event ingestion via the `/events/ingest` endpoint. Event IDs are case-sensitive and must match exactly.

## Response Details:

The response includes all event data including:

- Complete metadata key-value pairs - Original timestamp (preserved from ingestion) - Customer and business association - Event name and processing information

## Example Usage:

```text GET /events/api_call_12345 ```

func (*UsageEventService) Ingest added in v1.52.4

This endpoint allows you to ingest custom events that can be used for:

- Usage-based billing and metering - Analytics and reporting - Customer behavior tracking

## Important Notes:

- **Duplicate Prevention**:

  • Duplicate `event_id` values within the same request are rejected (entire request fails)
  • Subsequent requests with existing `event_id` values are ignored (idempotent behavior)
  • **Rate Limiting**: Maximum 1000 events per request
  • **Time Validation**: Events with timestamps older than 1 hour or more than 5 minutes in the future will be rejected
  • **Metadata Limits**: Maximum 50 key-value pairs per event, keys max 100 chars, values max 500 chars

## Example Usage:

```json

{
  "events": [
    {
      "event_id": "api_call_12345",
      "customer_id": "cus_abc123",
      "event_name": "api_request",
      "timestamp": "2024-01-15T10:30:00Z",
      "metadata": {
        "endpoint": "/api/v1/users",
        "method": "GET",
        "tokens_used": "150"
      }
    }
  ]
}

```

func (*UsageEventService) List added in v1.52.4

Fetch events from your account with powerful filtering capabilities. This endpoint is ideal for:

- Debugging event ingestion issues - Analyzing customer usage patterns - Building custom analytics dashboards - Auditing billing-related events

## Filtering Options:

  • **Customer filtering**: Filter by specific customer ID
  • **Event name filtering**: Filter by event type/name
  • **Meter-based filtering**: Use a meter ID to apply the meter's event name and filter criteria automatically
  • **Time range filtering**: Filter events within a specific date range
  • **Pagination**: Navigate through large result sets

## Meter Integration:

When using `meter_id`, the endpoint automatically applies:

- The meter's configured `event_name` filter - The meter's custom filter criteria (if any) - If you also provide `event_name`, it must match the meter's event name

## Example Queries:

  • Get all events for a customer: `?customer_id=cus_abc123`
  • Get API request events: `?event_name=api_request`
  • Get events from last 24 hours: `?start=2024-01-14T10:30:00Z&end=2024-01-15T10:30:00Z`
  • Get events with meter filtering: `?meter_id=mtr_xyz789`
  • Paginate results: `?page_size=50&page_number=2`

func (*UsageEventService) ListAutoPaging added in v1.52.4

Fetch events from your account with powerful filtering capabilities. This endpoint is ideal for:

- Debugging event ingestion issues - Analyzing customer usage patterns - Building custom analytics dashboards - Auditing billing-related events

## Filtering Options:

  • **Customer filtering**: Filter by specific customer ID
  • **Event name filtering**: Filter by event type/name
  • **Meter-based filtering**: Use a meter ID to apply the meter's event name and filter criteria automatically
  • **Time range filtering**: Filter events within a specific date range
  • **Pagination**: Navigate through large result sets

## Meter Integration:

When using `meter_id`, the endpoint automatically applies:

- The meter's configured `event_name` filter - The meter's custom filter criteria (if any) - If you also provide `event_name`, it must match the meter's event name

## Example Queries:

  • Get all events for a customer: `?customer_id=cus_abc123`
  • Get API request events: `?event_name=api_request`
  • Get events from last 24 hours: `?start=2024-01-14T10:30:00Z&end=2024-01-15T10:30:00Z`
  • Get events with meter filtering: `?meter_id=mtr_xyz789`
  • Paginate results: `?page_size=50&page_number=2`

type WebhookDetails added in v1.51.0

type WebhookDetails struct {
	// The webhook's ID.
	ID string `json:"id" api:"required"`
	// Created at timestamp
	CreatedAt string `json:"created_at" api:"required"`
	// An example webhook name.
	Description string `json:"description" api:"required"`
	// Metadata of the webhook
	Metadata map[string]string `json:"metadata" api:"required"`
	// Updated at timestamp
	UpdatedAt string `json:"updated_at" api:"required"`
	// Url endpoint of the webhook
	URL string `json:"url" api:"required"`
	// Status of the webhook.
	//
	// If true, events are not sent
	Disabled bool `json:"disabled" api:"nullable"`
	// Filter events to the webhook.
	//
	// Webhook event will only be sent for events in the list.
	FilterTypes []string `json:"filter_types" api:"nullable"`
	// Configured rate limit
	RateLimit int64              `json:"rate_limit" api:"nullable"`
	JSON      webhookDetailsJSON `json:"-"`
}

func (*WebhookDetails) UnmarshalJSON added in v1.51.0

func (r *WebhookDetails) UnmarshalJSON(data []byte) (err error)

type WebhookEventService

type WebhookEventService struct {
	Options []option.RequestOption
}

WebhookEventService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewWebhookEventService method instead.

func NewWebhookEventService

func NewWebhookEventService(opts ...option.RequestOption) (r *WebhookEventService)

NewWebhookEventService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

type WebhookEventType added in v1.47.0

type WebhookEventType string

Event types for Dodo events

const (
	WebhookEventTypePaymentSucceeded                WebhookEventType = "payment.succeeded"
	WebhookEventTypePaymentFailed                   WebhookEventType = "payment.failed"
	WebhookEventTypePaymentProcessing               WebhookEventType = "payment.processing"
	WebhookEventTypePaymentCancelled                WebhookEventType = "payment.cancelled"
	WebhookEventTypeRefundSucceeded                 WebhookEventType = "refund.succeeded"
	WebhookEventTypeRefundFailed                    WebhookEventType = "refund.failed"
	WebhookEventTypeDisputeOpened                   WebhookEventType = "dispute.opened"
	WebhookEventTypeDisputeExpired                  WebhookEventType = "dispute.expired"
	WebhookEventTypeDisputeAccepted                 WebhookEventType = "dispute.accepted"
	WebhookEventTypeDisputeCancelled                WebhookEventType = "dispute.cancelled"
	WebhookEventTypeDisputeChallenged               WebhookEventType = "dispute.challenged"
	WebhookEventTypeDisputeWon                      WebhookEventType = "dispute.won"
	WebhookEventTypeDisputeLost                     WebhookEventType = "dispute.lost"
	WebhookEventTypeSubscriptionActive              WebhookEventType = "subscription.active"
	WebhookEventTypeSubscriptionRenewed             WebhookEventType = "subscription.renewed"
	WebhookEventTypeSubscriptionOnHold              WebhookEventType = "subscription.on_hold"
	WebhookEventTypeSubscriptionPastDue             WebhookEventType = "subscription.past_due"
	WebhookEventTypeSubscriptionPaused              WebhookEventType = "subscription.paused"
	WebhookEventTypeSubscriptionUnpaused            WebhookEventType = "subscription.unpaused"
	WebhookEventTypeSubscriptionCancelled           WebhookEventType = "subscription.cancelled"
	WebhookEventTypeSubscriptionFailed              WebhookEventType = "subscription.failed"
	WebhookEventTypeSubscriptionExpired             WebhookEventType = "subscription.expired"
	WebhookEventTypeSubscriptionPlanChanged         WebhookEventType = "subscription.plan_changed"
	WebhookEventTypeSubscriptionUpdated             WebhookEventType = "subscription.updated"
	WebhookEventTypeSubscriptionUpdatePaymentMethod WebhookEventType = "subscription.update_payment_method"
	WebhookEventTypeLicenseKeyCreated               WebhookEventType = "license_key.created"
	WebhookEventTypePayoutCreated                   WebhookEventType = "payout.created"
	WebhookEventTypePayoutOnHold                    WebhookEventType = "payout.on_hold"
	WebhookEventTypePayoutInProgress                WebhookEventType = "payout.in_progress"
	WebhookEventTypePayoutFailed                    WebhookEventType = "payout.failed"
	WebhookEventTypePayoutSuccess                   WebhookEventType = "payout.success"
	WebhookEventTypeCreditAdded                     WebhookEventType = "credit.added"
	WebhookEventTypeCreditDeducted                  WebhookEventType = "credit.deducted"
	WebhookEventTypeCreditExpired                   WebhookEventType = "credit.expired"
	WebhookEventTypeCreditRolledOver                WebhookEventType = "credit.rolled_over"
	WebhookEventTypeCreditRolloverForfeited         WebhookEventType = "credit.rollover_forfeited"
	WebhookEventTypeCreditOverageCharged            WebhookEventType = "credit.overage_charged"
	WebhookEventTypeCreditOverageReset              WebhookEventType = "credit.overage_reset"
	WebhookEventTypeCreditManualAdjustment          WebhookEventType = "credit.manual_adjustment"
	WebhookEventTypeCreditBalanceLow                WebhookEventType = "credit.balance_low"
	WebhookEventTypeAbandonedCheckoutDetected       WebhookEventType = "abandoned_checkout.detected"
	WebhookEventTypeAbandonedCheckoutRecovered      WebhookEventType = "abandoned_checkout.recovered"
	WebhookEventTypeDunningStarted                  WebhookEventType = "dunning.started"
	WebhookEventTypeDunningRecovered                WebhookEventType = "dunning.recovered"
	WebhookEventTypeEntitlementGrantCreated         WebhookEventType = "entitlement_grant.created"
	WebhookEventTypeEntitlementGrantDelivered       WebhookEventType = "entitlement_grant.delivered"
	WebhookEventTypeEntitlementGrantFailed          WebhookEventType = "entitlement_grant.failed"
	WebhookEventTypeEntitlementGrantRevoked         WebhookEventType = "entitlement_grant.revoked"
)

func (WebhookEventType) IsKnown added in v1.47.0

func (r WebhookEventType) IsKnown() bool

type WebhookGetSecretResponse added in v1.49.0

type WebhookGetSecretResponse struct {
	Secret string                       `json:"secret" api:"required"`
	JSON   webhookGetSecretResponseJSON `json:"-"`
}

func (*WebhookGetSecretResponse) UnmarshalJSON added in v1.49.0

func (r *WebhookGetSecretResponse) UnmarshalJSON(data []byte) (err error)

type WebhookHeaderGetResponse added in v1.47.0

type WebhookHeaderGetResponse struct {
	// List of headers configured
	Headers map[string]string `json:"headers" api:"required"`
	// Sensitive headers without the value
	Sensitive []string                     `json:"sensitive" api:"required"`
	JSON      webhookHeaderGetResponseJSON `json:"-"`
}

The value of the headers is returned in the `headers` field.

Sensitive headers that have been redacted are returned in the sensitive field.

func (*WebhookHeaderGetResponse) UnmarshalJSON added in v1.47.0

func (r *WebhookHeaderGetResponse) UnmarshalJSON(data []byte) (err error)

type WebhookHeaderService added in v1.47.0

type WebhookHeaderService struct {
	Options []option.RequestOption
}

WebhookHeaderService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewWebhookHeaderService method instead.

func NewWebhookHeaderService added in v1.47.0

func NewWebhookHeaderService(opts ...option.RequestOption) (r *WebhookHeaderService)

NewWebhookHeaderService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*WebhookHeaderService) Get added in v1.47.0

func (r *WebhookHeaderService) Get(ctx context.Context, webhookID string, opts ...option.RequestOption) (res *WebhookHeaderGetResponse, err error)

Get a webhook by id

func (*WebhookHeaderService) Update added in v1.47.0

func (r *WebhookHeaderService) Update(ctx context.Context, webhookID string, body WebhookHeaderUpdateParams, opts ...option.RequestOption) (err error)

Patch a webhook by id

type WebhookHeaderUpdateParams added in v1.47.0

type WebhookHeaderUpdateParams struct {
	// Object of header-value pair to update or add
	Headers param.Field[map[string]string] `json:"headers" api:"required"`
}

func (WebhookHeaderUpdateParams) MarshalJSON added in v1.47.0

func (r WebhookHeaderUpdateParams) MarshalJSON() (data []byte, err error)

type WebhookListParams added in v1.47.0

type WebhookListParams struct {
	// The iterator returned from a prior invocation
	Iterator param.Field[string] `query:"iterator"`
	// Limit the number of returned items
	Limit param.Field[int64] `query:"limit"`
}

func (WebhookListParams) URLQuery added in v1.47.0

func (r WebhookListParams) URLQuery() (v url.Values)

URLQuery serializes WebhookListParams's query parameters as `url.Values`.

type WebhookNewParams added in v1.47.0

type WebhookNewParams struct {
	// Url of the webhook
	URL         param.Field[string] `json:"url" api:"required"`
	Description param.Field[string] `json:"description"`
	// Create the webhook in a disabled state.
	//
	// Default is false
	Disabled param.Field[bool] `json:"disabled"`
	// Filter events to the webhook.
	//
	// Webhook event will only be sent for events in the list.
	FilterTypes param.Field[[]WebhookEventType] `json:"filter_types"`
	// Custom headers to be passed
	Headers param.Field[map[string]string] `json:"headers"`
	// The request's idempotency key
	IdempotencyKey param.Field[string] `json:"idempotency_key"`
	// Metadata to be passed to the webhook Defaut is {}
	Metadata  param.Field[map[string]string] `json:"metadata"`
	RateLimit param.Field[int64]             `json:"rate_limit"`
}

func (WebhookNewParams) MarshalJSON added in v1.47.0

func (r WebhookNewParams) MarshalJSON() (data []byte, err error)

type WebhookService added in v1.47.0

type WebhookService struct {
	Options []option.RequestOption
	Headers *WebhookHeaderService
}

WebhookService contains methods and other services that help with interacting with the Dodo Payments API.

Note, unlike clients, this service does not read variables from the environment automatically. You should not instantiate this service directly, and instead use the NewWebhookService method instead.

func NewWebhookService added in v1.47.0

func NewWebhookService(opts ...option.RequestOption) (r *WebhookService)

NewWebhookService generates a new service that applies the given options to each request. These options are applied after the parent client's options (if there is one), and before any request-specific options.

func (*WebhookService) Delete added in v1.47.0

func (r *WebhookService) Delete(ctx context.Context, webhookID string, opts ...option.RequestOption) (err error)

Delete a webhook by id

func (*WebhookService) Get added in v1.47.0

func (r *WebhookService) Get(ctx context.Context, webhookID string, opts ...option.RequestOption) (res *WebhookDetails, err error)

Get a webhook by id

func (*WebhookService) GetSecret added in v1.49.0

func (r *WebhookService) GetSecret(ctx context.Context, webhookID string, opts ...option.RequestOption) (res *WebhookGetSecretResponse, err error)

Get webhook secret by id

func (*WebhookService) List added in v1.47.0

List all webhooks

func (*WebhookService) ListAutoPaging added in v1.47.0

List all webhooks

func (*WebhookService) New added in v1.47.0

func (r *WebhookService) New(ctx context.Context, body WebhookNewParams, opts ...option.RequestOption) (res *WebhookDetails, err error)

Create a new webhook

func (*WebhookService) UnsafeUnwrap added in v1.56.0

func (r *WebhookService) UnsafeUnwrap(payload []byte, opts ...option.RequestOption) (*UnsafeUnwrapWebhookEvent, error)

func (*WebhookService) Unwrap added in v1.56.0

func (r *WebhookService) Unwrap(payload []byte, headers http.Header, opts ...option.RequestOption) (*UnwrapWebhookEvent, error)

func (*WebhookService) Update added in v1.47.0

func (r *WebhookService) Update(ctx context.Context, webhookID string, body WebhookUpdateParams, opts ...option.RequestOption) (res *WebhookDetails, err error)

Patch a webhook by id

type WebhookUpdateParams added in v1.47.0

type WebhookUpdateParams struct {
	// Description of the webhook
	Description param.Field[string] `json:"description"`
	// To Disable the endpoint, set it to true.
	Disabled param.Field[bool] `json:"disabled"`
	// Filter events to the endpoint.
	//
	// Webhook event will only be sent for events in the list.
	FilterTypes param.Field[[]WebhookEventType] `json:"filter_types"`
	// Metadata
	Metadata param.Field[map[string]string] `json:"metadata"`
	// Rate limit
	RateLimit param.Field[int64] `json:"rate_limit"`
	// Url endpoint
	URL param.Field[string] `json:"url"`
}

func (WebhookUpdateParams) MarshalJSON added in v1.47.0

func (r WebhookUpdateParams) MarshalJSON() (data []byte, err error)

Directories

Path Synopsis
packages

Jump to

Keyboard shortcuts

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