Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions internal/db/migrations/00072_payment_provider_columns.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
-- +goose Up
-- Provider-neutral payment columns (#246 step 1).
--
-- Stripe was the only implementation, so every existing row is Stripe: payment_provider
-- defaults to 'stripe' and step 3 will start writing it explicitly once a second
-- provider exists. The old names stay in the migration history; renaming keeps the data.
ALTER TABLE bookings RENAME COLUMN stripe_session_id TO payment_session_id;
ALTER TABLE bookings RENAME COLUMN stripe_payment_intent_id TO payment_ref;
ALTER TABLE bookings ADD COLUMN payment_provider TEXT NOT NULL DEFAULT 'stripe';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DEFAULT 'stripe' also stamps every row the provider never touched: a new free booking ends up with payment_provider='stripe' while payment_status stays 'none', so the column asserts a payment path that did not happen (existing free rows get it too, via the ADD COLUMN backfill). The default is baked into the column, so revisiting it later costs another migration — DEFAULT '' plus UPDATE bookings SET payment_provider = 'stripe' WHERE payment_session_id <> '' would keep the Stripe rows correct and leave the rest honest.

Technical details
# `payment_provider` should not claim a provider for unpaid rows

## Affected sites
- `internal/db/migrations/00072_payment_provider_columns.sql:9` — `ADD COLUMN payment_provider TEXT NOT NULL DEFAULT 'stripe'` applies to all existing rows and to every future insert that omits it.
- `internal/handler/stripe_booking.go:38` — already writes `provider.Name()` explicitly on the paid path, so the default is only load-bearing for rows that never paid.
- `internal/db/migrations/00037_stripe_payments.sql` — `payment_status` defaults to `'none'`, so `payment_status = 'none'` identifies free bookings.

## Required outcome
- After migration: rows with a real payment session carry the provider that created it; rows with no payment carry no provider (`''`).
- Step 3's "refund follows the provider recorded on the booking" must not read a default that was never written.

## Suggested approach (optional)
- Up: `ADD COLUMN payment_provider TEXT NOT NULL DEFAULT '';` then backfill `WHERE payment_session_id <> ''` (every provider-touched row got a session id at checkout start).
- Down is unchanged — the column is dropped either way.


-- +goose Down
ALTER TABLE bookings DROP COLUMN payment_provider;
ALTER TABLE bookings RENAME COLUMN payment_ref TO stripe_payment_intent_id;
ALTER TABLE bookings RENAME COLUMN payment_session_id TO stripe_session_id;
6 changes: 3 additions & 3 deletions internal/handler/booking_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -994,15 +994,15 @@ func (h *Handler) CreateBooking(w http.ResponseWriter, r *http.Request) {
// send the booker to Stripe Checkout and DEFER all confirmation side-effects until the
// webhook marks the payment paid. Free event types fall through to the normal path.
if et.PriceCents > 0 {
sc := h.getStripe()
if sc == nil {
provider := h.getPaymentProvider()
if provider == nil {
// The price gate requires Stripe at save time, but never strand a charge:
// release the hold and tell the booker payments are unavailable.
_ = h.bookingSvc.CancelByID(r.Context(), b.ID, "payments unavailable")
h.writeError(w, http.StatusServiceUnavailable, "payments are temporarily unavailable")
return
}
checkoutURL, err := h.startBookingCheckout(r.Context(), sc, b.ID, et.PriceCents, et.Currency, et.Name, req.EventTypeSlug, req.Email)
checkoutURL, err := h.startBookingCheckout(r.Context(), provider, b.ID, et.PriceCents, et.Currency, et.Name, req.EventTypeSlug, req.Email)
if err != nil {
h.logger.ErrorContext(r.Context(), "create booking: start checkout", "error", err, "booking_id", b.ID)
_ = h.bookingSvc.CancelByID(r.Context(), b.ID, "checkout failed")
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/event_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -640,7 +640,7 @@ func (h *Handler) PatchEventType(w http.ResponseWriter, r *http.Request) {
}
// A price is only bookable once payments are configured — block the footgun of a
// paid event type that no one can actually book.
if *req.PriceCents > 0 && h.getStripe() == nil {
if *req.PriceCents > 0 && h.getPaymentProvider() == nil {
h.writeError(w, http.StatusBadRequest, "connect Stripe in Settings → Payments before setting a price")
return
}
Expand Down
28 changes: 14 additions & 14 deletions internal/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
"github.com/calnode/calnode/internal/livekit"
"github.com/calnode/calnode/internal/llm"
"github.com/calnode/calnode/internal/mailer"
"github.com/calnode/calnode/internal/stripe"
"github.com/calnode/calnode/internal/payments"
"github.com/calnode/calnode/internal/webhook"
"github.com/calnode/calnode/internal/zoom"
)
Expand Down Expand Up @@ -44,8 +44,8 @@ type Handler struct {
llm *llm.Client // nil when the optional LLM layer is off/unconfigured
zoomMu sync.RWMutex
zoom *zoom.Client // nil when no Zoom app is configured
stripeMu sync.RWMutex
stripe *stripe.Client // nil when payments are unconfigured
paymentsMu sync.RWMutex
payments payments.Provider // nil when payments are unconfigured
livekitMu sync.RWMutex
livekit *livekit.Client // nil when LiveKit video is unconfigured
demoMode bool // true on the public demo instance: disables calendar/Zoom connect
Expand Down Expand Up @@ -77,19 +77,19 @@ func (h *Handler) getLiveKit() *livekit.Client {
return h.livekit
}

// SetStripe swaps the active Stripe client (nil disables paid bookings). Hot-reloadable
// from the Payments settings page.
func (h *Handler) SetStripe(c *stripe.Client) {
h.stripeMu.Lock()
h.stripe = c
h.stripeMu.Unlock()
// SetPaymentProvider swaps the active payment provider (nil disables paid bookings).
// Hot-reloadable from the Payments settings page.
func (h *Handler) SetPaymentProvider(p payments.Provider) {
h.paymentsMu.Lock()
h.payments = p
h.paymentsMu.Unlock()
}

// getStripe returns the active Stripe client, or nil when payments are unconfigured.
func (h *Handler) getStripe() *stripe.Client {
h.stripeMu.RLock()
defer h.stripeMu.RUnlock()
return h.stripe
// getPaymentProvider returns the active provider, or nil when payments are unconfigured.
func (h *Handler) getPaymentProvider() payments.Provider {
h.paymentsMu.RLock()
defer h.paymentsMu.RUnlock()
return h.payments
}

// SetZoom swaps the active Zoom client (nil disables Zoom auto-minting). Hot-reloadable
Expand Down
59 changes: 28 additions & 31 deletions internal/handler/stripe_booking.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,22 @@ import (
"net/http"
"time"

"github.com/calnode/calnode/internal/stripe"
"github.com/calnode/calnode/internal/payments"
)

// checkoutHoldWindow is how long the slot is held while the booker pays. Stripe requires a
// Checkout session to expire between 30 minutes and 24 hours from creation.
const checkoutHoldWindow = 31 * time.Minute

// startBookingCheckout creates a Stripe Checkout session for a held (pending) booking, marks
// the booking pending_payment, and returns the hosted Checkout URL to redirect the booker to.
func (h *Handler) startBookingCheckout(ctx context.Context, sc *stripe.Client, bookingID string, priceCents int, currency, productName, slug, email string) (string, error) {
// startBookingCheckout creates a payment session for a held (pending) booking, marks the
// booking pending_payment, and returns the hosted checkout URL to redirect the booker to.
func (h *Handler) startBookingCheckout(ctx context.Context, provider payments.Provider, bookingID string, priceCents int, currency, productName, slug, email string) (string, error) {
if currency == "" {
currency = "usd"
}
base := h.publicURL()
sess, err := sc.CreateCheckoutSession(ctx, stripe.CheckoutParams{
AmountCents: int64(priceCents),
sess, err := provider.CreateCheckout(ctx, payments.CheckoutRequest{

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The neutral request still carries Stripe's vocabulary: SuccessURL embeds the {CHECKOUT_SESSION_ID} template and the success page reads ?paid=1&session_id=. A second adapter receives a placeholder it will not substitute, so every provider gets redirected to a URL with a literal {CHECKOUT_SESSION_ID} — worth settling the success contract (provider-neutral placeholder, or provider-supplied success params) before step 4 builds on it.

Technical details
# Checkout success URL is Stripe-shaped

## Affected sites
- `internal/handler/stripe_booking.go:28-29` — `"?paid=1&session_id={CHECKOUT_SESSION_ID}"` built in the provider-neutral caller; the comment above it already admits the token is Stripe's.
- `internal/handler/templates/book.html:388-391` — success page reads `params.get('session_id')` for `transaction_id` and the GA4 conversion, so the parameter name is part of the contract.
- `internal/payments/payments.go:51` — `SuccessURL string`, with no statement of who substitutes what.

## Required outcome
- A provider-agnostic way to get the provider's session/payment reference back to the success page (e.g. `SuccessURL` carries `{SESSION_ID}`, which each adapter replaces with its own value and forwards appropriately), and a booking page that reads a neutral parameter.

## Open questions for the human
- Does step 4 care about the GA4 `transaction_id` on a non-Stripe gateway, or is analytics Stripe-only?

AmountMinor: int64(priceCents),
Currency: currency,
ProductName: productName,
CustomerEmail: email,
Expand All @@ -35,8 +35,9 @@ func (h *Handler) startBookingCheckout(ctx context.Context, sc *stripe.Client, b
return "", err
}
if _, err := h.db.ExecContext(ctx,
`UPDATE bookings SET payment_status = 'pending', stripe_session_id = ? WHERE id = ?`,
sess.ID, bookingID); err != nil {
`UPDATE bookings SET payment_status = 'pending', payment_provider = ?, payment_session_id = ?
WHERE id = ?`,
provider.Name(), sess.ID, bookingID); err != nil {
return "", err
}
return sess.URL, nil
Expand All @@ -45,8 +46,8 @@ func (h *Handler) startBookingCheckout(ctx context.Context, sc *stripe.Client, b
// StripeWebhook handles POST /v1/stripe/webhook — Stripe's payment notifications. Public, but
// authenticated by the signing secret (no session cookie, so CSRF middleware doesn't apply).
func (h *Handler) StripeWebhook(w http.ResponseWriter, r *http.Request) {
sc := h.getStripe()
if sc == nil || !sc.WebhookConfigured() {
provider := h.getPaymentProvider()
if provider == nil || !provider.Capabilities().Webhooks {
h.writeError(w, http.StatusServiceUnavailable, "payments not configured")
return
}
Expand All @@ -55,28 +56,24 @@ func (h *Handler) StripeWebhook(w http.ResponseWriter, r *http.Request) {
h.writeError(w, http.StatusBadRequest, "could not read body")
return
}
ev, err := sc.VerifyWebhook(body, r.Header.Get("Stripe-Signature"), time.Now())
ev, err := provider.ParseWebhook(body, r.Header, time.Now())
if err != nil {
// Bad signature → 400 so Stripe surfaces the failure (and a forged call is rejected).
h.logger.WarnContext(r.Context(), "stripe webhook: verify failed", "error", err)
h.writeError(w, http.StatusBadRequest, "signature verification failed")
return
}

switch ev.Type {
case "checkout.session.completed":
sess, perr := ev.Session()
if perr != nil {
break
}
if sess.PaymentStatus == "paid" {
if id := sess.Metadata["booking_id"]; id != "" {
h.confirmPaidBooking(context.Background(), id, sess.PaymentIntent, int(sess.AmountTotal), sess.Currency)
switch ev.Kind {
case payments.EventCheckoutCompleted:
if ev.Session != nil && ev.Session.Paid {
if id := ev.Session.Metadata["booking_id"]; id != "" {
h.confirmPaidBooking(context.Background(), id, ev.Session.PaymentRef, int(ev.Session.AmountMinor), ev.Session.Currency)
}
}
case "checkout.session.expired":
if sess, perr := ev.Session(); perr == nil {
if id := sess.Metadata["booking_id"]; id != "" {
case payments.EventCheckoutExpired:
if ev.Session != nil {
if id := ev.Session.Metadata["booking_id"]; id != "" {
h.releaseUnpaidHold(context.Background(), id)
}
}
Expand All @@ -93,7 +90,7 @@ func (h *Handler) confirmPaidBooking(ctx context.Context, bookingID, paymentInte
defer cancel()

res, err := h.db.ExecContext(ctx,
`UPDATE bookings SET payment_status = 'paid', stripe_payment_intent_id = ?,
`UPDATE bookings SET payment_status = 'paid', payment_ref = ?,
amount_paid_cents = ?, amount_paid_currency = ?
WHERE id = ? AND payment_status = 'pending'`,
paymentIntentID, amountCents, currency, bookingID)
Expand Down Expand Up @@ -152,17 +149,17 @@ func (h *Handler) releaseUnpaidHold(ctx context.Context, bookingID string) {
// retried request returns the original refund, and a failed Stripe call reverts
// the claim so a later cancel retries instead of losing the refund.
func (h *Handler) refundBookingPayment(ctx context.Context, bookingID string) {
sc := h.getStripe()
if sc == nil {
provider := h.getPaymentProvider()
if provider == nil || !provider.Capabilities().Refunds {
return
}
var intentID string
var paymentRef string
if err := h.db.QueryRowContext(ctx,
`SELECT COALESCE(stripe_payment_intent_id, '') FROM bookings WHERE id = ?`,
bookingID).Scan(&intentID); err != nil {
`SELECT COALESCE(payment_ref, '') FROM bookings WHERE id = ?`,
bookingID).Scan(&paymentRef); err != nil {
return
}
if intentID == "" {
if paymentRef == "" {
return
}
// Claim the refund: only a row still marked paid flips to refunding. A
Expand All @@ -177,7 +174,7 @@ func (h *Handler) refundBookingPayment(ctx context.Context, bookingID string) {
if n, _ := claimed.RowsAffected(); n == 0 {
return // already refunded/refunding, or never paid
}
if err := sc.Refund(ctx, intentID, "refund:"+bookingID); err != nil {
if err := provider.Refund(ctx, payments.RefundRequest{PaymentRef: paymentRef, IdempotencyKey: "refund:" + bookingID}); err != nil {
h.logger.ErrorContext(ctx, "stripe: refund on cancel", "error", err, "booking_id", bookingID)
// Revert the claim so a later cancel retries; the money was not moved.
// If the revert itself fails, the row stays 'refunding' — still safe:
Expand Down
8 changes: 4 additions & 4 deletions internal/handler/stripe_refund_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"testing"

"github.com/calnode/calnode/internal/db"
"github.com/calnode/calnode/internal/stripe"
"github.com/calnode/calnode/internal/payments"
)

func newRefundTestSetup(t *testing.T) (*Handler, *sql.DB, string) {
Expand All @@ -38,7 +38,7 @@ func newRefundTestSetup(t *testing.T) (*Handler, *sql.DB, string) {
if _, err := database.Exec(`INSERT INTO event_types (id,user_id,slug,name,duration_minutes) VALUES ('et-pay',?,'et-pay','E',30)`, ownerID); err != nil {
t.Fatalf("event type: %v", err)
}
if _, err := database.Exec(`INSERT INTO bookings (id,event_type_id,host_id,start_at,end_at,status,payment_status,stripe_payment_intent_id)
if _, err := database.Exec(`INSERT INTO bookings (id,event_type_id,host_id,start_at,end_at,status,payment_status,payment_ref)
VALUES ('b-pay','et-pay',?,'2099-01-01T10:00:00Z','2099-01-01T10:30:00Z','confirmed','paid','pi_test_123')`, ownerID); err != nil {
t.Fatalf("booking: %v", err)
}
Expand All @@ -49,12 +49,12 @@ func refundTestClient(t *testing.T, h *Handler, handler func(w http.ResponseWrit
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(handler))
t.Cleanup(srv.Close)
sc, err := stripe.New("sk_test_x", "", "")
sc, err := payments.NewStripe("sk_test_x", "", "")
if err != nil {
t.Fatal(err)
}
sc.SetAPIBase(srv.URL)
h.SetStripe(sc)
h.SetPaymentProvider(sc)
}

// TestRefundBookingPayment_claimsOnce proves two cancels for the same paid booking
Expand Down
10 changes: 5 additions & 5 deletions internal/handler/stripe_settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import (
"fmt"
"net/http"

"github.com/calnode/calnode/internal/payments"
"github.com/calnode/calnode/internal/secret"
"github.com/calnode/calnode/internal/stripe"
)

// StripeConfig holds decrypted Stripe settings loaded from the DB.
Expand Down Expand Up @@ -103,7 +103,7 @@ func (h *Handler) PatchStripeSettings(w http.ResponseWriter, r *http.Request) {
h.writeError(w, http.StatusInternalServerError, "internal error")
return
}
h.SetStripe(nil)
h.SetPaymentProvider(nil)
h.GetStripeSettings(w, r)
return
}
Expand Down Expand Up @@ -156,13 +156,13 @@ func (h *Handler) PatchStripeSettings(w http.ResponseWriter, r *http.Request) {
return
}
if cfg == nil {
h.SetStripe(nil)
} else if sc, err := stripe.New(cfg.SecretKey, cfg.PublishableKey, cfg.WebhookSecret); err != nil {
h.SetPaymentProvider(nil)
} else if sc, err := payments.NewStripe(cfg.SecretKey, cfg.PublishableKey, cfg.WebhookSecret); err != nil {
h.logger.ErrorContext(r.Context(), "stripe settings: init client", "error", err)
h.writeError(w, http.StatusInternalServerError, "failed to initialize Stripe client")
return
} else {
h.SetStripe(sc)
h.SetPaymentProvider(sc)
h.logger.Info("stripe settings: credentials updated and client hot-reloaded")
}

Expand Down
Loading
Loading