Skip to content

Commit 1edce9d

Browse files
committed
feat(payments): extract a provider seam and neutralise the payment columns (#246)
Step 1 of #246. No behaviour change: Stripe is still the only implementation and the endpoint, settings and user-visible flow are untouched. What changes is that the handler no longer names Stripe. New package internal/payments: type Provider interface { Name() string Capabilities() Capabilities CreateCheckout(ctx, CheckoutRequest) (*CheckoutSession, error) GetSession(ctx, id) (*CheckoutSession, error) ParseWebhook(payload, headers, now) (*Event, error) Refund(ctx, RefundRequest) error } Two decisions are fixed at the boundary rather than left to each adapter: - Money crosses as an integer count of minor units plus an ISO currency code (Stripe's model). A gateway wanting a decimal string converts at its own edge, once; nothing else in Calnode sees a decimal amount. - Refunds are a declared capability. Capabilities{Refunds:false} means the UI must not offer the action, rather than offering a button that fails. Webhooks are verified per provider and normalized to EventKind (completed, expired, other). A failed signature returns an error and no event, never a zero-value one the handler could mistake for "nothing to do". Handler changes: stripe.Client -> payments.Provider (SetPaymentProvider / getPaymentProvider, guarded by the same mutex). The refund path now checks the refund capability before claiming the row, so a provider without refunds cannot half-claim it. Schema, migration 00072: stripe_session_id -> payment_session_id stripe_payment_intent_id -> payment_ref + payment_provider TEXT NOT NULL DEFAULT 'stripe' Existing rows are Stripe by definition, so the default is correct for them and for new rows until step 3 writes it explicitly. Verified: - Old binary on a fresh DB, with a paid booking holding cs_old_1/pi_old_1, then the new binary on the same database: 00072 applies and the row reads payment_provider=stripe, payment_session_id=cs_old_1, payment_ref=pi_old_1, payment_status=paid. Data survives the rename. - Payments-off paths unchanged: POST /v1/stripe/webhook 503, / 302, /admin/ 200. - New internal/payments tests cover the neutral session mapping, all three event kinds, and rejection of missing/wrong-secret/wrong-payload/stale signatures. - go test ./... green.
1 parent 2556e3b commit 1edce9d

11 files changed

Lines changed: 466 additions & 61 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
-- +goose Up
2+
-- Provider-neutral payment columns (#246 step 1).
3+
--
4+
-- Stripe was the only implementation, so every existing row is Stripe: payment_provider
5+
-- defaults to 'stripe' and step 3 will start writing it explicitly once a second
6+
-- provider exists. The old names stay in the migration history; renaming keeps the data.
7+
ALTER TABLE bookings RENAME COLUMN stripe_session_id TO payment_session_id;
8+
ALTER TABLE bookings RENAME COLUMN stripe_payment_intent_id TO payment_ref;
9+
ALTER TABLE bookings ADD COLUMN payment_provider TEXT NOT NULL DEFAULT 'stripe';
10+
11+
-- +goose Down
12+
ALTER TABLE bookings DROP COLUMN payment_provider;
13+
ALTER TABLE bookings RENAME COLUMN payment_ref TO stripe_payment_intent_id;
14+
ALTER TABLE bookings RENAME COLUMN payment_session_id TO stripe_session_id;

‎internal/handler/booking_handler.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -994,15 +994,15 @@ func (h *Handler) CreateBooking(w http.ResponseWriter, r *http.Request) {
994994
// send the booker to Stripe Checkout and DEFER all confirmation side-effects until the
995995
// webhook marks the payment paid. Free event types fall through to the normal path.
996996
if et.PriceCents > 0 {
997-
sc := h.getStripe()
998-
if sc == nil {
997+
provider := h.getPaymentProvider()
998+
if provider == nil {
999999
// The price gate requires Stripe at save time, but never strand a charge:
10001000
// release the hold and tell the booker payments are unavailable.
10011001
_ = h.bookingSvc.CancelByID(r.Context(), b.ID, "payments unavailable")
10021002
h.writeError(w, http.StatusServiceUnavailable, "payments are temporarily unavailable")
10031003
return
10041004
}
1005-
checkoutURL, err := h.startBookingCheckout(r.Context(), sc, b.ID, et.PriceCents, et.Currency, et.Name, req.EventTypeSlug, req.Email)
1005+
checkoutURL, err := h.startBookingCheckout(r.Context(), provider, b.ID, et.PriceCents, et.Currency, et.Name, req.EventTypeSlug, req.Email)
10061006
if err != nil {
10071007
h.logger.ErrorContext(r.Context(), "create booking: start checkout", "error", err, "booking_id", b.ID)
10081008
_ = h.bookingSvc.CancelByID(r.Context(), b.ID, "checkout failed")

‎internal/handler/event_type.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -640,7 +640,7 @@ func (h *Handler) PatchEventType(w http.ResponseWriter, r *http.Request) {
640640
}
641641
// A price is only bookable once payments are configured — block the footgun of a
642642
// paid event type that no one can actually book.
643-
if *req.PriceCents > 0 && h.getStripe() == nil {
643+
if *req.PriceCents > 0 && h.getPaymentProvider() == nil {
644644
h.writeError(w, http.StatusBadRequest, "connect Stripe in Settings → Payments before setting a price")
645645
return
646646
}

‎internal/handler/handler.go‎

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import (
1515
"github.com/calnode/calnode/internal/livekit"
1616
"github.com/calnode/calnode/internal/llm"
1717
"github.com/calnode/calnode/internal/mailer"
18-
"github.com/calnode/calnode/internal/stripe"
18+
"github.com/calnode/calnode/internal/payments"
1919
"github.com/calnode/calnode/internal/webhook"
2020
"github.com/calnode/calnode/internal/zoom"
2121
)
@@ -44,8 +44,8 @@ type Handler struct {
4444
llm *llm.Client // nil when the optional LLM layer is off/unconfigured
4545
zoomMu sync.RWMutex
4646
zoom *zoom.Client // nil when no Zoom app is configured
47-
stripeMu sync.RWMutex
48-
stripe *stripe.Client // nil when payments are unconfigured
47+
paymentsMu sync.RWMutex
48+
payments payments.Provider // nil when payments are unconfigured
4949
livekitMu sync.RWMutex
5050
livekit *livekit.Client // nil when LiveKit video is unconfigured
5151
demoMode bool // true on the public demo instance: disables calendar/Zoom connect
@@ -77,19 +77,19 @@ func (h *Handler) getLiveKit() *livekit.Client {
7777
return h.livekit
7878
}
7979

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

88-
// getStripe returns the active Stripe client, or nil when payments are unconfigured.
89-
func (h *Handler) getStripe() *stripe.Client {
90-
h.stripeMu.RLock()
91-
defer h.stripeMu.RUnlock()
92-
return h.stripe
88+
// getPaymentProvider returns the active provider, or nil when payments are unconfigured.
89+
func (h *Handler) getPaymentProvider() payments.Provider {
90+
h.paymentsMu.RLock()
91+
defer h.paymentsMu.RUnlock()
92+
return h.payments
9393
}
9494

9595
// SetZoom swaps the active Zoom client (nil disables Zoom auto-minting). Hot-reloadable

‎internal/handler/stripe_booking.go‎

Lines changed: 28 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,22 @@ import (
66
"net/http"
77
"time"
88

9-
"github.com/calnode/calnode/internal/stripe"
9+
"github.com/calnode/calnode/internal/payments"
1010
)
1111

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

16-
// startBookingCheckout creates a Stripe Checkout session for a held (pending) booking, marks
17-
// the booking pending_payment, and returns the hosted Checkout URL to redirect the booker to.
18-
func (h *Handler) startBookingCheckout(ctx context.Context, sc *stripe.Client, bookingID string, priceCents int, currency, productName, slug, email string) (string, error) {
16+
// startBookingCheckout creates a payment session for a held (pending) booking, marks the
17+
// booking pending_payment, and returns the hosted checkout URL to redirect the booker to.
18+
func (h *Handler) startBookingCheckout(ctx context.Context, provider payments.Provider, bookingID string, priceCents int, currency, productName, slug, email string) (string, error) {
1919
if currency == "" {
2020
currency = "usd"
2121
}
2222
base := h.publicURL()
23-
sess, err := sc.CreateCheckoutSession(ctx, stripe.CheckoutParams{
24-
AmountCents: int64(priceCents),
23+
sess, err := provider.CreateCheckout(ctx, payments.CheckoutRequest{
24+
AmountMinor: int64(priceCents),
2525
Currency: currency,
2626
ProductName: productName,
2727
CustomerEmail: email,
@@ -35,8 +35,9 @@ func (h *Handler) startBookingCheckout(ctx context.Context, sc *stripe.Client, b
3535
return "", err
3636
}
3737
if _, err := h.db.ExecContext(ctx,
38-
`UPDATE bookings SET payment_status = 'pending', stripe_session_id = ? WHERE id = ?`,
39-
sess.ID, bookingID); err != nil {
38+
`UPDATE bookings SET payment_status = 'pending', payment_provider = ?, payment_session_id = ?
39+
WHERE id = ?`,
40+
provider.Name(), sess.ID, bookingID); err != nil {
4041
return "", err
4142
}
4243
return sess.URL, nil
@@ -45,8 +46,8 @@ func (h *Handler) startBookingCheckout(ctx context.Context, sc *stripe.Client, b
4546
// StripeWebhook handles POST /v1/stripe/webhook — Stripe's payment notifications. Public, but
4647
// authenticated by the signing secret (no session cookie, so CSRF middleware doesn't apply).
4748
func (h *Handler) StripeWebhook(w http.ResponseWriter, r *http.Request) {
48-
sc := h.getStripe()
49-
if sc == nil || !sc.WebhookConfigured() {
49+
provider := h.getPaymentProvider()
50+
if provider == nil || !provider.Capabilities().Webhooks {
5051
h.writeError(w, http.StatusServiceUnavailable, "payments not configured")
5152
return
5253
}
@@ -55,28 +56,24 @@ func (h *Handler) StripeWebhook(w http.ResponseWriter, r *http.Request) {
5556
h.writeError(w, http.StatusBadRequest, "could not read body")
5657
return
5758
}
58-
ev, err := sc.VerifyWebhook(body, r.Header.Get("Stripe-Signature"), time.Now())
59+
ev, err := provider.ParseWebhook(body, r.Header, time.Now())
5960
if err != nil {
6061
// Bad signature → 400 so Stripe surfaces the failure (and a forged call is rejected).
6162
h.logger.WarnContext(r.Context(), "stripe webhook: verify failed", "error", err)
6263
h.writeError(w, http.StatusBadRequest, "signature verification failed")
6364
return
6465
}
6566

66-
switch ev.Type {
67-
case "checkout.session.completed":
68-
sess, perr := ev.Session()
69-
if perr != nil {
70-
break
71-
}
72-
if sess.PaymentStatus == "paid" {
73-
if id := sess.Metadata["booking_id"]; id != "" {
74-
h.confirmPaidBooking(context.Background(), id, sess.PaymentIntent, int(sess.AmountTotal), sess.Currency)
67+
switch ev.Kind {
68+
case payments.EventCheckoutCompleted:
69+
if ev.Session != nil && ev.Session.Paid {
70+
if id := ev.Session.Metadata["booking_id"]; id != "" {
71+
h.confirmPaidBooking(context.Background(), id, ev.Session.PaymentRef, int(ev.Session.AmountMinor), ev.Session.Currency)
7572
}
7673
}
77-
case "checkout.session.expired":
78-
if sess, perr := ev.Session(); perr == nil {
79-
if id := sess.Metadata["booking_id"]; id != "" {
74+
case payments.EventCheckoutExpired:
75+
if ev.Session != nil {
76+
if id := ev.Session.Metadata["booking_id"]; id != "" {
8077
h.releaseUnpaidHold(context.Background(), id)
8178
}
8279
}
@@ -93,7 +90,7 @@ func (h *Handler) confirmPaidBooking(ctx context.Context, bookingID, paymentInte
9390
defer cancel()
9491

9592
res, err := h.db.ExecContext(ctx,
96-
`UPDATE bookings SET payment_status = 'paid', stripe_payment_intent_id = ?,
93+
`UPDATE bookings SET payment_status = 'paid', payment_ref = ?,
9794
amount_paid_cents = ?, amount_paid_currency = ?
9895
WHERE id = ? AND payment_status = 'pending'`,
9996
paymentIntentID, amountCents, currency, bookingID)
@@ -152,17 +149,17 @@ func (h *Handler) releaseUnpaidHold(ctx context.Context, bookingID string) {
152149
// retried request returns the original refund, and a failed Stripe call reverts
153150
// the claim so a later cancel retries instead of losing the refund.
154151
func (h *Handler) refundBookingPayment(ctx context.Context, bookingID string) {
155-
sc := h.getStripe()
156-
if sc == nil {
152+
provider := h.getPaymentProvider()
153+
if provider == nil || !provider.Capabilities().Refunds {
157154
return
158155
}
159-
var intentID string
156+
var paymentRef string
160157
if err := h.db.QueryRowContext(ctx,
161-
`SELECT COALESCE(stripe_payment_intent_id, '') FROM bookings WHERE id = ?`,
162-
bookingID).Scan(&intentID); err != nil {
158+
`SELECT COALESCE(payment_ref, '') FROM bookings WHERE id = ?`,
159+
bookingID).Scan(&paymentRef); err != nil {
163160
return
164161
}
165-
if intentID == "" {
162+
if paymentRef == "" {
166163
return
167164
}
168165
// Claim the refund: only a row still marked paid flips to refunding. A
@@ -177,7 +174,7 @@ func (h *Handler) refundBookingPayment(ctx context.Context, bookingID string) {
177174
if n, _ := claimed.RowsAffected(); n == 0 {
178175
return // already refunded/refunding, or never paid
179176
}
180-
if err := sc.Refund(ctx, intentID, "refund:"+bookingID); err != nil {
177+
if err := provider.Refund(ctx, payments.RefundRequest{PaymentRef: paymentRef, IdempotencyKey: "refund:" + bookingID}); err != nil {
181178
h.logger.ErrorContext(ctx, "stripe: refund on cancel", "error", err, "booking_id", bookingID)
182179
// Revert the claim so a later cancel retries; the money was not moved.
183180
// If the revert itself fails, the row stays 'refunding' — still safe:

‎internal/handler/stripe_refund_test.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import (
1111
"testing"
1212

1313
"github.com/calnode/calnode/internal/db"
14-
"github.com/calnode/calnode/internal/stripe"
14+
"github.com/calnode/calnode/internal/payments"
1515
)
1616

1717
func newRefundTestSetup(t *testing.T) (*Handler, *sql.DB, string) {
@@ -38,7 +38,7 @@ func newRefundTestSetup(t *testing.T) (*Handler, *sql.DB, string) {
3838
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 {
3939
t.Fatalf("event type: %v", err)
4040
}
41-
if _, err := database.Exec(`INSERT INTO bookings (id,event_type_id,host_id,start_at,end_at,status,payment_status,stripe_payment_intent_id)
41+
if _, err := database.Exec(`INSERT INTO bookings (id,event_type_id,host_id,start_at,end_at,status,payment_status,payment_ref)
4242
VALUES ('b-pay','et-pay',?,'2099-01-01T10:00:00Z','2099-01-01T10:30:00Z','confirmed','paid','pi_test_123')`, ownerID); err != nil {
4343
t.Fatalf("booking: %v", err)
4444
}
@@ -49,12 +49,12 @@ func refundTestClient(t *testing.T, h *Handler, handler func(w http.ResponseWrit
4949
t.Helper()
5050
srv := httptest.NewServer(http.HandlerFunc(handler))
5151
t.Cleanup(srv.Close)
52-
sc, err := stripe.New("sk_test_x", "", "")
52+
sc, err := payments.NewStripe("sk_test_x", "", "")
5353
if err != nil {
5454
t.Fatal(err)
5555
}
5656
sc.SetAPIBase(srv.URL)
57-
h.SetStripe(sc)
57+
h.SetPaymentProvider(sc)
5858
}
5959

6060
// TestRefundBookingPayment_claimsOnce proves two cancels for the same paid booking

‎internal/handler/stripe_settings.go‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ import (
66
"fmt"
77
"net/http"
88

9+
"github.com/calnode/calnode/internal/payments"
910
"github.com/calnode/calnode/internal/secret"
10-
"github.com/calnode/calnode/internal/stripe"
1111
)
1212

1313
// StripeConfig holds decrypted Stripe settings loaded from the DB.
@@ -103,7 +103,7 @@ func (h *Handler) PatchStripeSettings(w http.ResponseWriter, r *http.Request) {
103103
h.writeError(w, http.StatusInternalServerError, "internal error")
104104
return
105105
}
106-
h.SetStripe(nil)
106+
h.SetPaymentProvider(nil)
107107
h.GetStripeSettings(w, r)
108108
return
109109
}
@@ -156,13 +156,13 @@ func (h *Handler) PatchStripeSettings(w http.ResponseWriter, r *http.Request) {
156156
return
157157
}
158158
if cfg == nil {
159-
h.SetStripe(nil)
160-
} else if sc, err := stripe.New(cfg.SecretKey, cfg.PublishableKey, cfg.WebhookSecret); err != nil {
159+
h.SetPaymentProvider(nil)
160+
} else if sc, err := payments.NewStripe(cfg.SecretKey, cfg.PublishableKey, cfg.WebhookSecret); err != nil {
161161
h.logger.ErrorContext(r.Context(), "stripe settings: init client", "error", err)
162162
h.writeError(w, http.StatusInternalServerError, "failed to initialize Stripe client")
163163
return
164164
} else {
165-
h.SetStripe(sc)
165+
h.SetPaymentProvider(sc)
166166
h.logger.Info("stripe settings: credentials updated and client hot-reloaded")
167167
}
168168

0 commit comments

Comments
 (0)