diff --git a/internal/db/migrations/00072_payment_provider_columns.sql b/internal/db/migrations/00072_payment_provider_columns.sql new file mode 100644 index 00000000..7789464e --- /dev/null +++ b/internal/db/migrations/00072_payment_provider_columns.sql @@ -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'; + +-- +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; diff --git a/internal/handler/booking_handler.go b/internal/handler/booking_handler.go index f7a09f26..74b51170 100644 --- a/internal/handler/booking_handler.go +++ b/internal/handler/booking_handler.go @@ -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") diff --git a/internal/handler/event_type.go b/internal/handler/event_type.go index dc8eff8e..41fe25c3 100644 --- a/internal/handler/event_type.go +++ b/internal/handler/event_type.go @@ -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 } diff --git a/internal/handler/handler.go b/internal/handler/handler.go index 05898e14..863d03c3 100644 --- a/internal/handler/handler.go +++ b/internal/handler/handler.go @@ -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" ) @@ -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 @@ -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 diff --git a/internal/handler/stripe_booking.go b/internal/handler/stripe_booking.go index 5bf2beb7..b2aba742 100644 --- a/internal/handler/stripe_booking.go +++ b/internal/handler/stripe_booking.go @@ -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{ + AmountMinor: int64(priceCents), Currency: currency, ProductName: productName, CustomerEmail: email, @@ -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 @@ -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 } @@ -55,7 +56,7 @@ 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) @@ -63,20 +64,16 @@ func (h *Handler) StripeWebhook(w http.ResponseWriter, r *http.Request) { 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) } } @@ -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) @@ -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 @@ -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: diff --git a/internal/handler/stripe_refund_test.go b/internal/handler/stripe_refund_test.go index 2fa3afca..0d8e94f1 100644 --- a/internal/handler/stripe_refund_test.go +++ b/internal/handler/stripe_refund_test.go @@ -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) { @@ -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) } @@ -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 diff --git a/internal/handler/stripe_settings.go b/internal/handler/stripe_settings.go index 6c65e35d..1d22067d 100644 --- a/internal/handler/stripe_settings.go +++ b/internal/handler/stripe_settings.go @@ -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. @@ -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 } @@ -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") } diff --git a/internal/payments/payments.go b/internal/payments/payments.go new file mode 100644 index 00000000..0f46d7f7 --- /dev/null +++ b/internal/payments/payments.go @@ -0,0 +1,110 @@ +// Package payments defines the seam between Calnode's booking flow and whichever +// payment gateway actually takes the money. +// +// Step 1 of #246: the interface exists, Stripe is its only implementation, and the +// booking columns are provider-neutral. No behaviour changes. The point is that the +// handler no longer knows what "Stripe" is — it asks a Provider for a checkout, hands +// it a webhook payload, and asks for a refund. +// +// Two decisions are fixed here rather than left to each implementation: +// +// - Money crosses the boundary as an integer count of the currency's minor units +// (Stripe's model: 1050 USD = $10.50) plus an ISO currency code. An adapter whose +// gateway wants a decimal string converts at its own edge, once. Nothing else in +// Calnode should ever see a decimal amount. +// - Refunds are a declared capability, not an assumption. A gateway without a refund +// API returns Capabilities{Refunds: false} and the UI must say so rather than offer +// a button that fails. +// +// Webhook verification is deliberately per-provider: the signature scheme and the +// event vocabulary differ, so each adapter normalizes its own payload into the small +// Event type below. The handler then switches on provider-neutral kinds. +package payments + +import ( + "context" + "errors" + "net/http" + "time" +) + +// ErrRefundNotSupported is returned by Refund when the provider has no refund API. +var ErrRefundNotSupported = errors.New("payments: provider does not support refunds") + +// Capabilities describes what an implementation can actually do. +type Capabilities struct { + // Refunds reports whether Refund() is implemented. False means the UI must not + // offer a refund action for this provider. + Refunds bool + // Webhooks reports whether the provider is configured to verify webhook payloads + // (a signing secret is present). Without it the endpoint refuses to act rather + // than accepting unverified events. + Webhooks bool +} + +// CheckoutRequest is a one-off payment for a held booking. +type CheckoutRequest struct { + AmountMinor int64 // price in the currency's minor units (see the package doc) + Currency string // ISO 4217, any case; adapters normalize + ProductName string // shown on the hosted payment page + CustomerEmail string + SuccessURL string + CancelURL string + ExpiresAt time.Time + // Metadata is echoed back on the webhook. Calnode puts booking_id here and relies + // on it to join the payment to the booking, so adapters must round-trip it. + Metadata map[string]string +} + +// CheckoutSession is the provider-neutral view of a hosted payment session. +type CheckoutSession struct { + ID string // provider session id, stored as bookings.payment_session_id + URL string // where to redirect the payer + Paid bool // whether the provider reports it settled + // PaymentRef is the provider's reference for the money movement (Stripe's + // PaymentIntent id). Stored as bookings.payment_ref; required to refund. + PaymentRef string + AmountMinor int64 + Currency string + Metadata map[string]string +} + +// EventKind is the normalized webhook vocabulary. Providers map their own event +// names onto these; anything Calnode does not act on becomes EventOther. +type EventKind int + +const ( + EventOther EventKind = iota + EventCheckoutCompleted + EventCheckoutExpired +) + +// Event is a provider webhook reduced to what the booking flow reacts to. +type Event struct { + Kind EventKind + Session *CheckoutSession // nil when the provider could not include the session +} + +// RefundRequest asks for a full refund of one payment. +type RefundRequest struct { + PaymentRef string // CheckoutSession.PaymentRef + IdempotencyKey string // e.g. "refund:"; makes retries safe +} + +// Provider is one payment gateway. +// +// Implementations must be safe for concurrent use: a single Provider is shared by +// every request and hot-swapped from the settings page. +type Provider interface { + // Name is the stable identifier persisted on a booking (e.g. "stripe"). + Name() string + Capabilities() Capabilities + CreateCheckout(ctx context.Context, req CheckoutRequest) (*CheckoutSession, error) + GetSession(ctx context.Context, sessionID string) (*CheckoutSession, error) + // ParseWebhook verifies the provider's signature over payload and normalizes the + // event. headers carries the whole request header set because signature header + // names differ per provider. A verification failure must return an error, never a + // zero-value Event, so a forged call can never be mistaken for "nothing to do". + ParseWebhook(payload []byte, headers http.Header, now time.Time) (*Event, error) + Refund(ctx context.Context, req RefundRequest) error +} diff --git a/internal/payments/stripe.go b/internal/payments/stripe.go new file mode 100644 index 00000000..4722cb58 --- /dev/null +++ b/internal/payments/stripe.go @@ -0,0 +1,120 @@ +package payments + +import ( + "context" + "net/http" + "time" + + "github.com/calnode/calnode/internal/stripe" +) + +// StripeProvider adapts internal/stripe to the payments seam. It is the only +// implementation in step 1 of #246; a second gateway is step 4 and is gated on a real +// account to test against. +type StripeProvider struct { + client *stripe.Client +} + +// NewStripe builds the adapter. The signature mirrors stripe.New, so callers that +// already hold the three credentials do not change shape. +func NewStripe(secretKey, publishableKey, webhookSecret string) (*StripeProvider, error) { + c, err := stripe.New(secretKey, publishableKey, webhookSecret) + if err != nil { + return nil, err + } + return &StripeProvider{client: c}, nil +} + +// Name is the value persisted in bookings.payment_provider. +func (p *StripeProvider) Name() string { return "stripe" } + +// Capabilities: Stripe's refund API is always available on a configured account, and +// webhooks are verifiable only once a signing secret is stored. +func (p *StripeProvider) Capabilities() Capabilities { + return Capabilities{Refunds: true, Webhooks: p.client.WebhookConfigured()} +} + +// WebhookConfigured reports whether a signing secret is present. Stripe-specific: the +// settings page uses it to warn before payments are enabled without one. +func (p *StripeProvider) WebhookConfigured() bool { return p.client.WebhookConfigured() } + +// SetAPIBase overrides the Stripe API endpoint. Test-only, mirroring +// stripe.Client.SetAPIBase so handler tests can point at a local fake. +func (p *StripeProvider) SetAPIBase(url string) { p.client.SetAPIBase(url) } + +// PublishableKey is the public key the settings page stores. +func (p *StripeProvider) PublishableKey() string { return p.client.PublishableKey() } + +func (p *StripeProvider) CreateCheckout(ctx context.Context, req CheckoutRequest) (*CheckoutSession, error) { + sess, err := p.client.CreateCheckoutSession(ctx, stripe.CheckoutParams{ + AmountCents: req.AmountMinor, + Currency: req.Currency, + ProductName: req.ProductName, + CustomerEmail: req.CustomerEmail, + SuccessURL: req.SuccessURL, + CancelURL: req.CancelURL, + ExpiresAt: req.ExpiresAt, + Metadata: req.Metadata, + }) + if err != nil { + return nil, err + } + return normalizeSession(sess), nil +} + +func (p *StripeProvider) GetSession(ctx context.Context, sessionID string) (*CheckoutSession, error) { + sess, err := p.client.GetCheckoutSession(ctx, sessionID) + if err != nil { + return nil, err + } + return normalizeSession(sess), nil +} + +// ParseWebhook verifies the Stripe-Signature header and maps the two events Calnode +// acts on. Everything else becomes EventOther, which the handler acknowledges and +// ignores. +func (p *StripeProvider) ParseWebhook(payload []byte, headers http.Header, now time.Time) (*Event, error) { + ev, err := p.client.VerifyWebhook(payload, headers.Get("Stripe-Signature"), now) + if err != nil { + return nil, err + } + + kind := EventOther + switch ev.Type { + case "checkout.session.completed": + kind = EventCheckoutCompleted + case "checkout.session.expired": + kind = EventCheckoutExpired + default: + return &Event{Kind: EventOther}, nil + } + + event := &Event{Kind: kind} + // A completed/expired session should carry one; if the payload cannot be decoded we + // still return the kind so the handler can decide, exactly as before. + if sess, serr := ev.Session(); serr == nil && sess != nil { + event.Session = normalizeSession(sess) + } + return event, nil +} + +func (p *StripeProvider) Refund(ctx context.Context, req RefundRequest) error { + return p.client.Refund(ctx, req.PaymentRef, req.IdempotencyKey) +} + +// normalizeSession maps Stripe's session onto the neutral shape. PaymentStatus is a +// string on Stripe's side; only "paid" means settled. +func normalizeSession(s *stripe.CheckoutSession) *CheckoutSession { + if s == nil { + return nil + } + return &CheckoutSession{ + ID: s.ID, + URL: s.URL, + Paid: s.PaymentStatus == "paid", + PaymentRef: s.PaymentIntent, + AmountMinor: s.AmountTotal, + Currency: s.Currency, + Metadata: s.Metadata, + } +} diff --git a/internal/payments/stripe_test.go b/internal/payments/stripe_test.go new file mode 100644 index 00000000..2d644f8a --- /dev/null +++ b/internal/payments/stripe_test.go @@ -0,0 +1,164 @@ +package payments + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "fmt" + "net/http" + "strconv" + "testing" + "time" +) + +// signStripe builds a valid Stripe-Signature header for payload, so the adapter can be +// tested through its real verification path rather than a stub. +func signStripe(t *testing.T, secret string, payload []byte, at time.Time) string { + t.Helper() + ts := strconv.FormatInt(at.Unix(), 10) + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write([]byte(ts)) + mac.Write([]byte(".")) + mac.Write(payload) + return fmt.Sprintf("t=%s,v1=%s", ts, hex.EncodeToString(mac.Sum(nil))) +} + +const testWebhookSecret = "whsec_test" + +func webhookPayload(eventType, sessionJSON string) []byte { + return []byte(fmt.Sprintf(`{"id":"evt_1","type":%q,"data":{"object":%s}}`, eventType, sessionJSON)) +} + +const paidSession = `{ + "id":"cs_test_1", + "url":"https://checkout.stripe.test/cs_test_1", + "payment_status":"paid", + "payment_intent":"pi_test_1", + "amount_total":2500, + "currency":"eur", + "metadata":{"booking_id":"bk_1"} +}` + +func newTestProvider(t *testing.T) *StripeProvider { + t.Helper() + p, err := NewStripe("sk_test_x", "pk_test_x", testWebhookSecret) + if err != nil { + t.Fatalf("NewStripe: %v", err) + } + return p +} + +func TestStripeProvider_Capabilities(t *testing.T) { + withSecret := newTestProvider(t) + got := withSecret.Capabilities() + if !got.Refunds || !got.Webhooks { + t.Errorf("Capabilities = %+v; want refunds and webhooks true", got) + } + + // Without a signing secret the endpoint must refuse to act rather than accept + // unverified events. + noSecret, err := NewStripe("sk_test_x", "pk_test_x", "") + if err != nil { + t.Fatalf("NewStripe: %v", err) + } + if noSecret.Capabilities().Webhooks { + t.Error("Webhooks = true without a signing secret; want false") + } + if noSecret.Name() != "stripe" { + t.Errorf("Name = %q; want stripe", noSecret.Name()) + } +} + +func TestStripeProvider_ParseWebhook_checkoutCompleted(t *testing.T) { + p := newTestProvider(t) + now := time.Unix(1_800_000_000, 0) + payload := webhookPayload("checkout.session.completed", paidSession) + + ev, err := p.ParseWebhook(payload, http.Header{ + "Stripe-Signature": {signStripe(t, testWebhookSecret, payload, now)}, + }, now) + if err != nil { + t.Fatalf("ParseWebhook: %v", err) + } + if ev.Kind != EventCheckoutCompleted { + t.Fatalf("Kind = %v; want EventCheckoutCompleted", ev.Kind) + } + if ev.Session == nil { + t.Fatal("Session is nil") + } + if !ev.Session.Paid { + t.Error("Paid = false; payment_status was paid") + } + if ev.Session.PaymentRef != "pi_test_1" { + t.Errorf("PaymentRef = %q; want pi_test_1", ev.Session.PaymentRef) + } + if ev.Session.AmountMinor != 2500 { + t.Errorf("AmountMinor = %d; want 2500", ev.Session.AmountMinor) + } + if ev.Session.Currency != "eur" { + t.Errorf("Currency = %q; want eur", ev.Session.Currency) + } + if ev.Session.Metadata["booking_id"] != "bk_1" { + t.Errorf("metadata booking_id = %q; want bk_1", ev.Session.Metadata["booking_id"]) + } +} + +func TestStripeProvider_ParseWebhook_expiredAndOther(t *testing.T) { + p := newTestProvider(t) + now := time.Unix(1_800_000_000, 0) + expired := `{"id":"cs_test_2","payment_status":"unpaid","metadata":{"booking_id":"bk_2"}}` + + payload := webhookPayload("checkout.session.expired", expired) + ev, err := p.ParseWebhook(payload, http.Header{ + "Stripe-Signature": {signStripe(t, testWebhookSecret, payload, now)}, + }, now) + if err != nil { + t.Fatalf("ParseWebhook: %v", err) + } + if ev.Kind != EventCheckoutExpired { + t.Fatalf("Kind = %v; want EventCheckoutExpired", ev.Kind) + } + if ev.Session == nil || ev.Session.Metadata["booking_id"] != "bk_2" { + t.Errorf("Session = %+v; want booking_id bk_2", ev.Session) + } + + // An event Calnode does not act on is acknowledged, not treated as a session. + payload = webhookPayload("payment_intent.created", `{"id":"pi_x"}`) + ev, err = p.ParseWebhook(payload, http.Header{ + "Stripe-Signature": {signStripe(t, testWebhookSecret, payload, now)}, + }, now) + if err != nil { + t.Fatalf("ParseWebhook: %v", err) + } + if ev.Kind != EventOther || ev.Session != nil { + t.Errorf("got Kind=%v Session=%v; want EventOther with no session", ev.Kind, ev.Session) + } +} + +// A forged or replayed payload must fail verification and yield no event, never a +// zero-value one the handler could mistake for "nothing to do". +func TestStripeProvider_ParseWebhook_rejectsBadSignature(t *testing.T) { + p := newTestProvider(t) + now := time.Unix(1_800_000_000, 0) + payload := webhookPayload("checkout.session.completed", paidSession) + + cases := map[string]http.Header{ + "missing header": {}, + "wrong secret": {"Stripe-Signature": {signStripe(t, "whsec_other", payload, now)}}, + "wrong payload": {"Stripe-Signature": {signStripe(t, testWebhookSecret, []byte(`{"id":"evt_evil"}`), now)}}, + "stale timestamp": {"Stripe-Signature": { + signStripe(t, testWebhookSecret, payload, now.Add(-10*time.Minute)), + }}, + } + for name, headers := range cases { + t.Run(name, func(t *testing.T) { + ev, err := p.ParseWebhook(payload, headers, now) + if err == nil { + t.Fatalf("ParseWebhook accepted a bad signature: ev=%+v", ev) + } + if ev != nil { + t.Errorf("event returned on verification failure: %+v", ev) + } + }) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 8116b500..8190241c 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -20,7 +20,7 @@ import ( "github.com/calnode/calnode/internal/mailer" "github.com/calnode/calnode/internal/secret" - "github.com/calnode/calnode/internal/stripe" + "github.com/calnode/calnode/internal/payments" "github.com/calnode/calnode/internal/webhook" "github.com/calnode/calnode/internal/worker" "github.com/calnode/calnode/internal/zoom" @@ -301,10 +301,10 @@ func BuildHandler(ctx context.Context, cfg *config.Config, db *sql.DB, logger *s if dbStripe, dbStripeErr := handler.LoadStripeSettingsFromDB(db, encKey); dbStripeErr != nil { logger.Warn("stripe settings: could not load from database", "error", dbStripeErr) } else if dbStripe != nil { - if sc, err := stripe.New(dbStripe.SecretKey, dbStripe.PublishableKey, dbStripe.WebhookSecret); err != nil { + if sc, err := payments.NewStripe(dbStripe.SecretKey, dbStripe.PublishableKey, dbStripe.WebhookSecret); err != nil { logger.Error("stripe: init failed", "error", err) } else { - h.SetStripe(sc) + h.SetPaymentProvider(sc) logger.Info("Stripe payments configured", "webhook_secret_set", dbStripe.WebhookSecret != "") } } else {