plugipay

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 16 Imported by: 0

README

plugipay (Go)

Official Go SDK for Plugipay — HMAC-signed REST client with full resource coverage (customers, plans, checkout sessions, invoices, subscriptions, refunds, adapters, payouts, ledger, reports, templates, webhooks, account, workspaces, admin).

Mirrors the public surface of @forjio/plugipay-node and the Python plugipay package. Stdlib-only — no external deps.

Install

go get github.com/hachimi-cat/plugipay-go

Quickstart

Env vars (or pass them to NewClient):

PLUGIPAY_KEY_ID=ak_live_...
PLUGIPAY_SECRET=sk_live_...
PLUGIPAY_BASE_URL=https://plugipay.com         # optional; default
PLUGIPAY_ON_BEHALF_OF=acc_...                  # optional; platform keys only
Create a customer + checkout session
package main

import (
    "context"
    "fmt"
    "log"

    plugipay "github.com/hachimi-cat/plugipay-go"
)

func ptr[T any](v T) *T { return &v }

func main() {
    c, err := plugipay.NewClient(plugipay.ClientOptions{})
    if err != nil {
        log.Fatal(err)
    }

    ctx := context.Background()

    cust, err := c.Customers.Create(ctx, plugipay.CustomerCreateInput{
        Email: ptr("buyer@example.com"),
        Name:  ptr("Buyer Adi"),
    })
    if err != nil {
        log.Fatal(err)
    }

    sess, err := c.CheckoutSessions.Create(ctx, plugipay.CheckoutSessionCreateInput{
        Amount:     50000,
        Currency:   plugipay.CurrencyIDR,
        Methods:    []plugipay.CheckoutMethod{plugipay.CheckoutMethodQRIS, plugipay.CheckoutMethodVA},
        SuccessURL: "https://yourapp.com/done",
        CancelURL:  "https://yourapp.com/cancel",
        CustomerID: &cust.ID,
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("hosted url:", sess.HostedURL)
}
Verify webhooks

Mount your handler so you can read the raw body — if a framework parses JSON first and re-stringifies it, whitespace drift will break the signature.

http.HandleFunc("/webhooks/plugipay", func(w http.ResponseWriter, r *http.Request) {
    body, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "bad body", 400)
        return
    }
    ev, err := plugipay.VerifyWebhook(
        body,
        r.Header.Get("X-Plugipay-Signature"),
        os.Getenv("PLUGIPAY_WEBHOOK_SECRET"),
        nil,
    )
    if err != nil {
        http.Error(w, "bad signature", 400)
        return
    }
    switch ev.Type {
    case "plugipay.invoice.paid.v1":
        var inv plugipay.Invoice
        _ = json.Unmarshal(ev.Data.Object, &inv)
        // ...
    }
    w.WriteHeader(204)
})

VerifyWebhookSignature(body, header, secret, nil) returns a bool if you just want a boolean check.

Platform-admin keys across many merchants
master, _ := plugipay.NewClient(plugipay.ClientOptions{
    KeyID: "ak_platform_...", Secret: "sk_platform_...",
})

for _, accountID := range merchants {
    scoped := master.ForMerchant(accountID)
    invs, err := scoped.Invoices.List(ctx, plugipay.InvoiceListParams{})
    // ...
}

ForMerchant returns a shallow clone with X-Plugipay-On-Behalf-Of set on every request. The underlying *http.Client is shared.

What's in the box

Symbol Purpose
NewClient(ClientOptions{}) Construct a client. KeyID + Secret default from env.
c.Customers / Plans / CheckoutSessions / Invoices / Subscriptions Core commerce primitives.
c.Refunds / Payouts / Ledger / Reports Money movement + accounting.
c.Adapters / ApiKeys / WebhookEndpoints / Templates / Uploads Configuration.
c.Account / Workspaces / Onboarding / Billing / CheckoutSettings Merchant self-service.
c.AdminPortal / Admin Plugipay-internal + platform-admin.
VerifyWebhook(body, hdr, secret, opts) Verify + parse webhook payload.
VerifyWebhookSignature(...) Bool-only variant.
Sign(secret, SignInput{...}) Low-level HMAC signing helper.
*Error Single error type — branch on .Code / .Status.

Errors

Every operation returns *plugipay.Error on failure (wrapped via the standard error interface). Extract with errors.As:

var pe *plugipay.Error
if errors.As(err, &pe) {
    switch pe.Code {
    case "rate_limited":
        time.Sleep(time.Second)
        // retry
    case "timeout", "network_error":
        // transport — also retry
    case "signature_invalid", "signature_stale":
        // webhook only
    }
}

License

MIT

Documentation

Overview

Package plugipay is the official Go SDK for the Plugipay payments API. It mirrors the public surface of @forjio/plugipay-node and the Python `plugipay` package: HMAC-signed REST requests, a single resource namespace per concept (customers, plans, checkout-sessions, invoices, subscriptions, refunds, adapters, payouts, ledger, reports, webhooks, etc.), and stdlib-only deps.

Quickstart:

c, err := plugipay.NewClient(plugipay.ClientOptions{
    KeyID:  "ak_live_...",
    Secret: "sk_...",
})
if err != nil { /* missing creds */ }

cust, err := c.Customers.Create(ctx, plugipay.CustomerCreateInput{
    Email: ptr("buyer@example.com"),
})

Index

Constants

View Source
const DefaultBaseURL = "https://plugipay.com"

DefaultBaseURL is the production Plugipay endpoint. Override via ClientOptions.BaseURL or PLUGIPAY_BASE_URL.

View Source
const DefaultTimeout = 30 * time.Second

DefaultTimeout is the per-request timeout when ClientOptions.Timeout is zero.

Variables

This section is empty.

Functions

func AuthorizationHeader

func AuthorizationHeader(keyID, signature string) string

AuthorizationHeader returns the value for the Authorization header given a keyId and signature. Format is:

Plugipay-HMAC-SHA256 keyId=<id>, scope=*, signature=<hex>

func VerifyWebhookSignature

func VerifyWebhookSignature(
	rawBody []byte,
	signatureHeader string,
	secret string,
	options *VerifyWebhookOptions,
) bool

VerifyWebhookSignature returns true iff the X-Plugipay-Signature header over the given raw request body validates against the secret within the tolerance window.

Plugipay signs webhooks with HMAC-SHA256 over `${timestamp}.${rawBody}` and sends the signature as

X-Plugipay-Signature: t=<unix>,v1=<hex>

Mount your webhook handler so that you can read the raw body — if a framework parses JSON first and re-stringifies, whitespace drift will break the signature. Pass the exact bytes that arrived on the wire.

net/http example:

func plugipayWebhook(w http.ResponseWriter, r *http.Request) {
    body, err := io.ReadAll(r.Body)
    if err != nil { http.Error(w, "bad body", 400); return }
    sig := r.Header.Get("X-Plugipay-Signature")
    if !plugipay.VerifyWebhookSignature(body, sig, os.Getenv("PLUGIPAY_WEBHOOK_SECRET"), nil) {
        http.Error(w, "bad signature", 400); return
    }
    // unmarshal body into plugipay.WebhookEvent, dispatch.
}

Types

type APIEnvelope

type APIEnvelope struct {
	Data  json.RawMessage `json:"data"`
	Error *APIError       `json:"error,omitempty"`
	Meta  *EnvelopeMeta   `json:"meta,omitempty"`
}

APIEnvelope is the standard Plugipay response shape: { data, error, meta }. Generic-free for simplicity — callers usually decode `Data` into a concrete type via json.Unmarshal a second time.

type APIError

type APIError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	DocURL  string `json:"docUrl,omitempty"`
}

APIError is the error block inside an envelope.

type AccountEmailChangeInput

type AccountEmailChangeInput struct {
	NewEmail string `json:"newEmail"`
	Password string `json:"password"`
}

type AccountEmailChangeResult

type AccountEmailChangeResult struct {
	PendingVerification bool `json:"pendingVerification"`
}

type AccountPasswordChangeInput

type AccountPasswordChangeInput struct {
	CurrentPassword string `json:"currentPassword"`
	NewPassword     string `json:"newPassword"`
}

type AccountProfile

type AccountProfile struct {
	ID            string  `json:"id"`
	Email         string  `json:"email"`
	EmailVerified bool    `json:"emailVerified"`
	Name          *string `json:"name"`
	MfaEnrolled   bool    `json:"mfaEnrolled"`
	CreatedAt     string  `json:"createdAt"`
}

type AccountResource

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

AccountResource — /api/v1/account (merchant profile + sessions + linked accounts)

func (*AccountResource) ChangeEmail

func (*AccountResource) ChangePassword

func (r *AccountResource) ChangePassword(ctx context.Context, in AccountPasswordChangeInput) error

func (*AccountResource) Get

func (*AccountResource) ListLinked

func (r *AccountResource) ListLinked(ctx context.Context) ([]LinkedAccount, error)

func (*AccountResource) ListMembers

func (r *AccountResource) ListMembers(ctx context.Context) ([]WorkspaceMember, error)

func (*AccountResource) ListSessions

func (r *AccountResource) ListSessions(ctx context.Context) ([]BrowserSession, error)

func (*AccountResource) RevokeAllSessions

func (r *AccountResource) RevokeAllSessions(ctx context.Context) (*AccountRevokeAllResult, error)

func (*AccountResource) RevokeSession

func (r *AccountResource) RevokeSession(ctx context.Context, id string) error
func (r *AccountResource) Unlink(ctx context.Context, provider string) error

func (*AccountResource) Update

type AccountRevokeAllResult

type AccountRevokeAllResult struct {
	Revoked int64 `json:"revoked"`
}

type AccountUpdateInput

type AccountUpdateInput struct {
	Name *string `json:"name,omitempty"`
}

type AdapterConfig

type AdapterConfig struct {
	Kind         AdapterKind    `json:"kind"`
	Configured   bool           `json:"configured"`
	PublicConfig map[string]any `json:"publicConfig,omitempty"`
	UpdatedAt    string         `json:"updatedAt,omitempty"`
}

type AdapterKind

type AdapterKind string
const (
	AdapterKindXendit   AdapterKind = "xendit"
	AdapterKindPaypal   AdapterKind = "paypal"
	AdapterKindMidtrans AdapterKind = "midtrans"
	AdapterKindManual   AdapterKind = "manual"
)

type AdaptersResource

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

AdaptersResource — /api/v1/adapters (payment provider config)

func (*AdaptersResource) List

func (*AdaptersResource) ManagedOnboardingState

func (r *AdaptersResource) ManagedOnboardingState(ctx context.Context) (*ManagedOnboardingState, error)

func (*AdaptersResource) SimulateManagedOnboarding

func (*AdaptersResource) StartManagedOnboarding

func (*AdaptersResource) UpdateManual

func (r *AdaptersResource) UpdateManual(ctx context.Context, config map[string]any) (*AdapterConfig, error)

func (*AdaptersResource) UpdateMidtrans

func (r *AdaptersResource) UpdateMidtrans(ctx context.Context, config map[string]any) (*AdapterConfig, error)

func (*AdaptersResource) UpdatePaypal

func (r *AdaptersResource) UpdatePaypal(ctx context.Context, config map[string]any) (*AdapterConfig, error)

func (*AdaptersResource) UpdateXendit

func (r *AdaptersResource) UpdateXendit(ctx context.Context, config map[string]any) (*AdapterConfig, error)

type AdminPartnerUsageParams

type AdminPartnerUsageParams struct {
	Partner string // storlaunch | fulkruma | ripllo
	From    string
	To      string
}

type AdminPortalIdentity

type AdminPortalIdentity struct {
	IdentityID string `json:"identityId"`
	Email      string `json:"email"`
	Role       string `json:"role"`
}

type AdminPortalResource

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

AdminPortalResource — /api/v1/admin-portal (Plugipay internal operators)

func (*AdminPortalResource) CreatePartner

func (r *AdminPortalResource) CreatePartner(ctx context.Context, in map[string]any) (json.RawMessage, error)

func (*AdminPortalResource) DeletePartner

func (r *AdminPortalResource) DeletePartner(ctx context.Context, id string) error

func (*AdminPortalResource) ListBillingAccounts

func (r *AdminPortalResource) ListBillingAccounts(ctx context.Context) ([]json.RawMessage, error)

func (*AdminPortalResource) ListPartners

func (r *AdminPortalResource) ListPartners(ctx context.Context) ([]json.RawMessage, error)

func (*AdminPortalResource) Me

func (*AdminPortalResource) UpdateBillingAccount

func (r *AdminPortalResource) UpdateBillingAccount(ctx context.Context, accountID string, patch map[string]any) (json.RawMessage, error)

func (*AdminPortalResource) UpdatePartner

func (r *AdminPortalResource) UpdatePartner(ctx context.Context, id string, patch map[string]any) (json.RawMessage, error)

type AdminProvisionWorkspaceInput

type AdminProvisionWorkspaceInput struct {
	AccountID     string  `json:"accountId"`
	Partner       string  `json:"partner"` // storlaunch | fulkruma | ripllo
	DiscountRate  float64 `json:"discountRate"`
	BrandName     *string `json:"brandName,omitempty"`
	BusinessEmail *string `json:"businessEmail,omitempty"`
}

type AdminResource

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

AdminResource — /api/v1/admin (requires plugipay:platform:admin scope)

func (*AdminResource) GetWorkspace

func (r *AdminResource) GetWorkspace(ctx context.Context, accountID string) (*PartnerWorkspace, error)

func (*AdminResource) PartnerUsage

func (*AdminResource) ProvisionWorkspace

type ApiKey

type ApiKey struct {
	ID          string  `json:"id"`
	AccountID   string  `json:"accountId"`
	KeyID       string  `json:"keyId"`
	Description *string `json:"description"`
	Scope       string  `json:"scope"`
	Secret      string  `json:"secret,omitempty"` // only on create
	CreatedAt   string  `json:"createdAt"`
	RevokedAt   *string `json:"revokedAt"`
}

type ApiKeyCreateInput

type ApiKeyCreateInput struct {
	Description *string `json:"description,omitempty"`
	Scope       *string `json:"scope,omitempty"`
}

type ApiKeysResource

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

ApiKeysResource — /api/v1/api-keys

func (*ApiKeysResource) Create

func (*ApiKeysResource) List

func (r *ApiKeysResource) List(ctx context.Context) ([]ApiKey, error)

func (*ApiKeysResource) Revoke

func (r *ApiKeysResource) Revoke(ctx context.Context, id string) error

type AvailableBalance

type AvailableBalance struct {
	LedgerBalance int64   `json:"ledgerBalance"`
	Locked        int64   `json:"locked"`
	Available     int64   `json:"available"`
	Currency      *string `json:"currency"`
}

type BankAccount

type BankAccount struct {
	BankCode          *string `json:"bankCode"`
	BankName          *string `json:"bankName"`
	BankAccountNumber *string `json:"bankAccountNumber"`
	BankAccountHolder *string `json:"bankAccountHolder"`
	Configured        bool    `json:"configured"`
}

type BankAccountInput

type BankAccountInput struct {
	BankCode          *string `json:"bankCode,omitempty"`
	BankName          string  `json:"bankName"`
	BankAccountNumber string  `json:"bankAccountNumber"`
	BankAccountHolder string  `json:"bankAccountHolder"`
}

type BillingRefreshResult

type BillingRefreshResult struct {
	Refreshed bool `json:"refreshed"`
}

type BillingResource

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

BillingResource — /api/v1/billing (merchant subscription to Plugipay itself)

func (*BillingResource) ListPlans

func (r *BillingResource) ListPlans(ctx context.Context) ([]Plan, error)

func (*BillingResource) ListTiers

func (r *BillingResource) ListTiers(ctx context.Context) ([]BillingTier, error)

func (*BillingResource) RefreshTiers

func (r *BillingResource) RefreshTiers(ctx context.Context) (*BillingRefreshResult, error)

type BillingTier

type BillingTier struct {
	ID       string   `json:"id"`
	Name     string   `json:"name"`
	Monthly  int64    `json:"monthly"`
	Features []string `json:"features"`
}

type BrowserSession

type BrowserSession struct {
	ID         string  `json:"id"`
	UserAgent  *string `json:"userAgent"`
	IPAddress  *string `json:"ipAddress"`
	Current    bool    `json:"current"`
	CreatedAt  string  `json:"createdAt"`
	LastSeenAt string  `json:"lastSeenAt"`
}

type CashFlowBucket

type CashFlowBucket struct {
	Day     string `json:"day"`
	Inflow  int64  `json:"inflow"`
	Outflow int64  `json:"outflow"`
	Net     int64  `json:"net"`
}

type CashFlowReport

type CashFlowReport struct {
	From         string           `json:"from"`
	To           string           `json:"to"`
	Currency     string           `json:"currency"`
	TotalInflow  int64            `json:"totalInflow"`
	TotalOutflow int64            `json:"totalOutflow"`
	Net          int64            `json:"net"`
	Buckets      []CashFlowBucket `json:"buckets"`
}

type CheckoutMethod

type CheckoutMethod string
const (
	CheckoutMethodQRIS    CheckoutMethod = "qris"
	CheckoutMethodVA      CheckoutMethod = "va"
	CheckoutMethodEwallet CheckoutMethod = "ewallet"
	CheckoutMethodCard    CheckoutMethod = "card"
	CheckoutMethodRetail  CheckoutMethod = "retail"
	CheckoutMethodPaypal  CheckoutMethod = "paypal"
)

type CheckoutSession

type CheckoutSession struct {
	ID          string            `json:"id"`
	AccountID   string            `json:"accountId"`
	CustomerID  *string           `json:"customerId"`
	Amount      int64             `json:"amount"`
	Currency    CurrencyCode      `json:"currency"`
	Status      string            `json:"status"`
	Methods     []CheckoutMethod  `json:"methods"`
	Adapter     *string           `json:"adapter"`
	LineItems   json.RawMessage   `json:"lineItems"`
	SuccessURL  string            `json:"successUrl"`
	CancelURL   string            `json:"cancelUrl"`
	HostedURL   string            `json:"hostedUrl"`
	ExpiresAt   string            `json:"expiresAt"`
	CompletedAt *string           `json:"completedAt"`
	Metadata    map[string]string `json:"metadata"`
	CreatedAt   string            `json:"createdAt"`
	UpdatedAt   string            `json:"updatedAt"`
}

type CheckoutSessionCreateInput

type CheckoutSessionCreateInput struct {
	Amount       int64                     `json:"amount"`
	Currency     CurrencyCode              `json:"currency"`
	Methods      []CheckoutMethod          `json:"methods"`
	SuccessURL   string                    `json:"successUrl"`
	CancelURL    string                    `json:"cancelUrl"`
	CustomerID   *string                   `json:"customerId,omitempty"`
	LineItems    []CheckoutSessionLineItem `json:"lineItems"`
	ExpiresInSec *int                      `json:"expiresInSec,omitempty"`
	Metadata     map[string]string         `json:"metadata,omitempty"`
	TemplateID   *string                   `json:"templateId,omitempty"`
}

type CheckoutSessionLineItem

type CheckoutSessionLineItem struct {
	Name       string `json:"name"`
	Quantity   int64  `json:"quantity"`
	UnitAmount int64  `json:"unitAmount"`
}

type CheckoutSessionListParams

type CheckoutSessionListParams struct {
	Limit      *int    `json:"limit,omitempty"`
	Status     *string `json:"status,omitempty"`
	CustomerID *string `json:"customerId,omitempty"`
}

type CheckoutSessionsResource

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

CheckoutSessionsResource — /api/v1/checkout-sessions

func (*CheckoutSessionsResource) Cancel

func (*CheckoutSessionsResource) Confirm

func (*CheckoutSessionsResource) Create

func (*CheckoutSessionsResource) Get

func (*CheckoutSessionsResource) List

type CheckoutSettings

type CheckoutSettings struct {
	AccountID         string  `json:"accountId"`
	BrandLogoURL      *string `json:"brandLogoUrl"`
	BrandColor        *string `json:"brandColor"`
	DefaultTemplateID *string `json:"defaultTemplateId"`
	TermsURL          *string `json:"termsUrl"`
	PrivacyURL        *string `json:"privacyUrl"`
	UpdatedAt         string  `json:"updatedAt"`
}

type CheckoutSettingsResource

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

CheckoutSettingsResource — /api/v1/checkout/settings

func (*CheckoutSettingsResource) Get

func (*CheckoutSettingsResource) Update

type CheckoutSettingsUpdateInput

type CheckoutSettingsUpdateInput struct {
	BrandLogoURL      *string `json:"brandLogoUrl,omitempty"`
	BrandColor        *string `json:"brandColor,omitempty"`
	DefaultTemplateID *string `json:"defaultTemplateId,omitempty"`
	TermsURL          *string `json:"termsUrl,omitempty"`
	PrivacyURL        *string `json:"privacyUrl,omitempty"`
}

type Client

type Client struct {

	// Resource groups — exposed as fields so callers do
	// c.Customers.Get(...) just like the Node SDK does c.customers.get(...).
	Customers        *CustomersResource
	Plans            *PlansResource
	CheckoutSessions *CheckoutSessionsResource
	Invoices         *InvoicesResource
	Subscriptions    *SubscriptionsResource
	PortalSessions   *PortalSessionsResource
	Receipts         *ReceiptsResource
	Payouts          *PayoutsResource
	Ledger           *LedgerResource
	Reports          *ReportsResource
	WebhookEndpoints *WebhookEndpointsResource
	Events           *EventsResource
	Refunds          *RefundsResource
	Adapters         *AdaptersResource
	ApiKeys          *ApiKeysResource
	Billing          *BillingResource
	Onboarding       *OnboardingResource
	CheckoutSettings *CheckoutSettingsResource
	Templates        *TemplatesResource
	Uploads          *UploadsResource
	Workspaces       *WorkspacesResource
	Account          *AccountResource
	AdminPortal      *AdminPortalResource
	Admin            *AdminResource
	// contains filtered or unexported fields
}

Client is the main SDK entry point. Construct with NewClient. Safe for concurrent use by multiple goroutines.

func NewClient

func NewClient(opts ClientOptions) (*Client, error)

NewClient builds a configured client. Returns an error if KeyID or Secret cannot be resolved from options or env.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the resolved base URL (no trailing slash).

func (*Client) Do

func (c *Client) Do(ctx context.Context, opts RequestOptions, out any) error

Do executes a signed request and unmarshals the envelope's `data` into out. Returns *Error on any failure. If out is nil, the response body is decoded but discarded — useful for endpoints that return void/empty payloads (DELETE, revoke, etc).

func (*Client) ForMerchant

func (c *Client) ForMerchant(accountID string) *Client

ForMerchant returns a shallow clone scoped to a different on-behalf-of account id — useful when a platform-admin key is reused across many merchant accounts. The clone shares the underlying *http.Client.

func (*Client) KeyID

func (c *Client) KeyID() string

KeyID returns the access key id used by this client.

func (*Client) OnBehalfOf

func (c *Client) OnBehalfOf() string

OnBehalfOf returns the default on-behalf-of merchant id, if any.

type ClientOptions

type ClientOptions struct {
	// HMAC access key id (e.g. "ak_live_..."). Defaults to PLUGIPAY_KEY_ID.
	KeyID string
	// HMAC secret. Defaults to PLUGIPAY_SECRET.
	Secret string
	// Base URL. Defaults to PLUGIPAY_BASE_URL or DefaultBaseURL.
	BaseURL string
	// Optional merchant accountId to scope calls against. Forwarded as
	// X-Plugipay-On-Behalf-Of. Only allowed for platform-admin keys.
	// Defaults to PLUGIPAY_ON_BEHALF_OF.
	OnBehalfOf string
	// Per-request timeout. Zero falls back to DefaultTimeout.
	Timeout time.Duration
	// HTTP client. Nil falls back to a fresh http.Client (does NOT use
	// http.DefaultClient — we want our own Timeout default).
	HTTP *http.Client
}

ClientOptions configures a Client. KeyID + Secret are required; the rest default from env vars (PLUGIPAY_KEY_ID, PLUGIPAY_SECRET, PLUGIPAY_BASE_URL, PLUGIPAY_ON_BEHALF_OF) so a zero-value ClientOptions{} works in production environments where the standard env vars are set.

type CurrencyCode

type CurrencyCode string
const (
	CurrencyIDR CurrencyCode = "IDR"
	CurrencyUSD CurrencyCode = "USD"
)

type Customer

type Customer struct {
	ID         string  `json:"id"`
	AccountID  string  `json:"accountId"`
	Email      *string `json:"email"`
	Name       *string `json:"name"`
	Phone      *string `json:"phone"`
	ExternalID *string `json:"externalId"`
	CreatedAt  string  `json:"createdAt"`
	UpdatedAt  string  `json:"updatedAt"`
}

type CustomerCreateInput

type CustomerCreateInput struct {
	Email      *string           `json:"email,omitempty"`
	Name       *string           `json:"name,omitempty"`
	Phone      *string           `json:"phone,omitempty"`
	ExternalID *string           `json:"externalId,omitempty"`
	Metadata   map[string]string `json:"metadata,omitempty"`
}

type CustomerListParams

type CustomerListParams struct {
	Limit  *int    `json:"limit,omitempty"`
	Cursor *string `json:"cursor,omitempty"`
	Email  *string `json:"email,omitempty"`
}

type CustomerUpdateInput

type CustomerUpdateInput struct {
	Email *string `json:"email,omitempty"`
	Name  *string `json:"name,omitempty"`
	Phone *string `json:"phone,omitempty"`
}

type CustomersResource

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

CustomersResource — /api/v1/customers

func (*CustomersResource) Create

func (*CustomersResource) Get

func (r *CustomersResource) Get(ctx context.Context, id string) (*Customer, error)

func (*CustomersResource) List

func (*CustomersResource) Update

type EnvelopeMeta

type EnvelopeMeta struct {
	RequestID string  `json:"requestId,omitempty"`
	Timestamp string  `json:"timestamp,omitempty"`
	Cursor    *string `json:"cursor,omitempty"`
	HasMore   bool    `json:"hasMore,omitempty"`
}

EnvelopeMeta covers all known meta fields. Cursor + HasMore appear on list endpoints; RequestID + Timestamp appear on every response.

type Error

type Error struct {
	// HTTP status code. 0 for transport-layer failures (timeout, DNS, etc).
	Status int
	// Stable error code (e.g. "rate_limited", "signature_invalid",
	// "network_error", "timeout", "invalid_response").
	Code string
	// Human-readable message. Safe to surface to operators; not safe to
	// surface to end users without context.
	Message string
	// RequestID from the API envelope's meta block, when present.
	RequestID string
}

Error is the single error type returned by every SDK operation. Wraps an HTTP status code, an opaque error code from the backend, a message, and an optional request id so callers can branch on well-defined reasons without matching strings.

Use errors.As to extract:

var pe *plugipay.Error
if errors.As(err, &pe) && pe.Code == "rate_limited" { ... }

func (*Error) Error

func (e *Error) Error() string

type EventListParams

type EventListParams struct {
	Limit          *int    `json:"limit,omitempty"`
	Cursor         *string `json:"cursor,omitempty"`
	Order          *string `json:"order,omitempty"`
	Type           *string `json:"type,omitempty"`
	OccurredAfter  *string `json:"occurredAfter,omitempty"`
	OccurredBefore *string `json:"occurredBefore,omitempty"`
}

type EventRecord

type EventRecord struct {
	ID         string          `json:"id"`
	Type       string          `json:"type"`
	AccountID  string          `json:"accountId"`
	OccurredAt string          `json:"occurredAt"`
	Data       json.RawMessage `json:"data"`
}

type EventsResource

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

EventsResource — /api/v1/events

func (*EventsResource) Get

func (r *EventsResource) Get(ctx context.Context, id string) (*EventRecord, error)

func (*EventsResource) List

type Invoice

type Invoice struct {
	ID               string        `json:"id"`
	AccountID        string        `json:"accountId"`
	CustomerID       string        `json:"customerId"`
	Status           string        `json:"status"`
	Number           string        `json:"number"`
	Currency         CurrencyCode  `json:"currency"`
	Subtotal         int64         `json:"subtotal"`
	Discount         int64         `json:"discount"`
	Tax              int64         `json:"tax"`
	Total            int64         `json:"total"`
	AmountPaid       int64         `json:"amountPaid"`
	AmountDue        int64         `json:"amountDue"`
	DueAt            *string       `json:"dueAt"`
	IssuedAt         *string       `json:"issuedAt"`
	PaidAt           *string       `json:"paidAt"`
	HostedInvoiceURL *string       `json:"hostedInvoiceUrl"`
	Lines            []InvoiceLine `json:"lines"`
	CreatedAt        string        `json:"createdAt"`
	UpdatedAt        string        `json:"updatedAt"`
}

type InvoiceCreateInput

type InvoiceCreateInput struct {
	CustomerID string              `json:"customerId"`
	Currency   CurrencyCode        `json:"currency"`
	Lines      []InvoiceCreateLine `json:"lines"`
	Discount   *int64              `json:"discount,omitempty"`
	Tax        *int64              `json:"tax,omitempty"`
	DueAt      *string             `json:"dueAt,omitempty"`
	Status     *string             `json:"status,omitempty"` // draft | open
	Memo       *string             `json:"memo,omitempty"`
}

type InvoiceCreateLine

type InvoiceCreateLine struct {
	Description string `json:"description"`
	Quantity    int64  `json:"quantity"`
	UnitAmount  int64  `json:"unitAmount"`
}

type InvoiceLine

type InvoiceLine struct {
	ID          string `json:"id"`
	Description string `json:"description"`
	Quantity    int64  `json:"quantity"`
	UnitAmount  int64  `json:"unitAmount"`
	Amount      int64  `json:"amount"`
}

type InvoiceListParams

type InvoiceListParams struct {
	Limit      *int    `json:"limit,omitempty"`
	Cursor     *string `json:"cursor,omitempty"`
	Status     *string `json:"status,omitempty"`
	CustomerID *string `json:"customerId,omitempty"`
}

type InvoiceSendEmailResult

type InvoiceSendEmailResult struct {
	Sent bool   `json:"sent"`
	To   string `json:"to"`
}

InvoiceSendEmailResult — what /send-email returns.

type InvoicesResource

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

InvoicesResource — /api/v1/invoices

func (*InvoicesResource) Create

func (*InvoicesResource) Finalize

func (r *InvoicesResource) Finalize(ctx context.Context, id string) (*Invoice, error)

func (*InvoicesResource) Get

func (r *InvoicesResource) Get(ctx context.Context, id string) (*Invoice, error)

func (*InvoicesResource) List

func (*InvoicesResource) Pay

func (r *InvoicesResource) Pay(ctx context.Context, id string) (*Invoice, error)

func (*InvoicesResource) SendEmail

func (r *InvoicesResource) SendEmail(ctx context.Context, id string, to *string) (*InvoiceSendEmailResult, error)

func (*InvoicesResource) Void

func (r *InvoicesResource) Void(ctx context.Context, id string) (*Invoice, error)

type LedgerBalance

type LedgerBalance struct {
	Code    string `json:"code"`
	Debits  int64  `json:"debits"`
	Credits int64  `json:"credits"`
	Balance int64  `json:"balance"`
}

type LedgerEntry

type LedgerEntry struct {
	ID         string  `json:"id"`
	AccountID  string  `json:"accountId"`
	TxID       string  `json:"txId"`
	Code       string  `json:"code"`
	Direction  string  `json:"direction"`
	Amount     int64   `json:"amount"`
	Currency   string  `json:"currency"`
	SourceType string  `json:"sourceType"`
	SourceID   string  `json:"sourceId"`
	Memo       *string `json:"memo"`
	PostedAt   string  `json:"postedAt"`
}

type LedgerListParams

type LedgerListParams struct {
	Limit      *int    `json:"limit,omitempty"`
	Cursor     *string `json:"cursor,omitempty"`
	Order      *string `json:"order,omitempty"`
	TxID       *string `json:"txId,omitempty"`
	Code       *string `json:"code,omitempty"`
	SourceType *string `json:"sourceType,omitempty"`
	SourceID   *string `json:"sourceId,omitempty"`
}

type LedgerResource

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

LedgerResource — /api/v1/ledger

func (*LedgerResource) Balances

func (r *LedgerResource) Balances(ctx context.Context) ([]LedgerBalance, error)

func (*LedgerResource) List

type LinkedAccount

type LinkedAccount struct {
	Provider string  `json:"provider"`
	Subject  string  `json:"subject"`
	Email    *string `json:"email"`
	LinkedAt string  `json:"linkedAt"`
}

type ManagedOnboardingSimulateInput

type ManagedOnboardingSimulateInput struct {
	Result string `json:"result"` // verified | failed
}

type ManagedOnboardingStartInput

type ManagedOnboardingStartInput struct {
	Kind    AdapterKind    `json:"kind"`
	Details map[string]any `json:"details,omitempty"`
}

type ManagedOnboardingState

type ManagedOnboardingState struct {
	State    string         `json:"state"`
	Provider string         `json:"provider"`
	Details  map[string]any `json:"details,omitempty"`
}

type OnboardingProvisionManagedInput

type OnboardingProvisionManagedInput struct {
	BusinessEmail string  `json:"businessEmail"`
	BrandName     *string `json:"brandName,omitempty"`
}

type OnboardingResource

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

OnboardingResource — /api/v1/onboarding

func (*OnboardingResource) ProvisionManaged

type Page

type Page[T any] struct {
	Data    []T     `json:"data"`
	Cursor  *string `json:"cursor"`
	HasMore bool    `json:"hasMore"`
}

Page wraps a list-endpoint result. Mirrors the Node SDK's requestList return shape: { data, cursor, hasMore }.

func DoList

func DoList[T any](ctx context.Context, c *Client, opts RequestOptions) (Page[T], error)

DoList executes a signed request that returns a list envelope and re-shapes it into a Page[T]. Mirrors PlugipayClient#requestList in the Node SDK.

type PartnerUsageLine

type PartnerUsageLine struct {
	AccountID        string  `json:"accountId"`
	BrandName        *string `json:"brandName"`
	TransactionCount int64   `json:"transactionCount"`
	GrossVolume      int64   `json:"grossVolume"`
	DiscountRate     float64 `json:"discountRate"`
	Fee              int64   `json:"fee"`
}

type PartnerUsageSummary

type PartnerUsageSummary struct {
	Partner  string             `json:"partner"`
	From     string             `json:"from"`
	To       string             `json:"to"`
	Currency string             `json:"currency"`
	Lines    []PartnerUsageLine `json:"lines"`
	Total    int64              `json:"total"`
}

type PartnerWorkspace

type PartnerWorkspace struct {
	AccountID     string  `json:"accountId"`
	Partner       string  `json:"partner"`
	DiscountRate  float64 `json:"discountRate"`
	BrandName     *string `json:"brandName"`
	BusinessEmail *string `json:"businessEmail"`
	CreatedAt     string  `json:"createdAt"`
}

type Payout

type Payout struct {
	ID                  string       `json:"id"`
	AccountID           string       `json:"accountId"`
	Amount              int64        `json:"amount"`
	Currency            string       `json:"currency"`
	Status              PayoutStatus `json:"status"`
	Method              PayoutMethod `json:"method"`
	BankCode            *string      `json:"bankCode"`
	BankName            string       `json:"bankName"`
	BankAccountNumber   string       `json:"bankAccountNumber"`
	BankAccountHolder   string       `json:"bankAccountHolder"`
	Note                *string      `json:"note"`
	Reference           *string      `json:"reference"`
	FailureReason       *string      `json:"failureReason"`
	LedgerTransactionID *string      `json:"ledgerTransactionId"`
	ProcessedAt         *string      `json:"processedAt"`
	CompletedAt         *string      `json:"completedAt"`
	CreatedAt           string       `json:"createdAt"`
	UpdatedAt           string       `json:"updatedAt"`
}

type PayoutCreateInput

type PayoutCreateInput struct {
	Amount            int64        `json:"amount"`
	Currency          CurrencyCode `json:"currency"`
	BankCode          *string      `json:"bankCode,omitempty"`
	BankName          *string      `json:"bankName,omitempty"`
	BankAccountNumber *string      `json:"bankAccountNumber,omitempty"`
	BankAccountHolder *string      `json:"bankAccountHolder,omitempty"`
	Note              *string      `json:"note,omitempty"`
}

type PayoutListParams

type PayoutListParams struct {
	Limit  *int          `json:"limit,omitempty"`
	Cursor *string       `json:"cursor,omitempty"`
	Status *PayoutStatus `json:"status,omitempty"`
}

type PayoutMethod

type PayoutMethod string
const (
	PayoutMethodManual             PayoutMethod = "manual"
	PayoutMethodXenditDisbursement PayoutMethod = "xendit_disbursement"
)

type PayoutStatus

type PayoutStatus string
const (
	PayoutStatusPending   PayoutStatus = "pending"
	PayoutStatusInTransit PayoutStatus = "in_transit"
	PayoutStatusPaid      PayoutStatus = "paid"
	PayoutStatusFailed    PayoutStatus = "failed"
	PayoutStatusCancelled PayoutStatus = "cancelled"
)

type PayoutsResource

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

PayoutsResource — /api/v1/payouts

func (*PayoutsResource) Balance

func (*PayoutsResource) Cancel

func (r *PayoutsResource) Cancel(ctx context.Context, id string) (*Payout, error)

func (*PayoutsResource) Create

func (*PayoutsResource) Get

func (r *PayoutsResource) Get(ctx context.Context, id string) (*Payout, error)

func (*PayoutsResource) GetBankAccount

func (r *PayoutsResource) GetBankAccount(ctx context.Context) (*BankAccount, error)

func (*PayoutsResource) List

func (r *PayoutsResource) List(ctx context.Context, params PayoutListParams) (Page[Payout], error)

func (*PayoutsResource) MarkFailed

func (r *PayoutsResource) MarkFailed(ctx context.Context, id string, failureReason string) (*Payout, error)

func (*PayoutsResource) MarkInTransit

func (r *PayoutsResource) MarkInTransit(ctx context.Context, id string, reference *string) (*Payout, error)

func (*PayoutsResource) MarkPaid

func (r *PayoutsResource) MarkPaid(ctx context.Context, id string, reference *string) (*Payout, error)

func (*PayoutsResource) UpdateBankAccount

func (r *PayoutsResource) UpdateBankAccount(ctx context.Context, in BankAccountInput) (*BankAccount, error)

type Plan

type Plan struct {
	ID        string       `json:"id"`
	AccountID string       `json:"accountId"`
	Name      string       `json:"name"`
	Currency  CurrencyCode `json:"currency"`
	Interval  string       `json:"interval"`
	Amount    int64        `json:"amount"`
	Active    bool         `json:"active"`
	CreatedAt string       `json:"createdAt"`
	UpdatedAt string       `json:"updatedAt"`
}

type PlanCreateInput

type PlanCreateInput struct {
	Name     string       `json:"name"`
	Currency CurrencyCode `json:"currency"`
	Amount   int64        `json:"amount"`
	Interval string       `json:"interval"` // day | week | month | year
}

type PlanListParams

type PlanListParams struct {
	Limit  *int    `json:"limit,omitempty"`
	Active *bool   `json:"active,omitempty"`
	Cursor *string `json:"cursor,omitempty"`
	Order  *string `json:"order,omitempty"` // asc | desc
}

type PlanUpdateInput

type PlanUpdateInput struct {
	Name        *string        `json:"name,omitempty"`
	Description *string        `json:"description,omitempty"`
	Active      *bool          `json:"active,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
}

type PlansResource

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

PlansResource — /api/v1/plans

func (*PlansResource) Archive

func (r *PlansResource) Archive(ctx context.Context, id string) (*Plan, error)

func (*PlansResource) Create

func (r *PlansResource) Create(ctx context.Context, in PlanCreateInput) (*Plan, error)

func (*PlansResource) Get

func (r *PlansResource) Get(ctx context.Context, id string) (*Plan, error)

func (*PlansResource) List

func (r *PlansResource) List(ctx context.Context, params PlanListParams) (Page[Plan], error)

func (*PlansResource) Update

func (r *PlansResource) Update(ctx context.Context, id string, patch PlanUpdateInput) (*Plan, error)

type PnLReport

type PnLReport struct {
	From         string          `json:"from"`
	To           string          `json:"to"`
	Currency     string          `json:"currency"`
	Revenue      int64           `json:"revenue"`
	Refunds      int64           `json:"refunds"`
	PlatformFees int64           `json:"platformFees"`
	Tax          int64           `json:"tax"`
	Net          int64           `json:"net"`
	Lines        []PnLReportLine `json:"lines"`
}

type PnLReportLine

type PnLReportLine struct {
	Code   string `json:"code"`
	Amount int64  `json:"amount"`
}

type PortalSession

type PortalSession struct {
	ID         string `json:"id"`
	CustomerID string `json:"customerId"`
	URL        string `json:"url"`
	ReturnURL  string `json:"returnUrl"`
	ExpiresAt  string `json:"expiresAt"`
}

type PortalSessionCreateInput

type PortalSessionCreateInput struct {
	CustomerID string `json:"customerId"`
	ReturnURL  string `json:"returnUrl"`
}

type PortalSessionsResource

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

PortalSessionsResource — /api/v1/portal-sessions

func (*PortalSessionsResource) Create

type ReceiptListParams

type ReceiptListParams struct {
	Limit        *int    `json:"limit,omitempty"`
	Cursor       *string `json:"cursor,omitempty"`
	SourceType   *string `json:"sourceType,omitempty"` // checkout_session | invoice
	CustomerID   *string `json:"customerId,omitempty"`
	IssuedAfter  *string `json:"issuedAfter,omitempty"`
	IssuedBefore *string `json:"issuedBefore,omitempty"`
}

type ReceiptSummary

type ReceiptSummary struct {
	ID         string  `json:"id"`
	Number     string  `json:"number"`
	SourceType string  `json:"sourceType"`
	SourceID   string  `json:"sourceId"`
	CustomerID *string `json:"customerId"`
	Amount     int64   `json:"amount"`
	Currency   string  `json:"currency"`
	Method     *string `json:"method"`
	Adapter    *string `json:"adapter"`
	IssuedAt   string  `json:"issuedAt"`
	EmailedAt  *string `json:"emailedAt"`
	EmailedTo  *string `json:"emailedTo"`
}

type ReceiptsResource

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

ReceiptsResource — /api/v1/receipts

func (*ReceiptsResource) Get

Get returns the raw receipt payload — the backend shape here is richer than ReceiptSummary and intentionally opaque to the SDK.

func (*ReceiptsResource) List

type Refund

type Refund struct {
	ID            string       `json:"id"`
	AccountID     string       `json:"accountId"`
	Amount        int64        `json:"amount"`
	Currency      CurrencyCode `json:"currency"`
	Status        RefundStatus `json:"status"`
	Reason        *string      `json:"reason"`
	SourceType    SourceType   `json:"sourceType"`
	SourceID      string       `json:"sourceId"`
	FailureReason *string      `json:"failureReason"`
	CreatedAt     string       `json:"createdAt"`
	UpdatedAt     string       `json:"updatedAt"`
}

type RefundCreateInput

type RefundCreateInput struct {
	SourceType SourceType `json:"sourceType"` // checkout_session | invoice
	SourceID   string     `json:"sourceId"`
	Amount     *int64     `json:"amount,omitempty"`
	Reason     *string    `json:"reason,omitempty"`
}

type RefundListParams

type RefundListParams struct {
	Limit    *int          `json:"limit,omitempty"`
	Cursor   *string       `json:"cursor,omitempty"`
	Status   *RefundStatus `json:"status,omitempty"`
	SourceID *string       `json:"sourceId,omitempty"`
}

type RefundStatus

type RefundStatus string
const (
	RefundStatusPending   RefundStatus = "pending"
	RefundStatusSucceeded RefundStatus = "succeeded"
	RefundStatusFailed    RefundStatus = "failed"
	RefundStatusCanceled  RefundStatus = "canceled"
)

type RefundsResource

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

RefundsResource — /api/v1/refunds

func (*RefundsResource) Create

func (*RefundsResource) Get

func (r *RefundsResource) Get(ctx context.Context, id string) (*Refund, error)

func (*RefundsResource) List

func (r *RefundsResource) List(ctx context.Context, params RefundListParams) (Page[Refund], error)

type ReportRangeParams

type ReportRangeParams struct {
	From     string  // ISO date
	To       string  // ISO date
	Currency *string // optional
}

type ReportsResource

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

ReportsResource — /api/v1/reports

func (*ReportsResource) CashFlow

func (*ReportsResource) PnL

type RequestOptions

type RequestOptions struct {
	Method         string // GET, POST, PATCH, PUT, DELETE
	Path           string // e.g. "/api/v1/customers"
	Body           any    // serialized via json.Marshal; nil → no body
	IdempotencyKey string
	OnBehalfOf     string // overrides the client default
}

RequestOptions tunes a single call. Body, IdempotencyKey, OnBehalfOf are all optional. Query is appended as a URL querystring (sorted-key order is not guaranteed; signatures cover the path-as-sent).

type SignInput

type SignInput struct {
	Method         string
	Path           string
	Body           string
	IdempotencyKey string
	Timestamp      int64 // unix seconds. If 0, time.Now().Unix() is used.
}

SignInput captures the bytes that go into a Plugipay HMAC signature. The string-to-sign is:

METHOD\nPATH\nTIMESTAMP\nHEX(SHA256(BODY))[\nIDEMPOTENCY_KEY]

where BODY is the raw request body as serialized over the wire (the empty string if no body), and IDEMPOTENCY_KEY is appended only when non-empty. This must match sdk/node/src/client.ts#sign and sdk/python/plugipay/_client.py#_sign byte-for-byte — drift will break every authenticated request.

type SignResult

type SignResult struct {
	Signature string
	Timestamp string
}

SignResult is the output of Sign — signature plus the timestamp that went into it (callers need both to set the request headers).

func Sign

func Sign(secret string, in SignInput) SignResult

Sign computes the HMAC-SHA256 signature for a Plugipay API request. Exposed so callers building lower-level integrations (proxies, per-merchant fan-out, custom retry loops) can re-derive the exact signature without going through Client.

type SourceType

type SourceType string
const (
	SourceTypeCheckoutSession SourceType = "checkout_session"
	SourceTypeInvoice         SourceType = "invoice"
)

type Subscription

type Subscription struct {
	ID                 string  `json:"id"`
	AccountID          string  `json:"accountId"`
	CustomerID         string  `json:"customerId"`
	PlanID             string  `json:"planId"`
	Status             string  `json:"status"`
	CurrentPeriodStart string  `json:"currentPeriodStart"`
	CurrentPeriodEnd   string  `json:"currentPeriodEnd"`
	CancelAtPeriodEnd  bool    `json:"cancelAtPeriodEnd"`
	TrialEndsAt        *string `json:"trialEndsAt"`
	CreatedAt          string  `json:"createdAt"`
	UpdatedAt          string  `json:"updatedAt"`
}

type SubscriptionCreateInput

type SubscriptionCreateInput struct {
	CustomerID       string            `json:"customerId"`
	PlanID           string            `json:"planId"`
	PriceID          string            `json:"priceId"`
	TrialDays        *int              `json:"trialDays,omitempty"`
	PaymentTokenID   *string           `json:"paymentTokenId,omitempty"`
	CollectionMethod *string           `json:"collectionMethod,omitempty"` // charge_automatically | send_invoice
	Metadata         map[string]string `json:"metadata,omitempty"`
	InitialDiscount  *int64            `json:"initialDiscount,omitempty"`
}

type SubscriptionListParams

type SubscriptionListParams struct {
	Limit      *int    `json:"limit,omitempty"`
	Status     *string `json:"status,omitempty"`
	CustomerID *string `json:"customerId,omitempty"`
	PlanID     *string `json:"planId,omitempty"`
}

type SubscriptionsResource

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

SubscriptionsResource — /api/v1/subscriptions

func (*SubscriptionsResource) Cancel

Cancel — pass "now" or "period_end" (default).

func (*SubscriptionsResource) Create

func (*SubscriptionsResource) Get

func (*SubscriptionsResource) List

func (*SubscriptionsResource) Pause

func (r *SubscriptionsResource) Pause(ctx context.Context, id string, resumeAt *string) (*Subscription, error)

Pause — optional resumeAt ISO timestamp.

func (*SubscriptionsResource) Resume

type Template

type Template struct {
	ID        string         `json:"id"`
	AccountID string         `json:"accountId"`
	Kind      TemplateKind   `json:"kind"`
	Name      string         `json:"name"`
	IsDefault bool           `json:"isDefault"`
	Document  map[string]any `json:"document"`
	CreatedAt string         `json:"createdAt"`
	UpdatedAt string         `json:"updatedAt"`
}

type TemplateCreateInput

type TemplateCreateInput struct {
	Kind     TemplateKind   `json:"kind"`
	Name     string         `json:"name"`
	Document map[string]any `json:"document"`
}

type TemplateKind

type TemplateKind string
const (
	TemplateKindCheckout TemplateKind = "checkout"
	TemplateKindReceipt  TemplateKind = "receipt"
	TemplateKindInvoice  TemplateKind = "invoice"
)

type TemplateListParams

type TemplateListParams struct {
	Kind *TemplateKind `json:"kind,omitempty"`
}

type TemplatePreviewInput

type TemplatePreviewInput struct {
	Kind       TemplateKind   `json:"kind"`
	Document   map[string]any `json:"document"`
	SampleData map[string]any `json:"sampleData,omitempty"`
}

type TemplatePreviewResult

type TemplatePreviewResult struct {
	HTML string `json:"html"`
}

type TemplateUpdateInput

type TemplateUpdateInput struct {
	Name     *string        `json:"name,omitempty"`
	Document map[string]any `json:"document,omitempty"`
}

type TemplatesResource

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

TemplatesResource — /api/v1/templates

func (*TemplatesResource) Create

func (*TemplatesResource) Delete

func (r *TemplatesResource) Delete(ctx context.Context, id string) error

func (*TemplatesResource) Duplicate

func (r *TemplatesResource) Duplicate(ctx context.Context, id string, name *string) (*Template, error)

func (*TemplatesResource) Get

func (r *TemplatesResource) Get(ctx context.Context, id string) (*Template, error)

func (*TemplatesResource) List

func (*TemplatesResource) MakeDefault

func (r *TemplatesResource) MakeDefault(ctx context.Context, id string) (*Template, error)

func (*TemplatesResource) Preview

func (*TemplatesResource) Update

type UploadImageInput

type UploadImageInput struct {
	Filename string `json:"filename"`
	Mime     string `json:"mime"`
	Base64   string `json:"base64"`
}

type UploadedFile

type UploadedFile struct {
	ID        string `json:"id"`
	AccountID string `json:"accountId"`
	URL       string `json:"url"`
	Mime      string `json:"mime"`
	Bytes     int64  `json:"bytes"`
	Filename  string `json:"filename"`
	CreatedAt string `json:"createdAt"`
}

type UploadsResource

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

UploadsResource — /api/v1/uploads

func (*UploadsResource) Image

Image uploads a base64-encoded image. Pass raw bytes + filename + mime.

type VerifyWebhookOptions

type VerifyWebhookOptions struct {
	// ToleranceSeconds rejects signatures with a timestamp older than this
	// many seconds. Zero or negative means "use the default" (300).
	ToleranceSeconds int64
	// Now is the clock used for the freshness check. Nil means time.Now.
	// Useful in tests.
	Now func() time.Time
}

VerifyWebhookOptions tunes the webhook verifier.

type WebhookEndpoint

type WebhookEndpoint struct {
	ID          string   `json:"id"`
	AccountID   string   `json:"accountId"`
	URL         string   `json:"url"`
	Events      []string `json:"events"`
	Description *string  `json:"description"`
	Active      bool     `json:"active"`
	Secret      string   `json:"secret,omitempty"` // only on create
	CreatedAt   string   `json:"createdAt"`
	UpdatedAt   string   `json:"updatedAt"`
}

type WebhookEndpointCreateInput

type WebhookEndpointCreateInput struct {
	URL         string   `json:"url"`
	Events      []string `json:"events,omitempty"`
	Description *string  `json:"description,omitempty"`
}

type WebhookEndpointsResource

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

WebhookEndpointsResource — /api/v1/webhook-endpoints

func (*WebhookEndpointsResource) Create

func (*WebhookEndpointsResource) Delete

func (*WebhookEndpointsResource) List

type WebhookEvent

type WebhookEvent struct {
	ID         string           `json:"id"`
	Type       string           `json:"type"`
	AccountID  string           `json:"accountId"`
	OccurredAt string           `json:"occurredAt"`
	Data       WebhookEventData `json:"data"`
}

WebhookEvent is the parsed webhook payload. The shape is type-tagged: inspect Type, then unmarshal Data.Object into the matching resource struct (CheckoutSession, Invoice, Subscription). Mirrors the discriminated-union in sdk/node/src/types.ts#WebhookEvent.

func VerifyWebhook

func VerifyWebhook(
	rawBody []byte,
	signatureHeader string,
	secret string,
	options *VerifyWebhookOptions,
) (*WebhookEvent, error)

VerifyWebhook is the typed convenience wrapper: verifies the signature AND unmarshals the body into a WebhookEvent. Returns *Error on any failure (signature_missing, signature_malformed, signature_stale, signature_invalid, invalid_payload).

type WebhookEventData

type WebhookEventData struct {
	Object json.RawMessage `json:"object"`
}

WebhookEventData wraps the resource snapshot at event time. Object is kept as a RawMessage so callers can decode it into the concrete type they care about.

type Workspace

type Workspace struct {
	ID            string  `json:"id"`
	AccountID     string  `json:"accountId"`
	BrandName     *string `json:"brandName"`
	BusinessEmail *string `json:"businessEmail"`
	CreatedAt     string  `json:"createdAt"`
	UpdatedAt     string  `json:"updatedAt"`
}

type WorkspaceCreateInput

type WorkspaceCreateInput struct {
	BrandName     *string `json:"brandName,omitempty"`
	BusinessEmail *string `json:"businessEmail,omitempty"`
}

type WorkspaceMember

type WorkspaceMember struct {
	ID       string `json:"id"`
	Email    string `json:"email"`
	Role     string `json:"role"`
	JoinedAt string `json:"joinedAt"`
}

type WorkspaceUpdateInput

type WorkspaceUpdateInput struct {
	BrandName     *string `json:"brandName,omitempty"`
	BusinessEmail *string `json:"businessEmail,omitempty"`
}

type WorkspacesResource

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

WorkspacesResource — /api/v1/workspaces (merchant-facing CRUD)

func (*WorkspacesResource) Create

func (*WorkspacesResource) Delete

func (r *WorkspacesResource) Delete(ctx context.Context, id string) error

func (*WorkspacesResource) List

func (r *WorkspacesResource) List(ctx context.Context) ([]Workspace, error)

func (*WorkspacesResource) Update

Jump to

Keyboard shortcuts

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