Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

31 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

Production-grade Go client for the [Lithic API](https://docs.lithic.com) — card issuing, fintech infrastructure, and embedded finance.

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages