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
- func IsAuthenticationError(err error) bool
- func IsNotFoundError(err error) bool
- func IsRateLimitError(err error) bool
- func IsServerError(err error) bool
- func IsValidationError(err error) bool
- func VerifyWebhookSignature(payload []byte, signature string, secret string) bool
- func VerifyWebhookSignatureWithTolerance(payload []byte, signature string, secret string, tolerance time.Duration) bool
- type AdjustTemporalParams
- type Cancellation
- type CancellationsService
- type Carrier
- type CarrierHealthEntry
- type ClaimParams
- type Client
- type ConfirmDigitalDeliveryParams
- type ConfirmManuallyParams
- type Consumer
- type ConsumerParams
- type CreateCancellationParams
- type CreateOrderParams
- type CreateShipmentParams
- type CreateWebhookParams
- type DeliverySource
- type DigitalDeliveryService
- type DurationUnit
- type ExtendTemporalParams
- type ListOrdersParams
- type Option
- type Order
- type OrderStatus
- type OrderStatusResponse
- type OrdersService
- func (s *OrdersService) Create(ctx context.Context, params CreateOrderParams) (*Order, error)
- func (s *OrdersService) Get(ctx context.Context, id string) (*Order, error)
- func (s *OrdersService) List(ctx context.Context, params *ListOrdersParams) (*PaginatedResponse, error)
- func (s *OrdersService) Status(ctx context.Context, id string) (*OrderStatusResponse, error)
- type PaginatedResponse
- type ProductType
- type ResolveClaimParams
- type Shipment
- type ShipmentStatus
- type ShipmentsService
- func (s *ShipmentsService) ConfirmManually(ctx context.Context, orderID string, params ConfirmManuallyParams) (*Order, error)
- func (s *ShipmentsService) Create(ctx context.Context, orderID string, params CreateShipmentParams) (*Shipment, error)
- func (s *ShipmentsService) List(ctx context.Context, orderID string) ([]Shipment, error)
- type SystemService
- type TemporalElement
- type TemporalService
- func (s *TemporalService) Adjust(ctx context.Context, orderID string, params AdjustTemporalParams) (*TemporalElement, error)
- func (s *TemporalService) Claim(ctx context.Context, orderID string, params ClaimParams) (*TemporalElement, error)
- func (s *TemporalService) Extend(ctx context.Context, orderID string, params ExtendTemporalParams) (*TemporalElement, error)
- func (s *TemporalService) Get(ctx context.Context, orderID string) (*TemporalElement, error)
- func (s *TemporalService) ResolveClaim(ctx context.Context, orderID string, params ResolveClaimParams) (*TemporalElement, error)
- type TemporalStatus
- type TemporalType
- type TrueTrialError
- func NewAuthenticationError(message string, body []byte) *TrueTrialError
- func NewNotFoundError(message string, body []byte) *TrueTrialError
- func NewRateLimitError(message string, retryAfter int, body []byte) *TrueTrialError
- func NewServerError(statusCode int, message string, body []byte) *TrueTrialError
- func NewValidationError(message string, errors map[string][]string, body []byte) *TrueTrialError
- type WebhookEvent
- type WebhookSubscription
- type WebhooksService
Constants ¶
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" )
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 ¶
IsAuthenticationError reports whether the error is an authentication error (401/403).
func IsNotFoundError ¶
IsNotFoundError reports whether the error is a not-found error (404).
func IsRateLimitError ¶
IsRateLimitError reports whether the error is a rate-limit error (429).
func IsServerError ¶
IsServerError reports whether the error is a server error (5xx).
func IsValidationError ¶
IsValidationError reports whether the error is a validation error (422).
func VerifyWebhookSignature ¶
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 ¶
func (s *CancellationsService) Create(ctx context.Context, orderID string, params CreateCancellationParams) (*Cancellation, error)
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 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.
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 ¶
func (s *DigitalDeliveryService) Confirm(ctx context.Context, orderID string, params ConfirmDigitalDeliveryParams) (*Order, error)
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 ¶
WithBaseURL overrides the default API base URL.
func WithHTTPClient ¶
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) List ¶
func (s *OrdersService) List(ctx context.Context, params *ListOrdersParams) (*PaginatedResponse, error)
List returns a paginated list of orders. Pass nil for params to use defaults.
func (*OrdersService) Status ¶
func (s *OrdersService) Status(ctx context.Context, id string) (*OrderStatusResponse, error)
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.
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 ¶
func (s *WebhooksService) Create(ctx context.Context, params CreateWebhookParams) (*WebhookSubscription, error)
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 ¶
func (s *WebhooksService) List(ctx context.Context) ([]WebhookSubscription, error)
List returns all webhook subscriptions for the authenticated tenant.