truetrial

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: May 20, 2026 License: MIT Imports: 14 Imported by: 0

README

TrueTrial Go SDK

Official Go client library for the TrueTrial API. Manage trial periods, warranties, subscriptions, and guarantees that begin on confirmed delivery -- not order placement.

Requirements

  • Go 1.21 or later
  • No external dependencies (stdlib only)

Installation

go get github.com/truetrial/truetrial-go

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/truetrial/truetrial-go"
)

func main() {
    client := truetrial.NewClient("your-api-key")
    ctx := context.Background()

    // Create an order
    order, err := client.Orders.Create(ctx, truetrial.CreateOrderParams{
        ExternalOrderID: "EXT-12345",
        ProductName:     "Premium Supplement",
        ProductType:     truetrial.ProductTypePhysical,
        PriceCents:      4999,
        Currency:        "USD",
        TemporalType:    truetrial.TemporalTypeTrial,
        DurationValue:   30,
        DurationUnit:    truetrial.DurationUnitDays,
        Consumer: truetrial.ConsumerParams{
            Email:     "customer@example.com",
            FirstName: "Jane",
            LastName:  "Doe",
        },
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Created order: %s\n", order.ID)
}

Configuration

// Default configuration
client := truetrial.NewClient("your-api-key")

// Custom base URL
client := truetrial.NewClient("your-api-key",
    truetrial.WithBaseURL("https://api.truetrial.com/api/v1"),
)

// Custom HTTP client (e.g., for proxies or custom TLS)
client := truetrial.NewClient("your-api-key",
    truetrial.WithHTTPClient(&http.Client{
        Timeout: 60 * time.Second,
    }),
)

API Reference

All methods accept a context.Context as their first parameter and return an error as their last return value.

Orders
// List orders with optional filters
resp, err := client.Orders.List(ctx, &truetrial.ListOrdersParams{
    Page:   1,
    Status: truetrial.OrderStatusDelivered,
})

// Create an order
order, err := client.Orders.Create(ctx, truetrial.CreateOrderParams{...})

// Get a single order
order, err := client.Orders.Get(ctx, "order-id")

// Get combined status (order + temporal + shipment)
status, err := client.Orders.Status(ctx, "order-id")
Shipments
// Create a shipment
shipment, err := client.Shipments.Create(ctx, "order-id", truetrial.CreateShipmentParams{
    Carrier:        truetrial.CarrierUPS,
    TrackingNumber: "1Z999AA10123456784",
})

// List shipments for an order
shipments, err := client.Shipments.List(ctx, "order-id")
Digital Delivery
// Confirm digital product delivery
order, err := client.DigitalDelivery.Confirm(ctx, "order-id", truetrial.ConfirmDigitalDeliveryParams{
    DeliverySource: truetrial.DeliverySourceWebhook,
})
Temporal Elements
// Get temporal element for an order
temporal, err := client.Temporal.Get(ctx, "order-id")

// Extend a trial/warranty/etc.
temporal, err := client.Temporal.Extend(ctx, "order-id", truetrial.ExtendTemporalParams{
    DurationValue: 7,
    DurationUnit:  truetrial.DurationUnitDays,
    Reason:        "Customer requested extension",
})

// Adjust the end time directly
temporal, err := client.Temporal.Adjust(ctx, "order-id", truetrial.AdjustTemporalParams{
    NewEndTime: "2026-03-15T00:00:00Z",
    Reason:     "Shipping delay compensation",
})

// Submit a warranty/guarantee claim
temporal, err := client.Temporal.Claim(ctx, "order-id", truetrial.ClaimParams{
    Reason:      "Product defective",
    Description: "Screen cracked on arrival",
})

// Resolve a claim
temporal, err := client.Temporal.ResolveClaim(ctx, "order-id", truetrial.ResolveClaimParams{
    Resolution: "approved",
    Notes:      "Replacement shipped",
})
Cancellations
// Create a cancellation
cancellation, err := client.Cancellations.Create(ctx, "order-id", truetrial.CreateCancellationParams{
    Reason: "Customer requested cancellation",
})

// Get cancellation details
cancellation, err := client.Cancellations.Get(ctx, "order-id")
Webhooks
// List webhook subscriptions
webhooks, err := client.Webhooks.List(ctx)

// Create a webhook subscription
webhook, err := client.Webhooks.Create(ctx, truetrial.CreateWebhookParams{
    URL: "https://example.com/webhooks/truetrial",
    Events: []truetrial.WebhookEvent{
        truetrial.WebhookEventOrderDelivered,
        truetrial.WebhookEventTrialExpiring,
        truetrial.WebhookEventTrialExpired,
    },
})
// Store webhook.Secret securely for signature verification.

// Delete a webhook subscription
err := client.Webhooks.Delete(ctx, "webhook-id")
System
// Check carrier health
carriers, err := client.System.CarrierHealth(ctx)
for _, c := range carriers {
    fmt.Printf("%s: %s (%dms)\n", c.Carrier, c.Status, c.Latency)
}

Error Handling

All API errors are returned as *truetrial.TrueTrialError with typed helper functions for common cases:

order, err := client.Orders.Get(ctx, "order-id")
if err != nil {
    if truetrial.IsNotFoundError(err) {
        // Order does not exist
        log.Println("Order not found")
        return
    }

    if truetrial.IsValidationError(err) {
        // Access field-level validation errors
        ttErr := err.(*truetrial.TrueTrialError)
        for field, messages := range ttErr.Errors {
            log.Printf("  %s: %v\n", field, messages)
        }
        return
    }

    if truetrial.IsRateLimitError(err) {
        ttErr := err.(*truetrial.TrueTrialError)
        log.Printf("Rate limited. Retry after %d seconds\n", ttErr.RetryAfter)
        return
    }

    if truetrial.IsAuthenticationError(err) {
        log.Fatal("Invalid API key")
    }

    if truetrial.IsServerError(err) {
        log.Println("TrueTrial server error, try again later")
        return
    }

    log.Fatal(err)
}

Webhook Verification

Verify incoming webhook signatures to ensure they are authentic:

import "github.com/truetrial/truetrial-go"

func handleWebhook(w http.ResponseWriter, r *http.Request) {
    payload, _ := io.ReadAll(r.Body)
    signature := r.Header.Get(truetrial.WebhookSignatureHeader)
    event := r.Header.Get(truetrial.WebhookEventHeader)
    secret := "your-webhook-secret"

    // Simple signature verification
    if !truetrial.VerifyWebhookSignature(payload, signature, secret) {
        http.Error(w, "Invalid signature", http.StatusForbidden)
        return
    }

    // Or verify with timestamp tolerance (prevents replay attacks)
    if !truetrial.VerifyWebhookSignatureWithTolerance(payload, signature, secret, 5*time.Minute) {
        http.Error(w, "Invalid or expired signature", http.StatusForbidden)
        return
    }

    switch truetrial.WebhookEvent(event) {
    case truetrial.WebhookEventOrderDelivered:
        // Handle delivery confirmation
    case truetrial.WebhookEventTrialExpiring:
        // Send reminder to customer
    case truetrial.WebhookEventTrialExpired:
        // Process conversion or return
    }

    w.WriteHeader(http.StatusOK)
}

Pagination

List endpoints return a PaginatedResponse with raw JSON data that you decode into the target type:

import "encoding/json"

resp, err := client.Orders.List(ctx, &truetrial.ListOrdersParams{Page: 1})
if err != nil {
    log.Fatal(err)
}

var orders []truetrial.Order
if err := json.Unmarshal(resp.Data, &orders); err != nil {
    log.Fatal(err)
}

fmt.Printf("Page %d of %d (%d total orders)\n", resp.CurrentPage, resp.LastPage, resp.Total)

License

See LICENSE for details.

Documentation

Overview

Package truetrial provides a Go client for the TrueTrial API.

TrueTrial is a compliance-first platform for managing trial, warranty, subscription, and guarantee periods. This SDK provides full access to the TrueTrial REST API and utilities for webhook signature verification.

Usage:

client := truetrial.NewClient("your-api-key")
order, err := client.Orders.Get(ctx, "order-id")

Index

Constants

View Source
const (
	// DefaultBaseURL is the default API base URL.
	DefaultBaseURL = "https://truetrial.test/api/v1"

	// DefaultTimeout is the default HTTP client timeout.
	DefaultTimeout = 30 * time.Second

	// Version is the SDK version.
	Version = "1.0.0"
)
View Source
const (
	// WebhookSignatureHeader is the HTTP header containing the webhook signature.
	WebhookSignatureHeader = "X-TrueTrial-Signature"

	// WebhookEventHeader is the HTTP header containing the webhook event type.
	WebhookEventHeader = "X-TrueTrial-Event"

	// WebhookTimestampHeader is the HTTP header containing the webhook timestamp.
	WebhookTimestampHeader = "X-TrueTrial-Timestamp"

	// DefaultWebhookTolerance is the default maximum age allowed for a webhook
	// delivery before it is considered stale. Five minutes is the default.
	DefaultWebhookTolerance = 5 * time.Minute
)

Variables

This section is empty.

Functions

func IsAuthenticationError

func IsAuthenticationError(err error) bool

IsAuthenticationError reports whether the error is an authentication error (401/403).

func IsNotFoundError

func IsNotFoundError(err error) bool

IsNotFoundError reports whether the error is a not-found error (404).

func IsRateLimitError

func IsRateLimitError(err error) bool

IsRateLimitError reports whether the error is a rate-limit error (429).

func IsServerError

func IsServerError(err error) bool

IsServerError reports whether the error is a server error (5xx).

func IsValidationError

func IsValidationError(err error) bool

IsValidationError reports whether the error is a validation error (422).

func VerifyWebhookSignature

func VerifyWebhookSignature(payload []byte, signature string, secret string) bool

VerifyWebhookSignature verifies that a webhook payload was signed by TrueTrial using the given signing secret. The signature should be the value of the X-TrueTrial-Signature header.

This performs a constant-time comparison to prevent timing attacks.

func VerifyWebhookSignatureWithTolerance

func VerifyWebhookSignatureWithTolerance(payload []byte, signature string, secret string, tolerance time.Duration) bool

VerifyWebhookSignatureWithTolerance verifies the webhook signature and additionally checks that the timestamp in the signature is within the given tolerance window.

The signature format is expected to be "t=<unix_timestamp>,v1=<hex_hmac>" where the HMAC is computed over "<timestamp>.<payload>".

If tolerance is zero, DefaultWebhookTolerance is used.

Types

type AdjustTemporalParams

type AdjustTemporalParams struct {
	NewEndTime string `json:"new_end_time"`
	Reason     string `json:"reason,omitempty"`
}

AdjustTemporalParams contains the fields for adjusting a temporal element.

type Cancellation

type Cancellation struct {
	ID          string `json:"id"`
	OrderID     string `json:"order_id"`
	Reason      string `json:"reason"`
	Status      string `json:"status"`
	CancelledAt string `json:"cancelled_at,omitempty"`
}

Cancellation represents a cancellation request for an order.

type CancellationsService

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

CancellationsService handles communication with the cancellation-related endpoints of the TrueTrial API.

func (*CancellationsService) Create

Create initiates a cancellation for the given order.

func (*CancellationsService) Get

func (s *CancellationsService) Get(ctx context.Context, orderID string) (*Cancellation, error)

Get retrieves the cancellation for the given order.

type Carrier

type Carrier string

Carrier represents a shipping carrier.

const (
	CarrierUPS       Carrier = "ups"
	CarrierFedEx     Carrier = "fedex"
	CarrierUSPS      Carrier = "usps"
	CarrierDHL       Carrier = "dhl"
	CarrierShippo    Carrier = "shippo"
	CarrierAfterShip Carrier = "aftership"
)

type CarrierHealthEntry

type CarrierHealthEntry struct {
	Carrier   Carrier `json:"carrier"`
	Status    string  `json:"status"`
	Latency   int     `json:"latency_ms"`
	CheckedAt string  `json:"checked_at"`
}

CarrierHealthEntry represents the health status of a single carrier.

type ClaimParams

type ClaimParams struct {
	Reason      string `json:"reason"`
	Description string `json:"description,omitempty"`
}

ClaimParams contains the fields for submitting a warranty or guarantee claim.

type Client

type Client struct {
	Orders          *OrdersService
	Shipments       *ShipmentsService
	DigitalDelivery *DigitalDeliveryService
	Temporal        *TemporalService
	Cancellations   *CancellationsService
	Webhooks        *WebhooksService
	System          *SystemService
	// contains filtered or unexported fields
}

Client is the TrueTrial API client. Use NewClient to create one.

func NewClient

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

NewClient creates a new TrueTrial API client authenticated with the given API key. Options can be provided to customize the client behaviour.

type ConfirmDigitalDeliveryParams

type ConfirmDigitalDeliveryParams struct {
	DeliveredAt    string         `json:"delivered_at,omitempty"`
	DeliverySource DeliverySource `json:"delivery_source,omitempty"`
}

ConfirmDigitalDeliveryParams contains the fields for confirming a digital product delivery.

type ConfirmManuallyParams added in v1.0.1

type ConfirmManuallyParams struct {
	DeliveredAt      string `json:"delivered_at"`
	Reason           string `json:"reason"`
	ConfirmedByEmail string `json:"confirmed_by_email,omitempty"`
}

ConfirmManuallyParams contains the fields for manually confirming delivery.

type Consumer

type Consumer struct {
	ID        string `json:"id"`
	Email     string `json:"email"`
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
	Phone     string `json:"phone,omitempty"`
}

Consumer represents a TrueTrial consumer.

type ConsumerParams

type ConsumerParams struct {
	Email     string `json:"email"`
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
	Phone     string `json:"phone,omitempty"`
}

ConsumerParams contains the consumer details when creating an order.

type CreateCancellationParams

type CreateCancellationParams struct {
	Reason string `json:"reason"`
}

CreateCancellationParams contains the fields for creating a cancellation.

type CreateOrderParams

type CreateOrderParams struct {
	ExternalOrderID string         `json:"external_order_id"`
	ProductName     string         `json:"product_name"`
	ProductType     ProductType    `json:"product_type"`
	PriceCents      int            `json:"product_price_cents"`
	Currency        string         `json:"product_currency"`
	TemporalType    TemporalType   `json:"temporal_type"`
	DurationValue   int            `json:"duration_value"`
	DurationUnit    DurationUnit   `json:"duration_unit"`
	Consumer        ConsumerParams `json:"consumer"`
	Metadata        any            `json:"metadata,omitempty"`
}

CreateOrderParams contains the fields for creating a new order.

type CreateShipmentParams

type CreateShipmentParams struct {
	Carrier           Carrier `json:"carrier"`
	TrackingNumber    string  `json:"tracking_number"`
	EstimatedDelivery string  `json:"estimated_delivery,omitempty"`
}

CreateShipmentParams contains the fields for creating a shipment.

type CreateWebhookParams

type CreateWebhookParams struct {
	URL    string         `json:"url"`
	Events []WebhookEvent `json:"events"`
}

CreateWebhookParams contains the fields for creating a webhook subscription.

type DeliverySource

type DeliverySource string

DeliverySource represents how a delivery was confirmed.

const (
	DeliverySourceWebhook         DeliverySource = "webhook"
	DeliverySourcePoll            DeliverySource = "poll"
	DeliverySourceManual          DeliverySource = "manual"
	DeliverySourceFallbackCarrier DeliverySource = "fallback_carrier"
)

type DigitalDeliveryService

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

DigitalDeliveryService handles communication with the digital delivery endpoints of the TrueTrial API.

func (*DigitalDeliveryService) Confirm

Confirm marks a digital product as delivered for the given order.

type DurationUnit

type DurationUnit string

DurationUnit represents the unit of a temporal duration.

const (
	DurationUnitDays   DurationUnit = "days"
	DurationUnitWeeks  DurationUnit = "weeks"
	DurationUnitMonths DurationUnit = "months"
	DurationUnitYears  DurationUnit = "years"
)

type ExtendTemporalParams

type ExtendTemporalParams struct {
	DurationValue int          `json:"duration_value"`
	DurationUnit  DurationUnit `json:"duration_unit"`
	Reason        string       `json:"reason,omitempty"`
}

ExtendTemporalParams contains the fields for extending a temporal element.

type ListOrdersParams

type ListOrdersParams struct {
	Page   int         `json:"page,omitempty"`
	Status OrderStatus `json:"status,omitempty"`
}

ListOrdersParams contains optional query parameters for listing orders.

type Option

type Option func(*Client)

Option configures the Client.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL overrides the default API base URL.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient overrides the default net/http client used for requests.

type Order

type Order struct {
	ID                string      `json:"id"`
	TenantID          string      `json:"tenant_id"`
	ConsumerID        string      `json:"consumer_id"`
	ExternalOrderID   string      `json:"external_order_id"`
	ProductName       string      `json:"product_name"`
	ProductType       ProductType `json:"product_type"`
	ProductPriceCents int         `json:"product_price_cents"`
	ProductCurrency   string      `json:"product_currency"`
	Status            OrderStatus `json:"status"`
	Metadata          any         `json:"metadata,omitempty"`
	CreatedAt         string      `json:"created_at"`
	Consumer          *Consumer   `json:"consumer,omitempty"`
}

Order represents a TrueTrial order.

type OrderStatus

type OrderStatus string

OrderStatus represents the status of an order.

const (
	OrderStatusReceived       OrderStatus = "received"
	OrderStatusShipped        OrderStatus = "shipped"
	OrderStatusInTransit      OrderStatus = "in_transit"
	OrderStatusDelivered      OrderStatus = "delivered"
	OrderStatusDeliveryFailed OrderStatus = "delivery_failed"
	OrderStatusTrialActive    OrderStatus = "trial_active"
	OrderStatusConverted      OrderStatus = "converted"
	OrderStatusReturned       OrderStatus = "returned"
	OrderStatusExpired        OrderStatus = "expired"
	OrderStatusCancelled      OrderStatus = "cancelled"
)

type OrderStatusResponse

type OrderStatusResponse struct {
	OrderID               string         `json:"order_id"`
	ExternalOrderID       string         `json:"external_order_id"`
	OrderStatus           OrderStatus    `json:"order_status"`
	TemporalElementStatus TemporalStatus `json:"temporal_element_status,omitempty"`
	ShipmentStatus        ShipmentStatus `json:"shipment_status,omitempty"`
}

OrderStatusResponse contains the combined status of an order, its temporal element, and its shipment.

type OrdersService

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

OrdersService handles communication with the order-related endpoints of the TrueTrial API.

func (*OrdersService) Create

func (s *OrdersService) Create(ctx context.Context, params CreateOrderParams) (*Order, error)

Create creates a new order and returns it.

func (*OrdersService) Get

func (s *OrdersService) Get(ctx context.Context, id string) (*Order, error)

Get retrieves a single order by its ID.

func (*OrdersService) List

List returns a paginated list of orders. Pass nil for params to use defaults.

func (*OrdersService) Status

Status retrieves the combined status of an order, its temporal element, and its shipment.

type PaginatedResponse

type PaginatedResponse struct {
	Data        json.RawMessage `json:"data"`
	CurrentPage int             `json:"current_page"`
	LastPage    int             `json:"last_page"`
	PerPage     int             `json:"per_page"`
	Total       int             `json:"total"`
}

PaginatedResponse wraps paginated API responses. Data contains the raw JSON array of results; use json.Unmarshal to decode into the target slice type.

type ProductType

type ProductType string

ProductType represents the type of product.

const (
	ProductTypePhysical ProductType = "physical"
	ProductTypeDigital  ProductType = "digital"
)

type ResolveClaimParams

type ResolveClaimParams struct {
	Resolution string `json:"resolution"`
	Notes      string `json:"notes,omitempty"`
}

ResolveClaimParams contains the fields for resolving a claim.

type Shipment

type Shipment struct {
	ID                string         `json:"id"`
	OrderID           string         `json:"order_id"`
	Carrier           Carrier        `json:"carrier"`
	TrackingNumber    string         `json:"tracking_number"`
	Status            ShipmentStatus `json:"status"`
	EstimatedDelivery string         `json:"estimated_delivery,omitempty"`
	DeliveredAt       string         `json:"delivered_at,omitempty"`
}

Shipment represents a shipment associated with an order.

type ShipmentStatus

type ShipmentStatus string

ShipmentStatus represents the status of a shipment.

const (
	ShipmentStatusPending          ShipmentStatus = "pending"
	ShipmentStatusInTransit        ShipmentStatus = "in_transit"
	ShipmentStatusOutForDelivery   ShipmentStatus = "out_for_delivery"
	ShipmentStatusDelivered        ShipmentStatus = "delivered"
	ShipmentStatusFailed           ShipmentStatus = "failed"
	ShipmentStatusReturnedToSender ShipmentStatus = "returned_to_sender"
)

type ShipmentsService

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

ShipmentsService handles communication with the shipment-related endpoints of the TrueTrial API.

func (*ShipmentsService) ConfirmManually added in v1.0.1

func (s *ShipmentsService) ConfirmManually(ctx context.Context, orderID string, params ConfirmManuallyParams) (*Order, error)

ConfirmManually manually confirms delivery of an order. Use this for the edge case where the carrier lost the package update but the consumer confirmed receipt. Records delivery_source = manual and starts the trial timer.

func (*ShipmentsService) Create

func (s *ShipmentsService) Create(ctx context.Context, orderID string, params CreateShipmentParams) (*Shipment, error)

Create creates a new shipment for the given order.

func (*ShipmentsService) List

func (s *ShipmentsService) List(ctx context.Context, orderID string) ([]Shipment, error)

List returns all shipments for the given order.

type SystemService

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

SystemService handles communication with system-level endpoints of the TrueTrial API.

func (*SystemService) CarrierHealth

func (s *SystemService) CarrierHealth(ctx context.Context) ([]CarrierHealthEntry, error)

CarrierHealth returns the health status of all configured shipping carriers.

type TemporalElement

type TemporalElement struct {
	ID            string         `json:"id"`
	OrderID       string         `json:"order_id"`
	Type          TemporalType   `json:"type"`
	Status        TemporalStatus `json:"status"`
	DurationValue int            `json:"duration_value"`
	DurationUnit  DurationUnit   `json:"duration_unit"`
	BeginTime     string         `json:"begin_time,omitempty"`
	EndTime       string         `json:"end_time,omitempty"`
	ExpiresAt     string         `json:"expires_at,omitempty"`
}

TemporalElement represents a trial, warranty, subscription, evaluation, or guarantee period attached to an order.

type TemporalService

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

TemporalService handles communication with the temporal element endpoints of the TrueTrial API.

func (*TemporalService) Adjust

func (s *TemporalService) Adjust(ctx context.Context, orderID string, params AdjustTemporalParams) (*TemporalElement, error)

Adjust sets a new end time for the temporal element on the given order.

func (*TemporalService) Claim

func (s *TemporalService) Claim(ctx context.Context, orderID string, params ClaimParams) (*TemporalElement, error)

Claim submits a warranty or guarantee claim for the given order.

func (*TemporalService) Extend

func (s *TemporalService) Extend(ctx context.Context, orderID string, params ExtendTemporalParams) (*TemporalElement, error)

Extend extends the temporal element for the given order by an additional duration.

func (*TemporalService) Get

func (s *TemporalService) Get(ctx context.Context, orderID string) (*TemporalElement, error)

Get retrieves the temporal element for the given order.

func (*TemporalService) ResolveClaim

func (s *TemporalService) ResolveClaim(ctx context.Context, orderID string, params ResolveClaimParams) (*TemporalElement, error)

ResolveClaim resolves an existing claim on the given order.

type TemporalStatus

type TemporalStatus string

TemporalStatus represents the status of a temporal element.

const (
	TemporalStatusPending       TemporalStatus = "pending"
	TemporalStatusActive        TemporalStatus = "active"
	TemporalStatusExpiring      TemporalStatus = "expiring"
	TemporalStatusExpired       TemporalStatus = "expired"
	TemporalStatusConverted     TemporalStatus = "converted"
	TemporalStatusCancelled     TemporalStatus = "cancelled"
	TemporalStatusSuspended     TemporalStatus = "suspended"
	TemporalStatusRenewed       TemporalStatus = "renewed"
	TemporalStatusClaimed       TemporalStatus = "claimed"
	TemporalStatusClaimApproved TemporalStatus = "claim_approved"
	TemporalStatusClaimDenied   TemporalStatus = "claim_denied"
)

type TemporalType

type TemporalType string

TemporalType represents the type of temporal element.

const (
	TemporalTypeTrial        TemporalType = "trial"
	TemporalTypeEvaluation   TemporalType = "evaluation"
	TemporalTypeSubscription TemporalType = "subscription"
	TemporalTypeWarranty     TemporalType = "warranty"
	TemporalTypeGuarantee    TemporalType = "guarantee"
)

type TrueTrialError

type TrueTrialError struct {
	// StatusCode is the HTTP status code from the API response.
	StatusCode int `json:"status_code"`

	// Message is the human-readable error message.
	Message string `json:"message"`

	// ResponseBody is the raw response body for debugging.
	ResponseBody []byte `json:"-"`

	// Errors contains field-level validation errors (only for 422 responses).
	Errors map[string][]string `json:"errors,omitempty"`

	// RetryAfter is the number of seconds to wait before retrying
	// (only for 429 responses).
	RetryAfter int `json:"retry_after,omitempty"`
}

TrueTrialError is the base error type returned by the TrueTrial API client. All API errors can be type-asserted to *TrueTrialError.

func NewAuthenticationError

func NewAuthenticationError(message string, body []byte) *TrueTrialError

NewAuthenticationError creates an error for 401/403 responses.

func NewNotFoundError

func NewNotFoundError(message string, body []byte) *TrueTrialError

NewNotFoundError creates an error for 404 responses.

func NewRateLimitError

func NewRateLimitError(message string, retryAfter int, body []byte) *TrueTrialError

NewRateLimitError creates an error for 429 responses.

func NewServerError

func NewServerError(statusCode int, message string, body []byte) *TrueTrialError

NewServerError creates an error for 5xx responses.

func NewValidationError

func NewValidationError(message string, errors map[string][]string, body []byte) *TrueTrialError

NewValidationError creates an error for 422 responses with field-level errors.

func (*TrueTrialError) Error

func (e *TrueTrialError) Error() string

Error implements the error interface.

type WebhookEvent

type WebhookEvent string

WebhookEvent represents a webhook event type.

const (
	WebhookEventOrderCreated          WebhookEvent = "order.created"
	WebhookEventOrderDelivered        WebhookEvent = "order.delivered"
	WebhookEventDeliveryFailed        WebhookEvent = "delivery.failed"
	WebhookEventTrialStarted          WebhookEvent = "trial.started"
	WebhookEventTrialExpiring         WebhookEvent = "trial.expiring"
	WebhookEventTrialExpired          WebhookEvent = "trial.expired"
	WebhookEventTrialConverted        WebhookEvent = "trial.converted"
	WebhookEventCancellationInitiated WebhookEvent = "cancellation.initiated"
	WebhookEventRiskScoreChanged      WebhookEvent = "risk_score.changed"
	WebhookEventSubscriptionRenewed   WebhookEvent = "subscription.renewed"
	WebhookEventWarrantyClaimed       WebhookEvent = "warranty.claimed"
	WebhookEventTemporalExtended      WebhookEvent = "temporal.extended"
	WebhookEventTemporalAdjusted      WebhookEvent = "temporal.adjusted"
	WebhookEventWarrantyClaimResolved WebhookEvent = "warranty.claim_resolved"
	WebhookEventPaymentSucceeded      WebhookEvent = "payment.succeeded"
	WebhookEventPaymentFailed         WebhookEvent = "payment.failed"
	WebhookEventDisputeCreated        WebhookEvent = "dispute.created"
	WebhookEventDisputeWon            WebhookEvent = "dispute.won"
	WebhookEventDisputeLost           WebhookEvent = "dispute.lost"
)

type WebhookSubscription

type WebhookSubscription struct {
	ID              string         `json:"id"`
	URL             string         `json:"url"`
	Events          []WebhookEvent `json:"events"`
	Secret          string         `json:"secret,omitempty"`
	LastTriggeredAt string         `json:"last_triggered_at,omitempty"`
}

WebhookSubscription represents a registered webhook endpoint.

type WebhooksService

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

WebhooksService handles communication with the webhook subscription endpoints of the TrueTrial API.

func (*WebhooksService) Create

Create registers a new webhook subscription and returns it. The response includes the signing secret which should be stored securely.

func (*WebhooksService) Delete

func (s *WebhooksService) Delete(ctx context.Context, id string) error

Delete removes a webhook subscription by its ID.

func (*WebhooksService) List

List returns all webhook subscriptions for the authenticated tenant.

Jump to

Keyboard shortcuts

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