// Package lnbits is a small client for the LNbits HTTP API. // // It was written against the LNbits source at v0.12.12 and checked against // v1.7.1. Only three calls are used and they are the same in both: // // POST /api/v1/payments create an invoice (invoice key) // GET /api/v1/payments/{hash} payment status (invoice key) // GET /api/v1/wallet wallet info, used as a health check // // The one difference: v0.12 returns the invoice as "payment_request", v1 // returns the payment object with "bolt11". Both are read. package lnbits import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "strings" "time" ) // ErrNotFound is returned when LNbits does not know a payment hash. var ErrNotFound = errors.New("lnbits: payment not found") // Invoice is a created Lightning invoice. type Invoice struct { PaymentHash string Bolt11 string } // Client talks to one LNbits wallet with its invoice key. The invoice key // can create invoices and read payments but cannot spend, so a leaked key // cannot drain the wallet. type Client struct { baseURL string key string http *http.Client } // New creates a client. baseURL is the LNbits root, for example // https://lnbits.example.com. func New(baseURL, invoiceKey string) *Client { return &Client{ baseURL: strings.TrimRight(baseURL, "/"), key: invoiceKey, http: &http.Client{Timeout: 20 * time.Second}, } } type createRequest struct { Out bool `json:"out"` Amount int64 `json:"amount"` Unit string `json:"unit"` Memo string `json:"memo"` Expiry int64 `json:"expiry,omitempty"` Webhook string `json:"webhook,omitempty"` } type createResponse struct { PaymentHash string `json:"payment_hash"` PaymentRequest string `json:"payment_request"` Bolt11 string `json:"bolt11"` } // CreateInvoice asks LNbits for an invoice of the given amount in sats. // webhook may be empty; LNbits posts to it once when the invoice is paid. func (c *Client) CreateInvoice(ctx context.Context, sats int64, memo string, expiry time.Duration, webhook string) (*Invoice, error) { if sats <= 0 { return nil, errors.New("lnbits: amount must be positive") } body, err := json.Marshal(createRequest{ Out: false, Amount: sats, Unit: "sat", Memo: memo, Expiry: int64(expiry.Seconds()), Webhook: webhook, }) if err != nil { return nil, err } var resp createResponse if err := c.do(ctx, http.MethodPost, "/api/v1/payments", body, &resp); err != nil { return nil, err } inv := &Invoice{PaymentHash: resp.PaymentHash, Bolt11: resp.PaymentRequest} if inv.Bolt11 == "" { inv.Bolt11 = resp.Bolt11 } if inv.PaymentHash == "" || inv.Bolt11 == "" { return nil, errors.New("lnbits: invoice response lacks payment_hash or invoice") } return inv, nil } type statusResponse struct { Paid bool `json:"paid"` } // Paid reports whether the invoice with the given payment hash is settled. func (c *Client) Paid(ctx context.Context, paymentHash string) (bool, error) { if !isHex(paymentHash) { return false, ErrNotFound } var resp statusResponse if err := c.do(ctx, http.MethodGet, "/api/v1/payments/"+paymentHash, nil, &resp); err != nil { return false, err } return resp.Paid, nil } // Health checks that LNbits is reachable and accepts the key. func (c *Client) Health(ctx context.Context) error { var resp map[string]any return c.do(ctx, http.MethodGet, "/api/v1/wallet", nil, &resp) } func (c *Client) do(ctx context.Context, method, path string, body []byte, out any) error { var rd io.Reader if body != nil { rd = bytes.NewReader(body) } req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, rd) if err != nil { return err } req.Header.Set("X-Api-Key", c.key) req.Header.Set("Accept", "application/json") if body != nil { req.Header.Set("Content-Type", "application/json") } resp, err := c.http.Do(req) if err != nil { // The error text of net/http includes the URL but never headers, so // the key cannot leak through it. return fmt.Errorf("lnbits: %s %s: %w", method, path, err) } defer resp.Body.Close() data, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if err != nil { return fmt.Errorf("lnbits: %s %s: %w", method, path, err) } switch { case resp.StatusCode == http.StatusNotFound: return ErrNotFound case resp.StatusCode < 200 || resp.StatusCode > 299: return &StatusError{Code: resp.StatusCode, Detail: detail(data)} } if out == nil { return nil } if err := json.Unmarshal(data, out); err != nil { return fmt.Errorf("lnbits: %s %s: bad response: %w", method, path, err) } return nil } // StatusError is a non-2xx answer from LNbits. type StatusError struct { Code int Detail string } func (e *StatusError) Error() string { return fmt.Sprintf("lnbits: http %d: %s", e.Code, e.Detail) } // detail extracts the "detail" field LNbits puts in error bodies. func detail(data []byte) string { var doc struct { Detail any `json:"detail"` } if json.Unmarshal(data, &doc) == nil && doc.Detail != nil { return fmt.Sprint(doc.Detail) } s := strings.TrimSpace(string(data)) if len(s) > 200 { s = s[:200] } return s } func isHex(s string) bool { if len(s) == 0 || len(s) > 128 { return false } for i := 0; i < len(s); i++ { c := s[i] if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F') { return false } } return true }