levee

package module
v0.0.0-...-8eb3b45 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2026 License: MIT Imports: 20 Imported by: 0

README

Levee SDK for Go

Official Go SDK for integrating Levee into your Go applications.

Table of Contents

Installation

go get github.com/almatuck/levee-go

Quick Start

package main

import (
    "context"
    "log"

    levee "github.com/almatuck/levee-go"
)

func main() {
    // Initialize the client with your API key
    client, err := levee.NewClient("lv_your_api_key_here")
    if err != nil {
        log.Fatal(err)
    }

    // Create a contact using the Contacts resource
    contact, err := client.Contacts.CreateContact(context.Background(), &levee.ContactRequest{
        Email: "user@example.com",
        Name:  "John Doe",
    })
    if err != nil {
        log.Fatal(err)
    }

    log.Printf("Contact created: %s", contact.ID)
}

Configuration

Basic Configuration
// Default configuration - connects to https://levee.sh
client, err := levee.NewClient("lv_your_api_key")
if err != nil {
    log.Fatal(err)
}
Custom Base URL

For self-hosted instances or development environments:

client, err := levee.NewClient("lv_your_api_key",
    levee.WithBaseURL("https://your-domain.com"),
)
Custom HTTP Client

For custom timeouts, proxies, or transport settings:

import (
    "net/http"
    "time"
)

httpClient := &http.Client{
    Timeout: 60 * time.Second,
    Transport: &http.Transport{
        MaxIdleConns:        100,
        MaxIdleConnsPerHost: 10,
    },
}

client, err := levee.NewClient("lv_your_api_key",
    levee.WithHTTPClient(httpClient),
)
Timeout Configuration
client, err := levee.NewClient("lv_your_api_key",
    levee.WithTimeout(60 * time.Second),
)

Authentication

The Auth resource provides customer authentication for your application. This enables end-user login/registration flows for your SaaS application.

Register a Customer
resp, err := client.Auth.Register(ctx, &levee.SDKRegisterRequest{
    Email:    "user@example.com",
    Password: "securepassword123",
    Name:     "John Doe",
})
if err != nil {
    log.Fatal(err)
}

log.Printf("Registered user: %s", resp.Customer.Email)
log.Printf("Access token: %s", resp.Token)
log.Printf("Refresh token: %s", resp.RefreshToken)
Login
resp, err := client.Auth.Login(ctx, &levee.SDKLoginRequest{
    Email:    "user@example.com",
    Password: "securepassword123",
})
if err != nil {
    log.Fatal(err)
}

log.Printf("Logged in: %s", resp.Customer.Email)
log.Printf("Token expires at: %s", resp.ExpiresAt)
Refresh Token
resp, err := client.Auth.RefreshToken(ctx, &levee.SDKRefreshTokenRequest{
    RefreshToken: "existing_refresh_token",
})
if err != nil {
    log.Fatal(err)
}

log.Printf("New access token: %s", resp.Token)
log.Printf("New refresh token: %s", resp.RefreshToken)
Forgot Password
resp, err := client.Auth.ForgotPassword(ctx, &levee.SDKForgotPasswordRequest{
    Email: "user@example.com",
})
if err != nil {
    log.Fatal(err)
}

log.Printf("Password reset email sent: %v", resp.Success)
Reset Password
resp, err := client.Auth.ResetPassword(ctx, &levee.SDKResetPasswordRequest{
    Token:           "reset_token_from_email",
    Password:        "newpassword123",
    ConfirmPassword: "newpassword123",
})
if err != nil {
    log.Fatal(err)
}

log.Printf("Password reset: %v", resp.Success)
Verify Email
resp, err := client.Auth.VerifyEmail(ctx, &levee.SDKVerifyEmailRequest{
    Token: "verification_token_from_email",
})
if err != nil {
    log.Fatal(err)
}

log.Printf("Email verified: %v", resp.Success)
Change Password

Change a customer's password while logged in (requires current password verification).

resp, err := client.Auth.ChangePassword(ctx, &levee.SDKChangePasswordRequest{
    Email:           "user@example.com",
    CurrentPassword: "oldpassword123",
    NewPassword:     "newpassword456",
})
if err != nil {
    log.Fatal(err)
}

log.Printf("Password changed: %v", resp.Success)

Embedded HTTP Handlers

The SDK provides embeddable HTTP handlers for white-label integration. This allows email tracking pixels, unsubscribe links, and webhooks to be served from your application's domain instead of Levee's domain.

Register Handlers
mux := http.NewServeMux()
client, _ := levee.NewClient("lv_your_api_key")

// Register all Levee handlers with a prefix
client.RegisterHandlers(mux, "/levee")

This registers the following endpoints on your server:

Endpoint Purpose
GET /levee/e/o/:token Email open tracking (serves 1x1 transparent GIF)
GET /levee/e/c/:token Click tracking (redirects to destination URL)
GET /levee/e/u/:token One-click unsubscribe
GET /levee/confirm-email Double opt-in email confirmation
POST /levee/webhooks/stripe Stripe webhook receiver
POST /levee/webhooks/ses AWS SES bounce/complaint receiver
Configuration Options
client.RegisterHandlers(mux, "/levee",
    // Redirect URL after unsubscribe (default: /unsubscribed)
    levee.WithUnsubscribeRedirect("/email-preferences"),

    // Redirect URL after email confirmation (default: /confirmed)
    levee.WithConfirmRedirect("/welcome"),

    // Redirect URL for expired confirmation tokens (default: /confirm-expired)
    levee.WithConfirmExpiredRedirect("/link-expired"),

    // Stripe webhook secret for signature verification
    levee.WithStripeWebhookSecret(os.Getenv("STRIPE_WEBHOOK_SECRET")),
)
Complete Example
package main

import (
    "log"
    "net/http"
    "os"

    levee "github.com/almatuck/levee-go"
)

func main() {
    mux := http.NewServeMux()
    client, err := levee.NewClient(os.Getenv("LEVEE_API_KEY"))
    if err != nil {
        log.Fatal(err)
    }

    // Register Levee handlers
    client.RegisterHandlers(mux, "/levee",
        levee.WithUnsubscribeRedirect("/unsubscribed"),
        levee.WithStripeWebhookSecret(os.Getenv("STRIPE_WEBHOOK_SECRET")),
    )

    // Your application routes
    mux.HandleFunc("/", homeHandler)
    mux.HandleFunc("/api/signup", signupHandler)

    log.Fatal(http.ListenAndServe(":8080", mux))
}
Required Pages

Your application must provide these pages for redirects:

Page Purpose Default Path
Unsubscribe confirmation Shown after user unsubscribes /unsubscribed
Email confirmed Shown after double opt-in confirmation /confirmed
Link expired Shown when confirmation token expires /confirm-expired

Override defaults with WithUnsubscribeRedirect(), WithConfirmRedirect(), and WithConfirmExpiredRedirect().

Email Configuration

When sending emails through Levee, configure your email templates to use your domain for tracking URLs:

// When creating emails, Levee will use these URLs:
// Open tracking:  https://yourdomain.com/levee/e/o/{token}
// Click tracking: https://yourdomain.com/levee/e/c/{token}?url={destination}
// Unsubscribe:    https://yourdomain.com/levee/e/u/{token}
// Confirm email:  https://yourdomain.com/levee/confirm-email?token={token}

Set your tracking domain in Levee dashboard or via API to match your embedded handler prefix.

Webhook Configuration

Configure your third-party services to send webhooks to your domain:

  • Stripe: Set webhook URL to https://yourdomain.com/levee/webhooks/stripe
  • AWS SES: Set SNS notification URL to https://yourdomain.com/levee/webhooks/ses

The handlers forward events to Levee API for processing while serving tracking pixels and handling redirects locally.

How It Works

The embedded handlers make Levee completely invisible to your end users:

+----------------------------------------------------------------+
|  Your App (brandivize.com)                                     |
|                                                                |
|  +---------------+    +--------------------------------+       |
|  | Your Routes   |    | Levee SDK Handlers             |       |
|  | /             |    | /levee/e/o/:token -> serves GIF|       |
|  | /dashboard    |    | /levee/e/c/:token -> redirects |       |
|  | /api/*        |    | /levee/e/u/:token -> unsubscribe|      |
|  +---------------+    | /levee/webhooks/* -> forwards  |       |
|                       +--------------------------------+       |
+----------------------------------------------------------------+
                                    |
                                    v (async forwarding)
                         +---------------------+
                         |  Levee API          |
                         |  levee.sh/sdk/v1/* |
                         +---------------------+
  • Email opens: GIF served locally, open recorded asynchronously
  • Link clicks: Redirect happens locally, click recorded asynchronously
  • Unsubscribes: Processed synchronously, then redirects to your page
  • Webhooks: Verified locally (Stripe), then forwarded to Levee API

LLM/AI Chat

The SDK provides access to Levee's LLM gateway for AI-powered chat capabilities. Supports both simple request/response and streaming via gRPC or WebSocket.

Simple Chat (Non-Streaming)
llm := levee.NewLLMClient("lv_your_api_key")
defer llm.Close()

resp, err := llm.Chat(ctx, levee.ChatRequest{
    Messages: []levee.ChatMessage{
        {Role: "user", Content: "What is the capital of France?"},
    },
    Model:       "sonnet", // "haiku", "sonnet", or "opus"
    MaxTokens:   1024,
    Temperature: 0.7,
})

log.Printf("Response: %s", resp.Content)
log.Printf("Tokens: %d in, %d out, Cost: $%.4f", resp.InputTokens, resp.OutputTokens, resp.CostUSD)
Streaming Chat (gRPC)
llm := levee.NewLLMClient("lv_your_api_key",
    levee.WithGRPCAddress("llm.levee.sh:9889"),
)
defer llm.Close()

// Create a streaming session
session, err := llm.NewChatSession(ctx, levee.ChatRequest{
    SystemPrompt: "You are a helpful assistant.",
    Model:        "sonnet",
    MaxTokens:    2048,
})
defer session.Close()

// Send message and stream response
resp, err := session.Send(ctx, "Tell me a story", func(chunk levee.StreamChunk) error {
    fmt.Print(chunk.Content) // Print each token as it arrives
    return nil
})

log.Printf("\nTotal tokens: %d", resp.OutputTokens)
Convenience Streaming Method
resp, err := llm.ChatStream(ctx, levee.ChatRequest{
    Messages: []levee.ChatMessage{
        {Role: "user", Content: "Explain quantum computing"},
    },
    Model:     "haiku",
    MaxTokens: 1024,
}, func(chunk levee.StreamChunk) error {
    fmt.Print(chunk.Content)
    return nil
})
WebSocket Chat Handler (Embedded)

For browser-based streaming, the SDK provides an embeddable WebSocket handler:

mux := http.NewServeMux()
client, _ := levee.NewClient("lv_your_api_key")
llm := levee.NewLLMClient("lv_your_api_key")

// Register handlers including WebSocket chat
client.RegisterHandlers(mux, "/levee",
    levee.WithLLMClient(llm),
    levee.WithWSCheckOrigin(func(r *http.Request) bool {
        return r.Host == "yourdomain.com" // Origin validation
    }),
)

// WebSocket endpoint available at: ws://yourdomain.com/levee/ws/chat
WebSocket Protocol

The WebSocket chat uses JSON messages:

Client Messages:

// Start session
{"type": "start", "data": {"system_prompt": "...", "model": "sonnet", "max_tokens": 1024}}

// Send message
{"type": "message", "data": {"content": "Hello!"}}

// Abort generation
{"type": "abort", "data": {"reason": "user cancelled"}}

Server Messages:

// Session started
{"type": "started", "data": {"session_id": "...", "provider": "anthropic", "model": "claude-3-sonnet"}}

// Content chunk (streaming)
{"type": "chunk", "data": {"content": "Hello", "index": 0}}

// Completion
{"type": "completion", "data": {"full_content": "...", "stop_reason": "end_turn", "input_tokens": 10, "output_tokens": 50}}

// Error
{"type": "error", "data": {"code": "rate_limit", "message": "...", "retryable": true}}

Content/CMS

Access published content for your static site or application.

List Posts
posts, err := client.Content.ListContentPosts(ctx, 1, 10, "tutorials") // page, pageSize, categorySlug

for _, post := range posts.Posts {
    log.Printf("%s: %s", post.Slug, post.Title)
}
log.Printf("Total posts: %d", posts.Total)
Get a Post
post, err := client.Content.GetContentPost(ctx, "getting-started-guide")

log.Printf("Title: %s", post.Title)
log.Printf("Content: %s", post.Content)
log.Printf("Category: %s", post.CategoryName)
log.Printf("Published: %s", post.PublishedAt)
List Pages
pages, err := client.Content.ListContentPages(ctx, 1, 20) // page, pageSize

for _, page := range pages.Pages {
    log.Printf("%s: %s (template: %s)", page.Slug, page.Title, page.TemplateName)
}
Get a Page
page, err := client.Content.GetContentPage(ctx, "about-us")

log.Printf("Title: %s", page.Title)
log.Printf("Content: %s", page.Content)
log.Printf("Meta Title: %s", page.MetaTitle)
List Categories
categories, err := client.Content.ListContentCategories(ctx)

for _, cat := range categories.Categories {
    log.Printf("%s: %s", cat.Slug, cat.Name)
}

Site Configuration

Access site settings, navigation menus, and author information for building your frontend.

Get Site Settings
settings, err := client.Site.GetSiteSettings(ctx)

log.Printf("Site: %s - %s", settings.SiteName, settings.Tagline)
log.Printf("Logo: %s", settings.LogoUrl)
log.Printf("Contact: %s", settings.ContactEmail)
log.Printf("Social: %v", settings.SocialLinks) // map[string]string
log.Printf("Default Meta: %s", settings.MetaTitleTemplate)
List Navigation Menus
// Get all menus
menus, err := client.Site.ListNavigationMenus(ctx, "")

// Filter by location (header, footer, sidebar)
menus, err := client.Site.ListNavigationMenus(ctx, "header")

for _, menu := range menus.Menus {
    log.Printf("Menu: %s (%s)", menu.Name, menu.Location)
    for _, item := range menu.Items {
        log.Printf("  - %s: %s", item.Label, item.Url)
        for _, child := range item.Children {
            log.Printf("    - %s: %s", child.Label, child.Url)
        }
    }
}
Get a Menu by Slug
menu, err := client.Site.GetNavigationMenu(ctx, "main-nav")

for _, item := range menu.Items {
    log.Printf("%s -> %s", item.Label, item.Url)
}
List Authors
authors, err := client.Site.ListAuthors(ctx)

for _, author := range authors.Authors {
    log.Printf("%s: %s", author.DisplayName, author.Bio)
}
Get Author by ID
author, err := client.Site.GetAuthor(ctx, "author-123")

log.Printf("Name: %s", author.DisplayName)
log.Printf("Bio: %s", author.Bio)
log.Printf("Avatar: %s", author.AvatarUrl)
log.Printf("Twitter: @%s", author.TwitterHandle)

Contacts

Contacts are the core of Levee. Create and manage contacts when users sign up, submit forms, or interact with your application.

Create a Contact
contact, err := client.Contacts.CreateContact(ctx, &levee.ContactRequest{
    Email: "user@example.com",
    Name:  "John Doe",
    Tags:  []string{"signup"},
})
Get a Contact
// Get by ID or email
contact, err := client.Contacts.GetContact(ctx, "user@example.com")

log.Printf("Contact: %s, Status: %s, Tags: %v", contact.Name, contact.Status, contact.Tags)
log.Printf("Emails sent: %d, opened: %d, clicked: %d", contact.EmailsSent, contact.EmailsOpened, contact.EmailsClicked)
Update a Contact
contact, err := client.Contacts.UpdateContact(ctx, "user@example.com", &levee.UpdateContactRequest{
    Name:    "John Smith",
    Phone:   "+1-555-123-4567",
    Company: "Acme Inc",
    CustomFields: map[string]string{
        "plan": "enterprise",
    },
})
Manage Contact Tags
// Add tags
_, err := client.Contacts.AddContactTags(ctx, "user@example.com", &levee.AddContactTagsRequest{
    Tags: []string{"vip", "enterprise"},
})

// Remove tags
_, err := client.Contacts.RemoveContactTags(ctx, "user@example.com", &levee.RemoveContactTagsRequest{
    Tags: []string{"trial"},
})
View Contact Activity
activities, err := client.Contacts.ListContactActivity(ctx, "user@example.com", 50)
for _, activity := range activities.Activities {
    log.Printf("%s: %s - %s", activity.Timestamp, activity.Event, activity.Details)
}
Global Unsubscribe
// Unsubscribe from all communications
_, err := client.Contacts.GlobalUnsubscribe(ctx, &levee.GlobalUnsubscribeRequest{
    Email:  "user@example.com",
    Reason: "User requested to stop all emails",
})

Email Lists

Manage email list subscriptions for newsletters, updates, and marketing.

Subscribe to a List
_, err := client.Lists.SubscribeToList(ctx, "newsletter", &levee.SubscribeRequest{
    Email: "user@example.com",
    Name:  "John Doe",
})
Unsubscribe from a List
_, err := client.Lists.UnsubscribeFromList(ctx, "newsletter", &levee.SubscribeRequest{
    Email: "user@example.com",
})

Transactional Emails

Send transactional emails for receipts, notifications, password resets, and more.

Send an Email
// Using a template
resp, err := client.Emails.SendEmail(ctx, &levee.SendEmailRequest{
    To:           "user@example.com",
    TemplateSlug: "welcome-email",
    Variables: map[string]string{
        "name":      "John",
        "login_url": "https://app.example.com/login",
    },
})

// Custom email
resp, err := client.Emails.SendEmail(ctx, &levee.SendEmailRequest{
    To:       "user@example.com",
    Subject:  "Your order has shipped!",
    Body:     "<h1>Order Shipped</h1><p>Your order #12345 is on its way.</p>",
    TextBody: "Order Shipped\n\nYour order #12345 is on its way.",
    FromName: "Acme Store",
    Tags:     []string{"shipping", "order-12345"},
})

log.Printf("Email sent, message ID: %s, status: %s", resp.MessageID, resp.Status)
Check Email Status
status, err := client.Emails.GetEmailStatus(ctx, messageID)

log.Printf("Email to %s: %s", status.To, status.Status)
log.Printf("Sent: %s, Delivered: %s, Opened: %s", status.SentAt, status.DeliveredAt, status.OpenedAt)
log.Printf("Opens: %d, Clicks: %d", status.Opens, status.Clicks)
Get Email Events
events, err := client.Emails.ListEmailEvents(ctx, messageID)
for _, event := range events.Events {
    log.Printf("%s: %s %s", event.Timestamp, event.Event, event.Data)
}
// Output:
// 2024-01-15T10:00:00Z: sent
// 2024-01-15T10:00:02Z: delivered
// 2024-01-15T10:15:30Z: opened
// 2024-01-15T10:16:45Z: clicked https://example.com/link

Email Sequences

Enroll contacts in automated email sequences for onboarding, nurturing, and drip campaigns.

Enroll in a Sequence
resp, err := client.Sequences.EnrollInSequence(ctx, &levee.EnrollSequenceRequest{
    SequenceSlug: "onboarding",
    Email:        "user@example.com",
    Variables: map[string]string{
        "first_name": "John",
        "plan":       "Pro",
    },
})

log.Printf("Enrollment ID: %s, Status: %s", resp.EnrollmentID, resp.Status)
Get Sequence Enrollments
// Get all enrollments for an email
enrollments, err := client.Sequences.GetSequenceEnrollments(ctx, "user@example.com", "")

// Get specific sequence enrollment
enrollments, err := client.Sequences.GetSequenceEnrollments(ctx, "user@example.com", "onboarding")

for _, e := range enrollments.Enrollments {
    log.Printf("Sequence: %s, Step %d/%d, Status: %s",
        e.SequenceName, e.CurrentStep, e.TotalSteps, e.Status)
    log.Printf("Next email at: %s", e.NextEmailAt)
}
Unenroll from Sequences
// Unenroll from specific sequence
_, err := client.Sequences.UnenrollFromSequence(ctx, &levee.UnenrollSequenceRequest{
    Email:        "user@example.com",
    SequenceSlug: "onboarding",
})

// Unenroll from all sequences
_, err := client.Sequences.UnenrollFromSequence(ctx, &levee.UnenrollSequenceRequest{
    Email: "user@example.com",
})
Pause and Resume
// Pause enrollment
_, err := client.Sequences.PauseSequenceEnrollment(ctx, &levee.PauseSequenceRequest{
    Email:        "user@example.com",
    SequenceSlug: "onboarding",
})

// Resume enrollment
_, err := client.Sequences.ResumeSequenceEnrollment(ctx, &levee.ResumeSequenceRequest{
    Email:        "user@example.com",
    SequenceSlug: "onboarding",
})

Orders & Checkout

Create checkout sessions for products, courses, or any purchasable items.

Create an Order
order, err := client.Orders.CreateOrder(ctx, &levee.OrderRequest{
    Email:       "user@example.com",
    ProductSlug: "pro-plan",
    SuccessUrl:  "https://yourapp.com/success",
    CancelUrl:   "https://yourapp.com/cancel",
})

// Redirect user to checkout
http.Redirect(w, r, order.CheckoutUrl, http.StatusSeeOther)

Products

Access product information for your catalog.

Get Product
product, err := client.Products.GetProduct(ctx, "pro-plan")

log.Printf("Product: %s - %s", product.Name, product.Description)
log.Printf("Type: %s, Category: %s", product.Type, product.Category)
for _, price := range product.Prices {
    log.Printf("  Price: $%.2f/%s", float64(price.UnitAmountCents)/100, price.RecurringInterval)
}

Funnels

Access funnel step information for multi-step sales processes.

Get Funnel Step
step, err := client.Funnels.GetFunnelStep(ctx, "onboarding-step-1")

log.Printf("Step: %s", step.Title)
log.Printf("Type: %s", step.StepType)
log.Printf("Next step ID: %d", step.NextStepID)

Quizzes

Access and submit quizzes for lead qualification or assessments.

Get Quiz
quiz, err := client.Quizzes.GetQuiz(ctx, "product-fit")

log.Printf("Quiz: %s", quiz.Title)
for _, q := range quiz.Questions {
    log.Printf("  Q: %s", q.Question)
}
Submit Quiz
result, err := client.Quizzes.SubmitQuiz(ctx, "product-fit", &levee.QuizSubmitRequest{
    Email: "user@example.com",
    Answers: map[string]string{
        "q1": "answer1",
        "q2": "answer2",
    },
})

log.Printf("Segments: %v", result.Segments)
log.Printf("Redirect: %s", result.RedirectUrl)

Offers

Process special offers and promotions.

Process Offer
result, err := client.Offers.ProcessOffer(ctx, &levee.OfferRequest{
    SessionID: "checkout_session_id",
    StepSlug:  "upsell-1",
    Accept:    true,
})

log.Printf("Success: %v", result.Success)
log.Printf("Next URL: %s", result.NextUrl)

Workshops

Access workshop and event information.

Get Workshop
workshop, err := client.Workshops.GetWorkshop(ctx, "intro-webinar")

log.Printf("Workshop: %s", workshop.Title)
log.Printf("Date: %s to %s", workshop.StartDate, workshop.EndDate)
log.Printf("Seats remaining: %d", workshop.SeatsRemaining)
Get Workshop by Product
workshop, err := client.Workshops.GetWorkshopByProduct(ctx, "webinar-product")

log.Printf("Workshop for product: %s", workshop.Title)

Customer Billing History

Access customer billing data including invoices, orders, subscriptions, and payments. Perfect for building customer account pages.

Get Customer Info
customer, err := client.Customers.GetCustomerByEmail(ctx, "user@example.com")

log.Printf("Customer: %s", customer.Name)
log.Printf("Total spent: $%.2f", float64(customer.TotalSpent)/100)
log.Printf("Orders: %d, Subscriptions: %d", customer.OrderCount, customer.SubscriptionCount)
List Invoices
invoices, err := client.Customers.ListCustomerInvoices(ctx, "user@example.com", 10)
for _, inv := range invoices.Invoices {
    log.Printf("Invoice #%s: $%.2f %s", inv.Number, float64(inv.AmountPaid)/100, inv.Status)
    if inv.InvoicePdfUrl != "" {
        log.Printf("  PDF: %s", inv.InvoicePdfUrl)
    }
}
List Orders
orders, err := client.Customers.ListCustomerOrders(ctx, "user@example.com", 10)
for _, order := range orders.Orders {
    log.Printf("Order %s: $%.2f %s", order.OrderNumber, float64(order.TotalCents)/100, order.Status)
    for _, item := range order.Items {
        log.Printf("  - %s x%d: $%.2f", item.ProductName, item.Quantity, float64(item.TotalPrice)/100)
    }
}
List Subscriptions
subs, err := client.Customers.ListCustomerSubscriptions(ctx, "user@example.com")
for _, sub := range subs.Subscriptions {
    log.Printf("Subscription: %s - %s ($%.2f/%s)",
        sub.ProductName, sub.Status, float64(sub.AmountCents)/100, sub.Interval)
    log.Printf("  Current period: %s to %s", sub.CurrentPeriodStart, sub.CurrentPeriodEnd)
}
List Payments
payments, err := client.Customers.ListCustomerPayments(ctx, "user@example.com", 20)
for _, p := range payments.Payments {
    log.Printf("Payment: $%.2f %s via %s", float64(p.AmountCents)/100, p.Status, p.PaymentMethod)
    if p.ReceiptUrl != "" {
        log.Printf("  Receipt: %s", p.ReceiptUrl)
    }
}
Update Customer

Update a customer's profile information (name, phone, avatar, status, metadata).

customer, err := client.Customers.UpdateCustomer(ctx, "customer-uuid", &levee.SDKUpdateCustomerRequest{
    Name:      "John Doe",
    Phone:     "+1-555-1234",
    AvatarUrl: "https://example.com/avatar.jpg",
    Status:    "active",
    Metadata:  `{"plan": "pro", "source": "website"}`,
})
if err != nil {
    log.Fatal(err)
}

log.Printf("Updated customer: %s (%s)", customer.Name, customer.Email)
Delete Customer

Permanently delete a customer (GDPR compliance - hard delete).

resp, err := client.Customers.DeleteCustomer(ctx, "customer-uuid")
if err != nil {
    log.Fatal(err)
}

log.Printf("Customer deleted: %v", resp.Success)

Event Tracking

Track custom events for analytics, automation triggers, and user behavior analysis.

Track Events
_, err := client.Events.TrackEvent(ctx, &levee.EventRequest{
    Event: "purchase_completed",
    Email: "user@example.com",
    Properties: map[string]interface{}{
        "product":  "pro-plan",
        "amount":   "99.00",
        "currency": "usd",
    },
})

Billing

Full Stripe billing integration for customers, subscriptions, and usage-based billing.

Create a Customer
customer, err := client.Billing.CreateCustomer(ctx, &levee.CustomerRequest{
    Email: "user@example.com",
    Name:  "John Doe",
})
Create a Checkout Session
checkout, err := client.Billing.CreateCheckoutSession(ctx, &levee.CheckoutRequest{
    CustomerEmail: "user@example.com",
    LineItems: []levee.CheckoutItem{
        {PriceID: "price_xxx", Quantity: 1},
    },
    Mode:       "subscription",
    SuccessUrl: "https://yourapp.com/success",
    CancelUrl:  "https://yourapp.com/cancel",
})
// Redirect to checkout.CheckoutUrl
Embedded Checkout

Embed Stripe checkout directly on your site instead of redirecting to Stripe's hosted page:

checkout, err := client.Billing.CreateCheckoutSession(ctx, &levee.CheckoutRequest{
    CustomerEmail: "user@example.com",
    LineItems: []levee.CheckoutItem{
        {PriceID: "price_xxx", Quantity: 1},
    },
    Mode:       "payment",
    SuccessUrl: "https://yourapp.com/success",
    Embedded:   true,
    ReturnUrl:  "https://yourapp.com/checkout/complete?session_id={CHECKOUT_SESSION_ID}",
})

// Use checkout.ClientSecret with Stripe.js to mount embedded checkout
log.Printf("Client Secret: %s", checkout.ClientSecret)

Frontend integration (JavaScript/TypeScript):

import { loadStripe } from '@stripe/stripe-js';

const stripe = await loadStripe(STRIPE_PUBLISHABLE_KEY);

// Use the client_secret from your backend
const checkout = await stripe.initEmbeddedCheckout({
    clientSecret: clientSecretFromBackend,
});

// Mount to a DOM element
checkout.mount('#checkout-container');

Benefits of embedded checkout:

  • Users stay on your site during payment
  • More control over the checkout appearance
  • Enable custom upsell flows before/after payment
  • Maintain your site branding throughout
Create a Subscription
sub, err := client.Billing.CreateSubscription(ctx, &levee.SubscriptionRequest{
    CustomerID: "cust_123",
    PriceIds:   []string{"price_xxx"},
})
Cancel a Subscription
_, err := client.Billing.CancelSubscription(ctx, "sub_123")
Record Metered Usage
_, err := client.Billing.RecordUsage(ctx, &levee.UsageRequest{
    SubscriptionItemID: "si_xxx",
    Quantity:           150,
})
Customer Portal
portal, err := client.Billing.GetCustomerPortal(ctx, &levee.PortalRequest{
    CustomerID: "cust_123",
    ReturnUrl:  "https://yourapp.com/settings",
})
// Redirect to portal.PortalUrl

Webhooks

Register webhook endpoints to receive real-time events from Levee.

Register a Webhook
resp, err := client.Webhooks.RegisterWebhook(ctx, &levee.RegisterWebhookRequest{
    Url: "https://yourapp.com/webhooks/levee",
    Events: []string{
        "contact.created",
        "email.opened",
        "payment.succeeded",
        "subscription.created",
    },
})

log.Printf("Webhook ID: %s", resp.WebhookID)
log.Printf("Secret: %s (save this for signature verification!)", resp.Secret)
Available Webhook Events
// Contact events
contact.created
contact.updated
contact.unsubscribed
contact.bounced

// Email events
email.sent
email.delivered
email.opened
email.clicked
email.bounced
email.complained

// Sequence events
sequence.enrolled
sequence.completed
sequence.paused
sequence.resumed

// Payment events
payment.succeeded
payment.failed
payment.refunded

// Subscription events
subscription.created
subscription.updated
subscription.cancelled
subscription.renewed

// Order events
order.created
order.completed
order.refunded
List Webhooks
webhooks, err := client.Webhooks.ListWebhooks(ctx)
for _, wh := range webhooks.Webhooks {
    log.Printf("Webhook %s: %s", wh.ID, wh.Url)
    log.Printf("  Events: %v", wh.Events)
    log.Printf("  Success rate: %d/%d", wh.DeliveriesSuccess, wh.DeliveriesTotal)
}
Get a Webhook
wh, err := client.Webhooks.GetWebhook(ctx, webhookID)
log.Printf("Webhook: %s -> %s", wh.ID, wh.Url)
Update a Webhook
wh, err := client.Webhooks.UpdateWebhook(ctx, webhookID, &levee.UpdateWebhookRequest{
    Events: []string{
        "payment.succeeded",
        "payment.failed",
    },
    Active: true,
})
Test a Webhook
result, err := client.Webhooks.TestWebhook(ctx, webhookID)
if result.Success {
    log.Printf("Webhook test succeeded! Status: %d", result.StatusCode)
} else {
    log.Printf("Webhook test failed: %s", result.Error)
}
View Webhook Logs
logs, err := client.Webhooks.ListWebhookLogs(ctx, webhookID, 20)
for _, l := range logs.Logs {
    log.Printf("%s: %s (status %d, %dms)", l.DeliveredAt, l.Event, l.StatusCode, l.Duration)
}
Delete a Webhook
_, err := client.Webhooks.DeleteWebhook(ctx, webhookID)

Stats & Analytics

Access statistics and analytics for your organization.

Overview Stats
stats, err := client.Stats.GetStatsOverview(ctx,
    "2024-01-01T00:00:00Z", // startDate
    "2024-01-31T23:59:59Z", // endDate
)

log.Printf("Contacts: %d total, %d new, %d active", stats.TotalContacts, stats.NewContacts, stats.ActiveContacts)
log.Printf("Emails: %d sent, %.1f%% open rate, %.1f%% click rate", stats.EmailsSent, stats.OpenRate, stats.ClickRate)
log.Printf("Revenue: $%.2f from %d orders", float64(stats.TotalRevenue)/100, stats.OrderCount)
Email Stats
emailStats, err := client.Stats.GetEmailStats(ctx,
    "2024-01-01T00:00:00Z", // startDate
    "2024-01-31T23:59:59Z", // endDate
    "day",                   // groupBy: day, week, or month
)

log.Printf("Totals: %d sent, %.1f%% open rate, %.1f%% click rate",
    emailStats.TotalSent, emailStats.AvgOpenRate, emailStats.AvgClickRate)

for _, day := range emailStats.Stats {
    log.Printf("%s: %d sent, %d opened (%.1f%%)", day.Date, day.Sent, day.Opened, day.OpenRate)
}
Revenue Stats
revenueStats, err := client.Stats.GetRevenueStats(ctx,
    "2024-01-01T00:00:00Z", // startDate
    "2024-01-31T23:59:59Z", // endDate
    "week",                  // groupBy
)

log.Printf("Total revenue: $%.2f", float64(revenueStats.TotalRevenue)/100)
log.Printf("MRR: $%.2f", float64(revenueStats.Mrr)/100)
log.Printf("Orders: %d, Subscriptions: %d, Churned: %d",
    revenueStats.TotalOrders, revenueStats.TotalSubscriptions, revenueStats.TotalChurned)
Contact Stats
contactStats, err := client.Stats.GetContactStats(ctx,
    "2024-01-01T00:00:00Z", // startDate
    "2024-01-31T23:59:59Z", // endDate
    "day",                   // groupBy
)

log.Printf("Active: %d, Unsubscribed: %d, Net growth: %d",
    contactStats.TotalActive, contactStats.TotalUnsubscribed, contactStats.NetGrowth)

Error Handling

The SDK returns errors for API failures, network issues, and validation problems.

contact, err := client.Contacts.CreateContact(ctx, &levee.ContactRequest{
    Email: "user@example.com",
})
if err != nil {
    // Error format: "API error (status 400): {\"error\": \"email is required\"}"
    log.Printf("Levee API error: %v", err)
    return
}

Complete Example

A complete SaaS application integration:

package main

import (
    "context"
    "encoding/json"
    "log"
    "net/http"
    "os"

    levee "github.com/almatuck/levee-go"
)

var client *levee.Client

func init() {
    var err error
    client, err = levee.NewClient(os.Getenv("LEVEE_API_KEY"))
    if err != nil {
        log.Fatal(err)
    }
}

func handleSignup(w http.ResponseWriter, r *http.Request) {
    var req struct {
        Email string `json:"email"`
        Name  string `json:"name"`
    }
    json.NewDecoder(r.Body).Decode(&req)
    ctx := r.Context()

    // Create contact and enroll in onboarding sequence
    contact, _ := client.Contacts.CreateContact(ctx, &levee.ContactRequest{
        Email:      req.Email,
        Name:       req.Name,
        FunnelSlug: "signup",
        Tags:       []string{"trial"},
    })

    // Enroll in onboarding sequence
    client.Sequences.EnrollInSequence(ctx, &levee.EnrollSequenceRequest{
        SequenceSlug: "onboarding",
        Email:        req.Email,
        Variables: map[string]string{
            "first_name": req.Name,
        },
    })

    // Send welcome email
    client.Emails.SendEmail(ctx, &levee.SendEmailRequest{
        To:           req.Email,
        TemplateSlug: "welcome",
        Variables: map[string]string{
            "name": req.Name,
        },
    })

    json.NewEncoder(w).Encode(map[string]string{
        "contact_id": contact.ID,
    })
}

func main() {
    http.HandleFunc("/api/signup", handleSignup)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

API Reference

All methods use the resource-based pattern: client.Resource.Method(ctx, ...)

Resource.Method Description
Client
NewClient(apiKey, opts...) Create a new client (returns *Client, error)
WithBaseURL(url) Set custom API base URL
WithHTTPClient(client) Set custom HTTP client
WithTimeout(duration) Set HTTP request timeout
Auth
Auth.Register(ctx, *SDKRegisterRequest) Register a new customer account
Auth.Login(ctx, *SDKLoginRequest) Authenticate and get tokens
Auth.RefreshToken(ctx, *SDKRefreshTokenRequest) Exchange refresh token for new tokens
Auth.ForgotPassword(ctx, *SDKForgotPasswordRequest) Initiate password reset
Auth.ResetPassword(ctx, *SDKResetPasswordRequest) Complete password reset
Auth.VerifyEmail(ctx, *SDKVerifyEmailRequest) Verify email address
Auth.ChangePassword(ctx, *SDKChangePasswordRequest) Change password while logged in
Billing
Billing.CreateCustomer(ctx, *CustomerRequest) Create billing customer
Billing.CreateCheckoutSession(ctx, *CheckoutRequest) Create Stripe checkout
Billing.CreateSubscription(ctx, *SubscriptionRequest) Create subscription
Billing.CancelSubscription(ctx, subscriptionID) Cancel subscription
Billing.RecordUsage(ctx, *UsageRequest) Record metered usage
Billing.GetCustomerPortal(ctx, *PortalRequest) Get portal URL
Contacts
Contacts.CreateContact(ctx, *ContactRequest) Create or get a contact
Contacts.GetContact(ctx, idOrEmail) Get contact details
Contacts.UpdateContact(ctx, id, *UpdateContactRequest) Update a contact
Contacts.AddContactTags(ctx, id, *AddContactTagsRequest) Add tags to contact
Contacts.RemoveContactTags(ctx, id, *RemoveContactTagsRequest) Remove tags from contact
Contacts.ListContactActivity(ctx, id, limit) Get contact activity
Contacts.GlobalUnsubscribe(ctx, *GlobalUnsubscribeRequest) Unsubscribe from all
Content
Content.ListContentPosts(ctx, page, pageSize, categorySlug) List published posts
Content.GetContentPost(ctx, slug) Get post by slug
Content.ListContentPages(ctx, page, pageSize) List published pages
Content.GetContentPage(ctx, slug) Get page by slug
Content.ListContentCategories(ctx) List content categories
Customers
Customers.GetCustomerByEmail(ctx, email) Get customer info
Customers.ListCustomerInvoices(ctx, email, limit) List invoices
Customers.ListCustomerOrders(ctx, email, limit) List orders
Customers.ListCustomerSubscriptions(ctx, email) List subscriptions
Customers.ListCustomerPayments(ctx, email, limit) List payments
Customers.UpdateCustomer(ctx, id, *SDKUpdateCustomerRequest) Update customer profile
Customers.DeleteCustomer(ctx, id) Delete customer (GDPR)
Emails
Emails.SendEmail(ctx, *SendEmailRequest) Send transactional email
Emails.GetEmailStatus(ctx, messageID) Get email delivery status
Emails.ListEmailEvents(ctx, messageID) Get email tracking events
Events
Events.TrackEvent(ctx, *EventRequest) Track custom event
Funnels
Funnels.GetFunnelStep(ctx, slug) Get funnel step info
Lists
Lists.SubscribeToList(ctx, slug, *SubscribeRequest) Subscribe to list
Lists.UnsubscribeFromList(ctx, slug, *SubscribeRequest) Unsubscribe from list
Llm
Llm.Chat(ctx, *LLMChatRequest) Simple chat via HTTP
Llm.Config(ctx) Get LLM configuration
Offers
Offers.ProcessOffer(ctx, *OfferRequest) Process an offer
Orders
Orders.CreateOrder(ctx, *OrderRequest) Create checkout session
Products
Products.GetProduct(ctx, slug) Get product by slug
Quizzes
Quizzes.GetQuiz(ctx, slug) Get quiz by slug
Quizzes.SubmitQuiz(ctx, slug, *QuizSubmitRequest) Submit quiz answers
Sequences
Sequences.EnrollInSequence(ctx, *EnrollSequenceRequest) Enroll in sequence
Sequences.GetSequenceEnrollments(ctx, email, sequenceSlug) Get enrollments
Sequences.UnenrollFromSequence(ctx, *UnenrollSequenceRequest) Unenroll from sequence
Sequences.PauseSequenceEnrollment(ctx, *PauseSequenceRequest) Pause enrollment
Sequences.ResumeSequenceEnrollment(ctx, *ResumeSequenceRequest) Resume enrollment
Site
Site.GetSiteSettings(ctx) Get site branding/settings
Site.ListNavigationMenus(ctx, location) List navigation menus
Site.GetNavigationMenu(ctx, slug) Get menu by slug
Site.ListAuthors(ctx) List all authors
Site.GetAuthor(ctx, id) Get author by ID
Stats
Stats.GetStatsOverview(ctx, startDate, endDate) Get overview stats
Stats.GetEmailStats(ctx, startDate, endDate, groupBy) Get email stats
Stats.GetRevenueStats(ctx, startDate, endDate, groupBy) Get revenue stats
Stats.GetContactStats(ctx, startDate, endDate, groupBy) Get contact stats
Tracking
Tracking.TrackOpen(ctx, *TrackOpenRequest) Track email open
Tracking.TrackClick(ctx, *TrackClickRequest) Track link click
Tracking.TrackUnsubscribe(ctx, *TrackUnsubscribeRequest) Track unsubscribe
Tracking.TrackConfirm(ctx, *TrackConfirmRequest) Track email confirmation
Webhooks
Webhooks.RegisterWebhook(ctx, *RegisterWebhookRequest) Register webhook
Webhooks.ListWebhooks(ctx) List webhooks
Webhooks.GetWebhook(ctx, webhookID) Get webhook details
Webhooks.UpdateWebhook(ctx, id, *UpdateWebhookRequest) Update webhook
Webhooks.DeleteWebhook(ctx, webhookID) Delete webhook
Webhooks.TestWebhook(ctx, webhookID) Send test event
Webhooks.ListWebhookLogs(ctx, webhookID, limit) Get delivery logs
Workshops
Workshops.GetWorkshop(ctx, slug) Get workshop by slug
Workshops.GetWorkshopByProduct(ctx, productSlug) Get workshop by product
Embedded Handlers
RegisterHandlers(mux, prefix, opts...) Register HTTP handlers on mux
WithUnsubscribeRedirect(url) Set unsubscribe redirect URL
WithConfirmRedirect(url) Set confirmation redirect URL
WithConfirmExpiredRedirect(url) Set expired token redirect URL
WithStripeWebhookSecret(secret) Set Stripe webhook secret
WithLLMClient(llm) Enable WebSocket chat handler
WithWSCheckOrigin(fn) Set WebSocket origin checker
LLM Client (gRPC)
NewLLMClient(apiKey, opts...) Create LLM client for streaming
WithGRPCAddress(addr) Set gRPC server address
Chat(ctx, ChatRequest) Simple chat (non-streaming)
NewChatSession(ctx, ChatRequest) Start streaming session
ChatStream(ctx, ChatRequest, callback) Convenience streaming method

License

MIT License - see LICENSE for details.

Documentation

Index

Constants

View Source
const (
	WSMsgTypeStart      = "start"
	WSMsgTypeMessage    = "message"
	WSMsgTypeAbort      = "abort"
	WSMsgTypeChunk      = "chunk"
	WSMsgTypeCompletion = "completion"
	WSMsgTypeError      = "error"
	WSMsgTypeStarted    = "started"
	WSMsgTypeToolCall   = "tool_call"
	WSMsgTypeToolResult = "tool_result"
)

WebSocket message types for LLM chat

Variables

This section is empty.

Functions

This section is empty.

Types

type AcceptInviteRequest

type AcceptInviteRequest struct {
	Token    string `json:"token"`
	Password string `json:"password,omitempty"`
	Name     string `json:"name,omitempty"`
}

AcceptInviteRequest represents the AcceptInviteRequest type.

type AcceptInviteResponse

type AcceptInviteResponse struct {
	Message string `json:"message"`
	OrgID   string `json:"org_id"`
	OrgName string `json:"org_name"`
	OrgSlug string `json:"org_slug"`
	Role    string `json:"role"`
}

AcceptInviteResponse represents the AcceptInviteResponse type.

type AddContactTagsRequest

type AddContactTagsRequest struct {
	Tags []string `json:"tags"`
}

AddContactTagsRequest represents the AddContactTagsRequest type.

type AuthResource

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

AuthResource provides access to auth resources.

func (*AuthResource) ChangePassword

func (r *AuthResource) ChangePassword(ctx context.Context, request *SDKChangePasswordRequest) (*Response, error)

ChangePassword

func (*AuthResource) ForgotPassword

func (r *AuthResource) ForgotPassword(ctx context.Context, request *SDKForgotPasswordRequest) (*Response, error)

ForgotPassword

func (*AuthResource) Login

func (r *AuthResource) Login(ctx context.Context, request *SDKLoginRequest) (*SDKAuthResponse, error)

Login

func (*AuthResource) RefreshToken

func (r *AuthResource) RefreshToken(ctx context.Context, request *SDKRefreshTokenRequest) (*SDKAuthResponse, error)

RefreshToken

func (*AuthResource) Register

func (r *AuthResource) Register(ctx context.Context, request *SDKRegisterRequest) (*SDKAuthResponse, error)

Register

func (*AuthResource) ResetPassword

func (r *AuthResource) ResetPassword(ctx context.Context, request *SDKResetPasswordRequest) (*Response, error)

ResetPassword

func (*AuthResource) VerifyEmail

func (r *AuthResource) VerifyEmail(ctx context.Context, request *SDKVerifyEmailRequest) (*Response, error)

VerifyEmail

type BillingPriceInfo

type BillingPriceInfo struct {
	ID                     string                 `json:"id"`
	OrgID                  string                 `json:"org_id"`
	ProductID              string                 `json:"product_id"`
	ProductName            string                 `json:"product_name,omitempty"`
	StripePriceID          string                 `json:"stripe_price_id,omitempty"`
	Provider               string                 `json:"provider,omitempty"`
	ProviderPriceID        string                 `json:"provider_price_id,omitempty"`
	Nickname               string                 `json:"nickname,omitempty"`
	DisplayName            string                 `json:"display_name,omitempty"`
	UnitAmountCents        int64                  `json:"unit_amount_cents"`
	CompareAtCents         int64                  `json:"compare_at_cents,omitempty"`
	Currency               string                 `json:"currency"`
	RecurringInterval      string                 `json:"recurring_interval,omitempty"`
	RecurringIntervalCount int                    `json:"recurring_interval_count,omitempty"`
	UsageType              string                 `json:"usage_type"`
	Active                 bool                   `json:"active"`
	PriceType              string                 `json:"price_type"`
	BillingModel           string                 `json:"billing_model"`
	MinimumQuantity        int                    `json:"minimum_quantity,omitempty"`
	MaximumQuantity        int                    `json:"maximum_quantity,omitempty"`
	TrialPeriodDays        int                    `json:"trial_period_days,omitempty"`
	IncludedUnits          int                    `json:"included_units,omitempty"`
	OverageUnitAmountCents int64                  `json:"overage_unit_amount_cents,omitempty"`
	FeatureLimits          map[string]interface{} `json:"feature_limits,omitempty"`
	DisplayOrder           int                    `json:"display_order"`
	Highlighted            bool                   `json:"highlighted"`
	Tiers                  []PriceTierInfo        `json:"tiers,omitempty"`
	Currencies             []PriceCurrencyInfo    `json:"currencies,omitempty"`
	CreatedAt              string                 `json:"created_at"`
}

BillingPriceInfo represents the BillingPriceInfo type.

type BillingProductInfo

type BillingProductInfo struct {
	ID                string             `json:"id"`
	OrgID             string             `json:"org_id"`
	Slug              string             `json:"slug,omitempty"`
	StripeProductID   string             `json:"stripe_product_id,omitempty"`
	Provider          string             `json:"provider,omitempty"`
	ProviderProductID string             `json:"provider_product_id,omitempty"`
	Name              string             `json:"name"`
	Description       string             `json:"description,omitempty"`
	Tagline           string             `json:"tagline,omitempty"`
	Type              string             `json:"type"`
	Category          string             `json:"category"`
	DeliveryMethod    string             `json:"delivery_method,omitempty"`
	Active            bool               `json:"active"`
	Features          []ProductFeature   `json:"features,omitempty"`
	WhatsIncluded     []string           `json:"whats_included,omitempty"`
	WhoItsFor         []string           `json:"who_its_for,omitempty"`
	TaxCode           string             `json:"tax_code,omitempty"`
	UnitLabel         string             `json:"unit_label,omitempty"`
	Shippable         bool               `json:"shippable"`
	Images            []string           `json:"images,omitempty"`
	InventoryType     string             `json:"inventory_type,omitempty"`
	InventoryCount    int                `json:"inventory_count,omitempty"`
	LowStockThreshold int                `json:"low_stock_threshold,omitempty"`
	DisplayOrder      int                `json:"display_order"`
	Highlighted       bool               `json:"highlighted"`
	CtaText           string             `json:"cta_text,omitempty"`
	Prices            []BillingPriceInfo `json:"prices,omitempty"`
	EmailSequenceID   int64              `json:"email_sequence_id,omitempty"`
	CreatedAt         string             `json:"created_at"`
}

BillingProductInfo represents the BillingProductInfo type.

type BillingResource

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

BillingResource provides access to billing resources.

func (*BillingResource) CancelSubscription

func (r *BillingResource) CancelSubscription(ctx context.Context, id string) (*Response, error)

CancelSubscription

func (*BillingResource) CreateCheckoutSession

func (r *BillingResource) CreateCheckoutSession(ctx context.Context, request *CheckoutRequest) (*CheckoutResponse, error)

CreateCheckoutSession

func (*BillingResource) CreateCustomer

func (r *BillingResource) CreateCustomer(ctx context.Context, request *CustomerRequest) (*CustomerResponse, error)

CreateCustomer

func (*BillingResource) CreateSubscription

func (r *BillingResource) CreateSubscription(ctx context.Context, request *SubscriptionRequest) (*SubscriptionResponse, error)

CreateSubscription

func (*BillingResource) GetCustomerPortal

func (r *BillingResource) GetCustomerPortal(ctx context.Context, request *PortalRequest) (*PortalResponse, error)

GetCustomerPortal

func (*BillingResource) RecordUsage

func (r *BillingResource) RecordUsage(ctx context.Context, request *UsageRequest) (*Response, error)

RecordUsage

type ChatMessage

type ChatMessage struct {
	Role    string `json:"role"` // "user", "assistant", "system"
	Content string `json:"content"`
}

ChatMessage represents a message in a conversation.

type ChatRequest

type ChatRequest struct {
	Messages     []ChatMessage
	SystemPrompt string
	Model        string // "haiku", "sonnet", "opus" or full model ID
	MaxTokens    int32
	Temperature  float32
}

ChatRequest represents an LLM chat request.

type ChatResponse

type ChatResponse struct {
	Content      string
	Model        string
	InputTokens  int64
	OutputTokens int64
	CostUSD      float64
	LatencyMs    int64
	StopReason   string
}

ChatResponse represents an LLM chat response.

type ChatSession

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

ChatSession represents an active chat session for bidirectional streaming.

func (*ChatSession) Abort

func (s *ChatSession) Abort(reason string) error

Abort aborts the current generation.

func (*ChatSession) Close

func (s *ChatSession) Close() error

Close closes the chat session.

func (*ChatSession) Send

func (s *ChatSession) Send(ctx context.Context, content string, callback StreamCallback) (*ChatResponse, error)

Send sends a user message and streams the response.

type CheckoutItem

type CheckoutItem struct {
	PriceID  string `json:"price_id"`
	Quantity int    `json:"quantity"`
}

CheckoutItem represents the CheckoutItem type.

type CheckoutRequest

type CheckoutRequest struct {
	CustomerEmail string         `json:"customer_email"`
	LineItems     []CheckoutItem `json:"line_items"`
	Mode          string         `json:"mode"`
	SuccessUrl    string         `json:"success_url"`
	CancelUrl     string         `json:"cancel_url,omitempty"`
	Embedded      bool           `json:"embedded,omitempty"`
	ReturnUrl     string         `json:"return_url,omitempty"`
}

CheckoutRequest represents the CheckoutRequest type.

type CheckoutResponse

type CheckoutResponse struct {
	SessionID    string `json:"session_id"`
	CheckoutUrl  string `json:"checkout_url,omitempty"`
	ClientSecret string `json:"client_secret,omitempty"`
}

CheckoutResponse represents the CheckoutResponse type.

type Client

type Client struct {

	// Lists provides access to lists resources.
	Lists *ListsResource
	// Orders provides access to orders resources.
	Orders *OrdersResource
	// Auth provides access to auth resources.
	Auth *AuthResource
	// Emails provides access to emails resources.
	Emails *EmailsResource
	// Stats provides access to stats resources.
	Stats *StatsResource
	// Team provides access to team resources.
	Team *TeamResource
	// Webhooks provides access to webhooks resources.
	Webhooks *WebhooksResource
	// Workshops provides access to workshops resources.
	Workshops *WorkshopsResource
	// Billing provides access to billing resources.
	Billing *BillingResource
	// Customers provides access to customers resources.
	Customers *CustomersResource
	// Sequences provides access to sequences resources.
	Sequences *SequencesResource
	// Site provides access to site resources.
	Site *SiteResource
	// Events provides access to events resources.
	Events *EventsResource
	// Offers provides access to offers resources.
	Offers *OffersResource
	// Products provides access to products resources.
	Products *ProductsResource
	// Quizzes provides access to quizzes resources.
	Quizzes *QuizzesResource
	// Content provides access to content resources.
	Content *ContentResource
	// Tracking provides access to tracking resources.
	Tracking *TrackingResource
	// Contacts provides access to contacts resources.
	Contacts *ContactsResource
	// Funnels provides access to funnels resources.
	Funnels *FunnelsResource
	// Llm provides access to llm resources.
	Llm *LlmResource
	// contains filtered or unexported fields
}

Client is the Levee API client.

func NewClient

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

NewClient creates a new Levee API client. baseURL is required - this is a self-hosted system, use your Levee instance URL.

func (*Client) ConfirmEmail

func (c *Client) ConfirmEmail(ctx context.Context, token string) (*ConfirmEmailResponse, error)

ConfirmEmail confirms an email subscription (double opt-in).

func (*Client) ForwardSESWebhook

func (c *Client) ForwardSESWebhook(ctx context.Context, payload []byte) error

ForwardSESWebhook forwards an SES webhook payload to Levee.

func (*Client) ForwardStripeWebhook

func (c *Client) ForwardStripeWebhook(ctx context.Context, payload []byte, signature string) error

ForwardStripeWebhook forwards a Stripe webhook payload to Levee.

func (*Client) HandleChatWebSocket

func (c *Client) HandleChatWebSocket(llm *LLMClient, opts ...WSOption) http.HandlerFunc

HandleChatWebSocket returns a handler for WebSocket LLM chat. This bridges WebSocket connections to the gRPC LLM stream. Route: GET /your-prefix/ws/chat (upgrades to WebSocket)

func (*Client) HandleClickTracking

func (c *Client) HandleClickTracking(cfg *HandlerConfig) http.HandlerFunc

HandleClickTracking returns a handler for email click tracking. Records the click and redirects to the destination URL. Route: GET /your-prefix/e/c/:token?url=...

func (*Client) HandleConfirmEmail

func (c *Client) HandleConfirmEmail(cfg *HandlerConfig) http.HandlerFunc

HandleConfirmEmail returns a handler for double opt-in email confirmation. Route: GET /your-prefix/confirm-email?token=...

func (*Client) HandleOpenTracking

func (c *Client) HandleOpenTracking(cfg *HandlerConfig) http.HandlerFunc

HandleOpenTracking returns a handler for email open tracking. Serves a 1x1 transparent GIF and records the open event. Route: GET /your-prefix/e/o/:token

func (*Client) HandleSESWebhook

func (c *Client) HandleSESWebhook(cfg *HandlerConfig) http.HandlerFunc

HandleSESWebhook returns a handler for AWS SES bounce/complaint notifications. Handles SNS subscription confirmation and forwards events to Levee API. Route: POST /your-prefix/webhooks/ses

func (*Client) HandleStripeWebhook

func (c *Client) HandleStripeWebhook(cfg *HandlerConfig) http.HandlerFunc

HandleStripeWebhook returns a handler for Stripe webhook events. Verifies signature and forwards to Levee API. Route: POST /your-prefix/webhooks/stripe

func (*Client) HandleUnsubscribe

func (c *Client) HandleUnsubscribe(cfg *HandlerConfig) http.HandlerFunc

HandleUnsubscribe returns a handler for one-click unsubscribe. Records the unsubscribe and redirects to the configured URL. Route: GET /your-prefix/e/u/:token

func (*Client) RecordClick

func (c *Client) RecordClick(ctx context.Context, token, url string) error

RecordClick records an email click event.

func (*Client) RecordOpen

func (c *Client) RecordOpen(ctx context.Context, token string) error

RecordOpen records an email open event.

func (*Client) RecordUnsubscribe

func (c *Client) RecordUnsubscribe(ctx context.Context, token string) error

RecordUnsubscribe records an unsubscribe event.

func (*Client) RegisterHandlers

func (c *Client) RegisterHandlers(mux *http.ServeMux, prefix string, opts ...HandlerOption)

RegisterHandlers registers all Levee HTTP handlers on the given mux with the specified prefix. Example: client.RegisterHandlers(mux, "/levee") registers handlers at /levee/e/o/:token, etc.

type ClientOption

type ClientOption func(*Client)

ClientOption is a function that configures the Client.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client.

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets the timeout for HTTP requests.

type ConfirmEmailResponse

type ConfirmEmailResponse struct {
	Success     bool   `json:"success"`
	Message     string `json:"message,omitempty"`
	RedirectURL string `json:"redirect_url,omitempty"`
}

ConfirmEmailResponse is the response from confirming an email.

type ContactActivityInfo

type ContactActivityInfo struct {
	Event     string `json:"event"`
	Timestamp string `json:"timestamp"`
	Details   string `json:"details,omitempty"`
}

ContactActivityInfo represents the ContactActivityInfo type.

type ContactRequest

type ContactRequest struct {
	Email       string            `json:"email"`
	Name        string            `json:"name,omitempty"`
	Phone       string            `json:"phone,omitempty"`
	Company     string            `json:"company,omitempty"`
	Employees   string            `json:"employees,omitempty"`
	Message     string            `json:"message,omitempty"`
	Source      string            `json:"source,omitempty"`
	Tags        []string          `json:"tags,omitempty"`
	FunnelSlug  string            `json:"funnel_slug,omitempty"`
	ListSlug    string            `json:"list_slug,omitempty"`
	Score       bool              `json:"score,omitempty"`
	UtmSource   string            `json:"utm_source,omitempty"`
	UtmMedium   string            `json:"utm_medium,omitempty"`
	UtmCampaign string            `json:"utm_campaign,omitempty"`
	Meta        map[string]string `json:"meta,omitempty"`
}

ContactRequest represents the ContactRequest type.

type ContactResponse

type ContactResponse struct {
	ID        string `json:"id"`
	Email     string `json:"email"`
	Name      string `json:"name"`
	Score     int    `json:"score,omitempty"`
	Qualified bool   `json:"qualified,omitempty"`
	Reasoning string `json:"reasoning,omitempty"`
	NextSteps string `json:"next_steps,omitempty"`
}

ContactResponse represents the ContactResponse type.

type ContactStatsPoint

type ContactStatsPoint struct {
	Date         string `json:"date"`
	NewContacts  int    `json:"new_contacts"`
	Unsubscribed int    `json:"unsubscribed"`
	Bounced      int    `json:"bounced"`
	NetGrowth    int    `json:"net_growth"`
}

ContactStatsPoint represents the ContactStatsPoint type.

type ContactsResource

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

ContactsResource provides access to contacts resources.

func (*ContactsResource) AddContactTags

func (r *ContactsResource) AddContactTags(ctx context.Context, id string, request *AddContactTagsRequest) (*Response, error)

AddContactTags

func (*ContactsResource) CreateContact

func (r *ContactsResource) CreateContact(ctx context.Context, request *ContactRequest) (*ContactResponse, error)

CreateContact

func (*ContactsResource) GetContact

func (r *ContactsResource) GetContact(ctx context.Context, id string) (*SDKContactInfo, error)

GetContact

func (*ContactsResource) GlobalUnsubscribe

func (r *ContactsResource) GlobalUnsubscribe(ctx context.Context, request *GlobalUnsubscribeRequest) (*Response, error)

GlobalUnsubscribe

func (*ContactsResource) ListContactActivity

func (r *ContactsResource) ListContactActivity(ctx context.Context, id string, limit int) (*ListContactActivityResponse, error)

ListContactActivity

func (*ContactsResource) RemoveContactTags

func (r *ContactsResource) RemoveContactTags(ctx context.Context, id string, request *RemoveContactTagsRequest) (*Response, error)

RemoveContactTags

func (*ContactsResource) UpdateContact

func (r *ContactsResource) UpdateContact(ctx context.Context, id string, request *UpdateContactRequest) (*SDKContactInfo, error)

UpdateContact

type ContentResource

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

ContentResource provides access to content resources.

func (*ContentResource) GetContentPage

func (r *ContentResource) GetContentPage(ctx context.Context, slug string) (*SDKContentPageInfo, error)

GetContentPage

func (*ContentResource) GetContentPost

func (r *ContentResource) GetContentPost(ctx context.Context, slug string) (*SDKContentPostInfo, error)

GetContentPost

func (*ContentResource) ListContentCategories

func (r *ContentResource) ListContentCategories(ctx context.Context) (*ListSDKContentCategoriesResponse, error)

ListContentCategories

func (*ContentResource) ListContentPages

func (r *ContentResource) ListContentPages(ctx context.Context, page int, pageSize int) (*ListSDKContentPagesResponse, error)

ListContentPages

func (*ContentResource) ListContentPosts

func (r *ContentResource) ListContentPosts(ctx context.Context, page int, pageSize int, categorySlug string) (*ListSDKContentPostsResponse, error)

ListContentPosts

type CustomerRequest

type CustomerRequest struct {
	Email string            `json:"email"`
	Name  string            `json:"name,omitempty"`
	Phone string            `json:"phone,omitempty"`
	Meta  map[string]string `json:"meta,omitempty"`
}

CustomerRequest represents the CustomerRequest type.

type CustomerResponse

type CustomerResponse struct {
	ID               string `json:"id"`
	StripeCustomerID string `json:"stripe_customer_id"`
	Email            string `json:"email"`
	Name             string `json:"name"`
}

CustomerResponse represents the CustomerResponse type.

type CustomersResource

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

CustomersResource provides access to customers resources.

func (*CustomersResource) DeleteCustomer

func (r *CustomersResource) DeleteCustomer(ctx context.Context, id string) (*Response, error)

DeleteCustomer

func (*CustomersResource) GetCustomerByEmail

func (r *CustomersResource) GetCustomerByEmail(ctx context.Context, email string) (*SDKCustomerInfo, error)

GetCustomerByEmail

func (*CustomersResource) GetCustomerById

func (r *CustomersResource) GetCustomerById(ctx context.Context, id string) (*SDKCustomerInfo, error)

GetCustomerById

func (*CustomersResource) ListCustomerInvoices

func (r *CustomersResource) ListCustomerInvoices(ctx context.Context, email string, limit int) (*ListCustomerInvoicesResponse, error)

ListCustomerInvoices

func (*CustomersResource) ListCustomerInvoicesById

func (r *CustomersResource) ListCustomerInvoicesById(ctx context.Context, id string, limit int) (*ListCustomerInvoicesResponse, error)

ListCustomerInvoicesById

func (*CustomersResource) ListCustomerOrders

func (r *CustomersResource) ListCustomerOrders(ctx context.Context, email string, limit int) (*ListCustomerOrdersResponse, error)

ListCustomerOrders

func (*CustomersResource) ListCustomerOrdersById

func (r *CustomersResource) ListCustomerOrdersById(ctx context.Context, id string, limit int) (*ListCustomerOrdersResponse, error)

ListCustomerOrdersById

func (*CustomersResource) ListCustomerPayments

func (r *CustomersResource) ListCustomerPayments(ctx context.Context, email string, limit int) (*ListCustomerPaymentsResponse, error)

ListCustomerPayments

func (*CustomersResource) ListCustomerPaymentsById

func (r *CustomersResource) ListCustomerPaymentsById(ctx context.Context, id string, limit int) (*ListCustomerPaymentsResponse, error)

ListCustomerPaymentsById

func (*CustomersResource) ListCustomerSubscriptions

func (r *CustomersResource) ListCustomerSubscriptions(ctx context.Context, email string) (*ListCustomerSubscriptionsResponse, error)

ListCustomerSubscriptions

func (*CustomersResource) ListCustomerSubscriptionsById

func (r *CustomersResource) ListCustomerSubscriptionsById(ctx context.Context, id string) (*ListCustomerSubscriptionsResponse, error)

ListCustomerSubscriptionsById

func (*CustomersResource) UpdateCustomer

func (r *CustomersResource) UpdateCustomer(ctx context.Context, id string, request *SDKUpdateCustomerRequest) (*SDKCustomerInfo, error)

UpdateCustomer

type EmailEventInfo

type EmailEventInfo struct {
	Event     string `json:"event"`
	Timestamp string `json:"timestamp"`
	Data      string `json:"data,omitempty"`
}

EmailEventInfo represents the EmailEventInfo type.

type EmailStatsPoint

type EmailStatsPoint struct {
	Date      string  `json:"date"`
	Sent      int     `json:"sent"`
	Delivered int     `json:"delivered"`
	Opened    int     `json:"opened"`
	Clicked   int     `json:"clicked"`
	Bounced   int     `json:"bounced"`
	OpenRate  float64 `json:"open_rate"`
	ClickRate float64 `json:"click_rate"`
}

EmailStatsPoint represents the EmailStatsPoint type.

type EmailStatusResponse

type EmailStatusResponse struct {
	MessageID   string `json:"message_id"`
	To          string `json:"to"`
	Subject     string `json:"subject"`
	Status      string `json:"status"`
	SentAt      string `json:"sent_at,omitempty"`
	DeliveredAt string `json:"delivered_at,omitempty"`
	OpenedAt    string `json:"opened_at,omitempty"`
	ClickedAt   string `json:"clicked_at,omitempty"`
	BouncedAt   string `json:"bounced_at,omitempty"`
	BounceType  string `json:"bounce_type,omitempty"`
	Opens       int    `json:"opens"`
	Clicks      int    `json:"clicks"`
}

EmailStatusResponse represents the EmailStatusResponse type.

type EmailsResource

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

EmailsResource provides access to emails resources.

func (*EmailsResource) GetEmailStatus

func (r *EmailsResource) GetEmailStatus(ctx context.Context, messageId string) (*EmailStatusResponse, error)

GetEmailStatus

func (*EmailsResource) ListEmailEvents

func (r *EmailsResource) ListEmailEvents(ctx context.Context, messageId string) (*ListEmailEventsResponse, error)

ListEmailEvents

func (*EmailsResource) SendEmail

func (r *EmailsResource) SendEmail(ctx context.Context, request *SendEmailRequest) (*SendEmailResponse, error)

SendEmail

type EnrollSequenceRequest

type EnrollSequenceRequest struct {
	SequenceSlug string            `json:"sequence_slug"`
	Email        string            `json:"email"`
	Variables    map[string]string `json:"variables,omitempty"`
	StartAtStep  int               `json:"start_at_step,omitempty"`
	ScheduledFor string            `json:"scheduled_for,omitempty"`
}

EnrollSequenceRequest represents the EnrollSequenceRequest type.

type EnrollSequenceResponse

type EnrollSequenceResponse struct {
	Success      bool   `json:"success"`
	EnrollmentID string `json:"enrollment_id"`
	Status       string `json:"status"`
	Message      string `json:"message,omitempty"`
}

EnrollSequenceResponse represents the EnrollSequenceResponse type.

type EventRequest

type EventRequest struct {
	Event       string                 `json:"event"`
	Email       string                 `json:"email,omitempty"`
	VisitorID   string                 `json:"visitor_id,omitempty"`
	SessionID   string                 `json:"session_id,omitempty"`
	Page        string                 `json:"page,omitempty"`
	Referrer    string                 `json:"referrer,omitempty"`
	FunnelSlug  string                 `json:"funnel_slug,omitempty"`
	FunnelStep  string                 `json:"funnel_step,omitempty"`
	ScrollDepth int                    `json:"scroll_depth,omitempty"`
	Properties  map[string]interface{} `json:"properties,omitempty"`
	UtmSource   string                 `json:"utm_source,omitempty"`
	UtmMedium   string                 `json:"utm_medium,omitempty"`
	UtmCampaign string                 `json:"utm_campaign,omitempty"`
}

EventRequest represents the EventRequest type.

type EventsResource

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

EventsResource provides access to events resources.

func (*EventsResource) TrackEvent

func (r *EventsResource) TrackEvent(ctx context.Context, request *EventRequest) (*Response, error)

TrackEvent

type FunnelStepInfo

type FunnelStepInfo struct {
	ID                   int64                  `json:"id"`
	FunnelID             int64                  `json:"funnel_id"`
	FunnelSlug           string                 `json:"funnel_slug,omitempty"`
	Slug                 string                 `json:"slug"`
	StepType             string                 `json:"step_type"`
	Position             int                    `json:"position"`
	Title                string                 `json:"title"`
	Headline             string                 `json:"headline,omitempty"`
	Subheadline          string                 `json:"subheadline,omitempty"`
	Content              map[string]interface{} `json:"content,omitempty"`
	ProductID            string                 `json:"product_id,omitempty"`
	Product              BillingProductInfo     `json:"product,omitempty"`
	OrderBumpProductID   string                 `json:"order_bump_product_id,omitempty"`
	OrderBumpProduct     BillingProductInfo     `json:"order_bump_product,omitempty"`
	OrderBumpHeadline    string                 `json:"order_bump_headline,omitempty"`
	OrderBumpDescription string                 `json:"order_bump_description,omitempty"`
	NextStepID           int64                  `json:"next_step_id,omitempty"`
	DeclineStepID        int64                  `json:"decline_step_id,omitempty"`
	SuccessRedirect      string                 `json:"success_redirect,omitempty"`
	EmailSequenceID      int64                  `json:"email_sequence_id,omitempty"`
	TriggerEvent         string                 `json:"trigger_event,omitempty"`
	IsActive             bool                   `json:"is_active"`
	CreatedAt            string                 `json:"created_at"`
}

FunnelStepInfo represents the FunnelStepInfo type.

type FunnelsResource

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

FunnelsResource provides access to funnels resources.

func (*FunnelsResource) GetFunnelStep

func (r *FunnelsResource) GetFunnelStep(ctx context.Context, slug string) (*FunnelStepInfo, error)

GetFunnelStep

type GetContactStatsResponse

type GetContactStatsResponse struct {
	Stats             []ContactStatsPoint `json:"stats"`
	TotalActive       int                 `json:"total_active"`
	TotalUnsubscribed int                 `json:"total_unsubscribed"`
	TotalBounced      int                 `json:"total_bounced"`
	NetGrowth         int                 `json:"net_growth"`
}

GetContactStatsResponse represents the GetContactStatsResponse type.

type GetEmailStatsResponse

type GetEmailStatsResponse struct {
	Stats          []EmailStatsPoint `json:"stats"`
	TotalSent      int               `json:"total_sent"`
	TotalDelivered int               `json:"total_delivered"`
	TotalOpened    int               `json:"total_opened"`
	TotalClicked   int               `json:"total_clicked"`
	TotalBounced   int               `json:"total_bounced"`
	AvgOpenRate    float64           `json:"avg_open_rate"`
	AvgClickRate   float64           `json:"avg_click_rate"`
}

GetEmailStatsResponse represents the GetEmailStatsResponse type.

type GetRevenueStatsResponse

type GetRevenueStatsResponse struct {
	Stats              []RevenueStatsPoint `json:"stats"`
	TotalRevenue       int64               `json:"total_revenue"`
	TotalOrders        int                 `json:"total_orders"`
	TotalSubscriptions int                 `json:"total_subscriptions"`
	TotalChurned       int                 `json:"total_churned"`
	Mrr                int64               `json:"mrr"`
}

GetRevenueStatsResponse represents the GetRevenueStatsResponse type.

type GlobalUnsubscribeRequest

type GlobalUnsubscribeRequest struct {
	Email  string `json:"email"`
	Reason string `json:"reason,omitempty"`
}

GlobalUnsubscribeRequest represents the GlobalUnsubscribeRequest type.

type HandlerConfig

type HandlerConfig struct {
	// UnsubscribeRedirect is the URL to redirect to after unsubscribe (default: /unsubscribed)
	UnsubscribeRedirect string
	// ConfirmRedirect is the URL to redirect to after email confirmation (default: /confirmed)
	ConfirmRedirect string
	// ConfirmExpiredRedirect is the URL to redirect to if confirmation token expired (default: /confirm-expired)
	ConfirmExpiredRedirect string
	// StripeWebhookSecret is the Stripe webhook signing secret for signature verification
	StripeWebhookSecret string
	// LLMClient is the optional LLM client for WebSocket chat handler
	LLMClient *LLMClient
	// WSCheckOrigin is the origin checker for WebSocket connections (nil allows all)
	WSCheckOrigin func(r *http.Request) bool
}

HandlerConfig configures the embedded HTTP handlers.

func NewHandlerConfig

func NewHandlerConfig(opts ...HandlerOption) *HandlerConfig

NewHandlerConfig creates a new HandlerConfig with the given options. Use this when registering handlers individually with custom routers.

type HandlerOption

type HandlerOption func(*HandlerConfig)

HandlerOption is a functional option for configuring handlers.

func WithConfirmExpiredRedirect

func WithConfirmExpiredRedirect(url string) HandlerOption

WithConfirmExpiredRedirect sets the redirect URL for expired confirmation tokens.

func WithConfirmRedirect

func WithConfirmRedirect(url string) HandlerOption

WithConfirmRedirect sets the redirect URL after email confirmation.

func WithLLMClient

func WithLLMClient(llm *LLMClient) HandlerOption

WithLLMClient sets the LLM client for WebSocket chat handler.

func WithStripeWebhookSecret

func WithStripeWebhookSecret(secret string) HandlerOption

WithStripeWebhookSecret sets the Stripe webhook signing secret.

func WithUnsubscribeRedirect

func WithUnsubscribeRedirect(url string) HandlerOption

WithUnsubscribeRedirect sets the redirect URL after unsubscribe.

func WithWSCheckOrigin

func WithWSCheckOrigin(fn func(r *http.Request) bool) HandlerOption

WithWSCheckOrigin sets the origin checker for WebSocket connections.

type LLMChatRequest

type LLMChatRequest struct {
	Messages     []LLMMessage `json:"messages"`
	SystemPrompt string       `json:"system_prompt,omitempty"`
	Model        string       `json:"model,omitempty"`
	MaxTokens    int          `json:"max_tokens,omitempty"`
	Temperature  float64      `json:"temperature,omitempty"`
}

LLMChatRequest represents the LLMChatRequest type.

type LLMChatResponse

type LLMChatResponse struct {
	Content      string  `json:"content"`
	Model        string  `json:"model"`
	InputTokens  int64   `json:"input_tokens"`
	OutputTokens int64   `json:"output_tokens"`
	CostUsd      float64 `json:"cost_usd"`
	LatencyMs    int64   `json:"latency_ms"`
	StopReason   string  `json:"stop_reason"`
}

LLMChatResponse represents the LLMChatResponse type.

type LLMClient

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

LLMClient provides access to the Levee LLM gateway.

func NewLLMClient

func NewLLMClient(apiKey string, baseURL string, opts ...LLMOption) *LLMClient

NewLLMClient creates a new LLM client.

baseURL is the Levee API URL (e.g., "https://levee.example.com"). TLS is automatically determined from the URL scheme:

  • https:// → TLS enabled
  • http:// → plaintext (development only)

The gRPC port is auto-discovered from /sdk/v1/llm/config unless explicitly set with WithGRPCAddress.

func (*LLMClient) Chat

func (c *LLMClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse, error)

Chat sends a simple (non-streaming) chat request.

func (*LLMClient) ChatStream

func (c *LLMClient) ChatStream(ctx context.Context, req ChatRequest, callback StreamCallback) (*ChatResponse, error)

ChatStream sends a message and streams the response via callback. This is a convenience method for simple streaming use cases.

func (*LLMClient) Close

func (c *LLMClient) Close() error

Close closes the gRPC connection.

func (*LLMClient) NewChatSession

func (c *LLMClient) NewChatSession(ctx context.Context, req ChatRequest) (*ChatSession, error)

NewChatSession starts a new bidirectional chat session.

type LLMConfigResponse

type LLMConfigResponse struct {
	Available           bool     `json:"available"`
	DefaultProvider     string   `json:"default_provider"`
	ConfiguredProviders []string `json:"configured_providers"`
	GrpcPort            int      `json:"grpc_port"`
}

LLMConfigResponse represents the LLMConfigResponse type.

type LLMMessage

type LLMMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

LLMMessage represents the LLMMessage type.

type LLMOption

type LLMOption func(*LLMClient)

LLMOption is a functional option for configuring the LLM client.

func WithGRPCAddress

func WithGRPCAddress(addr string) LLMOption

WithGRPCAddress sets the gRPC server address explicitly (host:port). If not set, the address will be auto-discovered from the config endpoint.

func WithLLMHTTPClient

func WithLLMHTTPClient(client *http.Client) LLMOption

WithLLMHTTPClient sets a custom HTTP client for config API calls.

type ListContactActivityResponse

type ListContactActivityResponse struct {
	Activities []ContactActivityInfo `json:"activities"`
}

ListContactActivityResponse represents the ListContactActivityResponse type.

type ListCustomerInvoicesResponse

type ListCustomerInvoicesResponse struct {
	Invoices []SDKInvoiceInfo `json:"invoices"`
	Total    int              `json:"total"`
}

ListCustomerInvoicesResponse represents the ListCustomerInvoicesResponse type.

type ListCustomerOrdersResponse

type ListCustomerOrdersResponse struct {
	Orders []SDKOrderInfo `json:"orders"`
	Total  int            `json:"total"`
}

ListCustomerOrdersResponse represents the ListCustomerOrdersResponse type.

type ListCustomerPaymentsResponse

type ListCustomerPaymentsResponse struct {
	Payments []SDKPaymentInfo `json:"payments"`
	Total    int              `json:"total"`
}

ListCustomerPaymentsResponse represents the ListCustomerPaymentsResponse type.

type ListCustomerSubscriptionsResponse

type ListCustomerSubscriptionsResponse struct {
	Subscriptions []SDKSubscriptionInfo `json:"subscriptions"`
}

ListCustomerSubscriptionsResponse represents the ListCustomerSubscriptionsResponse type.

type ListEmailEventsResponse

type ListEmailEventsResponse struct {
	Events []EmailEventInfo `json:"events"`
}

ListEmailEventsResponse represents the ListEmailEventsResponse type.

type ListSDKAuthorsResponse

type ListSDKAuthorsResponse struct {
	Authors []SDKAuthorInfo `json:"authors"`
}

ListSDKAuthorsResponse represents the ListSDKAuthorsResponse type.

type ListSDKContentCategoriesResponse

type ListSDKContentCategoriesResponse struct {
	Categories []SDKContentCategoryInfo `json:"categories"`
}

ListSDKContentCategoriesResponse represents the ListSDKContentCategoriesResponse type.

type ListSDKContentPagesResponse

type ListSDKContentPagesResponse struct {
	Pages []SDKContentPageInfo `json:"pages"`
	Total int                  `json:"total"`
}

ListSDKContentPagesResponse represents the ListSDKContentPagesResponse type.

type ListSDKContentPostsResponse

type ListSDKContentPostsResponse struct {
	Posts []SDKContentPostInfo `json:"posts"`
	Total int                  `json:"total"`
}

ListSDKContentPostsResponse represents the ListSDKContentPostsResponse type.

type ListSDKNavigationMenusResponse

type ListSDKNavigationMenusResponse struct {
	Menus []SDKNavigationMenu `json:"menus"`
}

ListSDKNavigationMenusResponse represents the ListSDKNavigationMenusResponse type.

type ListSequenceEnrollmentsResponse

type ListSequenceEnrollmentsResponse struct {
	Enrollments []SequenceEnrollmentInfo `json:"enrollments"`
}

ListSequenceEnrollmentsResponse represents the ListSequenceEnrollmentsResponse type.

type ListWebhookLogsResponse

type ListWebhookLogsResponse struct {
	Logs []WebhookLogInfo `json:"logs"`
}

ListWebhookLogsResponse represents the ListWebhookLogsResponse type.

type ListWebhooksResponse

type ListWebhooksResponse struct {
	Webhooks []WebhookInfo `json:"webhooks"`
}

ListWebhooksResponse represents the ListWebhooksResponse type.

type ListsResource

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

ListsResource provides access to lists resources.

func (*ListsResource) SubscribeToList

func (r *ListsResource) SubscribeToList(ctx context.Context, slug string, request *SubscribeRequest) (*Response, error)

SubscribeToList

func (*ListsResource) UnsubscribeFromList

func (r *ListsResource) UnsubscribeFromList(ctx context.Context, slug string, request *SubscribeRequest) (*Response, error)

UnsubscribeFromList

type LlmResource

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

LlmResource provides access to llm resources.

func (*LlmResource) Chat

func (r *LlmResource) Chat(ctx context.Context, request *LLMChatRequest) (*LLMChatResponse, error)

Chat

func (*LlmResource) Config

func (r *LlmResource) Config(ctx context.Context) (*LLMConfigResponse, error)

Config

type OfferRequest

type OfferRequest struct {
	SessionID string `json:"session_id"`
	StepSlug  string `json:"step_slug"`
	Accept    bool   `json:"accept"`
}

OfferRequest represents the OfferRequest type.

type OfferResponse

type OfferResponse struct {
	Success     bool   `json:"success"`
	NextUrl     string `json:"next_url,omitempty"`
	OrderItemID int64  `json:"order_item_id,omitempty"`
	Message     string `json:"message,omitempty"`
}

OfferResponse represents the OfferResponse type.

type OffersResource

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

OffersResource provides access to offers resources.

func (*OffersResource) ProcessOffer

func (r *OffersResource) ProcessOffer(ctx context.Context, request *OfferRequest) (*OfferResponse, error)

ProcessOffer

type OrderRequest

type OrderRequest struct {
	Email          string            `json:"email"`
	Name           string            `json:"name,omitempty"`
	Company        string            `json:"company,omitempty"`
	ProductSlug    string            `json:"product_slug,omitempty"`
	FunnelStepSlug string            `json:"funnel_step_slug,omitempty"`
	WorkshopID     int64             `json:"workshop_id,omitempty"`
	IncludeBump    bool              `json:"include_bump,omitempty"`
	AmountCents    int64             `json:"amount_cents,omitempty"`
	Currency       string            `json:"currency,omitempty"`
	SuccessUrl     string            `json:"success_url,omitempty"`
	CancelUrl      string            `json:"cancel_url,omitempty"`
	Meta           map[string]string `json:"meta,omitempty"`
}

OrderRequest represents the OrderRequest type.

type OrderResponse

type OrderResponse struct {
	Success     bool   `json:"success"`
	OrderID     string `json:"order_id,omitempty"`
	OrderNumber string `json:"order_number,omitempty"`
	CheckoutUrl string `json:"checkout_url,omitempty"`
	SessionID   string `json:"session_id,omitempty"`
	Message     string `json:"message,omitempty"`
}

OrderResponse represents the OrderResponse type.

type OrdersResource

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

OrdersResource provides access to orders resources.

func (*OrdersResource) CreateOrder

func (r *OrdersResource) CreateOrder(ctx context.Context, request *OrderRequest) (*OrderResponse, error)

CreateOrder

type OrgMember

type OrgMember struct {
	ID        string `json:"id"`
	Email     string `json:"email"`
	Name      string `json:"name"`
	AvatarUrl string `json:"avatar_url,omitempty"`
	Role      string `json:"role"`
	JoinedAt  string `json:"joined_at"`
}

OrgMember represents the OrgMember type.

type OrgMembersResponse

type OrgMembersResponse struct {
	Members        []OrgMember     `json:"members"`
	PendingInvites []PendingInvite `json:"pending_invites"`
	Total          int             `json:"total"`
}

OrgMembersResponse represents the OrgMembersResponse type.

type PauseSequenceRequest

type PauseSequenceRequest struct {
	Email        string `json:"email"`
	SequenceSlug string `json:"sequence_slug"`
}

PauseSequenceRequest represents the PauseSequenceRequest type.

type PendingInvite

type PendingInvite struct {
	Email     string `json:"email"`
	Name      string `json:"name"`
	Role      string `json:"role"`
	InvitedAt string `json:"invited_at"`
	ExpiresAt string `json:"expires_at"`
}

PendingInvite represents the PendingInvite type.

type PortalRequest

type PortalRequest struct {
	CustomerID string `json:"customer_id"`
	ReturnUrl  string `json:"return_url"`
}

PortalRequest represents the PortalRequest type.

type PortalResponse

type PortalResponse struct {
	PortalUrl string `json:"portal_url"`
}

PortalResponse represents the PortalResponse type.

type PriceCurrencyInfo

type PriceCurrencyInfo struct {
	ID              string `json:"id"`
	PriceID         string `json:"price_id"`
	Currency        string `json:"currency"`
	UnitAmountCents int64  `json:"unit_amount_cents"`
	CompareAtCents  int64  `json:"compare_at_cents,omitempty"`
	CreatedAt       string `json:"created_at"`
}

PriceCurrencyInfo represents the PriceCurrencyInfo type.

type PriceTierInfo

type PriceTierInfo struct {
	ID              string `json:"id"`
	PriceID         string `json:"price_id"`
	TierType        string `json:"tier_type"`
	UpTo            int    `json:"up_to,omitempty"`
	UnitAmountCents int64  `json:"unit_amount_cents"`
	FlatAmountCents int64  `json:"flat_amount_cents"`
	CreatedAt       string `json:"created_at"`
}

PriceTierInfo represents the PriceTierInfo type.

type ProductFeature

type ProductFeature struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Included    bool   `json:"included"`
}

ProductFeature represents the ProductFeature type.

type ProductsResource

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

ProductsResource provides access to products resources.

func (*ProductsResource) GetProduct

func (r *ProductsResource) GetProduct(ctx context.Context, slug string) (*BillingProductInfo, error)

GetProduct

type QuizInfo

type QuizInfo struct {
	Slug        string         `json:"slug"`
	Title       string         `json:"title"`
	Description string         `json:"description,omitempty"`
	Questions   []QuizQuestion `json:"questions"`
}

QuizInfo represents the QuizInfo type.

type QuizOption

type QuizOption struct {
	ID       string   `json:"id"`
	Label    string   `json:"label"`
	Value    string   `json:"value"`
	Segments []string `json:"segments,omitempty"`
}

QuizOption represents the QuizOption type.

type QuizQuestion

type QuizQuestion struct {
	ID       string       `json:"id"`
	Question string       `json:"question"`
	Type     string       `json:"type"`
	Options  []QuizOption `json:"options,omitempty"`
	Required bool         `json:"required"`
}

QuizQuestion represents the QuizQuestion type.

type QuizSubmitRequest

type QuizSubmitRequest struct {
	QuizSlug string            `json:"quiz_slug"`
	Answers  map[string]string `json:"answers"`
	Name     string            `json:"name,omitempty"`
	Email    string            `json:"email,omitempty"`
}

QuizSubmitRequest represents the QuizSubmitRequest type.

type QuizSubmitResponse

type QuizSubmitResponse struct {
	Success     bool     `json:"success"`
	Segments    []string `json:"segments"`
	RedirectUrl string   `json:"redirect_url,omitempty"`
	LeadID      string   `json:"lead_id,omitempty"`
}

QuizSubmitResponse represents the QuizSubmitResponse type.

type QuizzesResource

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

QuizzesResource provides access to quizzes resources.

func (*QuizzesResource) GetQuiz

func (r *QuizzesResource) GetQuiz(ctx context.Context, slug string) (*QuizInfo, error)

GetQuiz

func (*QuizzesResource) SubmitQuiz

func (r *QuizzesResource) SubmitQuiz(ctx context.Context, slug string, request *QuizSubmitRequest) (*QuizSubmitResponse, error)

SubmitQuiz

type RegisterWebhookRequest

type RegisterWebhookRequest struct {
	Url    string   `json:"url"`
	Events []string `json:"events"`
	Secret string   `json:"secret,omitempty"`
	Active bool     `json:"active,omitempty"`
}

RegisterWebhookRequest represents the RegisterWebhookRequest type.

type RegisterWebhookResponse

type RegisterWebhookResponse struct {
	Success   bool   `json:"success"`
	WebhookID string `json:"webhook_id"`
	Secret    string `json:"secret"`
	Message   string `json:"message,omitempty"`
}

RegisterWebhookResponse represents the RegisterWebhookResponse type.

type RemoveContactTagsRequest

type RemoveContactTagsRequest struct {
	Tags []string `json:"tags"`
}

RemoveContactTagsRequest represents the RemoveContactTagsRequest type.

type Response

type Response struct {
	Success bool   `json:"success"`
	Message string `json:"message,omitempty"`
}

Response represents the Response type.

type ResumeSequenceRequest

type ResumeSequenceRequest struct {
	Email        string `json:"email"`
	SequenceSlug string `json:"sequence_slug"`
}

ResumeSequenceRequest represents the ResumeSequenceRequest type.

type RevenueStatsPoint

type RevenueStatsPoint struct {
	Date             string `json:"date"`
	Revenue          int64  `json:"revenue"`
	OrderCount       int    `json:"order_count"`
	NewSubscriptions int    `json:"new_subscriptions"`
	Churned          int    `json:"churned"`
}

RevenueStatsPoint represents the RevenueStatsPoint type.

type SDKAuthCustomerInfo

type SDKAuthCustomerInfo struct {
	ID            string `json:"id"`
	Email         string `json:"email"`
	Name          string `json:"name,omitempty"`
	EmailVerified bool   `json:"email_verified"`
	CreatedAt     string `json:"created_at"`
	Role          string `json:"role,omitempty"`
	OrgID         string `json:"org_id,omitempty"`
}

SDKAuthCustomerInfo represents the SDKAuthCustomerInfo type.

type SDKAuthResponse

type SDKAuthResponse struct {
	Token        string              `json:"token"`
	RefreshToken string              `json:"refresh_token"`
	ExpiresAt    string              `json:"expires_at"`
	Customer     SDKAuthCustomerInfo `json:"customer"`
	CheckoutUrl  string              `json:"checkout_url,omitempty"`
}

SDKAuthResponse represents the SDKAuthResponse type.

type SDKAuthorInfo

type SDKAuthorInfo struct {
	ID            string `json:"id"`
	DisplayName   string `json:"display_name"`
	Bio           string `json:"bio,omitempty"`
	AvatarUrl     string `json:"avatar_url,omitempty"`
	WebsiteUrl    string `json:"website_url,omitempty"`
	TwitterHandle string `json:"twitter_handle,omitempty"`
	LinkedinUrl   string `json:"linkedin_url,omitempty"`
	GithubHandle  string `json:"github_handle,omitempty"`
}

SDKAuthorInfo represents the SDKAuthorInfo type.

type SDKChangePasswordRequest

type SDKChangePasswordRequest struct {
	Email           string `json:"email"`
	CurrentPassword string `json:"current_password"`
	NewPassword     string `json:"new_password"`
}

SDKChangePasswordRequest represents the SDKChangePasswordRequest type.

type SDKContactInfo

type SDKContactInfo struct {
	ID            string            `json:"id"`
	Email         string            `json:"email"`
	Name          string            `json:"name"`
	Phone         string            `json:"phone,omitempty"`
	Company       string            `json:"company,omitempty"`
	Status        string            `json:"status"`
	EmailVerified bool              `json:"email_verified"`
	Tags          []string          `json:"tags"`
	Lists         []string          `json:"lists"`
	CustomFields  map[string]string `json:"custom_fields,omitempty"`
	LeadScore     int               `json:"lead_score,omitempty"`
	Source        string            `json:"source,omitempty"`
	EmailsSent    int               `json:"emails_sent"`
	EmailsOpened  int               `json:"emails_opened"`
	EmailsClicked int               `json:"emails_clicked"`
	LastEmailAt   string            `json:"last_email_at,omitempty"`
	LastOpenAt    string            `json:"last_open_at,omitempty"`
	LastClickAt   string            `json:"last_click_at,omitempty"`
	CreatedAt     string            `json:"created_at"`
	UpdatedAt     string            `json:"updated_at"`
}

SDKContactInfo represents the SDKContactInfo type.

type SDKContentCategoryInfo

type SDKContentCategoryInfo struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Slug        string `json:"slug"`
	Description string `json:"description,omitempty"`
}

SDKContentCategoryInfo represents the SDKContentCategoryInfo type.

type SDKContentPageInfo

type SDKContentPageInfo struct {
	ID              string `json:"id"`
	Title           string `json:"title"`
	Slug            string `json:"slug"`
	Content         string `json:"content"`
	Status          string `json:"status"`
	MetaTitle       string `json:"meta_title,omitempty"`
	MetaDescription string `json:"meta_description,omitempty"`
	FeaturedImage   string `json:"featured_image,omitempty"`
	TemplateName    string `json:"template_name,omitempty"`
	TemplateSlug    string `json:"template_slug,omitempty"`
	CreatedAt       string `json:"created_at"`
	PublishedAt     string `json:"published_at,omitempty"`
}

SDKContentPageInfo represents the SDKContentPageInfo type.

type SDKContentPostInfo

type SDKContentPostInfo struct {
	ID              string `json:"id"`
	Title           string `json:"title"`
	Slug            string `json:"slug"`
	Content         string `json:"content"`
	Excerpt         string `json:"excerpt,omitempty"`
	Status          string `json:"status"`
	MetaTitle       string `json:"meta_title,omitempty"`
	MetaDescription string `json:"meta_description,omitempty"`
	FeaturedImage   string `json:"featured_image,omitempty"`
	CategoryName    string `json:"category_name,omitempty"`
	CategorySlug    string `json:"category_slug,omitempty"`
	AuthorID        string `json:"author_id,omitempty"`
	CreatedAt       string `json:"created_at"`
	PublishedAt     string `json:"published_at,omitempty"`
}

SDKContentPostInfo represents the SDKContentPostInfo type.

type SDKCustomerInfo

type SDKCustomerInfo struct {
	ID                string `json:"id"`
	Email             string `json:"email"`
	Name              string `json:"name"`
	Phone             string `json:"phone,omitempty"`
	StripeCustomerID  string `json:"stripe_customer_id,omitempty"`
	Status            string `json:"status"`
	TotalSpent        int64  `json:"total_spent"`
	OrderCount        int    `json:"order_count"`
	SubscriptionCount int    `json:"subscription_count"`
	CreatedAt         string `json:"created_at"`
}

SDKCustomerInfo represents the SDKCustomerInfo type.

type SDKForgotPasswordRequest

type SDKForgotPasswordRequest struct {
	Email     string `json:"email"`
	ResetPath string `json:"reset_path,omitempty"`
}

SDKForgotPasswordRequest represents the SDKForgotPasswordRequest type.

type SDKInviteTeamMemberRequest

type SDKInviteTeamMemberRequest struct {
	Email string `json:"email"`
	Role  string `json:"role"`
}

SDKInviteTeamMemberRequest represents the SDKInviteTeamMemberRequest type.

type SDKInvoiceInfo

type SDKInvoiceInfo struct {
	ID              string `json:"id"`
	StripeInvoiceID string `json:"stripe_invoice_id,omitempty"`
	Number          string `json:"number"`
	Status          string `json:"status"`
	AmountDue       int64  `json:"amount_due"`
	AmountPaid      int64  `json:"amount_paid"`
	Currency        string `json:"currency"`
	Description     string `json:"description,omitempty"`
	InvoicePdfUrl   string `json:"invoice_pdf_url,omitempty"`
	HostedUrl       string `json:"hosted_url,omitempty"`
	DueDate         string `json:"due_date,omitempty"`
	PaidAt          string `json:"paid_at,omitempty"`
	CreatedAt       string `json:"created_at"`
}

SDKInvoiceInfo represents the SDKInvoiceInfo type.

type SDKLoginRequest

type SDKLoginRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

SDKLoginRequest represents the SDKLoginRequest type.

type SDKNavigationItem

type SDKNavigationItem struct {
	ID       string              `json:"id"`
	Label    string              `json:"label"`
	Url      string              `json:"url,omitempty"`
	Target   string              `json:"target,omitempty"`
	Icon     string              `json:"icon,omitempty"`
	IsActive bool                `json:"is_active"`
	Children []SDKNavigationItem `json:"children,omitempty"`
}

SDKNavigationItem represents the SDKNavigationItem type.

type SDKNavigationMenu

type SDKNavigationMenu struct {
	ID       string              `json:"id"`
	Name     string              `json:"name"`
	Slug     string              `json:"slug"`
	Location string              `json:"location"`
	Items    []SDKNavigationItem `json:"items"`
}

SDKNavigationMenu represents the SDKNavigationMenu type.

type SDKOrderInfo

type SDKOrderInfo struct {
	ID            string         `json:"id"`
	OrderNumber   string         `json:"order_number"`
	Status        string         `json:"status"`
	TotalCents    int64          `json:"total_cents"`
	Currency      string         `json:"currency"`
	Items         []SDKOrderItem `json:"items"`
	PaymentMethod string         `json:"payment_method,omitempty"`
	PaidAt        string         `json:"paid_at,omitempty"`
	FulfilledAt   string         `json:"fulfilled_at,omitempty"`
	CreatedAt     string         `json:"created_at"`
}

SDKOrderInfo represents the SDKOrderInfo type.

type SDKOrderItem

type SDKOrderItem struct {
	ProductName string `json:"product_name"`
	Quantity    int    `json:"quantity"`
	UnitPrice   int64  `json:"unit_price"`
	TotalPrice  int64  `json:"total_price"`
}

SDKOrderItem represents the SDKOrderItem type.

type SDKPaymentInfo

type SDKPaymentInfo struct {
	ID              string `json:"id"`
	StripePaymentID string `json:"stripe_payment_id,omitempty"`
	AmountCents     int64  `json:"amount_cents"`
	Currency        string `json:"currency"`
	Status          string `json:"status"`
	Description     string `json:"description,omitempty"`
	PaymentMethod   string `json:"payment_method,omitempty"`
	ReceiptUrl      string `json:"receipt_url,omitempty"`
	RefundedAt      string `json:"refunded_at,omitempty"`
	CreatedAt       string `json:"created_at"`
}

SDKPaymentInfo represents the SDKPaymentInfo type.

type SDKRefreshTokenRequest

type SDKRefreshTokenRequest struct {
	RefreshToken string `json:"refresh_token"`
}

SDKRefreshTokenRequest represents the SDKRefreshTokenRequest type.

type SDKRegisterRequest

type SDKRegisterRequest struct {
	Email         string `json:"email"`
	Password      string `json:"password"`
	Name          string `json:"name,omitempty"`
	PriceNickname string `json:"price_nickname,omitempty"`
	SuccessUrl    string `json:"success_url,omitempty"`
	CancelUrl     string `json:"cancel_url,omitempty"`
}

SDKRegisterRequest represents the SDKRegisterRequest type.

type SDKResetPasswordRequest

type SDKResetPasswordRequest struct {
	Token           string `json:"token"`
	Password        string `json:"password"`
	ConfirmPassword string `json:"confirm_password"`
}

SDKResetPasswordRequest represents the SDKResetPasswordRequest type.

type SDKSiteSettings

type SDKSiteSettings struct {
	SiteName          string            `json:"site_name,omitempty"`
	Tagline           string            `json:"tagline,omitempty"`
	LogoUrl           string            `json:"logo_url,omitempty"`
	FaviconUrl        string            `json:"favicon_url,omitempty"`
	ContactEmail      string            `json:"contact_email,omitempty"`
	ContactPhone      string            `json:"contact_phone,omitempty"`
	ContactAddress    string            `json:"contact_address,omitempty"`
	SocialLinks       map[string]string `json:"social_links,omitempty"`
	MetaTitleTemplate string            `json:"meta_title_template,omitempty"`
	MetaDescription   string            `json:"meta_description,omitempty"`
	OgImageUrl        string            `json:"og_image_url,omitempty"`
}

SDKSiteSettings represents the SDKSiteSettings type.

type SDKSubscriptionInfo

type SDKSubscriptionInfo struct {
	ID                   string `json:"id"`
	StripeSubscriptionID string `json:"stripe_subscription_id,omitempty"`
	ProductName          string `json:"product_name"`
	PriceName            string `json:"price_name,omitempty"`
	Status               string `json:"status"`
	AmountCents          int64  `json:"amount_cents"`
	Currency             string `json:"currency"`
	Interval             string `json:"interval"`
	CurrentPeriodStart   string `json:"current_period_start"`
	CurrentPeriodEnd     string `json:"current_period_end"`
	CancelAtPeriodEnd    bool   `json:"cancel_at_period_end"`
	TrialEnd             string `json:"trial_end,omitempty"`
	CreatedAt            string `json:"created_at"`
}

SDKSubscriptionInfo represents the SDKSubscriptionInfo type.

type SDKUpdateCustomerRequest

type SDKUpdateCustomerRequest struct {
	Name      string `json:"name,omitempty"`
	Phone     string `json:"phone,omitempty"`
	AvatarUrl string `json:"avatar_url,omitempty"`
	Status    string `json:"status,omitempty"`
	Metadata  string `json:"metadata,omitempty"`
}

SDKUpdateCustomerRequest represents the SDKUpdateCustomerRequest type.

type SDKUpdateTeamMemberRoleRequest

type SDKUpdateTeamMemberRoleRequest struct {
	NewRole string `json:"new_role"`
}

SDKUpdateTeamMemberRoleRequest represents the SDKUpdateTeamMemberRoleRequest type.

type SDKVerifyEmailRequest

type SDKVerifyEmailRequest struct {
	Token string `json:"token"`
}

SDKVerifyEmailRequest represents the SDKVerifyEmailRequest type.

type SendEmailRequest

type SendEmailRequest struct {
	To           string            `json:"to"`
	TemplateSlug string            `json:"template_slug,omitempty"`
	Subject      string            `json:"subject,omitempty"`
	Body         string            `json:"body,omitempty"`
	TextBody     string            `json:"text_body,omitempty"`
	FromName     string            `json:"from_name,omitempty"`
	FromEmail    string            `json:"from_email,omitempty"`
	ReplyTo      string            `json:"reply_to,omitempty"`
	Variables    map[string]string `json:"variables,omitempty"`
	Tags         []string          `json:"tags,omitempty"`
	Meta         map[string]string `json:"meta,omitempty"`
}

SendEmailRequest represents the SendEmailRequest type.

type SendEmailResponse

type SendEmailResponse struct {
	Success   bool   `json:"success"`
	MessageID string `json:"message_id"`
	Status    string `json:"status"`
	Message   string `json:"message,omitempty"`
}

SendEmailResponse represents the SendEmailResponse type.

type SequenceEnrollmentInfo

type SequenceEnrollmentInfo struct {
	EnrollmentID  string `json:"enrollment_id"`
	SequenceSlug  string `json:"sequence_slug"`
	SequenceName  string `json:"sequence_name"`
	Status        string `json:"status"`
	CurrentStep   int    `json:"current_step"`
	TotalSteps    int    `json:"total_steps"`
	EnrolledAt    string `json:"enrolled_at"`
	NextEmailAt   string `json:"next_email_at,omitempty"`
	CompletedAt   string `json:"completed_at,omitempty"`
	EmailsSent    int    `json:"emails_sent"`
	EmailsOpened  int    `json:"emails_opened"`
	EmailsClicked int    `json:"emails_clicked"`
}

SequenceEnrollmentInfo represents the SequenceEnrollmentInfo type.

type SequencesResource

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

SequencesResource provides access to sequences resources.

func (*SequencesResource) EnrollInSequence

func (r *SequencesResource) EnrollInSequence(ctx context.Context, request *EnrollSequenceRequest) (*EnrollSequenceResponse, error)

EnrollInSequence

func (*SequencesResource) GetSequenceEnrollments

func (r *SequencesResource) GetSequenceEnrollments(ctx context.Context, email string, sequenceSlug string) (*ListSequenceEnrollmentsResponse, error)

GetSequenceEnrollments

func (*SequencesResource) PauseSequenceEnrollment

func (r *SequencesResource) PauseSequenceEnrollment(ctx context.Context, request *PauseSequenceRequest) (*Response, error)

PauseSequenceEnrollment

func (*SequencesResource) ResumeSequenceEnrollment

func (r *SequencesResource) ResumeSequenceEnrollment(ctx context.Context, request *ResumeSequenceRequest) (*Response, error)

ResumeSequenceEnrollment

func (*SequencesResource) UnenrollFromSequence

func (r *SequencesResource) UnenrollFromSequence(ctx context.Context, request *UnenrollSequenceRequest) (*Response, error)

UnenrollFromSequence

type SiteResource

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

SiteResource provides access to site resources.

func (*SiteResource) GetAuthor

func (r *SiteResource) GetAuthor(ctx context.Context, id string) (*SDKAuthorInfo, error)

GetAuthor

func (*SiteResource) GetNavigationMenu

func (r *SiteResource) GetNavigationMenu(ctx context.Context, slug string) (*SDKNavigationMenu, error)

GetNavigationMenu

func (*SiteResource) GetSiteSettings

func (r *SiteResource) GetSiteSettings(ctx context.Context) (*SDKSiteSettings, error)

GetSiteSettings

func (*SiteResource) ListAuthors

func (r *SiteResource) ListAuthors(ctx context.Context) (*ListSDKAuthorsResponse, error)

ListAuthors

func (*SiteResource) ListNavigationMenus

func (r *SiteResource) ListNavigationMenus(ctx context.Context, location string) (*ListSDKNavigationMenusResponse, error)

ListNavigationMenus

type StatsOverviewResponse

type StatsOverviewResponse struct {
	TotalContacts    int     `json:"total_contacts"`
	NewContacts      int     `json:"new_contacts"`
	ActiveContacts   int     `json:"active_contacts"`
	EmailsSent       int     `json:"emails_sent"`
	EmailsDelivered  int     `json:"emails_delivered"`
	EmailsOpened     int     `json:"emails_opened"`
	EmailsClicked    int     `json:"emails_clicked"`
	EmailsBounced    int     `json:"emails_bounced"`
	OpenRate         float64 `json:"open_rate"`
	ClickRate        float64 `json:"click_rate"`
	BounceRate       float64 `json:"bounce_rate"`
	TotalRevenue     int64   `json:"total_revenue"`
	OrderCount       int     `json:"order_count"`
	AvgOrderValue    int64   `json:"avg_order_value"`
	NewSubscriptions int     `json:"new_subscriptions"`
}

StatsOverviewResponse represents the StatsOverviewResponse type.

type StatsResource

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

StatsResource provides access to stats resources.

func (*StatsResource) GetContactStats

func (r *StatsResource) GetContactStats(ctx context.Context, startDate string, endDate string, groupBy string) (*GetContactStatsResponse, error)

GetContactStats

func (*StatsResource) GetEmailStats

func (r *StatsResource) GetEmailStats(ctx context.Context, startDate string, endDate string, groupBy string) (*GetEmailStatsResponse, error)

GetEmailStats

func (*StatsResource) GetRevenueStats

func (r *StatsResource) GetRevenueStats(ctx context.Context, startDate string, endDate string, groupBy string) (*GetRevenueStatsResponse, error)

GetRevenueStats

func (*StatsResource) GetStatsOverview

func (r *StatsResource) GetStatsOverview(ctx context.Context, startDate string, endDate string) (*StatsOverviewResponse, error)

GetStatsOverview

type StreamCallback

type StreamCallback func(chunk StreamChunk) error

StreamCallback is called for each chunk during streaming.

type StreamChunk

type StreamChunk struct {
	Content string
	Index   int32
}

StreamChunk represents a chunk of streamed content.

type SubscribeRequest

type SubscribeRequest struct {
	Email string `json:"email"`
	Name  string `json:"name,omitempty"`
}

SubscribeRequest represents the SubscribeRequest type.

type SubscriptionRequest

type SubscriptionRequest struct {
	CustomerID string   `json:"customer_id"`
	PriceIds   []string `json:"price_ids"`
}

SubscriptionRequest represents the SubscriptionRequest type.

type SubscriptionResponse

type SubscriptionResponse struct {
	ID                   string `json:"id"`
	StripeSubscriptionID string `json:"stripe_subscription_id"`
	Status               string `json:"status"`
}

SubscriptionResponse represents the SubscriptionResponse type.

type TeamResource

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

TeamResource provides access to team resources.

func (*TeamResource) AcceptInvite

func (r *TeamResource) AcceptInvite(ctx context.Context, request *AcceptInviteRequest) (*AcceptInviteResponse, error)

AcceptInvite

func (*TeamResource) InviteTeamMember

func (r *TeamResource) InviteTeamMember(ctx context.Context, request *SDKInviteTeamMemberRequest) (*Response, error)

InviteTeamMember

func (*TeamResource) ListTeamMembers

func (r *TeamResource) ListTeamMembers(ctx context.Context) (*OrgMembersResponse, error)

ListTeamMembers

func (*TeamResource) RemoveTeamMember

func (r *TeamResource) RemoveTeamMember(ctx context.Context, id string) (*Response, error)

RemoveTeamMember

func (*TeamResource) UpdateTeamMemberRole

func (r *TeamResource) UpdateTeamMemberRole(ctx context.Context, id string, request *SDKUpdateTeamMemberRoleRequest) (*Response, error)

UpdateTeamMemberRole

func (*TeamResource) ValidateInvite

func (r *TeamResource) ValidateInvite(ctx context.Context, token string) (*ValidateInviteTokenResponse, error)

ValidateInvite

type TestWebhookResponse

type TestWebhookResponse struct {
	Success    bool   `json:"success"`
	StatusCode int    `json:"status_code"`
	Response   string `json:"response,omitempty"`
	Error      string `json:"error,omitempty"`
}

TestWebhookResponse represents the TestWebhookResponse type.

type TrackClickRequest

type TrackClickRequest struct {
	Token string `json:"token"`
	Url   string `json:"url"`
}

TrackClickRequest represents the TrackClickRequest type.

type TrackConfirmRequest

type TrackConfirmRequest struct {
	Token string `json:"token"`
}

TrackConfirmRequest represents the TrackConfirmRequest type.

type TrackConfirmResponse

type TrackConfirmResponse struct {
	Success     bool   `json:"success"`
	Message     string `json:"message,omitempty"`
	RedirectUrl string `json:"redirect_url,omitempty"`
}

TrackConfirmResponse represents the TrackConfirmResponse type.

type TrackOpenRequest

type TrackOpenRequest struct {
	Token string `json:"token"`
}

TrackOpenRequest represents the TrackOpenRequest type.

type TrackUnsubscribeRequest

type TrackUnsubscribeRequest struct {
	Token string `json:"token"`
}

TrackUnsubscribeRequest represents the TrackUnsubscribeRequest type.

type TrackingResource

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

TrackingResource provides access to tracking resources.

func (*TrackingResource) TrackClick

func (r *TrackingResource) TrackClick(ctx context.Context, request *TrackClickRequest) (*Response, error)

TrackClick

func (*TrackingResource) TrackConfirm

TrackConfirm

func (*TrackingResource) TrackOpen

func (r *TrackingResource) TrackOpen(ctx context.Context, request *TrackOpenRequest) (*Response, error)

TrackOpen

func (*TrackingResource) TrackUnsubscribe

func (r *TrackingResource) TrackUnsubscribe(ctx context.Context, request *TrackUnsubscribeRequest) (*Response, error)

TrackUnsubscribe

type UnenrollSequenceRequest

type UnenrollSequenceRequest struct {
	Email        string `json:"email"`
	SequenceSlug string `json:"sequence_slug,omitempty"`
}

UnenrollSequenceRequest represents the UnenrollSequenceRequest type.

type UpdateContactRequest

type UpdateContactRequest struct {
	Name         string            `json:"name,omitempty"`
	Phone        string            `json:"phone,omitempty"`
	Company      string            `json:"company,omitempty"`
	CustomFields map[string]string `json:"custom_fields,omitempty"`
}

UpdateContactRequest represents the UpdateContactRequest type.

type UpdateWebhookRequest

type UpdateWebhookRequest struct {
	Url    string   `json:"url,omitempty"`
	Events []string `json:"events,omitempty"`
	Active bool     `json:"active,omitempty"`
}

UpdateWebhookRequest represents the UpdateWebhookRequest type.

type UsageRequest

type UsageRequest struct {
	SubscriptionItemID string `json:"subscription_item_id"`
	Quantity           int    `json:"quantity"`
}

UsageRequest represents the UsageRequest type.

type ValidateInviteTokenResponse

type ValidateInviteTokenResponse struct {
	Valid       bool   `json:"valid"`
	OrgName     string `json:"org_name,omitempty"`
	InviterName string `json:"inviter_name,omitempty"`
	Email       string `json:"email,omitempty"`
	Role        string `json:"role,omitempty"`
	Message     string `json:"message,omitempty"`
}

ValidateInviteTokenResponse represents the ValidateInviteTokenResponse type.

type WSAbortRequest

type WSAbortRequest struct {
	Reason string `json:"reason,omitempty"`
}

WSAbortRequest aborts the current generation.

type WSChunkResponse

type WSChunkResponse struct {
	Content string `json:"content"`
	Index   int32  `json:"index"`
}

WSChunkResponse streams content chunks.

type WSCompletionResponse

type WSCompletionResponse struct {
	FullContent  string  `json:"full_content"`
	StopReason   string  `json:"stop_reason"`
	InputTokens  int64   `json:"input_tokens"`
	OutputTokens int64   `json:"output_tokens"`
	CostUSD      float64 `json:"cost_usd"`
	LatencyMs    int64   `json:"latency_ms"`
}

WSCompletionResponse indicates generation complete.

type WSConfig

type WSConfig struct {
	// CheckOrigin is called to check the origin of the WebSocket request.
	// If nil, allows all origins.
	CheckOrigin func(r *http.Request) bool
}

WSConfig configures the WebSocket handler.

type WSErrorResponse

type WSErrorResponse struct {
	Code      string `json:"code"`
	Message   string `json:"message"`
	Retryable bool   `json:"retryable"`
}

WSErrorResponse indicates an error.

type WSMessage

type WSMessage struct {
	Type string          `json:"type"`
	Data json.RawMessage `json:"data,omitempty"`
}

WSMessage is the base WebSocket message envelope.

type WSOption

type WSOption func(*WSConfig)

WSOption is a functional option for configuring the WebSocket handler.

func WithCheckOrigin

func WithCheckOrigin(fn func(r *http.Request) bool) WSOption

WithCheckOrigin sets the origin checker for WebSocket connections.

type WSStartRequest

type WSStartRequest struct {
	SystemPrompt string        `json:"system_prompt,omitempty"`
	Model        string        `json:"model,omitempty"` // "haiku", "sonnet", "opus"
	MaxTokens    int32         `json:"max_tokens,omitempty"`
	Temperature  float32       `json:"temperature,omitempty"`
	Messages     []ChatMessage `json:"messages,omitempty"`
}

WSStartRequest starts a new chat session.

type WSStartedResponse

type WSStartedResponse struct {
	SessionID string `json:"session_id"`
	Provider  string `json:"provider"`
	Model     string `json:"model"`
}

WSStartedResponse confirms session started.

type WSToolCallResponse

type WSToolCallResponse struct {
	ToolCallID    string `json:"tool_call_id"`
	Name          string `json:"name"`
	ArgumentsJSON string `json:"arguments_json"`
}

WSToolCallResponse indicates LLM wants to call a tool.

type WSToolResult

type WSToolResult struct {
	ToolCallID string `json:"tool_call_id"`
	Result     string `json:"result"`
	IsError    bool   `json:"is_error,omitempty"`
}

WSToolResult provides a tool call result.

type WSUserMessage

type WSUserMessage struct {
	Content string `json:"content"`
}

WSUserMessage sends a user message.

type WebhookInfo

type WebhookInfo struct {
	ID                string   `json:"id"`
	Url               string   `json:"url"`
	Events            []string `json:"events"`
	Active            bool     `json:"active"`
	CreatedAt         string   `json:"created_at"`
	DeliveriesTotal   int      `json:"deliveries_total"`
	DeliveriesSuccess int      `json:"deliveries_success"`
	DeliveriesFailed  int      `json:"deliveries_failed"`
	LastDeliveryAt    string   `json:"last_delivery_at,omitempty"`
	LastStatus        int      `json:"last_status,omitempty"`
}

WebhookInfo represents the WebhookInfo type.

type WebhookLogInfo

type WebhookLogInfo struct {
	ID          string `json:"id"`
	Event       string `json:"event"`
	Payload     string `json:"payload"`
	StatusCode  int    `json:"status_code"`
	Response    string `json:"response,omitempty"`
	Error       string `json:"error,omitempty"`
	Duration    int    `json:"duration_ms"`
	DeliveredAt string `json:"delivered_at"`
}

WebhookLogInfo represents the WebhookLogInfo type.

type WebhooksResource

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

WebhooksResource provides access to webhooks resources.

func (*WebhooksResource) DeleteWebhook

func (r *WebhooksResource) DeleteWebhook(ctx context.Context, id string) (*Response, error)

DeleteWebhook

func (*WebhooksResource) GetWebhook

func (r *WebhooksResource) GetWebhook(ctx context.Context, id string) (*WebhookInfo, error)

GetWebhook

func (*WebhooksResource) ListWebhookLogs

func (r *WebhooksResource) ListWebhookLogs(ctx context.Context, id string, limit int) (*ListWebhookLogsResponse, error)

ListWebhookLogs

func (*WebhooksResource) ListWebhooks

func (r *WebhooksResource) ListWebhooks(ctx context.Context) (*ListWebhooksResponse, error)

ListWebhooks

func (*WebhooksResource) RegisterWebhook

RegisterWebhook

func (*WebhooksResource) TestWebhook

func (r *WebhooksResource) TestWebhook(ctx context.Context, id string) (*TestWebhookResponse, error)

TestWebhook

func (*WebhooksResource) UpdateWebhook

func (r *WebhooksResource) UpdateWebhook(ctx context.Context, id string, request *UpdateWebhookRequest) (*WebhookInfo, error)

UpdateWebhook

type WorkshopAgendaDay

type WorkshopAgendaDay struct {
	Day   string   `json:"day"`
	Title string   `json:"title"`
	Items []string `json:"items"`
}

WorkshopAgendaDay represents the WorkshopAgendaDay type.

type WorkshopEventInfo

type WorkshopEventInfo struct {
	ID                     int64               `json:"id"`
	Slug                   string              `json:"slug"`
	Title                  string              `json:"title"`
	Description            string              `json:"description,omitempty"`
	StartDate              string              `json:"start_date"`
	EndDate                string              `json:"end_date"`
	StartTime              string              `json:"start_time"`
	EndTime                string              `json:"end_time"`
	Timezone               string              `json:"timezone"`
	LocationType           string              `json:"location_type"`
	LocationDetails        string              `json:"location_details,omitempty"`
	PriceCents             int                 `json:"price_cents"`
	Currency               string              `json:"currency"`
	MaxSeats               int                 `json:"max_seats"`
	SeatsRemaining         int                 `json:"seats_remaining"`
	Status                 string              `json:"status"`
	WhatsIncluded          []string            `json:"whats_included"`
	WhoItsFor              []string            `json:"who_its_for"`
	Agenda                 []WorkshopAgendaDay `json:"agenda"`
	ProductID              string              `json:"product_id,omitempty"`
	ProductSlug            string              `json:"product_slug,omitempty"`
	ProductName            string              `json:"product_name,omitempty"`
	AllowWaitlist          bool                `json:"allow_waitlist"`
	WaitlistLimit          int                 `json:"waitlist_limit,omitempty"`
	WaitlistCount          int                 `json:"waitlist_count,omitempty"`
	FunnelID               int64               `json:"funnel_id,omitempty"`
	FunnelSlug             string              `json:"funnel_slug,omitempty"`
	ConfirmationSequenceID int64               `json:"confirmation_sequence_id,omitempty"`
	ReminderSequenceID     int64               `json:"reminder_sequence_id,omitempty"`
	OrderBumpProductIds    []string            `json:"order_bump_product_ids,omitempty"`
}

WorkshopEventInfo represents the WorkshopEventInfo type.

type WorkshopsResource

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

WorkshopsResource provides access to workshops resources.

func (*WorkshopsResource) GetWorkshop

func (r *WorkshopsResource) GetWorkshop(ctx context.Context, slug string) (*WorkshopEventInfo, error)

GetWorkshop

func (*WorkshopsResource) GetWorkshopByProduct

func (r *WorkshopsResource) GetWorkshopByProduct(ctx context.Context, productSlug string) (*WorkshopEventInfo, error)

GetWorkshopByProduct

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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