Skip to content

Commerce

Internals of the Commerce domain. For the public API, see Commerce API.

This page also describes the ticketing lane that Commerce, Advertising, Analytics and Notification share. Facts were checked against CoreAPI staging on 2026-11-16.

The ticketing lane

The four ticketing domains came from the separate johorzoo ticketing service, merged into CoreAPI in 2026. They still differ from the native /api/v1 domains:

Topic Ticketing lane Native domains
Wiring setupTicketingService in ticketing.go, mounted by mountTicketingLane. Modules wire in order: notifications, tenancy, identity, catalogue, advertising, commerce, analytics. routes_platform.go (mountPlatformLane)
Paths Root paths: /api/…, /payment/…, /pdf/…, /auth/… (no v1) /api/v1/<domain>/…
Response body { respCode, respDesc, result } from models.NewBaseSuccessResponse (respCode 2000) and NewBaseErrorResponse (respCode always 4000). Uncaught errors go through the app-level middleware.GlobalErrorHandler, which emits the same shape with codes from pkg/errors (4000–4004, 5000–5006). { success, data } via middleware.NativeErrorScope
Auth middleware errors ProtectedRS256, RequireWorkspacePermission and Protected answer { "message": "…" }, not the ticketing shape. same
Database Tables in the johorzoo schema of the CoreAPI database; models name it in TableName() (johorzoo.order_ticket_group). Since Phase 5 there is no separate ticketing DB: db.GetDB() everywhere. public schema
Schema changes SQL-seeded (Quickstart postgres-init/ticketing/); no GORM auto-migration for ticketing models. GORM pkg/db/migrate.go
Tokens Two kinds: the AuthAPI RS256 token (ProtectedRS256) for admin routes, and the legacy HS256 customer token (middleware.Protected(jwtService), issued by POST /auth/login) for customer routes. RS256 only
RBAC Admin routes check a workspace permission, either from :workspaceId in the path (RequireWorkspacePermission) or from the fixed workspace in SPATIO_TICKETING_WORKSPACE_ID (RequireWorkspacePermissionFixed). PopulateLegacyLocals maps the AuthAPI session onto the old fullName/role locals for audit strings. :workspaceId / :orgId
Consumers SpatioViewAdmin (TicketAdmin) and ticketcms parse {respCode} today. consoles

Planned (Phase 6): when both frontends move to { success }, mount NativeErrorScope on this lane and drop the reliance on the app-level handler. The seam is in ticketing.go.

How a purchase works

sequenceDiagram
    participant S as Storefront
    participant C as CoreAPI
    participant P as Payment provider
    participant POS as Park POS
    participant M as SMTP (ticket group email profile)

    S->>C: GET /payment/methods?ticketGroupId=
    S->>C: POST /api/orderTicketGroup
    C->>C: validate, create order (initiate), order log, admin notification
    C-->>S: 201 { orderID }
    S->>C: POST /payment/start { orderNo }
    C->>C: CheckoutService.Start: resolve payment profile, build StartRequest from the stored order
    C->>P: provider.StartPayment (JohorPay: fetch rand_key token, SHA-512 checksum)
    C-->>S: { kind: form_post | redirect, url, fields }
    S->>P: browser posts / opens url
    P->>C: GET /payment/return?tgid=&ppid=…&payload=… (browser), also server-to-server for JohorPay
    C->>C: DecodePaymentResult, applyPaymentResult (claim once)
    C->>POS: issue tickets (or internal QR codes)
    C->>M: ticket email + PDF
    C-->>S: 302 FRONTEND_BASE_URL/paymentRedirect?orderTicketGroupId=&transactionStatus=&orderNo=

Payment providers

  • Gateways live behind pkg/payment/providers.PaymentProvider (StartPayment, DecodeReturn, optional ListBanks and WebhookParser). Registry: johorpay, stripe (registry.go). Adding a gateway means adding a provider, not routes.
  • CheckoutService (domain/commerce/services/checkout_service.go) is the only code that turns an order into a gateway request. Everything sent (amount, buyer, bill) comes from the stored order: the browser used to send the amount and could edit the price before it was signed.
  • The return URL is BACKEND_BASE_URL + /payment/return?tgid=<ticketGroupId>&ppid=<paymentProfileId>. ppid tells the callback which profile's key to decrypt with.
  • Payment profiles (org-owned, shared across workspaces, linked to ticket groups) hold the gateway credentials, encrypted with the key in COREAPI_SECRETS_ENCRYPTION_KEY (crypto.SecretBox). The credentials themselves are stored only in the database, never in config or docs. Managed in the tenancy domain (PaymentProfileService, TicketGroupPaymentProfileService).
  • JohorPay appends ?payload=… to a return URL that already has a query string; callbackParams splits it back out.
  • Callbacks without ppid (payments started before it existed) go through decodeLegacyCallback: it tries every profile linked to the ticket group, and accepts a result only when it names a real order in that ticket group that wasn't recorded against another profile.
  • applyPaymentResult is shared by the browser return, JohorPay's server call, /payment/redirect and the Stripe webhook. RecordPaymentResult claims the result atomically (ClaimPaymentResult); only the claiming request runs side effects (customer log, notification, ticket issuing, email). rejectWrongAmount turns a success into a failure when the gateway reports a paid amount different from the order total (Stripe reports it; JohorPay doesn't).
  • /payment/webhook/:ppid verifies the Stripe signature with the profile's webhook secret, then checks the order was paid through that profile (checkOrderProfile).

Ticket issuing and emails

  • On success, issueTicketsAndEmail issues tickets through the park's POS profile (or internal QR codes), writes the order items, renders the ticket PDF and emails it from the ticket group's own email profile (TicketGroupEmailProfileService; email profiles live in public, built from coreDB).
  • The PDF branding comes from document.Resolver: the document template tied to the ticket group, else the platform default. Logos are read from object storage (catalogueServices.LogoBucket()); a logo that won't load renders the platform logo. Failures are logged, never returned: this runs after payment.
  • If the POS call fails or returns no tickets, the order stays paid with is_email_sent = false and the ticket-email retry scheduler issues and sends later.

Order status

transaction_status (raw, stored): initiate → pending → success | failed. Ticket issuing, sales analytics and the stale-order jobs branch on it; don't change these values.

displayStatus (computed in services/order_status_mapper.go, management API only) refines failed with keyword lists taken from observed JohorPay status_message values on production failed orders, checked in this order:

Result Matches
rejected "tidak dibenarkan", "baki akaun tidak mencukupi", "kekurangan baki", "invalid card", "reject", "blocked card", "pelanggaran polisi keselamatan", "unknown device", "kad tamat tempoh"
abandoned "tidak dijumpai", "no transaction(s) found", "click cancel", "memilih 'batal'", "cancel authentication"; also an empty message with no bank status (swept from initiate)
expired "timeout", "tamat tempoh"; also an empty message with a bank status (swept from pending)

Background jobs

Started in setupTicketingService, run by runScheduler in schedulers.go (one Postgres advisory lock per job, pg_try_advisory_lock, so one replica runs each tick).

Job Interval What it does Disable with
Ticket email retry 5 min Paid orders with is_email_sent = false: issue tickets if missing, send the email. DISABLE_TICKET_EMAIL_RETRY_SCHEDULER=true
Initiate order check 60 min Orders still initiate 60 min after created_at → failed. DISABLED_INITIATE_ORDER_CHECK_SCHEDULER=true
Pending order check 120 min Orders still pending 120 min after transaction_date → failed, with a customer log. DISABLED_PENDING_ORDER_CHECK_SCHEDULER=true

The report jobs belong to Analytics. Note the DISABLED_ prefix on the two order checks.

Data model

erDiagram
    OrderTicketGroup {
        uint orderTicketGroupId
        uint ticketGroupId
        string paymentProfileId
        string custId
        string langChosen
        string orderNo
        string transactionId
        string transactionStatus
        string transactionDate
        string bankCurrentStatus
        string statusMessage
        string bankCode
        float totalAmount
        string buyerName
        string buyerEmail
        string admitDate
        string programCd
        string scheduleTime
        bool isEmailSent
    }
    OrderTicketInfo {
        uint orderTicketInfoId
        uint orderTicketGroupId
        string itemId
        float unitPrice
        string printType
        int quantityBought
        string encryptedId
        string twbid
        string admitDate
    }
    OrderTicketLog {
        uint orderTicketLogId
        uint orderTicketGroupId
        string performedBy
        string type
        string title
        string message
        string date
    }
    OrderTicketGroup ||--o{ OrderTicketInfo : contains
    OrderTicketGroup ||--o{ OrderTicketLog : "has logs"

Tables: johorzoo.order_ticket_group, johorzoo.order_ticket_info, johorzoo.order_ticket_log. Order numbers are YYYYMMDD + TB + 9 random digits (generateOrderNumber). Dates in transaction_date and order-management filters are Malaysia time (UTC+8); the filter subtracts 8 hours to compare with created_at.

Environment variables

Names only; values are in the deployment's secret store and Quickstart's local env.

Variable Used for
BACKEND_BASE_URL CoreAPI's address as the browser reaches it; base of the gateway return URL.
FRONTEND_BASE_URL Storefront address; /payment/return redirects to <FRONTEND_BASE_URL>/paymentRedirect.
SPATIO_TICKETING_WORKSPACE_ID The fixed workspace for RequireWorkspacePermissionFixed and for admin notifications.
COREAPI_SECRETS_ENCRYPTION_KEY Base64 key that decrypts payment, POS and email profile credentials. Unset: ticket emails can't be sent.
DISABLE_TICKET_EMAIL_RETRY_SCHEDULER, DISABLED_INITIATE_ORDER_CHECK_SCHEDULER, DISABLED_PENDING_ORDER_CHECK_SCHEDULER Turn off a background job.

Known issues

Found while documenting on 2026-11-16; not fixed yet.

  • AllowBypass on POST /api/orderTicketGroup/free (public): with "AllowBypass": true the order-limit check and the zero-total check are skipped, so anyone can create a success order with a non-zero total without paying. Not on the partner page. Should be removed or put behind an admin permission.
  • GET /payment/decrypt is public and decrypts any gateway payload with the profile's key. Developer utility; not on the partner page.
  • GET /api/orderTicketGroup?orderTicketGroupId= is public and returns the full order (buyer name, email, tickets) for a sequential ID. Documented because the storefront uses it after payment; consider requiring the order number or a token.
  • POST /api/orderTicketGroup and /free accept only ticket groups 1 and 2 (TODO - remove it once the restriction is not needed for FAT in order_handler.go). Others get 400 Ticket group is not permitted to be bought at the moment.
  • GET /pdf/receipt returns a fixed sample PDF with dummy data, not an order's receipt. Not on the partner page.
  • GET /payment/success and /payment/failure render built-in HTML pages from query values; the normal flow redirects to the storefront instead. Not on the partner page.
  • Create-order returns orderID but not orderNo, so the storefront needs a second call before POST /payment/start.
  • GET /api/orderTicketGroups still branches on legacy userType/role claims (admin + SYSADMIN/ADMIN sees all orders, filterable by custId).

Change history

  • 2026-06-23: first commerce documentation, from the johorzoo service.