// Real HTTP client for the SettleKit API. // // SERVER-ONLY. Every request is authenticated with the signed-in merchant's // session token (the httpOnly `sk_session` cookie), which the API resolves to // the merchant's organization so all data is tenant-scoped. Because it reads // the cookie via `next/headers`, this module must run on the server — client // components route mutations through server actions (e.g. products/new) instead // of importing it. Failures and empty payloads degrade to empty arrays / nulls // so pages render graceful empty states instead of crashing. import "server-only"; import { cookies } from "next/headers"; import { API_URL } from "./config"; import type { SentInvoice, GrowthMetrics, TeamInvitation, TeamMember, WebhookDelivery, AgentService, AnalyticsSummary, ApiKey, Bundle, Coupon, CreateProductInput, Customer, DeliveryLog, DeliveryRun, DiscordAccessGrant, DiscordRole, DiscordServer, Dispute, DisputeReason, DunningState, Entitlement, EscrowTask, FileAsset, GithubAccessGrant, GithubInstallation, GithubRepository, GithubTeam, Invoice, CreditBalance, LicenseKey, MarketplaceListing, Money, OnboardingStatus, OrgSettings, UsageMeter, Payment, Payout, Product, Refund, RefundReason, SaasFeature, SaasPlan, Seat, Subscription, PayoutBalance, WebhookEndpoint, } from "./types"; export { API_URL }; /** Name of the cookie holding the merchant's opaque session token. */ const SESSION_COOKIE = "sk_session"; /** * Authorization header for the current request, derived from the signed-in * merchant's session cookie. Absent when there is no session — the API then * rejects the call (401), which pages surface as an error/empty state rather * than leaking another tenant's data. */ function authHeader(): Record { const token = cookies().get(SESSION_COOKIE)?.value; return token ? { authorization: `Bearer ${token}` } : {}; } /** * Discount payload accepted by `POST /v1/coupons`. A fixed-amount discount's * `amountOff` is sent as a decimal string (e.g. "25.00"), matching the API. */ export type CreateCouponDiscount = | { type: "percent"; percentOff: number } | { type: "amount"; amountOff: string } | { type: "free-trial-days"; days: number }; /** Webhook endpoint as the API stores it. */ interface ApiKeyRecord { id: string; customerId: string; keyPrefix: string; scopes: string[]; status: "active" | "revoked"; lastUsedAt?: string; createdAt: string; kind?: "platform" | "customer"; } function toApiKey(k: ApiKeyRecord): ApiKey { return { id: k.id, name: k.kind === "platform" ? k.customerId : `Buyer key (${k.customerId})`, prefix: k.keyPrefix, scopes: k.scopes, lastUsedAt: k.lastUsedAt ?? null, createdAt: k.createdAt, kind: k.kind ?? "customer", status: k.status, }; } interface ApiWebhookEndpoint { id: string; url: string; enabledEvents?: string[]; active?: boolean; signingSecret?: string; disabledReason?: string; consecutiveFailures?: number; } export interface ApiList { data: T[]; total: number; empty: boolean; error: string | null; } export interface ApiItem { data: T | null; error: string | null; } function listResult(data: T[], error: string | null): ApiList { return { data, total: data.length, empty: data.length === 0, error }; } async function request(path: string, init?: RequestInit): Promise<{ data: T | null; error: string | null }> { try { const res = await fetch(`${API_URL}${path}`, { ...init, headers: { "content-type": "application/json", ...authHeader(), ...(init?.headers ?? {}), }, // Server components: always fetch fresh dashboard data. cache: "no-store", }); if (!res.ok) { const failure = (await res.json().catch(() => null)) as { error?: { message?: string } } | null; const detail = failure?.error?.message; return { data: null, error: detail ? `${detail} (API ${res.status})` : `API ${res.status} ${res.statusText}` }; } const body = (await res.json()) as { data?: T } | T; const data = body && typeof body === "object" && "data" in (body as object) ? ((body as { data: T }).data ?? null) : (body as T); return { data, error: null }; } catch (err) { return { data: null, error: err instanceof Error ? err.message : "Network error", }; } } /** Fetch a binary API resource (PDF, CSV) with the merchant's session. */ export async function fetchApiRaw(path: string): Promise { return fetch(`${API_URL}${path}`, { headers: authHeader(), cache: "no-store" }); } async function getList(path: string): Promise> { const { data, error } = await request(path); if (error) return listResult([], error); return listResult(Array.isArray(data) ? data : [], null); } async function getItem(path: string): Promise> { const { data, error } = await request(path); return { data, error }; } async function post(path: string, payload: unknown): Promise> { return request(path, { method: "POST", body: JSON.stringify(payload) }); } const ZERO: Money = { amount: 0, currency: "USDC" }; export const api = { // ---- Overview / analytics ---- analytics: { metrics: (days = 30) => getItem(`/v1/analytics/metrics?days=${days}`), async summary(): Promise { const { data } = await getItem("/v1/analytics/summary"); return ( data ?? { revenue: ZERO, customers: 0, activeAccess: 0, expiringSubscriptions: 0, failedDeliveries: 0, mrr: ZERO, revenueSeries: [], } ); }, }, // ---- Onboarding / activation funnel ---- onboarding: { async status(): Promise { const { data } = await getItem("/v1/onboarding"); return data; }, }, // ---- Products ---- products: { list: () => getList("/v1/products"), get: (id: string) => getItem(`/v1/products/${id}`), create: (input: CreateProductInput) => post("/v1/products", input), }, // ---- Customers / payments / subscriptions ---- customers: { list: () => getList("/v1/customers") }, payments: { list: () => getList("/v1/payments") }, subscriptions: { list: () => getList("/v1/subscriptions") }, entitlements: { list: () => getList("/v1/entitlements") }, // ---- License keys / API keys / files ---- licenseKeys: { list: () => getList("/v1/license-keys") }, apiKeys: { list: async (): Promise> => { const raw = await getList("/v1/api-keys"); return listResult(raw.data.map(toApiKey), raw.error); }, /** Management key with restricted scopes; the plaintext is returned once. */ createPlatform: (label: string, scopes: string[]) => post<{ apiKey: ApiKeyRecord; plaintext: string }>("/v1/api-keys/platform", { label, scopes }), revoke: (id: string) => post(`/v1/api-keys/${encodeURIComponent(id)}/revoke`, {}), }, team: { get: () => getItem<{ members: TeamMember[]; invitations: TeamInvitation[]; roles: string[] }>("/v1/team"), invite: (email: string, role: string) => post<{ inviteUrl: string; emailed: boolean }>("/v1/team/invitations", { email, role }), revokeInvitation: (id: string) => post(`/v1/team/invitations/${encodeURIComponent(id)}/revoke`, {}), setRole: (accountId: string, role: string) => request(`/v1/team/members/${encodeURIComponent(accountId)}`, { method: "PATCH", body: JSON.stringify({ role }) }), remove: (accountId: string) => request<{ removed: string }>(`/v1/team/members/${encodeURIComponent(accountId)}`, { method: "DELETE" }), }, files: { list: () => getList("/v1/files") }, webhooks: { list: async (): Promise> => { const raw = await getList("/v1/webhooks/endpoints"); return listResult( raw.data.map((e) => ({ id: e.id, url: e.url, events: e.enabledEvents ?? [], status: e.active ? "enabled" : "disabled", lastDeliveryAt: null, signingSecret: e.signingSecret ?? "", disabledReason: e.disabledReason ?? null, consecutiveFailures: e.consecutiveFailures ?? 0, })), raw.error, ); }, create: (url: string, events: string[]) => post("/v1/webhooks/endpoints", { url, enabledEvents: events }), deliveries: (filter: { status?: string } = {}) => getList(`/v1/webhooks/deliveries${filter.status ? `?status=${encodeURIComponent(filter.status)}` : ""}`), resend: (eventId: string, endpointId?: string) => post(`/v1/webhooks/events/${encodeURIComponent(eventId)}/resend`, endpointId ? { endpointId } : {}), test: (endpointId: string) => post(`/v1/webhooks/endpoints/${encodeURIComponent(endpointId)}/test`, {}), rotate: (endpointId: string, graceHours: number) => post(`/v1/webhooks/endpoints/${encodeURIComponent(endpointId)}/rotate-secret`, { graceHours }), setActive: (endpointId: string, active: boolean) => post(`/v1/webhooks/endpoints/${encodeURIComponent(endpointId)}/${active ? "enable" : "disable"}`, {}), }, // ---- Refunds ---- refunds: { list: (filter?: { paymentId?: string; customerId?: string }) => { const params = new URLSearchParams(); if (filter?.paymentId) params.set("paymentId", filter.paymentId); if (filter?.customerId) params.set("customerId", filter.customerId); const qs = params.toString(); return getList(qs ? `/v1/refunds?${qs}` : "/v1/refunds"); }, create: (input: { paymentId: string; customerId: string; amount: string; reason: RefundReason; }) => post("/v1/refunds", input), succeed: (id: string) => post(`/v1/refunds/${encodeURIComponent(id)}/succeed`, {}), fail: (id: string, reason?: string) => post(`/v1/refunds/${encodeURIComponent(id)}/fail`, reason ? { reason } : {}), }, // ---- Dunning ---- dunning: { list: (due?: boolean) => getList(due ? "/v1/dunning?due=true" : "/v1/dunning"), start: (subscriptionId: string) => post("/v1/dunning", { subscriptionId }), attempt: (subscriptionId: string, outcome: "recovered" | "failed", failureReason?: string) => post(`/v1/dunning/${encodeURIComponent(subscriptionId)}/attempt`, { outcome, ...(failureReason ? { failureReason } : {}), }), recover: (subscriptionId: string) => post(`/v1/dunning/${encodeURIComponent(subscriptionId)}/recover`, {}), }, // ---- Disputes ---- disputes: { list: (status?: string) => getList(status ? `/v1/disputes?status=${encodeURIComponent(status)}` : "/v1/disputes"), get: (id: string) => getItem(`/v1/disputes/${encodeURIComponent(id)}`), open: (input: { paymentId: string; customerId: string; reason: DisputeReason }) => post("/v1/disputes", input), evidence: ( id: string, input: { kind: "text" | "receipt" | "shipping" | "communication" | "url" | "file"; description: string; value: string; }, ) => post(`/v1/disputes/${encodeURIComponent(id)}/evidence`, input), resolve: (id: string, outcome: "won" | "lost" | "refunded") => post(`/v1/disputes/${encodeURIComponent(id)}/resolve`, { outcome }), }, // ---- Payouts ---- payouts: { list: (organizationId?: string) => getList( organizationId ? `/v1/payouts?organizationId=${encodeURIComponent(organizationId)}` : "/v1/payouts", ), // Tenant-scoped via the session; returns the full take-rate breakdown. async balance(): Promise { const { data } = await getItem("/v1/payouts/balance"); return data; }, create: (input: { organizationId: string; walletAddress: string; amount: string; network: "arc" | "base" | "ethereum"; }) => post("/v1/payouts", input), paid: (id: string, txHash: string) => post(`/v1/payouts/${encodeURIComponent(id)}/paid`, { txHash }), fail: (id: string, reason?: string) => post(`/v1/payouts/${encodeURIComponent(id)}/fail`, reason ? { reason } : {}), }, // ---- GitHub ---- github: { installations: () => getList("/v1/integrations/github/installations"), repositories: () => getList("/v1/integrations/github/repositories"), teams: () => getList("/v1/integrations/github/teams"), access: () => getList("/v1/github/access"), grant: (customerEmail: string, target: string, kind: "repo" | "team") => post("/v1/github/access/grant", { customerEmail, target, kind, }), }, // ---- Discord ---- discord: { servers: () => getList("/v1/integrations/discord/guilds"), roles: () => getList("/v1/integrations/discord/roles"), access: () => getList("/v1/discord/access"), grant: (customerEmail: string, roleId: string) => post("/v1/discord/access/grant", { customerEmail, roleId, }), }, // ---- SaaS ---- saas: { plans: () => getList("/v1/saas/plans"), features: () => getList("/v1/saas/features"), seats: () => getList("/v1/saas/seats"), entitlements: () => getList("/v1/saas/entitlements"), createPlan: (name: string, amount: number, interval: "monthly" | "yearly") => post("/v1/saas/plans", { name, amount, interval }), }, // ---- Bundles ---- bundles: { list: () => getList("/v1/bundles"), get: (id: string) => getItem(`/v1/bundles/${id}`), create: (name: string, productIds: string[], amount: number) => post("/v1/bundles", { name, productIds, amount }), }, // ---- Coupons ---- coupons: { list: () => getList("/v1/coupons"), get: (code: string) => getItem(`/v1/coupons/${encodeURIComponent(code)}`), create: (input: { code: string; name?: string; // The API encodes a fixed `amount` discount's amountOff as a decimal string. discount: CreateCouponDiscount; maxRedemptions?: number; perCustomerLimit?: number; expiresAt?: string; }) => post("/v1/coupons", input), }, // ---- Invoices ---- invoices: { list: (customerId?: string) => getList( customerId ? `/v1/invoices?customerId=${encodeURIComponent(customerId)}` : "/v1/invoices", ), get: (id: string) => getItem(`/v1/invoices/${id}`), htmlUrl: (id: string) => `${API_URL}/v1/invoices/${id}.html`, create: (input: { organizationId: string; customerId: string; lineItems?: { description: string; quantity: number; unitAmount: string }[]; }) => post("/v1/invoices", input), /** Issue + email the pay link (idempotent: the link stays the same). */ send: (id: string, payerEmail?: string) => post(`/v1/invoices/${encodeURIComponent(id)}/send`, payerEmail ? { payerEmail } : {}), /** Ad-hoc payment request: amount + memo, sent to an email. */ request: (input: { amount: string; description: string; payerEmail: string; dueAt?: string }) => post("/v1/invoices/requests", input), }, // ---- Delivery ---- delivery: { runs: () => getList("/v1/delivery-runs"), logs: () => getList("/v1/delivery-runs/logs"), retry: (id: string) => post(`/v1/delivery-runs/${id}/retry`, {}), }, // ---- Agent services ---- agentServices: { list: () => getList("/v1/agent-services"), get: (id: string) => getItem(`/v1/agent-services/${id}`), create: (name: string, description: string, pricePerCall: number) => post("/v1/agent-services", { name, description, pricePerCall, }), }, // ---- Escrow ---- escrow: { tasks: () => getList("/v1/escrow/tasks"), get: (id: string) => getItem(`/v1/escrow/tasks/${id}`), create: (title: string, buyerEmail: string, amount: number) => post("/v1/escrow/tasks", { title, buyerEmail, amount }), assign: (id: string, workerCustomerId: string) => post(`/v1/escrow/tasks/${id}/assign`, { workerCustomerId }), fund: (id: string, fundingTxHash: string) => post(`/v1/escrow/tasks/${id}/fund`, { fundingTxHash }), submit: (id: string, content: string) => post(`/v1/escrow/tasks/${id}/submit`, { content }), approve: (id: string) => post(`/v1/escrow/tasks/${id}/approve`, {}), release: (id: string, releaseTxHash: string) => post(`/v1/escrow/tasks/${id}/release`, { releaseTxHash }), refund: (id: string, reason: string) => post(`/v1/escrow/tasks/${id}/refund`, { reason }), }, // ---- Usage-based billing ---- usage: { record: (input: { organizationId: string; customerId: string; productId: string; metric: string; quantity: number; }) => post("/v1/usage/record", input), grantCredits: (input: { organizationId: string; customerId: string; productId: string; credits: number; }) => post("/v1/usage/credits/grant", input), consumeCredits: (input: { organizationId: string; customerId: string; productId: string; credits: number; }) => post("/v1/usage/credits/consume", input), credits: (organizationId: string, customerId: string, productId: string) => getItem( `/v1/usage/credits?organizationId=${encodeURIComponent(organizationId)}&customerId=${encodeURIComponent(customerId)}&productId=${encodeURIComponent(productId)}`, ), }, // ---- Marketplace ---- marketplace: { listings: () => getList("/v1/marketplace/listings"), create: (input: { organizationId: string; merchantId: string; productId: string; title: string; summary: string; tags: string[]; }) => post("/v1/marketplace/listings", input), publish: (id: string) => post(`/v1/marketplace/listings/${encodeURIComponent(id)}/publish`, {}), }, // ---- Settings ---- settings: { async get(): Promise { const { data } = await getItem("/v1/settings"); return ( data ?? { orgName: "SettleKit Merchant", supportEmail: "", payoutCurrency: "USDC", webhookSecret: "", defaultRail: "circle", } ); }, update: (input: Partial) => post("/v1/settings", input), }, };