Phase 2 part 7: the end of the funnel
Posts can be written for a buying signal: the prompt gets its hypothesis and angle, and links carry its campaign tag. Plausible (Stats API v2) is read once a day for visitors on tagged links, recorded per signal as Visited. Stripe (restricted key) is read every hour: $0 checkouts are Signed up, paid invoices and one-time payments are Paid with their value, tied to a signal by the checkout's utm_campaign metadata or the payer's email. The Core's Cal.com has no API, so booking emails from Cal.com in the outreach mailbox count as Booked. New Settings → Website & sales; the signal page lists its posts and tagged links. Schema 11. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
// Package plausible reads visit numbers from Plausible's Stats API v2
|
||||
// (https://plausible.io/docs/stats-api), on plausible.io or a self-hosted
|
||||
// Plausible such as the one on a Federated Core.
|
||||
package plausible
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrUnauthorized means the key was refused.
|
||||
var ErrUnauthorized = errors.New("Plausible refused the API key")
|
||||
|
||||
// Client calls one Plausible with one key.
|
||||
type Client struct {
|
||||
base, key string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
// New takes Plausible's address (e.g. https://plausible.example.com) and a
|
||||
// Stats API key.
|
||||
func New(base, key string) *Client {
|
||||
return &Client{base: strings.TrimRight(base, "/"), key: key, http: &http.Client{Timeout: time.Minute}}
|
||||
}
|
||||
|
||||
// Query is a Stats API v2 query.
|
||||
type Query struct {
|
||||
SiteID string `json:"site_id"`
|
||||
Metrics []string `json:"metrics"`
|
||||
DateRange any `json:"date_range"` // "7d", or ["2026-11-01", "2026-11-21"]
|
||||
Dimensions []string `json:"dimensions,omitempty"`
|
||||
Filters [][]any `json:"filters,omitempty"`
|
||||
Pagination *Pagination `json:"pagination,omitempty"`
|
||||
}
|
||||
|
||||
// Pagination limits the rows.
|
||||
type Pagination struct {
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
|
||||
// Row is one result: the dimensions' values, then the metrics'.
|
||||
type Row struct {
|
||||
Metrics []float64 `json:"metrics"`
|
||||
Dimensions []string `json:"dimensions"`
|
||||
}
|
||||
|
||||
// Run sends a query.
|
||||
func (c *Client) Run(ctx context.Context, q Query) ([]Row, error) {
|
||||
body, err := json.Marshal(q)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.base+"/api/v2/query", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+c.key)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
res, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(res.Body, 32<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if res.StatusCode == http.StatusUnauthorized {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
if res.StatusCode != http.StatusOK {
|
||||
var e struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(raw, &e) == nil && e.Error != "" {
|
||||
return nil, fmt.Errorf("Plausible: %s", e.Error)
|
||||
}
|
||||
return nil, fmt.Errorf("Plausible: HTTP %d: %s", res.StatusCode, strings.TrimSpace(string(raw[:min(len(raw), 300)])))
|
||||
}
|
||||
var out struct {
|
||||
Results []Row `json:"results"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return nil, fmt.Errorf("Plausible: %w", err)
|
||||
}
|
||||
return out.Results, nil
|
||||
}
|
||||
|
||||
// Visitors is a site's visitors over the last 30 days: a cheap check that
|
||||
// the key can read the site.
|
||||
func (c *Client) Visitors(ctx context.Context, site string) (int, error) {
|
||||
rows, err := c.Run(ctx, Query{SiteID: site, Metrics: []string{"visitors"}, DateRange: "30d"})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if len(rows) == 0 || len(rows[0].Metrics) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
return int(rows[0].Metrics[0]), nil
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// Package stripe reads checkouts and paid invoices from Stripe's API
|
||||
// (https://docs.stripe.com/api) with a restricted, read-only key. It never
|
||||
// creates or changes anything in Stripe.
|
||||
package stripe
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const apiBase = "https://api.stripe.com"
|
||||
|
||||
// ErrUnauthorized means the key was refused.
|
||||
var ErrUnauthorized = errors.New("Stripe refused the API key")
|
||||
|
||||
// Client calls the API with one key.
|
||||
type Client struct {
|
||||
key, base string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
func New(key string) *Client {
|
||||
return &Client{key: key, base: apiBase, http: &http.Client{Timeout: time.Minute}}
|
||||
}
|
||||
|
||||
// WithBase points the client at another server (for tests).
|
||||
func (c *Client) WithBase(u string) *Client {
|
||||
c.base = strings.TrimRight(u, "/")
|
||||
return c
|
||||
}
|
||||
|
||||
// Live reports whether the key is for live data, not test mode.
|
||||
func (c *Client) Live() bool { return strings.Contains(c.key, "_live_") }
|
||||
|
||||
func (c *Client) get(ctx context.Context, path string, q url.Values, out any) error {
|
||||
u := c.base + path
|
||||
if len(q) > 0 {
|
||||
u += "?" + q.Encode()
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+c.key)
|
||||
res, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(res.Body, 32<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if res.StatusCode == http.StatusUnauthorized {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
if res.StatusCode != http.StatusOK {
|
||||
var e struct {
|
||||
Error struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(raw, &e) == nil && e.Error.Message != "" {
|
||||
return fmt.Errorf("Stripe %s: %s", path, e.Error.Message)
|
||||
}
|
||||
return fmt.Errorf("Stripe %s: HTTP %d", path, res.StatusCode)
|
||||
}
|
||||
return json.Unmarshal(raw, out)
|
||||
}
|
||||
|
||||
// list reads every page of a list endpoint, oldest first.
|
||||
func list[T interface{ id() string }](ctx context.Context, c *Client, path string, q url.Values, max int) ([]T, error) {
|
||||
var all []T
|
||||
q.Set("limit", "100")
|
||||
for {
|
||||
var page struct {
|
||||
Data []T `json:"data"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
if err := c.get(ctx, path, q, &page); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
all = append(all, page.Data...)
|
||||
if !page.HasMore || len(page.Data) == 0 || len(all) >= max {
|
||||
break
|
||||
}
|
||||
q.Set("starting_after", page.Data[len(page.Data)-1].id())
|
||||
}
|
||||
// Stripe lists newest first.
|
||||
for i, j := 0, len(all)-1; i < j; i, j = i+1, j-1 {
|
||||
all[i], all[j] = all[j], all[i]
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// Session is a completed Checkout Session: someone bought, subscribed or
|
||||
// started a trial.
|
||||
type Session struct {
|
||||
ID string `json:"id"`
|
||||
Created int64 `json:"created"`
|
||||
Status string `json:"status"` // complete, open, expired
|
||||
Mode string `json:"mode"` // payment, subscription, setup
|
||||
PaymentStatus string `json:"payment_status"` // paid, unpaid, no_payment_required
|
||||
AmountTotal int64 `json:"amount_total"`
|
||||
Currency string `json:"currency"`
|
||||
Customer string `json:"customer"`
|
||||
Invoice string `json:"invoice"`
|
||||
CustomerDetails struct {
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
} `json:"customer_details"`
|
||||
Metadata map[string]string `json:"metadata"`
|
||||
}
|
||||
|
||||
func (s Session) id() string { return s.ID }
|
||||
|
||||
// Sessions lists the completed Checkout Sessions created since a time.
|
||||
func (c *Client) Sessions(ctx context.Context, since time.Time) ([]Session, error) {
|
||||
q := url.Values{"status": {"complete"}, "created[gte]": {strconv.FormatInt(since.Unix(), 10)}}
|
||||
return list[Session](ctx, c, "/v1/checkout/sessions", q, 5000)
|
||||
}
|
||||
|
||||
// Invoice is a paid invoice: a subscription's first or later payment.
|
||||
type Invoice struct {
|
||||
ID string `json:"id"`
|
||||
Created int64 `json:"created"`
|
||||
Customer string `json:"customer"`
|
||||
CustomerEmail string `json:"customer_email"`
|
||||
CustomerName string `json:"customer_name"`
|
||||
AmountPaid int64 `json:"amount_paid"`
|
||||
Currency string `json:"currency"`
|
||||
BillingReason string `json:"billing_reason"` // subscription_create, subscription_cycle, manual…
|
||||
Transitions struct {
|
||||
PaidAt int64 `json:"paid_at"`
|
||||
} `json:"status_transitions"`
|
||||
}
|
||||
|
||||
func (i Invoice) id() string { return i.ID }
|
||||
|
||||
// PaidInvoices lists the paid invoices created since a time.
|
||||
func (c *Client) PaidInvoices(ctx context.Context, since time.Time) ([]Invoice, error) {
|
||||
q := url.Values{"status": {"paid"}, "created[gte]": {strconv.FormatInt(since.Unix(), 10)}}
|
||||
return list[Invoice](ctx, c, "/v1/invoices", q, 5000)
|
||||
}
|
||||
|
||||
// Check reads one session and one invoice, so a key missing either
|
||||
// permission says which.
|
||||
func (c *Client) Check(ctx context.Context) error {
|
||||
var page struct {
|
||||
Data []json.RawMessage `json:"data"`
|
||||
}
|
||||
if err := c.get(ctx, "/v1/checkout/sessions", url.Values{"limit": {"1"}}, &page); err != nil {
|
||||
return fmt.Errorf("reading checkouts: %w", err)
|
||||
}
|
||||
if err := c.get(ctx, "/v1/invoices", url.Values{"limit": {"1"}}, &page); err != nil {
|
||||
return fmt.Errorf("reading invoices: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user