lithic

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2026 License: MIT Imports: 28 Imported by: 0

README

lithic-go

Production-grade Go client for the Lithic API — card issuing, fintech infrastructure, and embedded finance.

Features

  • Complete API coverage — all 150+ endpoints: Cards, Payments, ACH, Tokenization, 3DS, Auth Rules V2, Events, Credit, Transaction Monitoring, and more
  • Generics-based iterator — lazy Iter[T] with cursor pagination and All() collector
  • Automatic retries — exponential backoff with jitter on 5xx and network errors
  • Idempotency keys — auto-generated on every mutating request
  • Webhook verification — HMAC-SHA256 for all webhook types (Events, ASA, Tokenization Decisioning, 3DS Decisioning)
  • Context-aware — every method accepts context.Context for cancellation and deadlines
  • Structured errors — typed *Error with category, status code, message, and request ID
  • Zero heavyweight dependencies — only stdlib

Installation

go get github.com/iamkanishka/lithic-go

Requires Go 1.25+.

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    lithic "github.com/iamkanishka/lithic-go"
)

func main() {
    // API key from LITHIC_API_KEY env var, or pass WithAPIKey("...")
    client := lithic.New(lithic.WithSandbox())

    ctx := context.Background()

    // Create a virtual card
    card, err := client.Cards.Create(ctx, lithic.CardCreateParams{
        Type: lithic.CardTypeVirtual,
        Memo: "My first card",
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Created card:", card.Token)

    // List cards with pagination
    iter := client.Cards.ListIter(lithic.CardsListParams{
        ListParams: lithic.ListParams{PageSize: 25},
        State:      lithic.CardStateOpen,
    })
    for iter.Next(ctx) {
        c := iter.Item()
        fmt.Printf("  %s  %s  %s\n", c["token"], c["type"], c["state"])
    }
    if err := iter.Err(); err != nil {
        log.Fatal(err)
    }
}

Configuration

client := lithic.New(
    lithic.WithAPIKey("your_api_key"),
    lithic.WithEnvironment(lithic.EnvironmentSandbox), // or EnvironmentProduction
    lithic.WithMaxRetries(3),
    lithic.WithHTTPClient(&http.Client{Timeout: 30 * time.Second}),
)

Error Handling

card, err := client.Cards.Get(ctx, "bad_token")
if err != nil {
    if apiErr, ok := err.(*lithic.Error); ok {
        switch {
        case apiErr.IsNotFound():
            fmt.Println("card not found")
        case apiErr.IsRateLimit():
            fmt.Println("rate limited, retry after backoff")
        case apiErr.IsAuthError():
            fmt.Println("check your API key")
        case apiErr.IsServerError():
            fmt.Println("lithic server error, retrying...")
        }
        fmt.Printf("request_id: %s\n", apiErr.RequestID)
    }
}

Pagination

// Iterator — lazy, memory-efficient
iter := client.Transactions.ListIter(lithic.TransactionsListParams{
    CardToken: "card_token",
})
for iter.Next(ctx) {
    txn := iter.Item()
    fmt.Println(txn["token"], txn["result"])
}

// Collect all pages at once
all, err := iter.All(ctx)

// Single page with manual cursor management
page, err := client.Cards.List(ctx, lithic.CardsListParams{
    ListParams: lithic.ListParams{PageSize: 50},
})
// page.HasMore, page.Data, nextCursorFromItems(page.Data)

Sandbox Simulation

// Simulate a full transaction lifecycle
txn, _ := client.Transactions.SimulateAuthorization(ctx, map[string]any{
    "card_token": card.Token,
    "amount":     1000, // $10.00
    "descriptor": "STARBUCKS",
    "mcc":        "5812",
})
client.Transactions.SimulateClearing(ctx, txn["token"].(string), nil)
// or SimulateVoid, SimulateReturn, SimulateReturnReversal

// ACH payment simulation
client.Payments.SimulateReceipt(ctx, map[string]any{
    "token":                   pmt.Token,
    "financial_account_token": "fa_token",
    "amount":                  5000,
})
client.Payments.SimulateRelease(ctx, pmt.Token)

Webhook Verification

// In your HTTP handler:
func handleWebhook(w http.ResponseWriter, r *http.Request) {
    body, _ := io.ReadAll(r.Body)
    signature := r.Header.Get("webhook-signature")
    timestamp := r.Header.Get("webhook-timestamp")

    // Get secret from client.Events.GetSubscriptionSecret(ctx, subToken)
    secret := "whsec_..."

    payload, err := client.Webhook.VerifyPayload(body, signature, timestamp, secret)
    if err != nil {
        http.Error(w, "invalid signature", 400)
        return
    }

    switch payload["type"] {
    case "card.created":
        // handle card created
    case "transaction.settled":
        // handle settlement
    }
    w.WriteHeader(200)
}

// Same API for ASA, Tokenization Decisioning, 3DS Decisioning webhooks
secret, _ := client.AuthStreamAccess.GetSecret(ctx)
payload, err := client.Webhook.VerifyPayload(body, sig, ts, secret["secret"].(string))

ACH Payments

// Link external bank account via micro-deposit
eba, _ := client.ExternalBankAccounts.Create(ctx, lithic.ExternalBankAccountCreateParams{
    RoutingNumber:      "021000021",
    AccountNumber:      "1234567890",
    AccountType:        "CHECKING",
    Owner:              "Jane Doe",
    OwnerType:          "INDIVIDUAL",
    VerificationMethod: "MICRO_DEPOSIT",
})

// After deposits arrive (1-3 business days):
client.ExternalBankAccounts.Verify(ctx, eba.Token, map[string]any{
    "micro_deposits": []int{12, 34},
})

// Send payment
pmt, _ := client.Payments.Create(ctx, lithic.PaymentCreateParams{
    FinancialAccountToken:    "fa_token",
    ExternalBankAccountToken: eba.Token,
    Amount:                   5000, // $50.00
    Direction:                "DEBIT",
    Method:                   "ACH_NEXT_DAY",
    MethodAttributes:         map[string]any{"sec_code": "PPD"},
    Type:                     "PAYMENT",
})

Auth Rules V2

// Create a velocity limit rule
rule, _ := client.AuthRules.Create(ctx, lithic.AuthRuleCreateParams{
    Name: "Daily spend limit",
    Parameters: map[string]any{
        "scope":  "CARD",
        "limits": []map[string]any{{"limit": 10000, "period": "DAY"}},
    },
})

// Draft → backtest → promote
client.AuthRules.Draft(ctx, rule.Token, map[string]any{"parameters": updatedParams})
bt, _ := client.AuthRules.RequestBacktest(ctx, rule.Token, map[string]any{
    "start": "2024-01-01T00:00:00Z",
    "end":   "2024-03-01T00:00:00Z",
})
client.AuthRules.Promote(ctx, rule.Token)

Resource Reference

Field Description
client.Accounts Account management and spend limits
client.AccountHolders KYC/KYB verification
client.AuthRules V2 rules engine with backtesting
client.AuthStreamAccess Real-time ASA webhook
client.Balances Balance queries
client.BookTransfers Internal fund transfers
client.CardBulkOrders Bulk physical card orders
client.Cards Card lifecycle, balances, provisioning
client.Chargebacks Chargeback/dispute (legacy)
client.Credit Credit products, statements, loan tapes
client.Disputes Disputes V2
client.Events Webhooks and event subscriptions
client.ExternalBankAccounts ACH counterparty accounts
client.ExternalPayments External payment lifecycle
client.FinancialAccounts Ledger, balances, credit config
client.FraudReports Fraud reporting
client.FundingEvents Program-level funding
client.Holds Financial holds
client.ManagementOperations Manual ledger adjustments
client.Network Network programs and totals
client.Payments ACH payments
client.Settlement Settlement summaries
client.ThreeDS 3DS auth and decisioning
client.Tokenization Digital wallet tokenization
client.TransactionMonitoring Cases and queues
client.Transactions Card transactions + sandbox simulation
client.Webhook Webhook HMAC verification

License

MIT

Documentation

Overview

Package lithic is the official Go SDK for the Lithic API (https://lithic.com). Create a Client with New, then call methods on its resource fields:

c := lithic.New(lithic.WithAPIKey("sk_..."), lithic.WithSandbox())
card, err := c.Cards.Create(ctx, lithic.CardCreateParams{Type: lithic.CardTypeVirtual})

Internally, the SDK is organized as a set of independent per-domain packages under domain/ (accounts, cards, transactions, ...), each depending only on the shared client package for HTTP/pagination/error mechanics — never on each other or on this root package. This file is the single place that composes those packages into one Client and re-exports their public types so the API surface above stays flat.

Index

Constants

View Source
const (
	EnvironmentProduction = client.EnvironmentProduction
	EnvironmentSandbox    = client.EnvironmentSandbox
)
View Source
const (
	ErrorCategoryAPI        = client.ErrorCategoryAPI
	ErrorCategoryAuth       = client.ErrorCategoryAuth
	ErrorCategoryValidation = client.ErrorCategoryValidation
	ErrorCategoryNotFound   = client.ErrorCategoryNotFound
	ErrorCategoryRateLimit  = client.ErrorCategoryRateLimit
	ErrorCategoryNetwork    = client.ErrorCategoryNetwork
	ErrorCategoryConfig     = client.ErrorCategoryConfig
	ErrorCategoryDecode     = client.ErrorCategoryDecode
)
View Source
const (
	AccountHolderStatusAccepted        = accountholders.AccountHolderStatusAccepted
	AccountHolderStatusRejected        = accountholders.AccountHolderStatusRejected
	AccountHolderStatusPendingResubmit = accountholders.AccountHolderStatusPendingResubmit
	AccountHolderStatusPendingDocument = accountholders.AccountHolderStatusPendingDocument
)
View Source
const (
	AccountStateActive = accounts.AccountStateActive
	AccountStatePaused = accounts.AccountStatePaused
	AccountStateClosed = accounts.AccountStateClosed
)
View Source
const (
	CardTypeVirtual        = cards.CardTypeVirtual
	CardTypePhysical       = cards.CardTypePhysical
	CardTypeMerchantLocked = cards.CardTypeMerchantLocked
	CardTypeSingleUse      = cards.CardTypeSingleUse

	CardStateOpen   = cards.CardStateOpen
	CardStatePaused = cards.CardStatePaused
	CardStateClosed = cards.CardStateClosed

	SpendLimitDurationTransaction = cards.SpendLimitDurationTransaction
	SpendLimitDurationMonthly     = cards.SpendLimitDurationMonthly
	SpendLimitDurationAnnually    = cards.SpendLimitDurationAnnually
	SpendLimitDurationForever     = cards.SpendLimitDurationForever
)
View Source
const (
	TransactionResultApproved = transactions.TransactionResultApproved
	TransactionResultDeclined = transactions.TransactionResultDeclined

	TransactionStatusPending  = transactions.TransactionStatusPending
	TransactionStatusSettled  = transactions.TransactionStatusSettled
	TransactionStatusDeclined = transactions.TransactionStatusDeclined
	TransactionStatusExpired  = transactions.TransactionStatusExpired
	TransactionStatusVoided   = transactions.TransactionStatusVoided
)

Variables

View Source
var (
	WithAPIKey      = client.WithAPIKey
	WithEnvironment = client.WithEnvironment
	WithSandbox     = client.WithSandbox
	WithHTTPClient  = client.WithHTTPClient
	WithMaxRetries  = client.WithMaxRetries
	WithBaseURL     = client.WithBaseURL
	WithLogger      = client.WithLogger
)

Functions

This section is empty.

Types

type Account

type Account = accounts.Account

type AccountHolder

type AccountHolder = accountholders.AccountHolder

type AccountHolderStatus

type AccountHolderStatus = accountholders.AccountHolderStatus

type AccountState

type AccountState = accounts.AccountState

type AccountUpdateParams

type AccountUpdateParams = accounts.AccountUpdateParams

type AccountsListParams

type AccountsListParams = accounts.AccountsListParams

type Address

type Address = client.Address

type AuthRule

type AuthRule = authrules.AuthRule

type AuthRuleBacktest

type AuthRuleBacktest = authrules.AuthRuleBacktest

type AuthRuleCreateParams

type AuthRuleCreateParams = authrules.AuthRuleCreateParams

type AuthRulesListParams

type AuthRulesListParams = authrules.AuthRulesListParams

type Balance

type Balance = balances.Balance

type BookTransfer

type BookTransfer = booktransfers.BookTransfer

type BookTransferCreateParams

type BookTransferCreateParams = booktransfers.BookTransferCreateParams

type Card

type Card = cards.Card

type CardBulkOrder

type CardBulkOrder = cardbulkorders.CardBulkOrder

type CardCreateParams

type CardCreateParams = cards.CardCreateParams

type CardState

type CardState = cards.CardState

type CardType

type CardType = cards.CardType

type CardUpdateParams

type CardUpdateParams = cards.CardUpdateParams

type CardsListParams

type CardsListParams = cards.CardsListParams

type Chargeback

type Chargeback = chargebacks.Chargeback

type Client

type Client struct {
	AccountHolders        *accountholders.Resource
	Accounts              *accounts.Resource
	AuthRules             *authrules.Resource
	AuthStreamAccess      *authstreamaccess.Resource
	Balances              *balances.Resource
	BookTransfers         *booktransfers.Resource
	CardBulkOrders        *cardbulkorders.Resource
	Cards                 *cards.Resource
	Chargebacks           *chargebacks.Resource
	Credit                *credit.Resource
	Disputes              *disputes.Resource
	Events                *events.Resource
	ExternalBankAccounts  *externalbankaccounts.Resource
	ExternalPayments      *externalpayments.Resource
	FinancialAccounts     *financialaccounts.Resource
	FraudReports          *fraudreports.Resource
	FundingEvents         *fundingevents.Resource
	Holds                 *holds.Resource
	ManagementOperations  *managementoperations.Resource
	Network               *network.Resource
	Payments              *payments.Resource
	Settlement            *settlement.Resource
	ThreeDS               *threeds.Resource
	Tokenization          *tokenization.Resource
	TransactionMonitoring *transactionmonitoring.Resource
	Transactions          *transactions.Resource

	// Webhook verifies Lithic webhook signatures (Event Subscriptions,
	// Auth Stream Access, Tokenization Decisioning, 3DS Decisioning).
	Webhook *WebhookClient
	// contains filtered or unexported fields
}

Client is the entry point to the Lithic API. Create one with New. It is safe for concurrent use.

func New

func New(opts ...Option) *Client

New creates a new Lithic client. If WithAPIKey is not passed, the LITHIC_API_KEY environment variable is used.

func (*Client) Status

func (c *Client) Status(ctx context.Context) (map[string]any, error)

Status checks API connectivity.

type Dispute

type Dispute = disputes.Dispute

type Environment

type Environment = client.Environment

type Error

type Error = client.Error

type ErrorCategory

type ErrorCategory = client.ErrorCategory

type Event

type Event = events.Event

type EventSubscription

type EventSubscription = events.EventSubscription

type EventSubscriptionCreateParams

type EventSubscriptionCreateParams = events.EventSubscriptionCreateParams

type ExternalPayment

type ExternalPayment = externalpayments.ExternalPayment

type FinancialAccount

type FinancialAccount = financialaccounts.FinancialAccount

type FraudReport

type FraudReport = fraudreports.FraudReport

type FundingEvent

type FundingEvent = fundingevents.FundingEvent

type Hold

type Hold = holds.Hold

type ListParams

type ListParams = client.ListParams

type Option

type Option = client.Option

type PageResponse

type PageResponse = client.PageResponse

type Payment

type Payment = payments.Payment

type PaymentCreateParams

type PaymentCreateParams = payments.PaymentCreateParams

type PaymentsListParams

type PaymentsListParams = payments.PaymentsListParams

type SettlementSummary

type SettlementSummary = settlement.SettlementSummary

type SpendLimitDuration

type SpendLimitDuration = cards.SpendLimitDuration

type Statement

type Statement = credit.Statement

type ThreeDSAuthentication

type ThreeDSAuthentication = threeds.ThreeDSAuthentication

type Tokenization

type Tokenization = tokenization.Tokenization

type Transaction

type Transaction = transactions.Transaction

type TransactionResult

type TransactionResult = transactions.TransactionResult

type TransactionStatus

type TransactionStatus = transactions.TransactionStatus

type TransactionsListParams

type TransactionsListParams = transactions.TransactionsListParams

type WebhookClient

type WebhookClient = client.WebhookClient

Directories

Path Synopsis
Package client implements the low-level HTTP mechanics shared by every Lithic domain package: request execution, retries, pagination, error mapping, and webhook verification.
Package client implements the low-level HTTP mechanics shared by every Lithic domain package: request execution, retries, pagination, error mapping, and webhook verification.
domain
account_holders
Package accountholders provides access to the Lithic Account Holders API.
Package accountholders provides access to the Lithic Account Holders API.
accounts
Package accounts provides access to the Lithic Accounts API.
Package accounts provides access to the Lithic Accounts API.
auth_rules
Package authrules provides access to the Lithic Auth Rules V2 API.
Package authrules provides access to the Lithic Auth Rules V2 API.
auth_stream_access
Package authstreamaccess provides access to the Auth Stream Access (ASA) API.
Package authstreamaccess provides access to the Auth Stream Access (ASA) API.
balances
Package balances provides access to the Lithic Balances API.
Package balances provides access to the Lithic Balances API.
book_transfers
Package booktransfers provides access to the Lithic Book Transfers API.
Package booktransfers provides access to the Lithic Book Transfers API.
card_bulk_orders
Package cardbulkorders provides access to the Lithic Card Bulk Orders API.
Package cardbulkorders provides access to the Lithic Card Bulk Orders API.
cards
Package cards provides access to the Lithic Cards API.
Package cards provides access to the Lithic Cards API.
chargebacks
Package chargebacks provides access to the Lithic Chargebacks (legacy dispute) API.
Package chargebacks provides access to the Lithic Chargebacks (legacy dispute) API.
credit
Package credit provides access to the Lithic Credit API.
Package credit provides access to the Lithic Credit API.
disputes
Package disputes provides access to the Lithic Disputes V2 API.
Package disputes provides access to the Lithic Disputes V2 API.
events
Package events provides access to the Lithic Events & Webhooks API.
Package events provides access to the Lithic Events & Webhooks API.
external_bank_accounts
Package externalbankaccounts provides access to the External Bank Accounts API.
Package externalbankaccounts provides access to the External Bank Accounts API.
external_payments
Package externalpayments provides access to the Lithic External Payments API.
Package externalpayments provides access to the Lithic External Payments API.
financial_accounts
Package financialaccounts provides access to the Lithic Financial Accounts API.
Package financialaccounts provides access to the Lithic Financial Accounts API.
fraud_reports
Package fraudreports provides access to the Lithic Fraud Reports API.
Package fraudreports provides access to the Lithic Fraud Reports API.
funding_events
Package fundingevents provides access to the Lithic Funding Events API.
Package fundingevents provides access to the Lithic Funding Events API.
holds
Package holds provides access to the Lithic Holds API.
Package holds provides access to the Lithic Holds API.
management_operations
Package managementoperations provides access to the Lithic Management Operations API.
Package managementoperations provides access to the Lithic Management Operations API.
network
Package network provides access to the Lithic Network API.
Package network provides access to the Lithic Network API.
payments
Package payments provides access to the Lithic Payments (ACH) API.
Package payments provides access to the Lithic Payments (ACH) API.
settlement
Package settlement provides access to the Lithic Settlement API.
Package settlement provides access to the Lithic Settlement API.
three_ds
Package threeds provides access to the Lithic 3-D Secure API.
Package threeds provides access to the Lithic 3-D Secure API.
tokenization
Package tokenization provides access to the Lithic Tokenization API.
Package tokenization provides access to the Lithic Tokenization API.
transaction_monitoring
Package transactionmonitoring provides access to the Lithic Transaction Monitoring API.
Package transactionmonitoring provides access to the Lithic Transaction Monitoring API.
transactions
Package transactions provides access to the Lithic Transactions API.
Package transactions provides access to the Lithic Transactions API.

Jump to

Keyboard shortcuts

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