Help us shape the future of Go! Take the 2026 Go Developer Survey

paylio

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2026 License: MIT Imports: 11 Imported by: 0

README

Paylio Go SDK

Go Reference CI

The Paylio Go SDK provides convenient access to the Paylio API from applications written in Go.

Documentation

See the Paylio API docs.

Requirements

  • Go 1.22+

Installation

go get github.com/paylio-org/paylio-go

Usage

package main

import (
	"context"
	"fmt"
	"log"

	paylio "github.com/paylio-org/paylio-go"
)

func main() {
	client, err := paylio.NewClient("sk_live_xxx")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	ctx := context.Background()

	// Retrieve current subscription
	sub, err := client.Subscription.Retrieve(ctx, "user_123")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Status: %s, Plan: %s\n", sub.Status, sub.Plan.Name)
}
List subscription history
list, err := client.Subscription.List(ctx, "user_123", &paylio.ListOptions{
    Page:     1,
    PageSize: 10,
})
if err != nil {
    log.Fatal(err)
}
for _, item := range list.Items {
    fmt.Printf("%s — %s (%s)\n", item.ID, item.PlanName, item.Status)
}
fmt.Println("Has more:", list.HasMore())
Cancel a subscription
// Cancel at end of billing period (safe default)
result, err := client.Subscription.Cancel(ctx, "sub_uuid", nil)

// Cancel immediately
result, err := client.Subscription.Cancel(ctx, "sub_uuid", &paylio.CancelOptions{
    CancelNow: true,
})
Configuration
// Custom base URL and timeout
client, err := paylio.NewClient("sk_live_xxx",
    paylio.WithBaseURL("https://custom-api.example.com/v1"),
    paylio.WithTimeout(60 * time.Second),
)

// Custom HTTP client
client, err := paylio.NewClient("sk_live_xxx",
    paylio.WithHTTPClient(&http.Client{
        Transport: customTransport,
    }),
)
Error handling
sub, err := client.Subscription.Retrieve(ctx, "user_123")
if err != nil {
    var authErr *paylio.AuthenticationError
    var notFoundErr *paylio.NotFoundError
    var rateLimitErr *paylio.RateLimitError
    var paylioErr *paylio.PaylioError

    switch {
    case errors.As(err, &authErr):
        fmt.Println("Invalid API key:", authErr.Message)
    case errors.As(err, &notFoundErr):
        fmt.Println("Not found:", notFoundErr.Message)
    case errors.As(err, &rateLimitErr):
        fmt.Println("Rate limited, try again later")
    case errors.As(err, &paylioErr):
        fmt.Printf("API error %d: %s\n", paylioErr.HTTPStatus, paylioErr.Message)
    default:
        fmt.Println("Unexpected error:", err)
    }
}

Error types

Error HTTP Status Description
AuthenticationError 401 Invalid or missing API key
InvalidRequestError 400 Bad request parameters
NotFoundError 404 Resource not found
RateLimitError 429 Rate limit exceeded
APIError 5xx Server error
APIConnectionError — Network or connection failure

All error types embed *PaylioError and work with errors.As.

Development

go test ./...
go vet ./...

License

MIT

Documentation

Overview

Package paylio provides a Go client library for the Paylio subscription API.

Index

Constants

View Source
const (
	// DefaultBaseURL is the default base URL for the Paylio API.
	DefaultBaseURL = "https://api.paylio.pro/flying/v1"

	// DefaultTimeout is the default request timeout.
	DefaultTimeout = 30 * time.Second
)
View Source
const Version = "0.1.3"

Version is the current version of the paylio-go SDK.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIConnectionError

type APIConnectionError struct{ *PaylioError }

APIConnectionError indicates a network failure or timeout.

func NewAPIConnectionError

func NewAPIConnectionError(p ErrorParams) *APIConnectionError

NewAPIConnectionError creates an APIConnectionError from the given params.

func (*APIConnectionError) Unwrap

func (e *APIConnectionError) Unwrap() error

Unwrap returns the underlying PaylioError.

type APIError

type APIError struct{ *PaylioError }

APIError indicates a server error or unexpected HTTP status.

func NewAPIError

func NewAPIError(p ErrorParams) *APIError

NewAPIError creates an APIError from the given params.

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap returns the underlying PaylioError.

type AuthenticationError

type AuthenticationError struct{ *PaylioError }

AuthenticationError indicates an invalid or missing API key (HTTP 401).

func NewAuthenticationError

func NewAuthenticationError(p ErrorParams) *AuthenticationError

NewAuthenticationError creates an AuthenticationError from the given params.

func (*AuthenticationError) Unwrap

func (e *AuthenticationError) Unwrap() error

Unwrap returns the underlying PaylioError.

type CancelOptions

type CancelOptions struct {
	CancelNow bool
}

CancelOptions configures subscription cancellation behavior.

type Client

type Client struct {
	// Subscription provides access to subscription operations.
	Subscription *SubscriptionService
	// contains filtered or unexported fields
}

Client is the entry point for the Paylio SDK.

func NewClient

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

NewClient creates a new Paylio SDK client. Returns an AuthenticationError if apiKey is empty.

func (*Client) Close

func (c *Client) Close()

Close releases resources held by the client.

type ErrorParams

type ErrorParams struct {
	Message    string
	HTTPStatus int
	HTTPBody   string
	JSONBody   map[string]any
	Headers    map[string]string
	Code       string
}

ErrorParams holds the parameters for constructing a PaylioError.

type InvalidRequestError

type InvalidRequestError struct{ *PaylioError }

InvalidRequestError indicates bad request parameters (HTTP 400).

func NewInvalidRequestError

func NewInvalidRequestError(p ErrorParams) *InvalidRequestError

NewInvalidRequestError creates an InvalidRequestError from the given params.

func (*InvalidRequestError) Unwrap

func (e *InvalidRequestError) Unwrap() error

Unwrap returns the underlying PaylioError.

type ListOptions

type ListOptions struct {
	Page     int
	PageSize int
}

ListOptions configures pagination for subscription list requests.

type NotFoundError

type NotFoundError struct{ *PaylioError }

NotFoundError indicates a resource was not found (HTTP 404).

func NewNotFoundError

func NewNotFoundError(p ErrorParams) *NotFoundError

NewNotFoundError creates a NotFoundError from the given params.

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

Unwrap returns the underlying PaylioError.

type Option

type Option func(*clientConfig)

Option configures a Client.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL sets a custom base URL for API requests.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets a custom net/http client.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets a custom request timeout.

type PaginatedList

type PaginatedList[T any] struct {
	Items      []T `json:"items"`
	Total      int `json:"total"`
	Page       int `json:"page"`
	PageSize   int `json:"page_size"`
	TotalPages int `json:"total_pages"`
}

PaginatedList is a generic paginated response container.

func (*PaginatedList[T]) HasMore

func (p *PaginatedList[T]) HasMore() bool

HasMore returns true if there are additional pages of results.

type PaylioError

type PaylioError struct {
	Message    string
	HTTPStatus int
	HTTPBody   string
	JSONBody   map[string]any
	Headers    map[string]string
	Code       string
}

PaylioError is the base error type for all Paylio SDK errors.

func (*PaylioError) Error

func (e *PaylioError) Error() string

type Period

type Period struct {
	Start string `json:"start"`
	End   string `json:"end"`
}

Period represents a time period with start and end timestamps.

type Plan

type Plan struct {
	Slug     string  `json:"slug"`
	Name     string  `json:"name"`
	Interval string  `json:"interval"`
	Amount   float64 `json:"amount"`
	Currency string  `json:"currency"`
}

Plan represents a subscription plan.

type RateLimitError

type RateLimitError struct{ *PaylioError }

RateLimitError indicates rate limit exceeded (HTTP 429).

func NewRateLimitError

func NewRateLimitError(p ErrorParams) *RateLimitError

NewRateLimitError creates a RateLimitError from the given params.

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

Unwrap returns the underlying PaylioError.

type Subscription

type Subscription struct {
	ID                 string  `json:"id"`
	Object             string  `json:"object"`
	Status             string  `json:"status"`
	UserID             string  `json:"user_id"`
	Plan               Plan    `json:"plan"`
	SubscriptionPeriod Period  `json:"subscription_period"`
	CancelAtPeriodEnd  bool    `json:"cancel_at_period_end"`
	CanceledAt         *string `json:"canceled_at"`
	Provider           string  `json:"provider"`
	CreatedAt          string  `json:"created_at"`
}

Subscription represents a user's subscription.

type SubscriptionCancel

type SubscriptionCancel struct {
	ID                string `json:"id"`
	Object            string `json:"object"`
	Success           bool   `json:"success"`
	CancelAtPeriodEnd bool   `json:"cancel_at_period_end"`
}

SubscriptionCancel represents the result of canceling a subscription.

type SubscriptionHistoryItem

type SubscriptionHistoryItem struct {
	ID                 string  `json:"id"`
	UserID             string  `json:"user_id"`
	PlanSlug           string  `json:"plan_slug"`
	PlanName           string  `json:"plan_name"`
	PlanAmount         float64 `json:"plan_amount"`
	PlanCurrency       string  `json:"plan_currency"`
	PlanInterval       string  `json:"plan_interval"`
	Status             string  `json:"status"`
	CurrentPeriodStart string  `json:"current_period_start"`
	CurrentPeriodEnd   string  `json:"current_period_end"`
	CreatedAt          string  `json:"created_at"`
}

SubscriptionHistoryItem represents a single item in subscription history.

type SubscriptionService

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

SubscriptionService provides methods for interacting with subscriptions.

func (*SubscriptionService) Cancel

func (s *SubscriptionService) Cancel(ctx context.Context, subscriptionID string, opts *CancelOptions) (*SubscriptionCancel, error)

Cancel cancels a subscription. By default cancels at end of billing period. Set CancelOptions.CancelNow to true for immediate cancellation.

func (*SubscriptionService) List

List fetches paginated subscription history for a user.

func (*SubscriptionService) Retrieve

func (s *SubscriptionService) Retrieve(ctx context.Context, userID string) (*Subscription, error)

Retrieve fetches the current subscription for a user.

Jump to

Keyboard shortcuts

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