Skip to content

An open-source, faster Devin alternative

TypeScript

billing: hide cost display on dashboard, link to Stripe Billing Portal (#146)

Mohamed Habib43e6783448dc
diff --git a/internal/api/dashboard_billing.go b/internal/api/dashboard_billing.go
index cabf20a4..daa15508 100644
--- a/internal/api/dashboard_billing.go
+++ b/internal/api/dashboard_billing.go
@@ -6,12 +6,10 @@ import (
"log"
"net/http"
"strconv"
- "time"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/opensandbox/opensandbox/internal/auth"
- "github.com/opensandbox/opensandbox/internal/billing"
)
// billingSetup initiates the upgrade flow: creates Stripe customer + Checkout session.
@@ -68,43 +66,6 @@ func (s *Server) billingGet(c echo.Context) error {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "org not found"})
}
- // Current month usage
- now := time.Now()
- monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
- usage, _ := s.store.GetOrgUsage(ctx, orgID.String(), monthStart, now)
-
- type tierUsage struct {
- MemoryMB int `json:"memoryMB"`
- VCPUs int `json:"vcpus"`
- DiskMB int `json:"diskMB"`
- TotalSeconds float64 `json:"totalSeconds"`
- CostCents float64 `json:"costCents"`
- }
- var tiers []tierUsage
- var totalCost float64
- var diskOverageGBSeconds float64
- for _, u := range usage {
- rate := billing.TierPricePerSecond[u.MemoryMB]
- cost := u.TotalSeconds * rate * 100
- totalCost += cost
- tiers = append(tiers, tierUsage{
- MemoryMB: u.MemoryMB,
- VCPUs: u.CPUPercent / 100,
- DiskMB: u.DiskMB,
- TotalSeconds: u.TotalSeconds,
- CostCents: cost,
- })
- diskOverageGBSeconds += billing.DiskOverageGBSeconds(u)
- }
- diskOverageCostCents := diskOverageGBSeconds * billing.DiskOveragePricePerGBPerSecond * 100
- totalCost += diskOverageCostCents
- diskOverage := map[string]interface{}{
- "freeAllowanceMB": billing.DiskFreeAllowanceMB,
- "pricePerGBPerSecond": billing.DiskOveragePricePerGBPerSecond,
- "gbSeconds": diskOverageGBSeconds,
- "costCents": diskOverageCostCents,
- }
-
// Stripe balance for pro users
var stripeCreditCents int64
if org.Plan == "pro" && org.StripeCustomerID != nil && s.stripeClient != nil {
@@ -114,19 +75,48 @@ func (s *Server) billingGet(c echo.Context) error {
}
}
+ // Cost estimates are intentionally not returned from here. Billing truth
+ // (usage, price, invoice totals) lives in Stripe — the dashboard links to
+ // the Stripe Billing Portal instead of re-computing cost locally against a
+ // hardcoded rate table that would diverge for grandfathered orgs.
return c.JSON(http.StatusOK, map[string]interface{}{
- "plan": org.Plan,
- "stripeCreditCents": stripeCreditCents,
- "maxConcurrentSandboxes": org.MaxConcurrentSandboxes,
- "hasPaymentMethod": org.StripeCustomerID != nil,
- "currentUsage": map[string]interface{}{
- "tiers": tiers,
- "diskOverage": diskOverage,
- "totalCostCents": totalCost,
- },
+ "plan": org.Plan,
+ "stripeCreditCents": stripeCreditCents,
+ "maxConcurrentSandboxes": org.MaxConcurrentSandboxes,
+ "hasPaymentMethod": org.StripeCustomerID != nil,
})
}
+// billingPortal creates a Stripe Billing Portal session and returns the URL.
+// The frontend opens this URL so the customer can view authoritative usage,
+// invoices, and manage their payment method — all served directly by Stripe.
+func (s *Server) billingPortal(c echo.Context) error {
+ if s.store == nil || s.stripeClient == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "billing not configured"})
+ }
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})
+ }
+ ctx := c.Request().Context()
+ org, err := s.store.GetOrg(ctx, orgID)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "org not found"})
+ }
+ if org.StripeCustomerID == nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "no billing customer — upgrade to Pro first"})
+ }
+
+ // Send the user back to wherever they came from when they close the portal.
+ returnURL := c.Request().Header.Get("Referer")
+ url, err := s.stripeClient.CreatePortalSession(*org.StripeCustomerID, returnURL)
+ if err != nil {
+ log.Printf("billing: create portal session failed for org %s: %v", orgID, err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to create portal session"})
+ }
+ return c.JSON(http.StatusOK, map[string]string{"url": url})
+}
+
// billingRedeem redeems a promotion code and applies the credit to the org's Stripe balance.
func (s *Server) billingRedeem(c echo.Context) error {
if s.store == nil || s.stripeClient == nil {
diff --git a/internal/api/router.go b/internal/api/router.go
index aa93b918..f95f2f5f 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -364,6 +364,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
dash.GET("/billing", s.billingGet)
dash.GET("/billing/invoices", s.billingInvoices)
dash.POST("/billing/redeem", s.billingRedeem)
+ dash.POST("/billing/portal", s.billingPortal)
// Admin endpoints
diff --git a/internal/billing/stripe.go b/internal/billing/stripe.go
index 5ad7ef24..ea7ca527 100644
--- a/internal/billing/stripe.go
+++ b/internal/billing/stripe.go
@@ -8,6 +8,7 @@ import (
"github.com/stripe/stripe-go/v82"
"github.com/stripe/stripe-go/v82/billing/meter"
"github.com/stripe/stripe-go/v82/billing/meterevent"
+ portalsession "github.com/stripe/stripe-go/v82/billingportal/session"
checkoutsession "github.com/stripe/stripe-go/v82/checkout/session"
"github.com/stripe/stripe-go/v82/customer"
"github.com/stripe/stripe-go/v82/customerbalancetransaction"
@@ -259,6 +260,20 @@ func (s *StripeClient) CreateSetupCheckoutSession(customerID, orgID string) (url
return sess.URL, sess.ID, nil
}
+// CreatePortalSession creates a Stripe Billing Portal session so the customer
+// can self-serve: view subscription, usage, invoices, and update payment method.
+// returnURL is where Stripe sends the user after they close the portal.
+func (s *StripeClient) CreatePortalSession(customerID, returnURL string) (string, error) {
+ sess, err := portalsession.New(&stripe.BillingPortalSessionParams{
+ Customer: stripe.String(customerID),
+ ReturnURL: stripe.String(returnURL),
+ })
+ if err != nil {
+ return "", fmt.Errorf("create portal session: %w", err)
+ }
+ return sess.URL, nil
+}
+
// CreateSubscription creates a subscription with metered prices for all tiers.
// Returns subscription ID and map of memoryMB → subscription item ID.
func (s *StripeClient) CreateSubscription(customerID string) (string, map[int]string, error) {
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index d1fd1917..3660d4a6 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -273,22 +273,11 @@ export const switchOrg = (orgId: string) =>
export const getCredits = () => apiFetch<Credits>('/org/credits')
// Billing types
-export interface BillingTierUsage {
- memoryMB: number
- vcpus: number
- totalSeconds: number
- costCents: number
-}
-
export interface BillingState {
plan: string
stripeCreditCents: number
maxConcurrentSandboxes: number
hasPaymentMethod: boolean
- currentUsage: {
- tiers: BillingTierUsage[]
- totalCostCents: number
- }
}
export interface StripeInvoice {
@@ -309,6 +298,9 @@ export const getBilling = () => apiFetch<BillingState>('/billing')
export const billingSetup = () =>
apiFetch<{ url: string }>('/billing/setup', { method: 'POST' })
+export const billingPortal = () =>
+ apiFetch<{ url: string }>('/billing/portal', { method: 'POST' })
+
export const getBillingInvoices = (limit = 10) =>
apiFetch<{ invoices: StripeInvoice[] }>(`/billing/invoices?limit=${limit}`)
diff --git a/web/src/pages/Billing.tsx b/web/src/pages/Billing.tsx
index 334ba40c..bd9d9645 100644
--- a/web/src/pages/Billing.tsx
+++ b/web/src/pages/Billing.tsx
@@ -1,19 +1,10 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
- getBilling, billingSetup, getBillingInvoices, redeemPromoCode,
- type BillingTierUsage, type StripeInvoice,
+ getBilling, billingSetup, billingPortal, getBillingInvoices, redeemPromoCode,
+ type StripeInvoice,
} from '../api/client'
-const PRICING_TIERS = [
- { memory: '1 GB', vcpus: 1, bestEffort: true, perSec: 0.000001080246914 },
- { memory: '4 GB', vcpus: 1, perSec: 0.000005787037037 },
- { memory: '8 GB', vcpus: 2, perSec: 0.00001350308642 },
- { memory: '16 GB', vcpus: 4, perSec: 0.00002700617284 },
- { memory: '32 GB', vcpus: 8, perSec: 0.0001929012346 },
- { memory: '64 GB', vcpus: 16, perSec: 0.0005401234568 },
-]
-
export default function Billing() {
const queryClient = useQueryClient()
const { data: billing, isLoading } = useQuery({ queryKey: ['billing'], queryFn: getBilling })
@@ -27,6 +18,11 @@ export default function Billing() {
onSuccess: (data) => { window.location.href = data.url },
})
+ const portalMutation = useMutation({
+ mutationFn: billingPortal,
+ onSuccess: (data) => { window.location.href = data.url },
+ })
+
const redeemMutation = useMutation({
mutationFn: () => redeemPromoCode(promoCode),
onSuccess: (data) => {
@@ -43,7 +39,7 @@ export default function Billing() {
<div>
<div style={{ marginBottom: 32 }}>
<h1 className="page-title">Billing</h1>
- <p className="page-subtitle">Manage your plan, usage, and payment settings</p>
+ <p className="page-subtitle">Manage your plan and payment settings</p>
</div>
{isLoading ? (
@@ -52,164 +48,109 @@ export default function Billing() {
</div>
) : (
<>
- {/* Plan + Usage row */}
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
-
- {/* Plan Card */}
- <div className="glass-card animate-in stagger-1" style={{ padding: 28 }}>
- <span className="section-title" style={{ marginBottom: 16, display: 'block' }}>
- Current Plan
+ {/* Plan Card */}
+ <div className="glass-card animate-in stagger-1" style={{ padding: 28, marginBottom: 14 }}>
+ <span className="section-title" style={{ marginBottom: 16, display: 'block' }}>
+ Current Plan
+ </span>
+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 8 }}>
+ <span className="metric-value" style={{
+ fontSize: 36, fontWeight: 700,
+ color: isPro ? 'var(--accent-indigo)' : 'var(--text-primary)',
+ }}>
+ {isPro ? 'Pro' : 'Free'}
</span>
- <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 8 }}>
- <span className="metric-value" style={{
- fontSize: 36, fontWeight: 700,
- color: isPro ? 'var(--accent-indigo)' : 'var(--text-primary)',
- }}>
- {isPro ? 'Pro' : 'Free'}
- </span>
- <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>
- {isPro
- ? `${billing?.maxConcurrentSandboxes ?? 5} concurrent sandboxes, all tiers`
- : `${billing?.maxConcurrentSandboxes ?? 5} concurrent sandboxes, up to 4GB / 1 vCPU`}
- </span>
- </div>
-
- {isPro && billing?.stripeCreditCents != null && billing.stripeCreditCents > 0 && (
- <div style={{ fontSize: 13, color: 'var(--accent-emerald)', marginBottom: 12 }}>
- ${(billing.stripeCreditCents / 100).toFixed(2)} promotional credit remaining
- </div>
- )}
-
- {!isPro && (
- <div style={{ marginTop: 16 }}>
- <div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 10 }}>
- Unlock larger machine sizes and get $30 free credit
- </div>
- <button
- onClick={() => setupMutation.mutate()}
- disabled={setupMutation.isPending}
- style={{
- padding: '10px 24px', fontSize: 14, fontWeight: 600,
- fontFamily: 'var(--font-body)', cursor: 'pointer',
- border: 'none', borderRadius: 'var(--radius-sm)',
- background: 'var(--accent-indigo)', color: '#fff',
- opacity: setupMutation.isPending ? 0.6 : 1,
- }}
- >
- {setupMutation.isPending ? 'Redirecting...' : 'Upgrade to Pro'}
- </button>
- {setupMutation.isError && (
- <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 8 }}>
- {(setupMutation.error as Error).message}
- </p>
- )}
- </div>
- )}
-
- {isPro && (
- <div style={{
- fontSize: 11, color: 'var(--accent-emerald)', marginTop: 4,
- display: 'flex', alignItems: 'center', gap: 6,
- }}>
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="20 6 9 17 4 12" /></svg>
- Payment method on file — billed monthly via Stripe
- </div>
- )}
+ <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>
+ {isPro
+ ? `${billing?.maxConcurrentSandboxes ?? 5} concurrent sandboxes, all tiers`
+ : `${billing?.maxConcurrentSandboxes ?? 5} concurrent sandboxes, up to 4GB / 1 vCPU`}
+ </span>
+ </div>
- <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginTop: 12 }}>
- Need more concurrency?{' '}
- <a href="https://cal.com/team/digger/opencomputer-founder-chat" target="_blank" rel="noreferrer"
- style={{ color: 'var(--accent-indigo)', textDecoration: 'none' }}>
- Talk to us
- </a>
+ {isPro && billing?.stripeCreditCents != null && billing.stripeCreditCents > 0 && (
+ <div style={{ fontSize: 13, color: 'var(--accent-emerald)', marginBottom: 12 }}>
+ ${(billing.stripeCreditCents / 100).toFixed(2)} promotional credit remaining
</div>
- </div>
+ )}
- {/* Current Usage */}
- <div className="glass-card animate-in stagger-2" style={{ padding: 28 }}>
- <span className="section-title" style={{ marginBottom: 16, display: 'block' }}>
- Current Month Usage
- </span>
- {!billing?.currentUsage?.tiers?.length ? (
- <div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--text-tertiary)', fontSize: 13 }}>
- No usage this month
+ {!isPro && (
+ <div style={{ marginTop: 16 }}>
+ <div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 10 }}>
+ Unlock larger machine sizes and get $30 free credit
</div>
- ) : (
- <>
- <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
- {billing.currentUsage.tiers.map((tier: BillingTierUsage) => (
- <div key={tier.memoryMB} style={{
- display: 'flex', justifyContent: 'space-between', alignItems: 'center',
- padding: '8px 12px', borderRadius: 'var(--radius-sm)',
- background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.03)',
- }}>
- <div>
- <span style={{ fontSize: 13, color: 'var(--text-primary)', fontWeight: 500 }}>
- {tier.memoryMB / 1024} GB
- </span>
- <span style={{ fontSize: 11, color: 'var(--text-tertiary)', marginLeft: 8 }}>
- {tier.vcpus} vCPU
- </span>
- </div>
- <div style={{ textAlign: 'right' }}>
- <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-primary)' }}>
- ${(tier.costCents / 100).toFixed(4)}
- </span>
- <span style={{ fontSize: 10, color: 'var(--text-tertiary)', marginLeft: 8 }}>
- {formatSeconds(tier.totalSeconds)}
- </span>
- </div>
- </div>
- ))}
- </div>
- <div style={{
- display: 'flex', justifyContent: 'space-between', alignItems: 'center',
- paddingTop: 12, borderTop: '1px solid var(--border-subtle)',
- }}>
- <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-secondary)' }}>Total</span>
- <span className="metric-value" style={{ fontSize: 18, color: 'var(--accent-cyan)' }}>
- ${(billing.currentUsage.totalCostCents / 100).toFixed(4)}
- </span>
- </div>
- </>
- )}
+ <button
+ onClick={() => setupMutation.mutate()}
+ disabled={setupMutation.isPending}
+ style={{
+ padding: '10px 24px', fontSize: 14, fontWeight: 600,
+ fontFamily: 'var(--font-body)', cursor: 'pointer',
+ border: 'none', borderRadius: 'var(--radius-sm)',
+ background: 'var(--accent-indigo)', color: '#fff',
+ opacity: setupMutation.isPending ? 0.6 : 1,
+ }}
+ >
+ {setupMutation.isPending ? 'Redirecting...' : 'Upgrade to Pro'}
+ </button>
+ {setupMutation.isError && (
+ <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 8 }}>
+ {(setupMutation.error as Error).message}
+ </p>
+ )}
+ </div>
+ )}
+
+ {isPro && (
+ <div style={{
+ fontSize: 11, color: 'var(--accent-emerald)', marginTop: 4,
+ display: 'flex', alignItems: 'center', gap: 6,
+ }}>
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="20 6 9 17 4 12" /></svg>
+ Payment method on file — billed monthly via Stripe
+ </div>
+ )}
+
+ <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginTop: 12 }}>
+ Need more concurrency?{' '}
+ <a href="https://cal.com/team/digger/opencomputer-founder-chat" target="_blank" rel="noreferrer"
+ style={{ color: 'var(--accent-indigo)', textDecoration: 'none' }}>
+ Talk to us
+ </a>
</div>
</div>
- {/* Pricing Table */}
- <div className="glass-card animate-in stagger-3" style={{ padding: '22px 24px', marginBottom: 14 }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
- <span className="section-title" style={{ marginBottom: 0 }}>Pricing</span>
- <span style={{ fontSize: 11, color: 'var(--accent-emerald)', fontFamily: 'var(--font-mono)' }}>
- Hibernated sandboxes are not charged
+ {/* Stripe Billing Portal CTA (pro only) */}
+ {isPro && (
+ <div className="glass-card animate-in stagger-2" style={{ padding: '22px 24px', marginBottom: 14 }}>
+ <span className="section-title" style={{ marginBottom: 10, display: 'block' }}>
+ Usage & Invoices
</span>
+ <p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 14, lineHeight: 1.5 }}>
+ View your current-cycle usage, invoices, and manage your payment method on Stripe.
+ </p>
+ <button
+ onClick={() => portalMutation.mutate()}
+ disabled={portalMutation.isPending}
+ style={{
+ padding: '10px 20px', fontSize: 13, fontWeight: 600,
+ fontFamily: 'var(--font-body)', cursor: 'pointer',
+ border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)',
+ background: 'rgba(255,255,255,0.02)', color: 'var(--text-primary)',
+ opacity: portalMutation.isPending ? 0.6 : 1,
+ }}
+ >
+ {portalMutation.isPending ? 'Opening Stripe…' : 'Open Stripe billing portal ↗'}
+ </button>
+ {portalMutation.isError && (
+ <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 10 }}>
+ {(portalMutation.error as Error).message}
+ </p>
+ )}
</div>
- <table className="data-table">
- <thead>
- <tr><th>Memory</th><th>vCPUs</th><th>Per Second</th></tr>
- </thead>
- <tbody>
- {PRICING_TIERS.map((t, i) => {
- const locked = !isPro && i > 0
- return (
- <tr key={t.memory} style={{ opacity: locked ? 0.35 : 1 }}>
- <td style={{ fontWeight: 600, color: 'var(--text-primary)' }}>
- {t.memory}{locked && ' — Pro'}
- </td>
- <td>{t.vcpus}{('bestEffort' in t) && <span style={{ fontSize: 10, color: 'var(--text-tertiary)', marginLeft: 4 }}>best-effort</span>}</td>
- <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: locked ? 'var(--text-tertiary)' : 'var(--accent-cyan)' }}>
- ${t.perSec.toFixed(11)}
- </td>
- </tr>
- )
- })}
- </tbody>
- </table>
- </div>
+ )}
{/* Redeem Promotion Code (pro only) */}
{isPro && (
- <div className="glass-card animate-in stagger-4" style={{ padding: '22px 24px', marginBottom: 14 }}>
+ <div className="glass-card animate-in stagger-3" style={{ padding: '22px 24px', marginBottom: 14 }}>
<span className="section-title" style={{ marginBottom: 12, display: 'block' }}>Promotion Code</span>
<div style={{ display: 'flex', alignItems: 'end', gap: 14 }}>
<div>
@@ -252,7 +193,7 @@ export default function Billing() {
{/* Invoice History (pro only) */}
{isPro && (
- <div className="glass-card animate-in stagger-5" style={{ padding: '22px 24px' }}>
+ <div className="glass-card animate-in stagger-4" style={{ padding: '22px 24px' }}>
<span className="section-title" style={{ marginBottom: 14, display: 'block' }}>Invoices</span>
{!invoiceData?.invoices?.length ? (
<div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--text-tertiary)', fontSize: 13 }}>
@@ -309,9 +250,3 @@ function InvoiceStatus({ status }: { status: string }) {
}}>{status}</span>
)
}
-
-function formatSeconds(s: number): string {
- if (s < 60) return `${Math.round(s)}s`
- if (s < 3600) return `${Math.round(s / 60)}m`
- return `${(s / 3600).toFixed(1)}h`
-}