From 7f4aff62c903ff921a3d75791bdc4d66d3c41326 Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Thu, 5 Nov 2026 19:08:50 +0200 Subject: [PATCH 01/16] MakeCommerce integration --- internal/handler/handler.go | 2 +- internal/handler/stripe_booking.go | 55 +- internal/handler/stripe_refund_test.go | 46 +- internal/handler/stripe_settings.go | 41 +- internal/makecommerce/makecommerce.go | 574 +++++++++++++++++++++ internal/makecommerce/makecommerce_test.go | 515 ++++++++++++++++++ internal/server/server.go | 16 +- 7 files changed, 1189 insertions(+), 60 deletions(-) create mode 100644 internal/makecommerce/makecommerce.go create mode 100644 internal/makecommerce/makecommerce_test.go diff --git a/internal/handler/handler.go b/internal/handler/handler.go index 05898e14..ed3712f1 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" + stripe "github.com/calnode/calnode/internal/makecommerce" "github.com/calnode/calnode/internal/webhook" "github.com/calnode/calnode/internal/zoom" ) diff --git a/internal/handler/stripe_booking.go b/internal/handler/stripe_booking.go index 5bf2beb7..0ac02e0b 100644 --- a/internal/handler/stripe_booking.go +++ b/internal/handler/stripe_booking.go @@ -6,27 +6,31 @@ import ( "net/http" "time" - "github.com/calnode/calnode/internal/stripe" + stripe "github.com/calnode/calnode/internal/makecommerce" ) -// 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. +// checkoutHoldWindow is how long the slot is held while the booker pays. +// MakeCommerce uses a fixed 30-minute expiry, but we keep 31 minutes for safety. 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. +// startBookingCheckout creates a payment transaction for a held (pending) booking, marks +// the booking pending_payment, and returns the hosted payment URL to redirect the booker to. +// For MakeCommerce, the transaction ID is used instead of Stripe's session ID. func (h *Handler) startBookingCheckout(ctx context.Context, sc *stripe.Client, bookingID string, priceCents int, currency, productName, slug, email string) (string, error) { if currency == "" { - currency = "usd" + currency = "eur" // MakeCommerce primarily uses EUR } base := h.publicURL() + // For MakeCommerce, we pass the transaction reference in the customer_url + // The transaction ID will be returned and can be used to query status sess, err := sc.CreateCheckoutSession(ctx, stripe.CheckoutParams{ AmountCents: int64(priceCents), Currency: currency, ProductName: productName, CustomerEmail: email, - // Stripe substitutes {CHECKOUT_SESSION_ID}; the page shows a "payment received" banner. - SuccessURL: base + "/book/" + slug + "?paid=1&session_id={CHECKOUT_SESSION_ID}", + // MakeCommerce doesn't use template variables like Stripe's {CHECKOUT_SESSION_ID} + // Instead, we include the booking_id in the reference and handle it on success + SuccessURL: base + "/book/" + slug + "?paid=1&session_id=" + bookingID, CancelURL: base + "/book/" + slug, ExpiresAt: time.Now().Add(checkoutHoldWindow), Metadata: map[string]string{"booking_id": bookingID}, @@ -42,8 +46,10 @@ func (h *Handler) startBookingCheckout(ctx context.Context, sc *stripe.Client, b return sess.URL, nil } -// 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). +// StripeWebhook handles POST /v1/stripe/webhook — payment provider notifications. +// For MakeCommerce, this receives transaction status updates. Public, but authenticated +// by the signing secret (no session cookie, so CSRF middleware doesn't apply). +// MakeCommerce sends webhook data as URL-encoded form with json and mac fields. func (h *Handler) StripeWebhook(w http.ResponseWriter, r *http.Request) { sc := h.getStripe() if sc == nil || !sc.WebhookConfigured() { @@ -55,10 +61,14 @@ 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()) + + // For MakeCommerce, the MAC is in the form data itself, not in a header. + // We pass the raw body which contains json={...}&mac=... + // The VerifyWebhook implementation will parse and verify the MAC. + ev, err := sc.VerifyWebhook(body, "", 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) + // Bad signature → 400 so the payment provider surfaces the failure. + h.logger.WarnContext(r.Context(), "payment webhook: verify failed", "error", err) h.writeError(w, http.StatusBadRequest, "signature verification failed") return } @@ -81,7 +91,7 @@ func (h *Handler) StripeWebhook(w http.ResponseWriter, r *http.Request) { } } } - // Acknowledge so Stripe stops retrying (we've durably acted, or chosen to ignore). + // Acknowledge so the payment provider stops retrying (we've durably acted, or chosen to ignore). w.WriteHeader(http.StatusOK) } @@ -92,13 +102,14 @@ func (h *Handler) confirmPaidBooking(ctx context.Context, bookingID, paymentInte ctx, cancel := context.WithTimeout(ctx, 15*time.Second) defer cancel() + // For MakeCommerce, paymentIntentID is actually the transaction ID res, err := h.db.ExecContext(ctx, `UPDATE bookings SET payment_status = 'paid', stripe_payment_intent_id = ?, amount_paid_cents = ?, amount_paid_currency = ? WHERE id = ? AND payment_status = 'pending'`, paymentIntentID, amountCents, currency, bookingID) if err != nil { - h.logger.ErrorContext(ctx, "stripe: mark booking paid", "error", err, "booking_id", bookingID) + h.logger.ErrorContext(ctx, "payment: mark booking paid", "error", err, "booking_id", bookingID) return } if n, _ := res.RowsAffected(); n == 0 { @@ -107,7 +118,7 @@ func (h *Handler) confirmPaidBooking(ctx context.Context, bookingID, paymentInte b, err := h.bookingSvc.Get(ctx, bookingID) if err != nil || b == nil { - h.logger.ErrorContext(ctx, "stripe: load paid booking", "error", err, "booking_id", bookingID) + h.logger.ErrorContext(ctx, "payment: load paid booking", "error", err, "booking_id", bookingID) return } // Reconstruct the confirmation context from the booking's event type + organizer. @@ -119,11 +130,11 @@ func (h *Handler) confirmPaidBooking(ctx context.Context, bookingID, paymentInte JOIN booking_attendees a ON a.booking_id = b.id AND a.is_organizer = 1 WHERE b.id = ?`, bookingID). Scan(&in.EventTypeName, &in.EventTypeSlug, &in.LocationType, &in.OrganizerName, &in.OrganizerEmail, &in.OrganizerTimezone, &in.OrganizerLocale); err != nil { - h.logger.ErrorContext(ctx, "stripe: load confirmation input", "error", err, "booking_id", bookingID) + h.logger.ErrorContext(ctx, "payment: load confirmation input", "error", err, "booking_id", bookingID) return } // Run the same side-effects a free booking gets (calendar, emails, Zoom/Meet, webhooks) in - // the background, so the webhook is acknowledged immediately (well under Stripe's timeout). + // the background, so the webhook is acknowledged immediately. // dispatchBookingConfirmation manages its own context, so fire-and-forget is safe. go h.dispatchBookingConfirmation(b, in) // #nosec G118 -- deliberately its own context.Background(); see dispatchBookingConfirmation's doc comment } @@ -151,12 +162,14 @@ func (h *Handler) releaseUnpaidHold(ctx context.Context, bookingID string) { // (only one claimant wins), the Stripe call carries an idempotency key so a // retried request returns the original refund, and a failed Stripe call reverts // the claim so a later cancel retries instead of losing the refund. +// For MakeCommerce, intentID is actually the transaction ID. func (h *Handler) refundBookingPayment(ctx context.Context, bookingID string) { sc := h.getStripe() if sc == nil { return } var intentID string + // For MakeCommerce, we store the transaction ID in stripe_payment_intent_id if err := h.db.QueryRowContext(ctx, `SELECT COALESCE(stripe_payment_intent_id, '') FROM bookings WHERE id = ?`, bookingID).Scan(&intentID); err != nil { @@ -171,14 +184,14 @@ func (h *Handler) refundBookingPayment(ctx context.Context, bookingID string) { `UPDATE bookings SET payment_status = 'refunding' WHERE id = ? AND payment_status = 'paid'`, bookingID) if err != nil { - h.logger.ErrorContext(ctx, "stripe: claim refund", "error", err, "booking_id", bookingID) + h.logger.ErrorContext(ctx, "payment: claim refund", "error", err, "booking_id", bookingID) return } if n, _ := claimed.RowsAffected(); n == 0 { return // already refunded/refunding, or never paid } if err := sc.Refund(ctx, intentID, "refund:"+bookingID); err != nil { - h.logger.ErrorContext(ctx, "stripe: refund on cancel", "error", err, "booking_id", bookingID) + h.logger.ErrorContext(ctx, "payment: 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: // no other cancel will claim it, and the error is logged above. @@ -190,6 +203,6 @@ func (h *Handler) refundBookingPayment(ctx context.Context, bookingID string) { if _, err := h.db.ExecContext(ctx, `UPDATE bookings SET payment_status = 'refunded' WHERE id = ? AND payment_status = 'refunding'`, bookingID); err != nil { - h.logger.ErrorContext(ctx, "stripe: mark refunded", "error", err, "booking_id", bookingID) + h.logger.ErrorContext(ctx, "payment: mark refunded", "error", err, "booking_id", bookingID) } } diff --git a/internal/handler/stripe_refund_test.go b/internal/handler/stripe_refund_test.go index 2fa3afca..4050ea15 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" + stripe "github.com/calnode/calnode/internal/makecommerce" ) func newRefundTestSetup(t *testing.T) (*Handler, *sql.DB, string) { @@ -58,26 +58,39 @@ func refundTestClient(t *testing.T, h *Handler, handler func(w http.ResponseWrit } // TestRefundBookingPayment_claimsOnce proves two cancels for the same paid booking -// produce a single Stripe refund call: the conditional claim UPDATE lets exactly one -// claimant through, and the Stripe call carries an idempotency key. +// produce a single refund call: the conditional claim UPDATE lets exactly one +// claimant through, and the refund call carries an idempotency key. +// For MakeCommerce, this also requires mocking the GetCheckoutSession endpoint. func TestRefundBookingPayment_claimsOnce(t *testing.T) { h, database, _ := newRefundTestSetup(t) - var calls atomic.Int32 + var refundCalls atomic.Int32 var idemKey string refundTestClient(t, h, func(w http.ResponseWriter, r *http.Request) { - calls.Add(1) - idemKey = r.Header.Get("Idempotency-Key") - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"id":"re_test"}`)) + // Only count POST /v1/refunds requests (not GET /v1/transactions/{id}) + if r.Method == http.MethodPost && r.URL.Path == "/v1/refunds" { + refundCalls.Add(1) + idemKey = r.Header.Get("Idempotency-Key") + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"re_test"}`)) + return + } + // For GET /v1/transactions/{id}, return a mock transaction + if r.Method == http.MethodGet { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"pi_test_123","status":"COMPLETED","amount":"100.00","currency":"EUR"}`)) + return + } + // For other requests, return empty + w.WriteHeader(http.StatusOK) }) ctx := context.Background() h.refundBookingPayment(ctx, "b-pay") - h.refundBookingPayment(ctx, "b-pay") // second cancel: must not hit Stripe again + h.refundBookingPayment(ctx, "b-pay") // second cancel: must not hit refund endpoint again - if calls.Load() != 1 { - t.Fatalf("Stripe refund called %d times; want 1", calls.Load()) + if refundCalls.Load() != 1 { + t.Fatalf("refund endpoint called %d times; want 1", refundCalls.Load()) } if idemKey != "refund:b-pay" { t.Fatalf("Idempotency-Key = %q; want refund:b-pay", idemKey) @@ -89,13 +102,20 @@ func TestRefundBookingPayment_claimsOnce(t *testing.T) { } } -// TestRefundBookingPayment_failureRevertsClaim proves a Stripe error leaves the +// TestRefundBookingPayment_failureRevertsClaim proves a refund error leaves the // booking payable-again: the claim reverts to paid so a later cancel retries // instead of silently keeping the money. func TestRefundBookingPayment_failureRevertsClaim(t *testing.T) { h, database, _ := newRefundTestSetup(t) refundTestClient(t, h, func(w http.ResponseWriter, r *http.Request) { + // Mock GetCheckoutSession + if r.Method == http.MethodGet { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"pi_test_123","status":"COMPLETED","amount":"100.00","currency":"EUR"}`)) + return + } + // Mock Refund - return error w.WriteHeader(http.StatusInternalServerError) _, _ = w.Write([]byte(`{"error":{"message":"boom"}}`)) }) @@ -104,6 +124,6 @@ func TestRefundBookingPayment_failureRevertsClaim(t *testing.T) { var status string database.QueryRow(`SELECT payment_status FROM bookings WHERE id='b-pay'`).Scan(&status) if status != "paid" { - t.Fatalf("payment_status = %q after Stripe failure; want paid (claim reverted)", status) + t.Fatalf("payment_status = %q after refund failure; want paid (claim reverted)", status) } } diff --git a/internal/handler/stripe_settings.go b/internal/handler/stripe_settings.go index 6c65e35d..b9a187be 100644 --- a/internal/handler/stripe_settings.go +++ b/internal/handler/stripe_settings.go @@ -6,19 +6,21 @@ import ( "fmt" "net/http" + stripe "github.com/calnode/calnode/internal/makecommerce" "github.com/calnode/calnode/internal/secret" - "github.com/calnode/calnode/internal/stripe" ) -// StripeConfig holds decrypted Stripe settings loaded from the DB. +// StripeConfig holds decrypted payment provider settings loaded from the DB. +// For MakeCommerce, this contains the API secret key and optional public key. type StripeConfig struct { SecretKey string PublishableKey string WebhookSecret string } -// LoadStripeSettingsFromDB reads Stripe credentials from server_settings and decrypts the +// LoadStripeSettingsFromDB reads payment provider credentials from server_settings and decrypts the // secret key + webhook secret. Returns nil (not an error) when the secret key is unset. +// For MakeCommerce, the secret key is the API key, and webhook secret is the same. func LoadStripeSettingsFromDB(db *sql.DB, encKey [32]byte) (*StripeConfig, error) { var secretEnc, pubKey, whEnc string err := db.QueryRow(` @@ -33,20 +35,22 @@ func LoadStripeSettingsFromDB(db *sql.DB, encKey [32]byte) (*StripeConfig, error } cfg := &StripeConfig{PublishableKey: pubKey} if cfg.SecretKey, err = secret.Decrypt(encKey, secretEnc); err != nil { - return nil, fmt.Errorf("decrypt stripe secret key: %w", err) + return nil, fmt.Errorf("decrypt payment secret key: %w", err) } if whEnc != "" { if cfg.WebhookSecret, err = secret.Decrypt(encKey, whEnc); err != nil { - return nil, fmt.Errorf("decrypt stripe webhook secret: %w", err) + return nil, fmt.Errorf("decrypt payment webhook secret: %w", err) } } return cfg, nil } -// stripeWebhookURL is the endpoint to register in the Stripe dashboard. +// stripeWebhookURL is the endpoint to register in the payment provider dashboard. +// For MakeCommerce, this is the notification URL. func (h *Handler) stripeWebhookURL() string { return h.baseURL + "/v1/stripe/webhook" } // GetStripeSettings handles GET /v1/settings/stripe (admin only). +// For MakeCommerce, this returns the payment provider configuration. func (h *Handler) GetStripeSettings(w http.ResponseWriter, r *http.Request) { if _, ok := h.requireAdmin(w, r); !ok { return @@ -57,7 +61,7 @@ func (h *Handler) GetStripeSettings(w http.ResponseWriter, r *http.Request) { FROM server_settings WHERE id = 1`). Scan(&secretEnc, &pubKey, &whEnc) if err != nil && err != sql.ErrNoRows { - h.logger.ErrorContext(r.Context(), "stripe settings: query", "error", err) + h.logger.ErrorContext(r.Context(), "payment settings: query", "error", err) h.writeError(w, http.StatusInternalServerError, "internal error") return } @@ -72,7 +76,8 @@ func (h *Handler) GetStripeSettings(w http.ResponseWriter, r *http.Request) { } // PatchStripeSettings handles PATCH /v1/settings/stripe (admin only). Saves credentials and -// hot-reloads the Stripe client. Blank secret_key/webhook_secret keep the stored values. +// hot-reloads the payment client. Blank secret_key/webhook_secret keep the stored values. +// For MakeCommerce, the secret key is the API key, and webhook secret should match. func (h *Handler) PatchStripeSettings(w http.ResponseWriter, r *http.Request) { if _, ok := h.requireAdmin(w, r); !ok { return @@ -99,7 +104,7 @@ func (h *Handler) PatchStripeSettings(w http.ResponseWriter, r *http.Request) { stripe_secret_key_enc = '', stripe_publishable_key = '', stripe_webhook_secret_enc = '', updated_at = datetime('now') WHERE id = 1`); err != nil { - h.logger.ErrorContext(r.Context(), "stripe settings: clear", "error", err) + h.logger.ErrorContext(r.Context(), "payment settings: clear", "error", err) h.writeError(w, http.StatusInternalServerError, "internal error") return } @@ -113,7 +118,7 @@ func (h *Handler) PatchStripeSettings(w http.ResponseWriter, r *http.Request) { if _, err := h.db.ExecContext(r.Context(), `UPDATE server_settings SET stripe_publishable_key = ?, updated_at = datetime('now') WHERE id = 1`, *req.PublishableKey); err != nil { - h.logger.ErrorContext(r.Context(), "stripe settings: update pub key", "error", err) + h.logger.ErrorContext(r.Context(), "payment settings: update pub key", "error", err) h.writeError(w, http.StatusInternalServerError, "internal error") return } @@ -122,13 +127,13 @@ func (h *Handler) PatchStripeSettings(w http.ResponseWriter, r *http.Request) { if req.SecretKey != "" { enc, err := secret.Encrypt(h.encKey, req.SecretKey) if err != nil { - h.logger.ErrorContext(r.Context(), "stripe settings: encrypt secret key", "error", err) + h.logger.ErrorContext(r.Context(), "payment settings: encrypt secret key", "error", err) h.writeError(w, http.StatusInternalServerError, "internal error") return } if _, err := h.db.ExecContext(r.Context(), `UPDATE server_settings SET stripe_secret_key_enc = ?, updated_at = datetime('now') WHERE id = 1`, enc); err != nil { - h.logger.ErrorContext(r.Context(), "stripe settings: update secret key", "error", err) + h.logger.ErrorContext(r.Context(), "payment settings: update secret key", "error", err) h.writeError(w, http.StatusInternalServerError, "internal error") return } @@ -136,13 +141,13 @@ func (h *Handler) PatchStripeSettings(w http.ResponseWriter, r *http.Request) { if req.WebhookSecret != "" { enc, err := secret.Encrypt(h.encKey, req.WebhookSecret) if err != nil { - h.logger.ErrorContext(r.Context(), "stripe settings: encrypt webhook secret", "error", err) + h.logger.ErrorContext(r.Context(), "payment settings: encrypt webhook secret", "error", err) h.writeError(w, http.StatusInternalServerError, "internal error") return } if _, err := h.db.ExecContext(r.Context(), `UPDATE server_settings SET stripe_webhook_secret_enc = ?, updated_at = datetime('now') WHERE id = 1`, enc); err != nil { - h.logger.ErrorContext(r.Context(), "stripe settings: update webhook secret", "error", err) + h.logger.ErrorContext(r.Context(), "payment settings: update webhook secret", "error", err) h.writeError(w, http.StatusInternalServerError, "internal error") return } @@ -151,19 +156,19 @@ func (h *Handler) PatchStripeSettings(w http.ResponseWriter, r *http.Request) { // Hot-reload from the now-current DB state. cfg, err := LoadStripeSettingsFromDB(h.db, h.encKey) if err != nil { - h.logger.ErrorContext(r.Context(), "stripe settings: reload", "error", err) + h.logger.ErrorContext(r.Context(), "payment settings: reload", "error", err) h.writeError(w, http.StatusInternalServerError, "internal error") return } if cfg == nil { h.SetStripe(nil) } else if sc, err := stripe.New(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") + h.logger.ErrorContext(r.Context(), "payment settings: init client", "error", err) + h.writeError(w, http.StatusInternalServerError, "failed to initialize payment client") return } else { h.SetStripe(sc) - h.logger.Info("stripe settings: credentials updated and client hot-reloaded") + h.logger.Info("payment settings: credentials updated and client hot-reloaded") } h.GetStripeSettings(w, r) diff --git a/internal/makecommerce/makecommerce.go b/internal/makecommerce/makecommerce.go new file mode 100644 index 00000000..59096f2f --- /dev/null +++ b/internal/makecommerce/makecommerce.go @@ -0,0 +1,574 @@ +// Package makecommerce implements a Stripe-compatible client using the MakeCommerce API. +// This allows replacing Stripe Connect with MakeCommerce with minimal codebase changes, +// keeping the Stripe nomenclature while using MakeCommerce for payment processing. +// +// The implementation follows the Regular Payment Flow as documented at: +// https://developer.makecommerce.net/guides/custom-api/RegularPaymentFlow/ +package makecommerce + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/sha512" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +// API base URLs +const ( + apiBaseDefault = "https://api.test.maksekeskus.ee" + apiVersion = "v1" +) + +// Client talks to MakeCommerce using API keys. +// It implements the same interface as stripe.Client for compatibility. +type Client struct { + // API credentials + secretKey string + publicKey string + webhookSecret string // Same as secretKey for MakeCommerce MAC verification + + // HTTP client + http *http.Client + + // API base URL (overridable for testing) + apiBase string +} + +// New builds a MakeCommerce client from the API keys. +// The secretKey is used for authentication and webhook verification. +// The publishableKey is optional and used for client-side operations if needed. +// The webhookSecret should be the same as secretKey for MakeCommerce. +func New(secretKey, publishableKey, webhookSecret string) (*Client, error) { + if secretKey == "" { + return nil, fmt.Errorf("makecommerce: secret key required") + } + return &Client{ + secretKey: secretKey, + publicKey: publishableKey, + webhookSecret: webhookSecret, + http: &http.Client{Timeout: 20 * time.Second}, + apiBase: apiBaseDefault, + }, nil +} + +// SetAPIBase overrides the API endpoint. Test-only: lets handler tests point +// the client at a fake server without touching production construction. +func (c *Client) SetAPIBase(url string) { c.apiBase = url } + +// PublishableKey returns the configured publishable key (safe to expose client-side). +func (c *Client) PublishableKey() string { return c.publicKey } + +// WebhookConfigured reports whether a signing secret is set (so the webhook can be verified). +func (c *Client) WebhookConfigured() bool { return c.webhookSecret != "" } + +// CheckoutParams describes a one-off payment Checkout Session. +// This is identical to stripe.CheckoutParams for compatibility. +type CheckoutParams struct { + AmountCents int64 + Currency string + ProductName string // shown on the payment page + CustomerEmail string // prefills the email field + SuccessURL string // redirect URL after successful payment + CancelURL string // redirect URL if payment is cancelled + ExpiresAt time.Time // session expiry (MakeCommerce uses 30 min fixed) + Metadata map[string]string // e.g. booking_id — echoed back on the webhook +} + +// CheckoutSession is the subset of a Stripe Checkout Session we use. +// This is identical to stripe.CheckoutSession for compatibility. +type CheckoutSession struct { + ID string `json:"id"` + URL string `json:"url"` // hosted payment page to redirect the booker to + PaymentStatus string `json:"payment_status"` // "paid" | "unpaid" | "pending" + PaymentIntent string `json:"payment_intent"` // set once paid (used for refunds) + AmountTotal int64 `json:"amount_total"` // charged amount in minor units (cents) + Currency string `json:"currency"` // charged currency (lowercase) + Metadata map[string]string `json:"metadata"` +} + +// Event is a minimal webhook event envelope. +// This is identical to stripe.Event for compatibility. +type Event struct { + ID string `json:"id"` + Type string `json:"type"` + Data struct { + Object json.RawMessage `json:"object"` + } `json:"data"` +} + +// CreateCheckoutSession creates a MakeCommerce transaction and returns it as a CheckoutSession. +// This implements the same interface as stripe.Client.CreateCheckoutSession. +func (c *Client) CreateCheckoutSession(ctx context.Context, p CheckoutParams) (*CheckoutSession, error) { + // Convert cents to decimal string (MakeCommerce expects "10.00", not 1000) + // Use 2 decimal places to ensure proper currency formatting + amountStr := strconv.FormatFloat(float64(p.AmountCents)/100.0, 'f', 2, 64) + + // Extract booking_id from metadata for reference + bookingID := p.Metadata["booking_id"] + if bookingID == "" { + bookingID = fmt.Sprintf("booking_%s", p.ProductName) + } + + // Build MakeCommerce transaction request + reqBody := map[string]interface{}{ + "transaction": map[string]interface{}{ + "amount": amountStr, + "currency": strings.ToUpper(p.Currency), + "transaction_url": map[string]interface{}{ + "return_url": map[string]interface{}{ + "url": p.SuccessURL, + "method": "GET", + }, + "cancel_url": map[string]interface{}{ + "url": p.CancelURL, + "method": "GET", + }, + "notification_url": map[string]interface{}{ + "url": "https://romelia-hypermetaphoric-clarinda.ngrok-free.dev/v1/stripe/webhook", + "method": "POST", + }, + }, + }, + "customer": map[string]interface{}{ + "email": p.CustomerEmail, + "ip": "176.46.60.160", + "country": "EE", // Default to Estonia, can be parameterized + "locale": "en", // Default to English + }, + "app_info": map[string]interface{}{ + "module": "makecommerce", + "module_version": "0.0.1", + "platform": "calnode", + "version": "0.12.0", + }, + } + + // Add product name to reference + if p.ProductName != "" { + reqBody["transaction"].(map[string]interface{})["reference"] = fmt.Sprintf("%s - %s", p.ProductName, bookingID) + } + + jsonBody, err := json.Marshal(reqBody) + if err != nil { + return nil, fmt.Errorf("makecommerce: marshal request: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, + c.apiBase+"/"+apiVersion+"/transactions", + bytes.NewReader(jsonBody)) + if err != nil { + return nil, fmt.Errorf("makecommerce: create request: %w", err) + } + + // MakeCommerce uses Basic Auth with secret key + req.SetBasicAuth("f7741ab2-7445-45f9-9af4-0d0408ef1e4c", c.secretKey) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json") + + resp, err := c.http.Do(req) + if err != nil { + return nil, fmt.Errorf("makecommerce: request: %w", err) + } + defer resp.Body.Close() + + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if resp.StatusCode >= 300 { + var e struct { + Error string `json:"error"` + } + _ = json.Unmarshal(body, &e) + msg := e.Error + if msg == "" { + msg = strings.TrimSpace(string(body)) + } + return nil, fmt.Errorf("makecommerce: %s %s returned %d: %s", + http.MethodPost, "/transactions", resp.StatusCode, msg) + } + + // Parse MakeCommerce transaction response + var txnResp struct { + ID string `json:"id"` + Status string `json:"status"` + Amount string `json:"net_amount"` + PaymentMethods struct { + Other []struct { + Name string `json:"name"` + URL string `json:"url"` + } `json:"other"` + } `json:"payment_methods"` + } + + if err := json.Unmarshal(body, &txnResp); err != nil { + return nil, fmt.Errorf("makecommerce: decode response: %w", err) + } + + var redirectURL string + for _, pm := range txnResp.PaymentMethods.Other { + if pm.Name == "redirect" { + redirectURL = pm.URL + break + } + } + + if redirectURL == "" { + return nil, fmt.Errorf("makecommerce: no redirect URL found") + } + + // Convert amount back to cents for compatibility + amountCents, _ := strconv.ParseFloat(txnResp.Amount, 64) + + // Map to CheckoutSession (Stripe-compatible format) + return &CheckoutSession{ + ID: txnResp.ID, + URL: redirectURL, + PaymentStatus: mapStatus(txnResp.Status), + PaymentIntent: txnResp.ID, // Use transaction ID as payment intent for compatibility + AmountTotal: int64(amountCents * 100), + Currency: "eur", + Metadata: p.Metadata, + }, nil +} + +// GetCheckoutSession fetches a transaction by id (used by the success page to confirm payment). +// This implements the same interface as stripe.Client.GetCheckoutSession. +func (c *Client) GetCheckoutSession(ctx context.Context, id string) (*CheckoutSession, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, + c.apiBase+"/"+apiVersion+"/transactions/"+url.PathEscape(id), nil) + if err != nil { + return nil, fmt.Errorf("makecommerce: create request: %w", err) + } + + req.SetBasicAuth("f7741ab2-7445-45f9-9af4-0d0408ef1e4c", c.secretKey) + req.Header.Set("Accept", "application/json") + + resp, err := c.http.Do(req) + if err != nil { + return nil, fmt.Errorf("makecommerce: request: %w", err) + } + defer resp.Body.Close() + + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if resp.StatusCode >= 300 { + return nil, fmt.Errorf("makecommerce: get transaction returned %d: %s", + resp.StatusCode, string(body)) + } + + // Parse transaction response + var txnResp struct { + ID string `json:"id"` + Status string `json:"status"` + Amount string `json:"amount"` + Currency string `json:"currency"` + Reference string `json:"reference"` + Metadata map[string]string `json:"metadata"` + } + + if err := json.Unmarshal(body, &txnResp); err != nil { + return nil, fmt.Errorf("makecommerce: decode response: %w", err) + } + + amountCents, _ := strconv.ParseFloat(txnResp.Amount, 64) + + return &CheckoutSession{ + ID: txnResp.ID, + PaymentStatus: mapStatus(txnResp.Status), + PaymentIntent: txnResp.ID, + AmountTotal: int64(amountCents * 100), + Currency: strings.ToLower(txnResp.Currency), + Metadata: txnResp.Metadata, + }, nil +} + +// Refund issues a full refund for a transaction. +// idempotencyKey (e.g. "refund:") makes retries safe. +// This implements the same interface as stripe.Client.Refund. +func (c *Client) Refund(ctx context.Context, paymentIntentID, idempotencyKey string) error { + // If paymentIntentID is empty, return nil (no-op) + if paymentIntentID == "" { + return nil + } + + // MakeCommerce refund API: POST /v1/refunds + // For now, we'll make a basic refund request + // In production, this would need the actual MakeCommerce refund endpoint details + + // First get the transaction to get amount and currency + sess, err := c.GetCheckoutSession(ctx, paymentIntentID) + if err != nil { + return fmt.Errorf("makecommerce: failed to get transaction: %w", err) + } + + // Convert cents back to decimal string + amountStr := strconv.FormatFloat(float64(sess.AmountTotal)/100.0, 'f', 2, 64) + + // Build refund request + reqBody := map[string]interface{}{ + "transaction_id": paymentIntentID, + "amount": amountStr, + "currency": strings.ToUpper(sess.Currency), + "description": "Refund for booking", + } + + jsonBody, err := json.Marshal(reqBody) + if err != nil { + return fmt.Errorf("makecommerce: marshal refund request: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, + c.apiBase+"/"+apiVersion+"/refunds", + bytes.NewReader(jsonBody)) + if err != nil { + return fmt.Errorf("makecommerce: create refund request: %w", err) + } + + req.SetBasicAuth("f7741ab2-7445-45f9-9af4-0d0408ef1e4c", c.secretKey) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json") + req.Header.Set("Idempotency-Key", idempotencyKey) + + resp, err := c.http.Do(req) + if err != nil { + return fmt.Errorf("makecommerce: refund request: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 300 { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + return fmt.Errorf("makecommerce: refund returned %d: %s", resp.StatusCode, string(body)) + } + + return nil +} + +// mapStatus maps MakeCommerce transaction status to Stripe-compatible payment status. +func mapStatus(mcStatus string) string { + switch mcStatus { + case "COMPLETED": + return "paid" + case "PENDING", "CREATED": + return "pending" + case "CANCELLED", "EXPIRED": + return "unpaid" + default: + return "unpaid" + } +} + +// VerifyWebhook verifies + parses a webhook payload using the configured signing secret. +// This implements the same interface as stripe.Client.VerifyWebhook. +// MakeCommerce sends webhook data as URL-encoded form with json and mac fields. +// The MAC is calculated as UPPERCASE(HEX(SHA-512(string(JSON) + string(Secret Key)))). +// See: https://developer.makecommerce.net/guides/custom-api/RegularPaymentFlow#validation-of-mac-value +func (c *Client) VerifyWebhook(payload []byte, sigHeader string, now time.Time) (*Event, error) { + if c.webhookSecret == "" { + return nil, fmt.Errorf("makecommerce: webhook signing secret not configured") + } + + // MakeCommerce sends webhook as URL-encoded form: json={...}&mac=... + // Parse the form data to extract json and mac + formValues, err := url.ParseQuery(string(payload)) + if err != nil { + // If not form-encoded, try parsing as raw JSON (fallback for testing) + return c.verifyWebhookFromJSON(payload) + } + + // Extract json and mac from form values + jsonStr := formValues.Get("json") + macReceived := formValues.Get("mac") + + if jsonStr == "" { + return nil, fmt.Errorf("makecommerce: missing json field in webhook payload") + } + if macReceived == "" { + return nil, fmt.Errorf("makecommerce: missing mac field in webhook payload") + } + + expectedMac := CalculateSignature(jsonStr, c.secretKey) + + // Constant-time comparison + if !hmac.Equal([]byte(macReceived), []byte(expectedMac)) { + return nil, fmt.Errorf("makecommerce: signature verification failed: expected %s, got %s", expectedMac, macReceived) + } + + // Parse the JSON payload + // Transaction can be a string (transaction ID) or an object, depending on MakeCommerce API version + var notify struct { + Amount string `json:"amount"` + Currency string `json:"currency"` + MessageTime string `json:"message_time"` + MessageType string `json:"message_type"` + Reference string `json:"reference"` + Shop string `json:"shop"` + Signature string `json:"signature"` + Status string `json:"status"` + Transaction string `json:"transaction"` // Transaction ID as string (per MakeCommerce docs) + Metadata map[string]string `json:"metadata"` + } + + if err := json.Unmarshal([]byte(jsonStr), ¬ify); err != nil { + return nil, fmt.Errorf("makecommerce: decode webhook json: %w", err) + } + + // Map to Event format for compatibility + eventType := mapWebhookType(notify.Status) + + // Build the CheckoutSession from the notification + amountCents, _ := strconv.ParseFloat(notify.Amount, 64) + + // Extract booking_id from reference if present + metadata := notify.Metadata + if metadata == nil { + metadata = map[string]string{} + } + // Reference often contains booking info + if notify.Reference != "" && metadata["booking_id"] == "" { + metadata["booking_id"] = notify.Reference + } + + sessionJSON, _ := json.Marshal(CheckoutSession{ + ID: notify.Transaction, + PaymentStatus: mapStatus(notify.Status), + PaymentIntent: notify.Transaction, + AmountTotal: int64(amountCents * 100), + Currency: strings.ToLower(notify.Currency), + Metadata: metadata, + }) + + ev := &Event{ + ID: notify.Transaction, + Type: eventType, + Data: struct { + Object json.RawMessage `json:"object"` + }{ + Object: sessionJSON, + }, + } + + return ev, nil +} + +func CalculateSignature(receivedJson string, secretKey string) string { + concatted := receivedJson + secretKey + sum := sha512.Sum512([]byte(concatted)) + hash := strings.ToUpper(hex.EncodeToString(sum[:])) + + return hash +} + +// verifyWebhookFromJSON handles raw JSON payload (for testing compatibility). +func (c *Client) verifyWebhookFromJSON(payload []byte) (*Event, error) { + // Parse the JSON payload + // Transaction can be a string (transaction ID) or an object, depending on MakeCommerce API version + var notify struct { + Amount string `json:"amount"` + Currency string `json:"currency"` + MessageTime string `json:"message_time"` + MessageType string `json:"message_type"` + Reference string `json:"reference"` + Shop string `json:"shop"` + Signature string `json:"signature"` + Status string `json:"status"` + Transaction string `json:"transaction"` // Transaction ID as string (per MakeCommerce docs) + Metadata map[string]string `json:"metadata"` + } + + if err := json.Unmarshal(payload, ¬ify); err != nil { + return nil, fmt.Errorf("makecommerce: decode webhook json: %w", err) + } + + // For raw JSON, we need the MAC from somewhere - in this case we'll skip verification + // since this is a fallback path for testing + // In production, always use the form-encoded format with mac field + + // Map to Event format for compatibility + eventType := mapWebhookType(notify.Status) + + // Build the CheckoutSession from the notification + amountCents, _ := strconv.ParseFloat(notify.Amount, 64) + + // Extract booking_id from reference if present + metadata := notify.Metadata + if metadata == nil { + metadata = map[string]string{} + } + if notify.Reference != "" && metadata["booking_id"] == "" { + metadata["booking_id"] = notify.Reference + } + + sessionJSON, _ := json.Marshal(CheckoutSession{ + ID: notify.Transaction, + PaymentStatus: mapStatus(notify.Status), + PaymentIntent: notify.Transaction, + AmountTotal: int64(amountCents * 100), + Currency: strings.ToLower(notify.Currency), + Metadata: metadata, + }) + + ev := &Event{ + ID: notify.Transaction, + Type: eventType, + Data: struct { + Object json.RawMessage `json:"object"` + }{ + Object: sessionJSON, + }, + } + + return ev, nil +} + +// extractMACFromHeader attempts to extract the MAC from various header formats. +func extractMACFromHeader(header string) string { + if header == "" { + return "" + } + + // Try Stripe-like format: t=...,v1=... + // But MakeCommerce likely uses a different format + // For now, return the header as-is + return header +} + +// mapWebhookType maps MakeCommerce transaction status to Stripe webhook event types. +func mapWebhookType(status string) string { + switch status { + case "COMPLETED": + return "checkout.session.completed" + case "EXPIRED": + return "checkout.session.expired" + case "CANCELLED": + return "checkout.session.expired" // Treat as expired for compatibility + default: + return "checkout.session.unknown" + } +} + +// Session parses the event's data.object as a Checkout Session. +// This implements the same interface as stripe.Event.Session. +func (e *Event) Session() (*CheckoutSession, error) { + var s CheckoutSession + if err := json.Unmarshal(e.Data.Object, &s); err != nil { + return nil, err + } + return &s, nil +} + +// ConstructEvent is provided for compatibility with stripe.ConstructEvent. +// It uses the Client's VerifyWebhook method. +func ConstructEvent(payload []byte, sigHeader, secret string, now time.Time) (*Event, error) { + // Create a temporary client for verification + c, err := New(secret, "", secret) + if err != nil { + return nil, err + } + return c.VerifyWebhook(payload, sigHeader, now) +} diff --git a/internal/makecommerce/makecommerce_test.go b/internal/makecommerce/makecommerce_test.go new file mode 100644 index 00000000..e4a733ec --- /dev/null +++ b/internal/makecommerce/makecommerce_test.go @@ -0,0 +1,515 @@ +package makecommerce + +import ( + "context" + "crypto/sha512" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "testing" + "time" +) + +// signMC produces a valid MakeCommerce MAC signature for the given data. +// Format: UPPERCASE(HEX(SHA-512(string(JSON) + string(Secret Key)))) +// This matches the MakeCommerce documentation at: +// https://developer.makecommerce.net/guides/custom-api/RegularPaymentFlow#validation-of-mac-value +func signMC(secret, jsonStr string) string { + // MakeCommerce MAC: UPPERCASE(HEX(SHA-512(string(JSON) + string(Secret Key)))) + message := jsonStr + secret + hash := sha512.Sum512([]byte(message)) + return fmt.Sprintf("%X", hash) +} + +func TestNew(t *testing.T) { + // Valid client creation + c, err := New("secret_key_123", "pub_key_456", "whsec_789") + if err != nil { + t.Fatalf("New: %v", err) + } + if c.secretKey != "secret_key_123" { + t.Errorf("secretKey = %q", c.secretKey) + } + if c.publicKey != "pub_key_456" { + t.Errorf("publicKey = %q", c.publicKey) + } + if c.webhookSecret != "whsec_789" { + t.Errorf("webhookSecret = %q", c.webhookSecret) + } + + // Empty secret key should fail + if _, err := New("", "pub", "wh"); err == nil { + t.Error("expected error with empty secret key") + } +} + +func TestPublishableKey(t *testing.T) { + c, _ := New("secret", "pub_key", "whsec") + if c.PublishableKey() != "pub_key" { + t.Errorf("PublishableKey = %q", c.PublishableKey()) + } +} + +func TestWebhookConfigured(t *testing.T) { + c, _ := New("secret", "pub", "") + if c.WebhookConfigured() { + t.Error("expected WebhookConfigured to be false with empty webhook secret") + } + + c, _ = New("secret", "pub", "whsec") + if !c.WebhookConfigured() { + t.Error("expected WebhookConfigured to be true with webhook secret") + } +} + +func TestSetAPIBase(t *testing.T) { + c, _ := New("secret", "pub", "whsec") + c.SetAPIBase("https://api.test.example.com") + if c.apiBase != "https://api.test.example.com" { + t.Errorf("apiBase = %q", c.apiBase) + } +} + +func TestMapStatus(t *testing.T) { + tests := []struct { + mcStatus string + want string + }{ + {"COMPLETED", "paid"}, + {"PENDING", "pending"}, + {"CREATED", "pending"}, + {"CANCELLED", "unpaid"}, + {"EXPIRED", "unpaid"}, + {"UNKNOWN", "unpaid"}, + } + + for _, tt := range tests { + t.Run(tt.mcStatus, func(t *testing.T) { + if got := mapStatus(tt.mcStatus); got != tt.want { + t.Errorf("mapStatus(%q) = %q, want %q", tt.mcStatus, got, tt.want) + } + }) + } +} + +func TestMapWebhookType(t *testing.T) { + tests := []struct { + status string + want string + }{ + {"COMPLETED", "checkout.session.completed"}, + {"EXPIRED", "checkout.session.expired"}, + {"CANCELLED", "checkout.session.expired"}, + {"PENDING", "checkout.session.unknown"}, + } + + for _, tt := range tests { + t.Run(tt.status, func(t *testing.T) { + if got := mapWebhookType(tt.status); got != tt.want { + t.Errorf("mapWebhookType(%q) = %q, want %q", tt.status, got, tt.want) + } + }) + } +} + +func TestCreateCheckoutSession(t *testing.T) { + var gotPath, gotAuth, gotBody string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + gotAuth = r.Header.Get("Authorization") + b, _ := io.ReadAll(r.Body) + gotBody = string(b) + w.Header().Set("Content-Type", "application/json") + // Return a mock MakeCommerce transaction response with other as array + io.WriteString(w, `{ + "id": "txn_123", + "status": "CREATED", + "net_amount": "50.00", + "payment_methods": { + "other": [ + {"name": "redirect", "url": "https://payment.maksekeskus.ee/pay.html?trx=txn_123"} + ] + } + }`) + })) + defer srv.Close() + + c, _ := New("sk_test_abc", "pk_test_abc", "whsec_test") + c.apiBase = srv.URL + + sess, err := c.CreateCheckoutSession(context.Background(), CheckoutParams{ + AmountCents: 5000, + Currency: "EUR", + ProductName: "Intro call", + CustomerEmail: "alex@example.com", + SuccessURL: "https://x/success", + CancelURL: "https://x/cancel", + Metadata: map[string]string{"booking_id": "bk_1"}, + }) + if err != nil { + t.Fatalf("CreateCheckoutSession: %v", err) + } + + // Verify the session was created correctly + if sess.ID != "txn_123" { + t.Errorf("session ID = %q, want txn_123", sess.ID) + } + if sess.URL != "https://payment.maksekeskus.ee/pay.html?trx=txn_123" { + t.Errorf("session URL = %q", sess.URL) + } + if sess.PaymentStatus != "pending" { + t.Errorf("payment status = %q, want pending", sess.PaymentStatus) + } + if sess.PaymentIntent != "txn_123" { + t.Errorf("payment intent = %q, want txn_123", sess.PaymentIntent) + } + if sess.AmountTotal != 5000 { + t.Errorf("amount total = %d, want 5000", sess.AmountTotal) + } + if sess.Currency != "eur" { + t.Errorf("currency = %q, want eur", sess.Currency) + } + + // Verify the request was made correctly + if gotPath != "/v1/transactions" { + t.Errorf("path = %q, want /v1/transactions", gotPath) + } + if gotAuth == "" { + t.Error("missing basic auth") + } + + // Verify the request body contains the expected data + var reqBody map[string]interface{} + if err := json.Unmarshal([]byte(gotBody), &reqBody); err != nil { + t.Fatalf("failed to parse request body: %v", err) + } + + txn, ok := reqBody["transaction"].(map[string]interface{}) + if !ok { + t.Fatal("transaction field missing or not an object") + } + + if txn["amount"] != "50.00" { + t.Errorf("amount = %v, want 50.00", txn["amount"]) + } + if txn["currency"] != "EUR" { + t.Errorf("currency = %v, want EUR", txn["currency"]) + } +} + +func TestCreateCheckoutSession_DefaultCurrency(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{ + "id": "txn_1", + "status": "CREATED", + "net_amount": "10.00", + "payment_methods": {"other": [{"name": "redirect", "url": "https://payment.example.com/pay.html?trx=txn_1"}]} + }`) + })) + defer srv.Close() + + c, _ := New("secret", "pub", "whsec") + c.apiBase = srv.URL + + // Test with empty currency - should still work + _, err := c.CreateCheckoutSession(context.Background(), CheckoutParams{ + AmountCents: 1000, + Currency: "", // Empty - should use default or as-is + ProductName: "Test", + CustomerEmail: "test@example.com", + SuccessURL: "https://x/success", + CancelURL: "https://x/cancel", + Metadata: map[string]string{"booking_id": "bk_1"}, + }) + if err != nil { + t.Fatalf("CreateCheckoutSession with empty currency: %v", err) + } +} + +func TestGetCheckoutSession(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1/transactions/txn_123" { + t.Errorf("unexpected path: %s", r.URL.Path) + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{ + "id": "txn_123", + "status": "COMPLETED", + "amount": "100.00", + "currency": "EUR", + "reference": "booking_1" + }`) + })) + defer srv.Close() + + c, _ := New("secret", "pub", "whsec") + c.apiBase = srv.URL + + sess, err := c.GetCheckoutSession(context.Background(), "txn_123") + if err != nil { + t.Fatalf("GetCheckoutSession: %v", err) + } + + if sess.ID != "txn_123" { + t.Errorf("session ID = %q", sess.ID) + } + if sess.PaymentStatus != "paid" { + t.Errorf("payment status = %q, want paid", sess.PaymentStatus) + } + if sess.AmountTotal != 10000 { + t.Errorf("amount total = %d, want 10000", sess.AmountTotal) + } + if sess.Currency != "eur" { + t.Errorf("currency = %q, want eur", sess.Currency) + } +} + +func TestRefund(t *testing.T) { + // First, mock GetCheckoutSession for the Refund method + var getCalled, refundCalled bool + var refundBody string + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && r.URL.Path == "/v1/transactions/txn_123" { + getCalled = true + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{ + "id": "txn_123", + "status": "COMPLETED", + "amount": "25.00", + "currency": "EUR" + }`) + return + } + if r.Method == http.MethodPost && r.URL.Path == "/v1/refunds" { + refundCalled = true + b, _ := io.ReadAll(r.Body) + refundBody = string(b) + w.WriteHeader(http.StatusOK) + io.WriteString(w, `{"id": "ref_123", "status": "CREATED"}`) + return + } + w.WriteHeader(http.StatusNotFound) + })) + defer srv.Close() + + c, _ := New("secret", "pub", "whsec") + c.apiBase = srv.URL + + // Test successful refund + err := c.Refund(context.Background(), "txn_123", "refund:book_1") + if err != nil { + t.Fatalf("Refund: %v", err) + } + + if !getCalled { + t.Error("GetCheckoutSession was not called") + } + if !refundCalled { + t.Error("refund request was not made") + } + + // Verify the refund request body + var reqBody map[string]interface{} + if err := json.Unmarshal([]byte(refundBody), &reqBody); err != nil { + t.Fatalf("failed to parse refund body: %v", err) + } + + if reqBody["transaction_id"] != "txn_123" { + t.Errorf("transaction_id = %v, want txn_123", reqBody["transaction_id"]) + } + // The amount should be "25.00" with 2 decimal places + if reqBody["amount"] != "25.00" { + t.Errorf("amount = %v, want 25.00", reqBody["amount"]) + } + if reqBody["currency"] != "EUR" { + t.Errorf("currency = %v, want EUR", reqBody["currency"]) + } +} + +func TestRefund_EmptyPaymentIntent(t *testing.T) { + c, _ := New("secret", "pub", "whsec") + c.apiBase = "https://api.example.com" + + // Should return nil without error + err := c.Refund(context.Background(), "", "refund:123") + if err != nil { + t.Errorf("Refund with empty paymentIntentID should return nil, got: %v", err) + } +} + +func TestVerifyWebhook(t *testing.T) { + secret := "whsec_test" + txnID := "f291af44-8d3c-4dc8-b4a9-31592023aae3" // Use transaction ID as string + amount := "90.95" + currency := "EUR" + status := "COMPLETED" + + // Create JSON payload matching MakeCommerce documentation format + // Based on: https://developer.makecommerce.net/guides/custom-api/RegularPaymentFlow#validation-of-mac-value + jsonPayload := fmt.Sprintf(`{"amount":"%s","currency":"%s","message_time":"2024-11-13T12:03:48+0000","message_type":"payment_return","reference":"booking_123","shop":"1ad3a943-6958-430b-b58b-e55524a4e360","status":"%s","transaction":"%s"}`, amount, currency, status, txnID) + + // Create MAC using MakeCommerce format: SHA-512(JSON + Secret) + mac := signMC(secret, jsonPayload) + + c, _ := New(secret, "pub", secret) // webhookSecret same as secret for MC + + // Create form-encoded payload manually to ensure exact encoding + // json=&mac= + formPayload := "json=" + url.QueryEscape(jsonPayload) + "&mac=" + mac + + // Test with correct signature + ev, err := c.VerifyWebhook([]byte(formPayload), "", time.Now()) + if err != nil { + t.Fatalf("VerifyWebhook with correct signature: %v", err) + } + + if ev.ID != txnID { + t.Errorf("event ID = %q, want %q", ev.ID, txnID) + } + if ev.Type != "checkout.session.completed" { + t.Errorf("event type = %q, want checkout.session.completed", ev.Type) + } + + // Verify session can be parsed + sess, err := ev.Session() + if err != nil { + t.Fatalf("Session: %v", err) + } + if sess.PaymentStatus != "paid" { + t.Errorf("session payment status = %q, want paid", sess.PaymentStatus) + } +} + +func TestVerifyWebhook_BadSignature(t *testing.T) { + secret := "whsec_test" + // Create JSON payload with transaction as string (per MakeCommerce docs) + jsonPayload := `{"amount":"10.00","currency":"EUR","message_type":"payment_return","status":"COMPLETED","transaction":"txn_1"}` + // Signed with a different secret + mac := signMC("wrong_secret", jsonPayload) + + c, _ := New(secret, "pub", secret) + + formPayload := "json=" + url.QueryEscape(jsonPayload) + "&mac=" + mac + + if _, err := c.VerifyWebhook([]byte(formPayload), "", time.Now()); err == nil { + t.Error("expected signature verification to fail with wrong secret") + } +} + +func TestVerifyWebhook_TamperedPayload(t *testing.T) { + secret := "whsec_test" + + // Sign the original payload with transaction as string + jsonPayload := `{"amount":"10.00","currency":"EUR","message_type":"payment_return","status":"COMPLETED","transaction":"txn_1"}` + mac := signMC(secret, jsonPayload) + + c, _ := New(secret, "pub", secret) + + // Create tampered form payload + tamperedJSON := `{"amount":"10.00","currency":"EUR","message_type":"payment_return","status":"COMPLETED","transaction":"txn_TAMPERED"}` + formPayload := "json=" + url.QueryEscape(tamperedJSON) + "&mac=" + mac + + if _, err := c.VerifyWebhook([]byte(formPayload), "", time.Now()); err == nil { + t.Error("expected verification to fail for tampered payload") + } +} + +func TestVerifyWebhook_NoSecret(t *testing.T) { + c, _ := New("secret", "pub", "") // Use valid secret but empty webhook secret + + if _, err := c.VerifyWebhook([]byte(`{"transaction_id":"txn_1"}`), "some_sig", time.Now()); err == nil { + t.Error("expected error with no webhook secret configured") + } +} + +func TestEventSession(t *testing.T) { + event := &Event{ + ID: "evt_1", + Type: "checkout.session.completed", + Data: struct { + Object json.RawMessage `json:"object"` + }{ + Object: []byte(`{"id":"cs_1","payment_status":"paid","payment_intent":"pi_1","amount_total":5000,"currency":"eur","metadata":{"booking_id":"bk_1"}}`), + }, + } + + sess, err := event.Session() + if err != nil { + t.Fatalf("Session: %v", err) + } + + if sess.ID != "cs_1" { + t.Errorf("session ID = %q", sess.ID) + } + if sess.PaymentStatus != "paid" { + t.Errorf("payment status = %q", sess.PaymentStatus) + } + if sess.PaymentIntent != "pi_1" { + t.Errorf("payment intent = %q", sess.PaymentIntent) + } + if sess.AmountTotal != 5000 { + t.Errorf("amount total = %d", sess.AmountTotal) + } + if sess.Currency != "eur" { + t.Errorf("currency = %q", sess.Currency) + } + if sess.Metadata["booking_id"] != "bk_1" { + t.Errorf("metadata booking_id = %q", sess.Metadata["booking_id"]) + } +} + +func TestConstructEvent(t *testing.T) { + secret := "whsec_test" + txnID := "txn_123" + amount := "50.00" + currency := "EUR" + status := "COMPLETED" + + // Create JSON payload with transaction as string + jsonPayload := fmt.Sprintf(`{"amount":"%s","currency":"%s","message_type":"payment_return","status":"%s","transaction":"%s"}`, amount, currency, status, txnID) + + mac := signMC(secret, jsonPayload) + + // Create form-encoded payload + formPayload := "json=" + url.QueryEscape(jsonPayload) + "&mac=" + mac + + ev, err := ConstructEvent([]byte(formPayload), "", secret, time.Now()) + if err != nil { + t.Fatalf("ConstructEvent: %v", err) + } + + if ev.ID != txnID { + t.Errorf("event ID = %q", ev.ID) + } + if ev.Type != "checkout.session.completed" { + t.Errorf("event type = %q", ev.Type) + } +} + +func TestSignatureCalculation(t *testing.T) { + + //payload := `json={"amount":"1.0","currency":"EUR","customer_name":"Tõõger Leõpäöld","merchant_data":null,"message_time":"2026-11-05T20:51:06+0000","message_type":"payment_return","reference":"Test - 0fa5ed8a-5311-43c3-9705-ad78c456c58c","shop":"f7741ab2-7445-45f9-9af4-0d0408ef1e4c","signature":"F6891653FD35AF105F8D2251B7CC27DBD11E9D8B80B835CF4D2E6194E273F04EA4DD9D8CB27AD5A0DF4A26C49344714EEA4424E9E751A40A38E38B9193EBB435","status":"COMPLETED","transaction":"24cec1e3-3101-4093-bf3b-0aa3d40cec6b"}&mac=DF3B2B21201DF358501088C48B80B77978F22DA41EE5B55F23907D7EB4C5566E34FD3634D8E4E9E61B303BD77BD3EAE1A95C17800FA57A55C4F5BB636D64F26C` + payload := "json=%7B%22amount%22%3A%2290.95%22%2C%22currency%22%3A%22EUR%22%2C%22customer_name%22%3A%22ec1adce4-b485-49c3-acf1-319bf80d5e29%22%2C%22merchant_data%22%3A%22internalid321%22%2C%22message_time%22%3A%222024-11-13T12%3A03%3A48%2B0000%22%2C%22message_type%22%3A%22payment_return%22%2C%22reference%22%3A%22123abc%22%2C%22shop%22%3A%221ad3a943-6958-430b-b58b-e55524a4e360%22%2C%22signature%22%3A%2275DCA7CF1050E045C574D423B5A2E4BB62BC12B399F7E4415D20D4FBDD0DD95E62FFF2DFAAF135D6FCBAF1B01CD925F9C098409215DDCD6995B7FA89917FD919%22%2C%22status%22%3A%22COMPLETED%22%2C%22transaction%22%3A%22f291af44-8d3c-4dc8-b4a9-31592023aae3%22%7D&mac=E4812E5D0EE8FE6A158826C52EF0E45D13E3746A4CA0BE43562F09758C956E9D6C09671EF641C02BB967E5AFE2F0AFD4BB3749EE36315F624763A2CBBD5DF34A" + + secretKey := "pfOsGD9oPaFEILwqFLHEHkPf7vZz4j3t36nAcufP1abqT9l99koyuC1IWAOcBeqt" + + // Parse the payload (simulating what VerifyWebhook does) + formValues, err := url.ParseQuery(payload) + if err != nil { + t.Fatalf("payload parsing failed: %v", err) + } + + receivedJson := formValues.Get("json") + receivedMac := formValues.Get("mac") + calculatedSignature := CalculateSignature(receivedJson, secretKey) + + // Verify the MAC matches + if receivedMac != calculatedSignature { + t.Errorf("MAC verification failed: expected %.10s..., got %.10s...", calculatedSignature, receivedMac) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 5d904b4d..dc762d50 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" + stripe "github.com/calnode/calnode/internal/makecommerce" "github.com/calnode/calnode/internal/webhook" "github.com/calnode/calnode/internal/worker" "github.com/calnode/calnode/internal/zoom" @@ -256,18 +256,19 @@ func BuildHandler(ctx context.Context, cfg *config.Config, db *sql.DB, logger *s logger.Info("Zoom not configured — add credentials in Settings → Zoom") } - // Optional Stripe payments — paid bookings. Off unless configured in Settings → Payments. + // Optional payments — paid bookings. Off unless configured in Settings → Payments. + // For MakeCommerce, this uses the API secret key. if dbStripe, dbStripeErr := handler.LoadStripeSettingsFromDB(db, encKey); dbStripeErr != nil { - logger.Warn("stripe settings: could not load from database", "error", dbStripeErr) + logger.Warn("payment 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 { - logger.Error("stripe: init failed", "error", err) + logger.Error("payment: init failed", "error", err) } else { h.SetStripe(sc) - logger.Info("Stripe payments configured", "webhook_secret_set", dbStripe.WebhookSecret != "") + logger.Info("Payments configured", "webhook_secret_set", dbStripe.WebhookSecret != "") } } else { - logger.Info("Stripe not configured — add credentials in Settings → Payments") + logger.Info("Payments not configured — add credentials in Settings → Payments") } // Optional LiveKit video — built-in meeting rooms. Off unless configured in Settings → Video. @@ -543,8 +544,9 @@ func New(ctx context.Context, cfg *config.Config, db *sql.DB, logger *slog.Logge mux.HandleFunc("GET /v1/zoom/status", h.RequireAuth(h.ZoomStatus)) mux.HandleFunc("DELETE /v1/zoom", h.RequireAuth(h.DisconnectZoom)) - // Stripe payment webhook — public, authenticated by the signing secret (no session + // Payment webhook — public, authenticated by the signing secret (no session // cookie, so the CSRF check doesn't apply). Must receive the raw body. + // For MakeCommerce, this receives transaction status notifications. mux.HandleFunc("POST /v1/stripe/webhook", h.StripeWebhook) // Resend inbound email (email.received): RSVPs to Calnode-sent invites. Public, // authenticated by the webhook signature. From 7200219e293530b62ac289cff4222a5694283c20 Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Sat, 7 Nov 2026 22:31:46 +0200 Subject: [PATCH 02/16] Read bookingId from query param --- internal/handler/stripe_booking.go | 15 ++++++++------- internal/makecommerce/makecommerce.go | 6 +++--- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/internal/handler/stripe_booking.go b/internal/handler/stripe_booking.go index 0ac02e0b..a6046c55 100644 --- a/internal/handler/stripe_booking.go +++ b/internal/handler/stripe_booking.go @@ -73,6 +73,11 @@ func (h *Handler) StripeWebhook(w http.ResponseWriter, r *http.Request) { return } + bookingId := r.URL.Query().Get("booking_id") + if bookingId == "" { + h.writeError(w, http.StatusBadRequest, "param missing") + } + switch ev.Type { case "checkout.session.completed": sess, perr := ev.Session() @@ -80,15 +85,11 @@ func (h *Handler) StripeWebhook(w http.ResponseWriter, r *http.Request) { break } if sess.PaymentStatus == "paid" { - if id := sess.Metadata["booking_id"]; id != "" { - h.confirmPaidBooking(context.Background(), id, sess.PaymentIntent, int(sess.AmountTotal), sess.Currency) - } + h.confirmPaidBooking(context.Background(), bookingId, sess.PaymentIntent, int(sess.AmountTotal), sess.Currency) } case "checkout.session.expired": - if sess, perr := ev.Session(); perr == nil { - if id := sess.Metadata["booking_id"]; id != "" { - h.releaseUnpaidHold(context.Background(), id) - } + if _, perr := ev.Session(); perr == nil { + h.releaseUnpaidHold(context.Background(), bookingId) } } // Acknowledge so the payment provider stops retrying (we've durably acted, or chosen to ignore). diff --git a/internal/makecommerce/makecommerce.go b/internal/makecommerce/makecommerce.go index 59096f2f..2398d6d3 100644 --- a/internal/makecommerce/makecommerce.go +++ b/internal/makecommerce/makecommerce.go @@ -141,8 +141,8 @@ func (c *Client) CreateCheckoutSession(ctx context.Context, p CheckoutParams) (* "customer": map[string]interface{}{ "email": p.CustomerEmail, "ip": "176.46.60.160", - "country": "EE", // Default to Estonia, can be parameterized - "locale": "en", // Default to English + "country": "EE", + "locale": "en", }, "app_info": map[string]interface{}{ "module": "makecommerce", @@ -154,7 +154,7 @@ func (c *Client) CreateCheckoutSession(ctx context.Context, p CheckoutParams) (* // Add product name to reference if p.ProductName != "" { - reqBody["transaction"].(map[string]interface{})["reference"] = fmt.Sprintf("%s - %s", p.ProductName, bookingID) + reqBody["transaction"].(map[string]interface{})["reference"] = p.ProductName } jsonBody, err := json.Marshal(reqBody) From 9f18cee30e562b66eeebb0a7514fc3286f907e36 Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Mon, 9 Nov 2026 09:34:44 +0200 Subject: [PATCH 03/16] Construct notification URL in CheckoutParams --- internal/handler/stripe_booking.go | 9 +++++---- internal/makecommerce/makecommerce.go | 25 ++++++++++--------------- 2 files changed, 15 insertions(+), 19 deletions(-) diff --git a/internal/handler/stripe_booking.go b/internal/handler/stripe_booking.go index a6046c55..84788f31 100644 --- a/internal/handler/stripe_booking.go +++ b/internal/handler/stripe_booking.go @@ -30,10 +30,11 @@ func (h *Handler) startBookingCheckout(ctx context.Context, sc *stripe.Client, b CustomerEmail: email, // MakeCommerce doesn't use template variables like Stripe's {CHECKOUT_SESSION_ID} // Instead, we include the booking_id in the reference and handle it on success - SuccessURL: base + "/book/" + slug + "?paid=1&session_id=" + bookingID, - CancelURL: base + "/book/" + slug, - ExpiresAt: time.Now().Add(checkoutHoldWindow), - Metadata: map[string]string{"booking_id": bookingID}, + SuccessURL: base + "/book/" + slug + "?paid=1&session_id=" + bookingID, + CancelURL: base + "/book/" + slug, + NotificationURL: base + "/v1/stripe/webhook?booking_id=" + bookingID, + ExpiresAt: time.Now().Add(checkoutHoldWindow), + Metadata: map[string]string{"booking_id": bookingID}, }) if err != nil { return "", err diff --git a/internal/makecommerce/makecommerce.go b/internal/makecommerce/makecommerce.go index 2398d6d3..601027f8 100644 --- a/internal/makecommerce/makecommerce.go +++ b/internal/makecommerce/makecommerce.go @@ -73,14 +73,15 @@ func (c *Client) WebhookConfigured() bool { return c.webhookSecret != "" } // CheckoutParams describes a one-off payment Checkout Session. // This is identical to stripe.CheckoutParams for compatibility. type CheckoutParams struct { - AmountCents int64 - Currency string - ProductName string // shown on the payment page - CustomerEmail string // prefills the email field - SuccessURL string // redirect URL after successful payment - CancelURL string // redirect URL if payment is cancelled - ExpiresAt time.Time // session expiry (MakeCommerce uses 30 min fixed) - Metadata map[string]string // e.g. booking_id — echoed back on the webhook + AmountCents int64 + Currency string + ProductName string // shown on the payment page + CustomerEmail string // prefills the email field + SuccessURL string // redirect URL after successful payment + CancelURL string // redirect URL if payment is cancelled + NotificationURL string // redirect URL if payment is cancelled + ExpiresAt time.Time // session expiry (MakeCommerce uses 30 min fixed) + Metadata map[string]string } // CheckoutSession is the subset of a Stripe Checkout Session we use. @@ -112,12 +113,6 @@ func (c *Client) CreateCheckoutSession(ctx context.Context, p CheckoutParams) (* // Use 2 decimal places to ensure proper currency formatting amountStr := strconv.FormatFloat(float64(p.AmountCents)/100.0, 'f', 2, 64) - // Extract booking_id from metadata for reference - bookingID := p.Metadata["booking_id"] - if bookingID == "" { - bookingID = fmt.Sprintf("booking_%s", p.ProductName) - } - // Build MakeCommerce transaction request reqBody := map[string]interface{}{ "transaction": map[string]interface{}{ @@ -133,7 +128,7 @@ func (c *Client) CreateCheckoutSession(ctx context.Context, p CheckoutParams) (* "method": "GET", }, "notification_url": map[string]interface{}{ - "url": "https://romelia-hypermetaphoric-clarinda.ngrok-free.dev/v1/stripe/webhook", + "url": p.NotificationURL, "method": "POST", }, }, From a256169a494164c29c15d5c860d79ba9cdcdd2b0 Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Mon, 9 Nov 2026 10:32:12 +0200 Subject: [PATCH 04/16] Semi-dynamic shopId for MakeCommerce integration --- internal/makecommerce/makecommerce.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/internal/makecommerce/makecommerce.go b/internal/makecommerce/makecommerce.go index 601027f8..e766cde8 100644 --- a/internal/makecommerce/makecommerce.go +++ b/internal/makecommerce/makecommerce.go @@ -35,6 +35,7 @@ type Client struct { secretKey string publicKey string webhookSecret string // Same as secretKey for MakeCommerce MAC verification + shopId string // HTTP client http *http.Client @@ -52,6 +53,7 @@ func New(secretKey, publishableKey, webhookSecret string) (*Client, error) { return nil, fmt.Errorf("makecommerce: secret key required") } return &Client{ + shopId: "f7741ab2-7445-45f9-9af4-0d0408ef1e4c", // TODO secretKey: secretKey, publicKey: publishableKey, webhookSecret: webhookSecret, @@ -165,7 +167,7 @@ func (c *Client) CreateCheckoutSession(ctx context.Context, p CheckoutParams) (* } // MakeCommerce uses Basic Auth with secret key - req.SetBasicAuth("f7741ab2-7445-45f9-9af4-0d0408ef1e4c", c.secretKey) + req.SetBasicAuth(c.shopId, c.secretKey) req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") @@ -242,7 +244,7 @@ func (c *Client) GetCheckoutSession(ctx context.Context, id string) (*CheckoutSe return nil, fmt.Errorf("makecommerce: create request: %w", err) } - req.SetBasicAuth("f7741ab2-7445-45f9-9af4-0d0408ef1e4c", c.secretKey) + req.SetBasicAuth(c.shopId, c.secretKey) req.Header.Set("Accept", "application/json") resp, err := c.http.Do(req) From 4626967f25322e16aa4ead09da794506fe2fa5a1 Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Mon, 9 Nov 2026 11:27:51 +0200 Subject: [PATCH 05/16] Bump calnode version --- internal/makecommerce/makecommerce.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/makecommerce/makecommerce.go b/internal/makecommerce/makecommerce.go index e766cde8..d10b0c01 100644 --- a/internal/makecommerce/makecommerce.go +++ b/internal/makecommerce/makecommerce.go @@ -145,7 +145,7 @@ func (c *Client) CreateCheckoutSession(ctx context.Context, p CheckoutParams) (* "module": "makecommerce", "module_version": "0.0.1", "platform": "calnode", - "version": "0.12.0", + "version": "0.13.0", }, } From d44406a83ed706425343c9999b87aa426539054e Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Mon, 9 Nov 2026 11:28:07 +0200 Subject: [PATCH 06/16] Add remote client header detection --- internal/server/middleware.go | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/internal/server/middleware.go b/internal/server/middleware.go index 949b613a..7cf05291 100644 --- a/internal/server/middleware.go +++ b/internal/server/middleware.go @@ -50,12 +50,39 @@ func Logging(logger *slog.Logger, next http.Handler) http.Handler { "path", redactTokenPaths(r.URL.Path), "status", rw.status, "duration_ms", time.Since(start).Milliseconds(), - "remote_addr", r.RemoteAddr, + "remote_addr", ClientIP(r), "request_id", reqID, ) }) } +// ClientIP returns the most likely client IP for the request. +func ClientIP(r *http.Request) string { + // X-Real-Ip is set by Traefik from the PROXY protocol source address. + if ip := net.ParseIP(strings.TrimSpace(r.Header.Get("X-Real-Ip"))); ip != nil { + return ip.String() + } + + // X-Forwarded-For: client, proxy1, proxy2, ... The leftmost entry + // is the original client. Parse it to reject garbage. + if xff := r.Header.Get("X-Forwarded-For"); xff != "" { + if i := strings.IndexByte(xff, ','); i >= 0 { + xff = xff[:i] + } + if ip := net.ParseIP(strings.TrimSpace(xff)); ip != nil { + return ip.String() + } + } + + // Fallback: direct connection (or misconfigured proxy). This will be + // Traefik's IP when the proxy is in front but headers are missing. + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return strings.TrimSpace(r.RemoteAddr) + } + return host +} + // redactTokenPaths replaces bearer credentials carried in URL paths before they // reach the logs: manage tokens (/manage/{token}), room join URLs (/room/...), // and invite tokens (/invites/{token}) would otherwise land verbatim in stdout From ad6e9e89cc216101b89f716cf06aba915004e418 Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Mon, 9 Nov 2026 11:39:32 +0200 Subject: [PATCH 07/16] Carry remote client IP to MakeCommerce checkout --- internal/handler/booking_handler.go | 34 ++++++++++++++++++++++++++- internal/handler/stripe_booking.go | 7 ++++-- internal/makecommerce/makecommerce.go | 2 +- internal/server/middleware.go | 14 ++++++----- 4 files changed, 47 insertions(+), 10 deletions(-) diff --git a/internal/handler/booking_handler.go b/internal/handler/booking_handler.go index f7a09f26..325e1ea7 100644 --- a/internal/handler/booking_handler.go +++ b/internal/handler/booking_handler.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "log/slog" + "net" "net/http" "net/mail" "net/url" @@ -27,6 +28,34 @@ import ( "github.com/calnode/calnode/internal/zoom" ) +// clientIP extracts the most likely client IP from the request headers. +// It tries X-Real-Ip first (set by Traefik from PROXY protocol), then X-Forwarded-For, +// then falls back to the TCP remote address. +func clientIP(r *http.Request) string { + // X-Real-Ip is set by Traefik from the PROXY protocol source address. + if ip := net.ParseIP(strings.TrimSpace(r.Header.Get("X-Real-Ip"))); ip != nil { + return ip.String() + } + + // X-Forwarded-For: client, proxy1, proxy2, ... The leftmost entry + // is the original client. + if xff := r.Header.Get("X-Forwarded-For"); xff != "" { + if i := strings.IndexByte(xff, ','); i >= 0 { + xff = xff[:i] + } + if ip := net.ParseIP(strings.TrimSpace(xff)); ip != nil { + return ip.String() + } + } + + // Fallback: direct connection (or misconfigured proxy). + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return strings.TrimSpace(r.RemoteAddr) + } + return host +} + // errInvalidBookerEmail is returned by normalizeBookerEmail for an address net/mail // cannot parse. Callers map it to their own protocol (400 on the REST path, a short // retry hint for the assistant). @@ -1002,7 +1031,10 @@ func (h *Handler) CreateBooking(w http.ResponseWriter, r *http.Request) { 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) + + clientIp := clientIP(r) + + checkoutURL, err := h.startBookingCheckout(r.Context(), sc, b.ID, et.PriceCents, et.Currency, et.Name, req.EventTypeSlug, req.Email, clientIp) 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/stripe_booking.go b/internal/handler/stripe_booking.go index 84788f31..2edf7d2d 100644 --- a/internal/handler/stripe_booking.go +++ b/internal/handler/stripe_booking.go @@ -16,7 +16,7 @@ const checkoutHoldWindow = 31 * time.Minute // startBookingCheckout creates a payment transaction for a held (pending) booking, marks // the booking pending_payment, and returns the hosted payment URL to redirect the booker to. // For MakeCommerce, the transaction ID is used instead of Stripe's session ID. -func (h *Handler) startBookingCheckout(ctx context.Context, sc *stripe.Client, bookingID string, priceCents int, currency, productName, slug, email string) (string, error) { +func (h *Handler) startBookingCheckout(ctx context.Context, sc *stripe.Client, bookingID string, priceCents int, currency, productName, slug, email string, clientIp string) (string, error) { if currency == "" { currency = "eur" // MakeCommerce primarily uses EUR } @@ -34,7 +34,10 @@ func (h *Handler) startBookingCheckout(ctx context.Context, sc *stripe.Client, b CancelURL: base + "/book/" + slug, NotificationURL: base + "/v1/stripe/webhook?booking_id=" + bookingID, ExpiresAt: time.Now().Add(checkoutHoldWindow), - Metadata: map[string]string{"booking_id": bookingID}, + Metadata: map[string]string{ + "booking_id": bookingID, + "client_ip": clientIp, + }, }) if err != nil { return "", err diff --git a/internal/makecommerce/makecommerce.go b/internal/makecommerce/makecommerce.go index d10b0c01..20ecfc21 100644 --- a/internal/makecommerce/makecommerce.go +++ b/internal/makecommerce/makecommerce.go @@ -137,7 +137,7 @@ func (c *Client) CreateCheckoutSession(ctx context.Context, p CheckoutParams) (* }, "customer": map[string]interface{}{ "email": p.CustomerEmail, - "ip": "176.46.60.160", + "ip": p.Metadata["client_ip"], "country": "EE", "locale": "en", }, diff --git a/internal/server/middleware.go b/internal/server/middleware.go index 7cf05291..1126bed8 100644 --- a/internal/server/middleware.go +++ b/internal/server/middleware.go @@ -45,22 +45,24 @@ func Logging(logger *slog.Logger, next http.Handler) http.Handler { next.ServeHTTP(rw, r) reqID, _ := r.Context().Value(requestIDKey).(string) + ipSource, ip := ClientIP(r) logger.InfoContext(r.Context(), "request", "method", r.Method, "path", redactTokenPaths(r.URL.Path), "status", rw.status, "duration_ms", time.Since(start).Milliseconds(), - "remote_addr", ClientIP(r), + "remote_addr_source", ipSource, + "remote_addr", ip, "request_id", reqID, ) }) } // ClientIP returns the most likely client IP for the request. -func ClientIP(r *http.Request) string { +func ClientIP(r *http.Request) (string, string) { // X-Real-Ip is set by Traefik from the PROXY protocol source address. if ip := net.ParseIP(strings.TrimSpace(r.Header.Get("X-Real-Ip"))); ip != nil { - return ip.String() + return "X-Real-Ip", ip.String() } // X-Forwarded-For: client, proxy1, proxy2, ... The leftmost entry @@ -70,7 +72,7 @@ func ClientIP(r *http.Request) string { xff = xff[:i] } if ip := net.ParseIP(strings.TrimSpace(xff)); ip != nil { - return ip.String() + return "X-Forwarded-For", ip.String() } } @@ -78,9 +80,9 @@ func ClientIP(r *http.Request) string { // Traefik's IP when the proxy is in front but headers are missing. host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { - return strings.TrimSpace(r.RemoteAddr) + return "r.RemoteAddr", strings.TrimSpace(r.RemoteAddr) } - return host + return "host", host } // redactTokenPaths replaces bearer credentials carried in URL paths before they From 8b7bd4cc6635d13e412a7c27769df5d02ab869d3 Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Mon, 9 Nov 2026 16:47:07 +0200 Subject: [PATCH 08/16] Drop hardcoded locale and country settings from MakeCommerce checkout payload --- internal/makecommerce/makecommerce.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/internal/makecommerce/makecommerce.go b/internal/makecommerce/makecommerce.go index 20ecfc21..5878f942 100644 --- a/internal/makecommerce/makecommerce.go +++ b/internal/makecommerce/makecommerce.go @@ -136,10 +136,8 @@ func (c *Client) CreateCheckoutSession(ctx context.Context, p CheckoutParams) (* }, }, "customer": map[string]interface{}{ - "email": p.CustomerEmail, - "ip": p.Metadata["client_ip"], - "country": "EE", - "locale": "en", + "email": p.CustomerEmail, + "ip": p.Metadata["client_ip"], }, "app_info": map[string]interface{}{ "module": "makecommerce", From f2a0f114a8b15d16cf0c5acf30a11c9e4df87993 Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Mon, 9 Nov 2026 16:58:34 +0200 Subject: [PATCH 09/16] Vertically center booking element --- internal/handler/templates/book.html | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/internal/handler/templates/book.html b/internal/handler/templates/book.html index 583489f5..3de3207f 100644 --- a/internal/handler/templates/book.html +++ b/internal/handler/templates/book.html @@ -59,6 +59,11 @@ /* Mobile back-to-calendar button (step-flow); hidden on desktop. */ .cal-back { display: none; } +.card { + margin-top: auto; + margin-bottom: auto; +} + /* ── Mobile ──────────────────────────────────────── */ @media (max-width: 700px) { body { padding: 0 0 1.5rem; align-items: center; gap: 1rem; } From 4067cef763c528db704044c40e1503971fbd87b1 Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Mon, 9 Nov 2026 17:05:43 +0200 Subject: [PATCH 10/16] Force use of et-EE locale in booking page time formatting --- internal/handler/templates/book.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/handler/templates/book.html b/internal/handler/templates/book.html index 3de3207f..1511d41a 100644 --- a/internal/handler/templates/book.html +++ b/internal/handler/templates/book.html @@ -358,7 +358,7 @@

{{call .T "booking_confirmed"}}

// [] — otherwise a visitor who picked a language via the switcher, or whose // Accept-Language differs from navigator.language, would see translated chrome next // to month/day names in a different language. See internal-docs/i18n-plan.md. - function fmtTime(iso) { return BookingLogic.formatTime(iso, TZ, LOCALE); } + function fmtTime(iso) { return BookingLogic.formatTime(iso, TZ, "et-EE"); } function fmtDate(d) { return d.toLocaleDateString(LOCALE, { weekday: 'short', month: 'short', day: 'numeric' }); } From f6d0bfacc1da4871d81085994b6ea89d543f1f51 Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Mon, 9 Nov 2026 17:14:16 +0200 Subject: [PATCH 11/16] Add Europe/Tallinn timezone to supported list --- frontend/src/lib/prefs.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/frontend/src/lib/prefs.ts b/frontend/src/lib/prefs.ts index 1be44414..eef1189f 100644 --- a/frontend/src/lib/prefs.ts +++ b/frontend/src/lib/prefs.ts @@ -75,6 +75,7 @@ export const TIMEZONES = [ 'Europe/Paris', 'Europe/Berlin', 'Europe/Amsterdam', + 'Europe/Tallinn', 'America/New_York', 'America/Chicago', 'America/Denver', From c335a8aa5e06f5c6b04aac259d47bd03e9e60e8d Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Tue, 10 Nov 2026 11:10:47 +0200 Subject: [PATCH 12/16] Read MK secrets from env --- internal/makecommerce/makecommerce.go | 28 ++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/internal/makecommerce/makecommerce.go b/internal/makecommerce/makecommerce.go index 5878f942..95138840 100644 --- a/internal/makecommerce/makecommerce.go +++ b/internal/makecommerce/makecommerce.go @@ -17,6 +17,7 @@ import ( "io" "net/http" "net/url" + "os" "strconv" "strings" "time" @@ -24,8 +25,7 @@ import ( // API base URLs const ( - apiBaseDefault = "https://api.test.maksekeskus.ee" - apiVersion = "v1" + apiVersion = "v1" ) // Client talks to MakeCommerce using API keys. @@ -48,15 +48,33 @@ type Client struct { // The secretKey is used for authentication and webhook verification. // The publishableKey is optional and used for client-side operations if needed. // The webhookSecret should be the same as secretKey for MakeCommerce. -func New(secretKey, publishableKey, webhookSecret string) (*Client, error) { +func New(_, _, _ string) (*Client, error) { + + shopId := os.Getenv("MK_SHOPID") + if shopId == "" { + return nil, fmt.Errorf("makecommerce: shop ID required") + } + + secretKey := os.Getenv("MK_SECRETKEY") if secretKey == "" { return nil, fmt.Errorf("makecommerce: secret key required") } + + publishableKey := os.Getenv("MK_PUBLISHABLEKEY") + if publishableKey == "" { + return nil, fmt.Errorf("makecommerce: publishable key required") + } + + apiBaseDefault := os.Getenv("MK_APIURL") + if apiBaseDefault == "" { + return nil, fmt.Errorf("makecommerce: api url required") + } + return &Client{ - shopId: "f7741ab2-7445-45f9-9af4-0d0408ef1e4c", // TODO + shopId: shopId, secretKey: secretKey, publicKey: publishableKey, - webhookSecret: webhookSecret, + webhookSecret: "webhookSecret", http: &http.Client{Timeout: 20 * time.Second}, apiBase: apiBaseDefault, }, nil From fccf0ab1862a49a873f0c807dd2da84dfc072804 Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Wed, 11 Nov 2026 15:18:34 +0200 Subject: [PATCH 13/16] Allow setting event type ID of an availability rule in the API request --- internal/handler/availability.go | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/internal/handler/availability.go b/internal/handler/availability.go index 3eb766ec..f0e5bc2a 100644 --- a/internal/handler/availability.go +++ b/internal/handler/availability.go @@ -123,9 +123,10 @@ func (h *Handler) UpdateAvailabilityRule(w http.ResponseWriter, r *http.Request) r.Body = http.MaxBytesReader(w, r.Body, 32<<10) var req struct { - DayOfWeek *int `json:"day_of_week"` - StartTime *string `json:"start_time"` - EndTime *string `json:"end_time"` + EventTypeId *string `json:"event_type_id"` + DayOfWeek *int `json:"day_of_week"` + StartTime *string `json:"start_time"` + EndTime *string `json:"end_time"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { h.writeError(w, http.StatusBadRequest, "invalid JSON") @@ -137,11 +138,10 @@ func (h *Handler) UpdateAvailabilityRule(w http.ResponseWriter, r *http.Request) } var current availRuleJSON - var etID sql.NullString err := h.db.QueryRowContext(r.Context(), `SELECT id, event_type_id, day_of_week, start_time, end_time FROM availability_rules WHERE id = ? AND user_id = ?`, id, user.ID). - Scan(¤t.ID, &etID, ¤t.DayOfWeek, ¤t.StartTime, ¤t.EndTime) + Scan(¤t.ID, ¤t.EventTypeID, ¤t.DayOfWeek, ¤t.StartTime, ¤t.EndTime) if err == sql.ErrNoRows { h.writeError(w, http.StatusNotFound, "rule not found") return @@ -151,8 +151,14 @@ func (h *Handler) UpdateAvailabilityRule(w http.ResponseWriter, r *http.Request) h.writeError(w, http.StatusInternalServerError, "internal error") return } - if etID.Valid { - current.EventTypeID = &etID.String + + if req.EventTypeId != nil { + etID := req.EventTypeId + if *etID == "null" { + current.EventTypeID = nil + } else { + current.EventTypeID = req.EventTypeId + } } if req.DayOfWeek != nil { @@ -174,8 +180,8 @@ func (h *Handler) UpdateAvailabilityRule(w http.ResponseWriter, r *http.Request) } _, err = h.db.ExecContext(r.Context(), - `UPDATE availability_rules SET day_of_week=?, start_time=?, end_time=? WHERE id=? AND user_id=?`, - current.DayOfWeek, current.StartTime, current.EndTime, id, user.ID) + `UPDATE availability_rules SET event_type_id=?, day_of_week=?, start_time=?, end_time=? WHERE id=? AND user_id=?`, + current.EventTypeID, current.DayOfWeek, current.StartTime, current.EndTime, id, user.ID) if err != nil { if db.IsUniqueViolation(err) { h.writeError(w, http.StatusConflict, "a rule for this day and time already exists") From 33bbae37cc4c1af808a86193c6a5e07b86ee1055 Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Wed, 11 Nov 2026 15:18:48 +0200 Subject: [PATCH 14/16] Add margin auto to booking element for centering --- internal/handler/templates/booking.css | 2 ++ 1 file changed, 2 insertions(+) diff --git a/internal/handler/templates/booking.css b/internal/handler/templates/booking.css index ba0ce4a9..412be3f8 100644 --- a/internal/handler/templates/booking.css +++ b/internal/handler/templates/booking.css @@ -31,6 +31,8 @@ overflow: hidden; width: 100%; max-width: 860px; + margin-left: auto; + margin-right: auto; } /* ── Info panel ──────────────────────────────────── */ From c8a8859edf66f6dffd90ed24aa731902e6cdf5d3 Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Wed, 11 Nov 2026 15:19:23 +0200 Subject: [PATCH 15/16] Force et-EE locale in time formatting in embedded widget --- internal/handler/embed.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/handler/embed.js b/internal/handler/embed.js index e45944a3..4f6530f4 100644 --- a/internal/handler/embed.js +++ b/internal/handler/embed.js @@ -94,8 +94,8 @@ function dayKey(iso) { return new Intl.DateTimeFormat('en-CA', { timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(iso)); } // locale is the resolved server-side locale (this.locale), not the browser's own // ([]) — see the matching fix/comment in book.html / internal-docs/i18n-plan.md. - function timeLabel(iso, locale) { return new Intl.DateTimeFormat(locale || [], { timeZone: TZ, hour: 'numeric', minute: '2-digit' }).format(new Date(iso)); } - function shortDay(iso, locale) { return new Intl.DateTimeFormat(locale || [], { timeZone: TZ, weekday: 'short', month: 'short', day: 'numeric' }).format(new Date(iso)); } + function timeLabel(iso, locale) { return new Intl.DateTimeFormat("et-EE", { timeZone: TZ, hour: 'numeric', minute: '2-digit' }).format(new Date(iso)); } + function shortDay(iso, locale) { return new Intl.DateTimeFormat("et-EE", { timeZone: TZ, weekday: 'short', month: 'short', day: 'numeric' }).format(new Date(iso)); } function ymd(d) { return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); } function startOfMonth(d) { return new Date(d.getFullYear(), d.getMonth(), 1); } function endOfMonth(d) { return new Date(d.getFullYear(), d.getMonth() + 1, 0); } From cd5f0a8b7fa85c6c9569edf36ff9dbb3d04399a7 Mon Sep 17 00:00:00 2001 From: Kaur Palang Date: Wed, 11 Nov 2026 21:21:17 +0200 Subject: [PATCH 16/16] Add UI to select event type for availability rule --- frontend/src/routes/availability/+page.svelte | 49 +++++++++++++++++-- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/frontend/src/routes/availability/+page.svelte b/frontend/src/routes/availability/+page.svelte index 76464108..6c297742 100644 --- a/frontend/src/routes/availability/+page.svelte +++ b/frontend/src/routes/availability/+page.svelte @@ -1,6 +1,6 @@ {block.error} {/if} + + updateBlock(block)} + disabled={block.saving || !block.id} + > + + {#if block.event_type_id === "null"} + All + {:else} + {eventName(block.event_type_id)?.name ?? block.event_type_id} + {/if} + + + All + {#each eventTypes as e}{e.name}{/each} + + +