From 2e881968b7701be1562cc3d6e782f99da3dcbb13 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 05:05:28 +0700 Subject: [PATCH] feat(payment): make Mayar the only gateway with API key, Web Token and webhook - Remove DOKU (provider, /api/webhooks/doku, env, scripts). Legacy PAYMENT_GATEWAY_PROVIDER=doku / SUBSCRIPTION_PAYMENT_MODE=doku_* still boot, read as Mayar with a system-status warning. - Webhook auth: MAYAR_WEBHOOK_TOKEN (Mayar dashboard "Web Token") via the X-Callback-Token header, ?token= on the URL, or an HMAC of the raw body. The API key is never accepted as a webhook token. - Never trust a "paid" webhook on its own: re-read GET /hl/v2/payments/{id} with the reference stored at creation and require a matching amount before settling POS orders or activating subscriptions. Non-payment events and orders KaffePOS does not know are acknowledged with 200. - Online payment only opens when both MAYAR_API_KEY and MAYAR_WEBHOOK_TOKEN are set. Sandbox host defaults to api.mayar.io (current Mayar docs). - Redact ?token= from request logs and alerts. - Add backend/scripts/mayar-connect.mjs (check key, register + test webhook), scripts/smoke-local-mayar.mjs (local end-to-end run with a fake Mayar API) and docs/engineering/MAYAR_INTEGRATION_GUIDE.md. Update env templates, release checks and staging scripts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011vndxq8hQ8FPSGhexsE9Tz --- .env.example | 2 +- .env.staging.example | 4 +- README.md | 26 +- SECURITY.md | 2 +- backend/.env.example | 32 +- backend/.env.staging.example | 28 +- backend/package.json | 1 + backend/scripts/mayar-connect.mjs | 195 +++++ backend/src/core/billing.ts | 58 +- backend/src/core/env.ts | 75 +- backend/src/core/errorHandler.ts | 15 +- backend/src/core/paymentConfig.test.ts | 102 +++ backend/src/index.ts | 3 +- backend/src/lib/deploymentReadiness.test.ts | 90 +-- backend/src/lib/deploymentReadiness.ts | 34 +- backend/src/lib/redactUrl.test.ts | 16 + backend/src/lib/redactUrl.ts | 10 + backend/src/middleware/apm.ts | 9 +- .../payments/payment-provider.factory.test.ts | 32 +- .../src/payments/payment-provider.factory.ts | 3 +- .../src/payments/payment-provider.types.ts | 25 +- .../payments/providers/doku.provider.test.ts | 121 --- .../src/payments/providers/doku.provider.ts | 271 ------- .../payments/providers/mayar.provider.test.ts | 532 ++++++++----- .../src/payments/providers/mayar.provider.ts | 699 ++++++++++-------- backend/src/routes/__tests__/webhooks.test.ts | 341 ++++++--- backend/src/routes/health.ts | 20 +- backend/src/routes/payment.ts | 20 +- backend/src/routes/subscriptions.ts | 12 +- backend/src/routes/webhooks.ts | 248 ++++++- backend/src/services/PaymentService.ts | 12 +- .../services/__tests__/PaymentService.test.ts | 32 +- coolify.backend.minimal.env.example | 31 +- coolify.frontend.minimal.env.example | 2 +- docs/engineering/COOLIFY_ENV_MAPPING.md | 15 +- docs/engineering/ENV_CONTRACT.md | 15 +- docs/engineering/MAYAR_INTEGRATION_GUIDE.md | 184 +++++ .../PAYMENT_PROVIDER_MIGRATION_REPORT.md | 33 +- package.json | 3 +- scripts/coolify-staging-deploy.mjs | 36 +- scripts/smoke-billing-production.mjs | 2 +- scripts/smoke-doku-staging.mjs | 133 ---- scripts/smoke-local-mayar.mjs | 327 ++++++++ scripts/smoke-mayar-staging.mjs | 2 +- scripts/smoke-production-readiness.mjs | 4 +- scripts/verify-release-config.mjs | 12 +- scripts/verify-staging-env.mjs | 33 +- .../settings/SubscriptionSection.tsx | 2 +- src/lib/backendApi.ts | 5 +- .../SubscriptionCheckoutFlow.test.tsx | 14 +- .../components/SubscriptionSection.test.tsx | 12 +- src/test/releaseConfigScript.test.ts | 16 +- 52 files changed, 2424 insertions(+), 1527 deletions(-) create mode 100644 backend/scripts/mayar-connect.mjs create mode 100644 backend/src/core/paymentConfig.test.ts create mode 100644 backend/src/lib/redactUrl.test.ts create mode 100644 backend/src/lib/redactUrl.ts delete mode 100644 backend/src/payments/providers/doku.provider.test.ts delete mode 100644 backend/src/payments/providers/doku.provider.ts create mode 100644 docs/engineering/MAYAR_INTEGRATION_GUIDE.md delete mode 100644 scripts/smoke-doku-staging.mjs create mode 100644 scripts/smoke-local-mayar.mjs diff --git a/.env.example b/.env.example index bf18c02..a06b583 100644 --- a/.env.example +++ b/.env.example @@ -22,7 +22,7 @@ VITE_GA_MEASUREMENT_ID=G-VNQJ3XPCGG VITE_CLARITY_PROJECT_ID=wf7x39iiqr VITE_SENTRY_DSN= VITE_SENTRY_TRACES_SAMPLE_RATE=0 -# Midtrans secret/server keys are backend-only. Do not add VITE_MIDTRANS_* keys. +# Mayar API key / webhook token are backend-only. Never add VITE_MAYAR_* keys. # ── Affiliate & Referral Safe Rollout Flags ─────────────────────── # Defaults are off. Enable gradually per docs/RELEASE_CHECKLIST_AFFILIATE_REFERRAL.md. diff --git a/.env.staging.example b/.env.staging.example index c8848e3..75bdde7 100644 --- a/.env.staging.example +++ b/.env.staging.example @@ -6,7 +6,6 @@ VITE_APP_ENV=staging VITE_STAGING_PROFILE=minimal VITE_API_BASE_URL=https://staging-api.example.com VITE_ANALYTICS_ENABLED=false -VITE_MIDTRANS_IS_PRODUCTION=false # Smoke runner env (local only; do not commit real values) KAFFEPOS_STAGING_API_URL=https://staging-api.example.com @@ -23,7 +22,6 @@ KAFFEPOS_STOCK_SMOKE_CONFIRM=1 VITE_GA4_MEASUREMENT_ID=G-XXXXXXXXXX VITE_CLARITY_PROJECT_ID=change-me VITE_PUBLIC_ASSET_BASE_URL=https://assets.example.com -VITE_MIDTRANS_CLIENT_KEY=SB-Mid-client-change-me # Feature flags VITE_AFFILIATE_REFERRAL_ENABLED=false @@ -32,7 +30,7 @@ VITE_AFFILIATE_ENABLED=false VITE_ADMIN_COMMISSION_ENABLED=false # C. Optional integrations skipped in minimal mode -# GA4, Clarity, Midtrans Snap client key, and public asset CDN may remain placeholders in minimal staging. +# GA4, Clarity, and public asset CDN may remain placeholders in minimal staging. # Frontend payment provider only; no Mayar secrets in frontend VITE_PAYMENT_GATEWAY_PROVIDER=mayar diff --git a/README.md b/README.md index 1d4c263..ef5aa5c 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,7 @@ The repair command reads ignored local staging env files, requires `STAGING_PROF | **Deployment Guide** | [`docs/launch/DEPLOYMENT_GUIDE.md`](docs/launch/DEPLOYMENT_GUIDE.md) | Production deployment procedures | | **Validation Checklist** | [`docs/launch/VALIDATION_CHECKLIST.md`](docs/launch/VALIDATION_CHECKLIST.md) | End-to-end validation | | **Android Release Signing** | [`docs/launch/ANDROID_RELEASE_SIGNING.md`](docs/launch/ANDROID_RELEASE_SIGNING.md) | Android APK signing guide | -| **Midtrans Production Switch** | [`docs/launch/MIDTRANS_PRODUCTION_SWITCH.md`](docs/launch/MIDTRANS_PRODUCTION_SWITCH.md) | Payment production setup | +| **Mayar Integration Guide** | [`docs/engineering/MAYAR_INTEGRATION_GUIDE.md`](docs/engineering/MAYAR_INTEGRATION_GUIDE.md) | Payment gateway setup (API key, webhook token, webhook URL) | ### Operations Documentation @@ -215,7 +215,7 @@ The repair command reads ignored local staging env files, requires `STAGING_PROF ### Infrastructure & Cloud Services - **Cloud Backend & Database:** InsForge Cloud PostgreSQL (`6x4q2bgn.ap-southeast.insforge.app`, 46 tables with full RLS + 160+ indexes) & InsForge Edge Functions (`@insforge/sdk`) -- **Payment Gateway:** Mayar Headless API v2 (`https://api.mayar.id/hl/v2` production / `https://api.mayar.club/hl/v2` sandbox) +- **Payment Gateway:** Mayar Headless API v2 (`https://api.mayar.id/hl/v2` production / `https://api.mayar.io/hl/v2` sandbox) - **CDN & Storage:** Cloudflare CDN & R2 / InsForge Storage - **Transactional Email:** Resend - **Analytics & Observability:** Google Analytics 4, Microsoft Clarity, Sentry Error Tracking & Custom Database APM @@ -495,15 +495,15 @@ KaffePOS uses PostgreSQL with a custom migration system. ## 💳 Mayar Payment Gateway (Headless API v2) -- Payment gateway default menggunakan **Mayar (`PAYMENT_GATEWAY_PROVIDER=mayar`)** berbasis REST API v2 resmi (`https://api.mayar.id/hl/v2` untuk production dan `https://api.mayar.club/hl/v2` untuk sandbox). -- Mendukung baik **Subscription Billing** (`POST /api/payments/start` dan `POST /api/subscriptions/payments/create`) maupun **POS Online Checkout** (`POST /api/payment/create`). -- Daftarkan URL Webhook Mayar pada **Mayar Dashboard → Integration → Webhook**: - - `https://api.kaffepos.my.id/api/webhooks/mayar` -- Customer redirect URL setelah pembayaran: - - `https://kaffepos.my.id/settings?billing=mayar-return` -- Verifikasi pembayaran dilakukan sepenuhnya di sisi server melalui webhook terautentikasi (`x-callback-token` / `x-mayar-signature` / `HMAC-SHA256`) atau pengecekan status server (`POST /api/payments/:paymentId/check` → `GET /hl/v2/payments/:id`). -- `MAYAR_API_KEY` dan `MAYAR_WEBHOOK_TOKEN` bersifat **backend-only** dan tidak pernah diekspos ke bundle frontend (`VITE_*`). -- Smoke test integrasi Mayar & InsForge: - - `npm run smoke:insforge` +- Mayar adalah **satu-satunya** payment gateway (`PAYMENT_GATEWAY_PROVIDER=mayar`; DOKU sudah dihapus). API resmi: `https://api.mayar.id/hl/v2` (production) dan `https://api.mayar.io/hl/v2` (sandbox). +- Dipakai untuk **Subscription Billing** (`POST /api/payments/start`, `POST /api/subscriptions/payments/create`) dan **POS Online Checkout** (`POST /api/payment/create-transaction`). +- Tiga hal yang menghubungkan KaffePOS ke Mayar (semuanya backend-only, tidak pernah `VITE_*`): + - `MAYAR_API_KEY` — Bearer key untuk membuat payment request & cek status. + - `MAYAR_WEBHOOK_TOKEN` — Web Token dari dashboard Mayar; Mayar mengirimnya di header `X-Callback-Token` (`?token=` di URL juga diterima). + - URL webhook di **Mayar → Integrasi → Webhook**: `https://api.kaffepos.my.id/api/webhooks/mayar`. +- Webhook `payment.received` tidak pernah dipercaya begitu saja: backend mengecek ulang `GET /hl/v2/payments/:id` (status `paid` + nominal sama) sebelum melunasi order POS atau mengaktifkan langganan. Cek manual: `POST /api/payments/:paymentId/check`. +- Hubungkan & uji: + - `node scripts/mayar-connect.mjs --register` (di container backend) atau `npm run mayar:connect -- --register` - `MAYAR_API_KEY=... MAYAR_ENVIRONMENT=sandbox npm run smoke:staging:mayar` -- Implementasi provider: [`backend/src/payments/providers/mayar.provider.ts`](backend/src/payments/providers/mayar.provider.ts) & skill referensi: [`.agent/skills/mayar/SKILL.md`](.agent/skills/mayar/SKILL.md). + - `npm run smoke:local:mayar` (end-to-end dengan Mayar palsu + Postgres lokal) +- Panduan lengkap: [`docs/engineering/MAYAR_INTEGRATION_GUIDE.md`](docs/engineering/MAYAR_INTEGRATION_GUIDE.md) · Implementasi: [`backend/src/payments/providers/mayar.provider.ts`](backend/src/payments/providers/mayar.provider.ts), [`backend/src/routes/webhooks.ts`](backend/src/routes/webhooks.ts). diff --git a/SECURITY.md b/SECURITY.md index 6e80b11..3963468 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -17,7 +17,7 @@ undo the exposure. | `SESSION_SECRET` | ❌ no refs | Dead config. No rotation needed. | | `ENCRYPTION_KEY` | ❌ no refs | Dead — the code reads `PII_ENCRYPTION_KEY`, not `ENCRYPTION_KEY`. No rotation needed. | -(Duitku/Midtrans have since been removed; the gateway is DOKU. Treat any committed `DOKU_SECRET_KEY` as compromised and rotate it in the DOKU Back Office.) +(Duitku, Midtrans and DOKU have since been removed; the only gateway is Mayar. Treat any committed `DOKU_SECRET_KEY` as compromised and revoke it in the DOKU Back Office. `MAYAR_API_KEY` and `MAYAR_WEBHOOK_TOKEN` are backend-only secrets: if either leaks, create a new API key / Web Token in the Mayar dashboard, update Coolify, and re-run `node scripts/mayar-connect.mjs` — see `docs/engineering/MAYAR_INTEGRATION_GUIDE.md`.) > ⚠️ **DB password ↔ PII key coupling.** `lib/encryption.ts` derives the > affiliate payout/bank-account (PII) encryption key from `PII_ENCRYPTION_KEY`, diff --git a/backend/.env.example b/backend/.env.example index 5feab9a..4a07423 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -41,18 +41,6 @@ DB_SSL_CA= RESEND_API_KEY= RESEND_FROM_EMAIL=KaffePOS -# Midtrans subscription payments -MIDTRANS_ENVIRONMENT=sandbox -MIDTRANS_SERVER_KEY= -MIDTRANS_CLIENT_KEY= -MIDTRANS_MERCHANT_ID= -MIDTRANS_SNAP_ENABLED=true -MIDTRANS_WEBHOOK_BASE_URL=https://api.kaffepos.my.id -MIDTRANS_FINISH_URL=https://kaffepos.my.id/settings?billing=success -MIDTRANS_UNFINISH_URL=https://kaffepos.my.id/settings?billing=pending -MIDTRANS_ERROR_URL=https://kaffepos.my.id/settings?billing=failed -SUBSCRIPTION_PAYMENT_MODE=auto - # Abuse protection AUTH_RATE_LIMIT_WINDOW_MS=900000 AUTH_LOGIN_RATE_LIMIT_MAX=10 @@ -60,8 +48,6 @@ AUTH_EMAIL_RATE_LIMIT_MAX=5 AUTH_VERIFY_RATE_LIMIT_MAX=20 PAYMENT_CREATE_RATE_LIMIT_MAX=12 -# MIDTRANS_SERVER_KEY stays backend-only. Never expose it as VITE_*. - # Optional for /api/ai-insight. Leave empty if AI insight is not used yet. GEMINI_API_KEY= SENTRY_DSN= @@ -71,15 +57,25 @@ SENTRY_TRACES_SAMPLE_RATE=0 # Comma-separated. Leave empty to use sane defaults. CORS_ORIGIN=http://localhost:5173,http://127.0.0.1:5173,http://localhost:4173,http://127.0.0.1:4173,https://kaffepos.my.id,https://www.kaffepos.my.id,https://api.kaffepos.my.id,capacitor://localhost,https://localhost,http://localhost -# Payment provider abstraction (Mayar Headless API v2 — https://docs.mayar.id) +# ── Payment gateway: Mayar Headless API v2 (https://docs.mayar.id) ───────── +# Panduan lengkap: docs/engineering/MAYAR_INTEGRATION_GUIDE.md +# Semua MAYAR_* bersifat backend-only. Jangan pernah dibuat sebagai VITE_*. PAYMENT_GATEWAY_PROVIDER=mayar PAYMENT_INTEGRATION_ENABLED=true +# sandbox → key dari https://web.mayar.io/api-keys (API https://api.mayar.io/hl/v2) +# production → key dari https://web.mayar.id/api-keys (API https://api.mayar.id/hl/v2) MAYAR_ENVIRONMENT=sandbox +# 1) API key (Bearer) untuk create payment & cek status. MAYAR_API_KEY=change-me +# 2) Web Token dari dashboard Mayar. Mayar mengirimnya di header X-Callback-Token. +# (Akun tanpa Web Token: pakai token sendiri dan tambahkan ?token=... di URL webhook.) MAYAR_WEBHOOK_TOKEN=change-me -MAYAR_SANDBOX_BASE_URL=https://api.mayar.club +MAYAR_SANDBOX_BASE_URL=https://api.mayar.io MAYAR_PRODUCTION_BASE_URL=https://api.mayar.id -MAYAR_REDIRECT_URL=https://kaffepos.my.id/settings?billing=mayar-return +# 3) URL webhook yang didaftarkan di Mayar → Integrasi → Webhook. MAYAR_CALLBACK_URL=https://api.kaffepos.my.id/api/webhooks/mayar -SUBSCRIPTION_PAYMENT_MODE=mayar_sandbox +MAYAR_REDIRECT_URL=https://kaffepos.my.id/settings?billing=mayar-return +MAYAR_PAYMENT_DUE_MINUTES=60 +# auto = sandbox/production mengikuti MAYAR_ENVIRONMENT +SUBSCRIPTION_PAYMENT_MODE=auto PII_ENCRYPTION_KEY=change-me-in-production diff --git a/backend/.env.staging.example b/backend/.env.staging.example index 7881ce7..dddf89e 100644 --- a/backend/.env.staging.example +++ b/backend/.env.staging.example @@ -20,13 +20,7 @@ R2_STORAGE_ENABLED=false ANALYTICS_SERVER_ENABLED=false # B. Full staging required (production-candidate external provider verification) -# Required only when STAGING_PROFILE=full/unset. -MIDTRANS_IS_PRODUCTION=false -MIDTRANS_ENVIRONMENT=sandbox -MIDTRANS_SNAP_ENABLED=true -MIDTRANS_SERVER_KEY=SB-Mid-server-change-me -MIDTRANS_CLIENT_KEY=SB-Mid-client-change-me - +# Required only when STAGING_PROFILE=full/unset. Payment keys: see the Mayar block below. RESEND_API_KEY=re_change_me RESEND_FROM_EMAIL=KaffePOS Staging EMAIL_REPLY_TO=support@example.com @@ -48,19 +42,21 @@ ADMIN_COMMISSION_ENABLED=false REFERRAL_COMMISSION_CREATION_ENABLED=false # C. Optional integrations skipped in minimal mode -# Midtrans, Resend, Cloudflare/R2, GA4, and server analytics may remain placeholders in minimal staging. +# Mayar, Resend, Cloudflare/R2, GA4, and server analytics may remain placeholders in minimal staging. -# Mayar sandbox staging — Mayar is the ACTIVE payment gateway. +# Mayar sandbox staging — Mayar is the only payment gateway. # The backend env schema (backend/src/core/env.ts) accepts: -# PAYMENT_GATEWAY_PROVIDER = mayar | doku | disabled -# SUBSCRIPTION_PAYMENT_MODE = auto | manual | disabled | mayar_sandbox | mayar_production | doku_sandbox | doku_production +# PAYMENT_GATEWAY_PROVIDER = mayar | disabled +# SUBSCRIPTION_PAYMENT_MODE = auto | manual | disabled | mayar_sandbox | mayar_production +# Guide: docs/engineering/MAYAR_INTEGRATION_GUIDE.md PAYMENT_GATEWAY_PROVIDER=mayar PAYMENT_INTEGRATION_ENABLED=true MAYAR_ENVIRONMENT=sandbox MAYAR_API_KEY=change-me MAYAR_WEBHOOK_TOKEN=change-me -MAYAR_CALLBACK_URL=https://api.kaffepos.my.id/api/webhooks/mayar -MAYAR_REDIRECT_URL=https://kaffepos.my.id/settings?billing=mayar-return +MAYAR_SANDBOX_BASE_URL=https://api.mayar.io +MAYAR_CALLBACK_URL=https://staging-api.example.com/api/webhooks/mayar +MAYAR_REDIRECT_URL=https://staging.example.com/settings?billing=mayar-return SUBSCRIPTION_PAYMENT_MODE=mayar_sandbox # Payment staging profile (Mayar sandbox) @@ -69,9 +65,9 @@ SUBSCRIPTION_PAYMENT_MODE=mayar_sandbox # PAYMENT_INTEGRATION_ENABLED=true # MAYAR_ENVIRONMENT=sandbox # MAYAR_API_KEY=ISI_DARI_MAYAR -# MAYAR_WEBHOOK_TOKEN=ISI_DARI_MAYAR -# MAYAR_CALLBACK_URL=https://api.kaffepos.my.id/api/webhooks/mayar +# MAYAR_WEBHOOK_TOKEN=ISI_DENGAN_WEB_TOKEN_DARI_MAYAR +# MAYAR_CALLBACK_URL=https://staging-api.example.com/api/webhooks/mayar # SUBSCRIPTION_PAYMENT_MODE=mayar_sandbox # # For production: MAYAR_ENVIRONMENT=production and SUBSCRIPTION_PAYMENT_MODE=mayar_production. -# Legacy Midtrans/Duitku keys are NOT read by the code and may be omitted. +# Legacy DOKU/Midtrans/Duitku keys are NOT read by the code and may be removed. diff --git a/backend/package.json b/backend/package.json index 30ecf2d..cbf598f 100644 --- a/backend/package.json +++ b/backend/package.json @@ -11,6 +11,7 @@ "start:coolify": "node scripts/run-migrations.mjs && node dist/index.js", "check": "npm run typecheck && npm run build", "migrate": "node scripts/run-migrations.mjs", + "mayar:connect": "node scripts/mayar-connect.mjs", "backup:critical": "node scripts/backup-critical-data.mjs", "deploy:kds": "cd .. && bash scripts/deploy-kds-one-command.sh" }, diff --git a/backend/scripts/mayar-connect.mjs b/backend/scripts/mayar-connect.mjs new file mode 100644 index 0000000..fed91fe --- /dev/null +++ b/backend/scripts/mayar-connect.mjs @@ -0,0 +1,195 @@ +#!/usr/bin/env node +/** + * Hubungkan KaffePOS ke Mayar (Headless API v2): cek API key, cek token webhook, + * dan (opsional) daftarkan URL webhook ke akun Mayar. + * + * Jalankan di container backend (Coolify → backend → Terminal): + * node scripts/mayar-connect.mjs # cek saja, tidak mengubah apa pun + * node scripts/mayar-connect.mjs --register # daftarkan URL webhook ke Mayar + tes + * + * Atau dari laptop (membaca backend/.env bila ada): + * npm run mayar:connect -- --register + * + * MAYAR_WEBHOOK_TOKEN = "Web Token" dari dashboard Mayar. Mayar mengirimnya sendiri di header + * X-Callback-Token, jadi URL webhook didaftarkan tanpa token. + * + * Opsi: + * --register Ganti URL webhook di akun Mayar (POST /hl/v2/webhooks/update) lalu tes. + * --test Minta Mayar mengirim webhook tes ke URL (POST /hl/v2/webhooks/test). + * --url-token Tambahkan ?token= ke URL yang didaftarkan + * (untuk akun yang tidak punya Web Token; pakai token buatan sendiri). + * --skip-backend Lewati pengecekan endpoint webhook KaffePOS. + * --env-file=PATH Muat variabel dari file env tertentu. + * + * Secrets never leave this machine except to Mayar (API key) and to your own + * backend (webhook token). Output masks both. + */ +import fs from 'node:fs'; +import path from 'node:path'; + +const args = new Set(process.argv.slice(2)); +const envFileArg = process.argv.slice(2).find((arg) => arg.startsWith('--env-file=')); + +function loadEnvFile(file) { + const full = path.resolve(process.cwd(), file); + if (!fs.existsSync(full)) return false; + for (const line of fs.readFileSync(full, 'utf8').split(/\r?\n/)) { + const match = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/); + if (match && !(match[1] in process.env)) { + process.env[match[1]] = match[2].replace(/^['"]|['"]$/g, ''); + } + } + return true; +} + +if (envFileArg) { + if (!loadEnvFile(envFileArg.slice('--env-file='.length))) { + console.error(`✗ File env tidak ditemukan: ${envFileArg.slice('--env-file='.length)}`); + process.exit(2); + } +} else { + for (const candidate of ['.env', 'backend/.env', '.env.staging.local', 'backend/.env.staging.local']) { + loadEnvFile(candidate); + } +} + +const PLACEHOLDER = /^(change-?me|__.*__|isi_.*|xxx+)$/i; +const read = (name) => (process.env[name] || '').trim(); +const isSet = (value) => Boolean(value) && !PLACEHOLDER.test(value); +const mask = (value) => (value.length <= 10 ? '•'.repeat(value.length) : `${value.slice(0, 4)}…${value.slice(-4)} (${value.length} karakter)`); + +const environment = read('MAYAR_ENVIRONMENT') === 'production' ? 'production' : 'sandbox'; +const baseUrl = ( + environment === 'production' + ? read('MAYAR_PRODUCTION_BASE_URL') || 'https://api.mayar.id' + : read('MAYAR_SANDBOX_BASE_URL') || 'https://api.mayar.io' +).replace(/\/+$/, ''); +const apiKey = read('MAYAR_API_KEY'); +const webhookToken = read('MAYAR_WEBHOOK_TOKEN'); +const webhookPath = read('MAYAR_WEBHOOK_PATH') || '/api/webhooks/mayar'; +const webhookUrl = + read('MAYAR_CALLBACK_URL') || + `${(read('API_BASE_URL') || 'https://api.kaffepos.my.id').replace(/\/+$/, '')}${webhookPath.startsWith('/') ? webhookPath : `/${webhookPath}`}`; +const useUrlToken = args.has('--url-token'); + +let failures = 0; +const pass = (message) => console.log(` ✓ ${message}`); +const warn = (message) => console.log(` ! ${message}`); +const fail = (message) => { + failures += 1; + console.log(` ✗ ${message}`); +}; + +async function call(method, url, { headers = {}, body } = {}) { + try { + const response = await fetch(url, { + method, + headers: { Accept: 'application/json', ...(body ? { 'Content-Type': 'application/json' } : {}), ...headers }, + ...(body ? { body: JSON.stringify(body) } : {}), + signal: AbortSignal.timeout(20_000), + }); + const text = await response.text(); + let json = null; + try { + json = JSON.parse(text); + } catch { + // not JSON + } + return { status: response.status, ok: response.ok, json, text }; + } catch (error) { + return { status: 0, ok: false, json: null, text: String(error?.message || error) }; + } +} + +const mayarMessage = (res) => res.json?.messages || res.json?.message || res.text.slice(0, 200); +const mayar = (method, apiPath, body) => + call(method, `${baseUrl}${apiPath}`, { headers: { Authorization: `Bearer ${apiKey}` }, body }); + +function registeredHookUrl() { + if (!useUrlToken) return webhookUrl; + const url = new URL(webhookUrl); + url.searchParams.set('token', webhookToken); + return url.toString(); +} + +async function main() { + console.log('── KaffePOS × Mayar ──'); + console.log(`Environment : ${environment}`); + console.log(`Mayar API : ${baseUrl}/hl/v2`); + console.log(`Webhook URL : ${webhookUrl}${useUrlToken ? '?token=' : ''}`); + + console.log('\n1. Konfigurasi'); + if (isSet(apiKey)) pass(`MAYAR_API_KEY terisi ${mask(apiKey)}`); + else fail(`MAYAR_API_KEY belum diisi. Buat di ${environment === 'production' ? 'https://web.mayar.id/api-keys' : 'https://web.mayar.io/api-keys'}.`); + if (isSet(webhookToken) && webhookToken.length >= 16) pass(`MAYAR_WEBHOOK_TOKEN terisi ${mask(webhookToken)}`); + else if (isSet(webhookToken)) warn('MAYAR_WEBHOOK_TOKEN terlalu pendek. Pakai Web Token dari dashboard Mayar.'); + else fail('MAYAR_WEBHOOK_TOKEN belum diisi. Salin Web Token dari dashboard Mayar.'); + if (failures > 0) { + console.log('\nLengkapi env di atas lalu jalankan lagi.'); + process.exit(2); + } + + console.log('\n2. API key Mayar'); + const probe = await mayar('GET', '/hl/v2/payments?limit=1'); + if (probe.ok) pass(`API key diterima Mayar (${environment}).`); + else if (probe.status === 401 || probe.status === 403) + fail(`API key ditolak (${probe.status}). Pastikan key berasal dari dashboard ${environment} yang sama dengan MAYAR_ENVIRONMENT.`); + else fail(`Mayar tidak bisa dihubungi (${probe.status || 'network'}): ${mayarMessage(probe)}`); + + if (!args.has('--skip-backend')) { + console.log('\n3. Endpoint webhook KaffePOS'); + const health = await call('GET', webhookUrl); + if (health.ok && health.json?.provider === 'mayar') { + pass('Endpoint aktif.'); + if (health.json.webhookTokenConfigured === false) { + fail('Backend belum punya MAYAR_WEBHOOK_TOKEN. Isi env di server lalu redeploy.'); + } + } else { + fail(`Endpoint tidak menjawab dengan benar (${health.status || 'network'}). Backend sudah di-deploy?`); + } + + // A harmless, non-payment event: the backend must accept the token and ignore it. + const ping = { event: 'kaffepos.connection_test', data: { note: 'mayar-connect self test' } }; + const withToken = await call('POST', webhookUrl, { headers: { 'X-Callback-Token': webhookToken }, body: ping }); + if (withToken.ok && withToken.json?.ignored) pass('Backend menerima token webhook yang sama dengan env ini.'); + else if (withToken.status === 401) fail('Backend menolak token: MAYAR_WEBHOOK_TOKEN di server berbeda dengan env ini.'); + else if (withToken.status === 503) fail('Backend belum punya MAYAR_WEBHOOK_TOKEN (503).'); + else fail(`Tes token ke backend gagal (${withToken.status || 'network'}): ${withToken.text.slice(0, 200)}`); + + const withoutToken = await call('POST', webhookUrl, { body: ping }); + if (withoutToken.status === 401) pass('Webhook tanpa token ditolak (401).'); + else fail(`Webhook tanpa token seharusnya ditolak, tapi dijawab ${withoutToken.status || 'network'}.`); + } + + if (args.has('--register')) { + console.log('\n4. Daftarkan URL webhook ke Mayar'); + const update = await mayar('POST', '/hl/v2/webhooks/update', { urlHook: registeredHookUrl() }); + if (update.ok) pass('URL webhook tersimpan di akun Mayar.'); + else fail(`Gagal menyimpan URL webhook (${update.status || 'network'}): ${mayarMessage(update)}`); + } + + if (args.has('--register') || args.has('--test')) { + console.log('\n5. Tes webhook dari Mayar'); + const test = await mayar('POST', '/hl/v2/webhooks/test', { urlHook: registeredHookUrl() }); + if (test.ok) { + pass('Mayar berhasil mengirim webhook tes. Cek juga riwayat di Mayar → Integrasi → Webhook.'); + } else { + fail(`Tes webhook gagal (${test.status || 'network'}): ${mayarMessage(test)}`); + if (!useUrlToken) { + console.log(' Kalau riwayat webhook Mayar menunjukkan 401, MAYAR_WEBHOOK_TOKEN belum sama dengan Web Token,'); + console.log(' atau akun ini tidak mengirim X-Callback-Token — jalankan ulang dengan --register --url-token.'); + } + } + } else { + console.log('\nURL webhook belum diubah. Jalankan dengan --register untuk mendaftarkannya ke Mayar,'); + console.log('atau isi manual di Mayar → Integrasi → Webhook.'); + } + + console.log(failures === 0 ? '\n✓ Mayar terhubung.' : `\n✗ ${failures} pengecekan gagal.`); + process.exit(failures === 0 ? 0 : 1); +} + +main().catch((error) => { + console.error('✗ Gagal:', error?.message || error); + process.exit(1); +}); diff --git a/backend/src/core/billing.ts b/backend/src/core/billing.ts index 5b4cb96..272ae81 100644 --- a/backend/src/core/billing.ts +++ b/backend/src/core/billing.ts @@ -11,67 +11,71 @@ export type SubscriptionPaymentMode = | 'manual' | 'disabled' | 'mayar_sandbox' - | 'mayar_production' - | 'doku_sandbox' - | 'doku_production'; + | 'mayar_production'; +/** API key present — enough to create payments and run status checks. */ +export function isMayarApiKeyConfigured() { + return Boolean(env.MAYAR_API_KEY?.trim()); +} + +/** Webhook token present — required to accept Mayar webhooks. */ +export function isMayarWebhookTokenConfigured() { + return Boolean(env.MAYAR_WEBHOOK_TOKEN?.trim()); +} + +/** + * Mayar is only "configured" when both the API key and the webhook token are set: + * without the token every webhook is rejected and paid orders would never settle. + */ export function isMayarConfigured() { - return Boolean(env.MAYAR_API_KEY); + return isMayarApiKeyConfigured() && isMayarWebhookTokenConfigured(); } -export function isDokuConfigured() { - return Boolean(env.DOKU_CLIENT_ID && env.DOKU_SECRET_KEY && env.DOKU_CALLBACK_URL); +/** Public webhook URL to register in Mayar → Integrasi → Webhook (without the token). */ +export function getMayarWebhookUrl() { + if (env.MAYAR_CALLBACK_URL) return env.MAYAR_CALLBACK_URL; + const path = env.MAYAR_WEBHOOK_PATH.startsWith('/') ? env.MAYAR_WEBHOOK_PATH : `/${env.MAYAR_WEBHOOK_PATH}`; + return `${env.API_BASE_URL.replace(/\/+$/, '')}${path}`; } export function isActivePaymentGatewayConfigured() { const provider = env.PAYMENT_INTEGRATION_ENABLED === 'false' ? 'disabled' : env.PAYMENT_GATEWAY_PROVIDER; - if (provider === 'mayar') return isMayarConfigured(); - if (provider === 'doku') return isDokuConfigured(); - return false; + return provider === 'mayar' && isMayarConfigured(); } export function resolveSubscriptionPaymentConfig() { const provider = env.PAYMENT_INTEGRATION_ENABLED === 'false' ? 'disabled' : env.PAYMENT_GATEWAY_PROVIDER; - const mayarConfigured = provider === 'mayar' && isMayarConfigured(); - const dokuConfigured = provider === 'doku' && isDokuConfigured(); - const gatewayConfigured = mayarConfigured || dokuConfigured; + const gatewayConfigured = provider === 'mayar' && isMayarConfigured(); const requestedMode = env.SUBSCRIPTION_PAYMENT_MODE; - const gatewayEnvironment = provider === 'doku' ? env.DOKU_ENVIRONMENT : env.MAYAR_ENVIRONMENT; + const gatewayEnvironment = env.MAYAR_ENVIRONMENT; const isProductionGateway = gatewayEnvironment === 'production'; - const prodMode: SubscriptionPaymentMode = provider === 'doku' ? 'doku_production' : 'mayar_production'; - const sandboxMode: SubscriptionPaymentMode = provider === 'doku' ? 'doku_sandbox' : 'mayar_sandbox'; let mode: SubscriptionPaymentMode; if (provider === 'disabled' || requestedMode === 'disabled') { mode = 'disabled'; } else if (requestedMode === 'auto') { - mode = gatewayConfigured ? (isProductionGateway ? prodMode : sandboxMode) : 'manual'; - } else if ((requestedMode === 'mayar_production' || requestedMode === 'doku_production') && !isProductionGateway) { + mode = gatewayConfigured ? (isProductionGateway ? 'mayar_production' : 'mayar_sandbox') : 'manual'; + } else if (requestedMode === 'mayar_production' && !isProductionGateway) { mode = 'manual'; - } else if ((requestedMode === 'mayar_sandbox' || requestedMode === 'doku_sandbox') && isProductionGateway) { + } else if (requestedMode === 'mayar_sandbox' && isProductionGateway) { mode = 'manual'; - } else if (provider === 'mayar' && requestedMode === 'doku_sandbox') { - mode = gatewayConfigured && !isProductionGateway ? 'mayar_sandbox' : 'manual'; - } else if (provider === 'mayar' && requestedMode === 'doku_production') { - mode = gatewayConfigured && isProductionGateway ? 'mayar_production' : 'manual'; } else { - mode = requestedMode as SubscriptionPaymentMode; + mode = requestedMode; } - const isProdMode = mode === 'mayar_production' || mode === 'doku_production'; - const isSandboxMode = mode === 'mayar_sandbox' || mode === 'doku_sandbox'; + const isProdMode = mode === 'mayar_production'; + const isSandboxMode = mode === 'mayar_sandbox'; const onlinePaymentAvailable = gatewayConfigured && ((isProdMode && isProductionGateway) || (isSandboxMode && !isProductionGateway)); const commerciallyReady = onlinePaymentAvailable && isProdMode && isProductionGateway; const manualActivationAvailable = mode === 'manual' || !onlinePaymentAvailable; - const providerLabel = provider === 'doku' ? 'DOKU' : 'Mayar'; + const providerLabel = 'Mayar'; return { mode, provider, environment: gatewayEnvironment, mayarEnvironment: env.MAYAR_ENVIRONMENT, - dokuEnvironment: gatewayEnvironment, onlinePaymentAvailable, manualActivationAvailable, commerciallyReady, diff --git a/backend/src/core/env.ts b/backend/src/core/env.ts index 98f3c68..5868e8b 100644 --- a/backend/src/core/env.ts +++ b/backend/src/core/env.ts @@ -4,6 +4,40 @@ */ import { z } from 'zod'; +/** + * Deprecation notes collected while parsing env (e.g. a deployment that still says + * PAYMENT_GATEWAY_PROVIDER=doku). Surfaced in /api/admin/system-status warnings. + */ +export const envDeprecations: string[] = []; + +/** Payment gateways that were removed; deployments still pointing at them now use Mayar. */ +const LEGACY_GATEWAYS = new Set(['doku', 'duitku', 'midtrans']); + +const paymentGatewayProviderSchema = z.preprocess((value) => { + const normalized = typeof value === 'string' ? value.trim().toLowerCase() : value; + if (typeof normalized === 'string' && LEGACY_GATEWAYS.has(normalized)) { + envDeprecations.push( + `PAYMENT_GATEWAY_PROVIDER=${normalized} sudah tidak didukung; backend memakai Mayar. Ubah env ke PAYMENT_GATEWAY_PROVIDER=mayar.`, + ); + return 'mayar'; + } + return normalized === '' ? undefined : normalized; +}, z.enum(['mayar', 'disabled']).default('mayar')); + +const subscriptionPaymentModeSchema = z.preprocess((value) => { + const normalized = typeof value === 'string' ? value.trim().toLowerCase() : value; + if (typeof normalized === 'string') { + const legacy = normalized.match(/^(doku|duitku|midtrans)_(sandbox|production)$/); + if (legacy) { + envDeprecations.push( + `SUBSCRIPTION_PAYMENT_MODE=${normalized} sudah tidak didukung; dibaca sebagai mayar_${legacy[2]}.`, + ); + return `mayar_${legacy[2]}`; + } + } + return normalized === '' ? undefined : normalized; +}, z.enum(['auto', 'manual', 'disabled', 'mayar_sandbox', 'mayar_production']).default('auto')); + export const envSchema = z.object({ SERVICE_NAME: z.string().trim().default('kaffepos-backend'), APP_VERSION: z.string().trim().default('1.0.0'), @@ -49,42 +83,29 @@ export const envSchema = z.object({ CLOUDFLARE_IMAGES_DELIVERY_URL: z.string().trim().url().optional(), RESEND_API_KEY: z.string().trim().optional(), RESEND_FROM_EMAIL: z.string().trim().optional(), - PAYMENT_GATEWAY_PROVIDER: z.enum(['mayar', 'doku', 'disabled']).default('mayar'), + // Payment gateway: Mayar is the only online gateway. `disabled` turns online payment off. + PAYMENT_GATEWAY_PROVIDER: paymentGatewayProviderSchema, PAYMENT_INTEGRATION_ENABLED: z.union([z.literal('true'), z.literal('false')]).optional().default('true'), - // Mayar Headless API v2 (https://api.mayar.id/hl/v2 for production, https://api.mayar.club/hl/v2 for sandbox). + // Mayar Headless API v2 — https://docs.mayar.id/api-reference-v2/introduction + // production: https://api.mayar.id/hl/v2 (key: https://web.mayar.id/api-keys) + // sandbox: https://api.mayar.io/hl/v2 (key: https://web.mayar.io/api-keys) + // Older sandbox accounts created on web.mayar.club use MAYAR_SANDBOX_BASE_URL=https://api.mayar.club. MAYAR_ENVIRONMENT: z.enum(['sandbox', 'production']).default('sandbox'), + // Bearer API key for create-payment and status-check calls. Backend-only secret. MAYAR_API_KEY: z.string().trim().optional(), + // "Web Token" from the Mayar dashboard; Mayar sends it as X-Callback-Token (?token= on the URL also works). MAYAR_WEBHOOK_TOKEN: z.string().trim().optional(), - MAYAR_SANDBOX_BASE_URL: z.string().trim().url().default('https://api.mayar.club'), + MAYAR_SANDBOX_BASE_URL: z.string().trim().url().default('https://api.mayar.io'), MAYAR_PRODUCTION_BASE_URL: z.string().trim().url().default('https://api.mayar.id'), MAYAR_CREATE_PAYMENT_PATH: z.string().trim().default('/hl/v2/payments/create'), MAYAR_STATUS_PATH_PREFIX: z.string().trim().default('/hl/v2/payments'), MAYAR_WEBHOOK_PATH: z.string().trim().default('/api/webhooks/mayar'), + // Where Mayar sends the customer after paying a subscription (optional). MAYAR_REDIRECT_URL: z.string().trim().url().optional(), + // Public webhook URL registered in Mayar (defaults to API_BASE_URL + MAYAR_WEBHOOK_PATH). MAYAR_CALLBACK_URL: z.string().trim().url().optional(), MAYAR_PAYMENT_DUE_MINUTES: z.coerce.number().int().positive().default(60), - // DOKU Checkout (legacy secondary payment provider). - DOKU_ENVIRONMENT: z.enum(['sandbox', 'production']).default('sandbox'), - DOKU_CLIENT_ID: z.string().trim().optional(), - DOKU_SECRET_KEY: z.string().trim().optional(), - DOKU_SANDBOX_BASE_URL: z.string().trim().url().default('https://api-sandbox.doku.com'), - DOKU_PRODUCTION_BASE_URL: z.string().trim().url().default('https://api.doku.com'), - DOKU_CHECKOUT_PATH: z.string().trim().default('/checkout/v1/payment'), - DOKU_STATUS_PATH_PREFIX: z.string().trim().default('/orders/v1/status'), - DOKU_NOTIFICATION_PATH: z.string().trim().default('/api/webhooks/doku'), - DOKU_CALLBACK_URL: z.string().trim().url().optional(), - DOKU_PAYMENT_DUE_MINUTES: z.coerce.number().int().positive().default(60), - SUBSCRIPTION_PAYMENT_MODE: z - .enum([ - 'auto', - 'manual', - 'disabled', - 'mayar_sandbox', - 'mayar_production', - 'doku_sandbox', - 'doku_production', - ]) - .default('auto'), + SUBSCRIPTION_PAYMENT_MODE: subscriptionPaymentModeSchema, AUTH_RATE_LIMIT_WINDOW_MS: z.coerce.number().int().positive().default(15 * 60 * 1000), AUTH_LOGIN_RATE_LIMIT_MAX: z.coerce.number().int().positive().default(10), AUTH_EMAIL_RATE_LIMIT_MAX: z.coerce.number().int().positive().default(5), @@ -108,6 +129,10 @@ export type Env = z.infer; export const env = envSchema.parse(process.env); +for (const note of envDeprecations) { + console.warn(`[env] ${note}`); +} + // In production, ADMIN_EMAILS must be set explicitly — a hardcoded fallback would // hand admin access to whoever controls that address if the env var is ever missing. const adminEmailsRaw = diff --git a/backend/src/core/errorHandler.ts b/backend/src/core/errorHandler.ts index c1c5c69..ed5d3cf 100644 --- a/backend/src/core/errorHandler.ts +++ b/backend/src/core/errorHandler.ts @@ -9,6 +9,7 @@ import type { Request, Response, NextFunction } from 'express'; import { z } from 'zod'; import { ApiError, log, serializeError, getSafeApiErrorMessage } from './errors'; import { KitchenStatusError } from '../lib/kitchenStatus'; +import { redactUrlSecrets } from '../lib/redactUrl'; import { captureBackendException } from './errorTracking'; import { createErrorResponse, @@ -38,7 +39,7 @@ export function errorHandler(error: unknown, req: Request, res: Response, _next: log('warn', 'request.validation_error', { requestId: req.requestId ?? null, method: req.method, - path: req.originalUrl, + path: redactUrlSecrets(req.originalUrl), issues: error.issues, }); @@ -58,7 +59,7 @@ export function errorHandler(error: unknown, req: Request, res: Response, _next: log('warn', 'request.api_error_with_code', { requestId: req.requestId ?? null, method: req.method, - path: req.originalUrl, + path: redactUrlSecrets(req.originalUrl), statusCode: error.status, errorCode: error.code, message: error.message, @@ -77,7 +78,7 @@ export function errorHandler(error: unknown, req: Request, res: Response, _next: log('warn', 'request.api_error', { requestId: req.requestId ?? null, method: req.method, - path: req.originalUrl, + path: redactUrlSecrets(req.originalUrl), statusCode: error.status, errorCode, message: error.message, @@ -94,7 +95,7 @@ export function errorHandler(error: unknown, req: Request, res: Response, _next: log('warn', 'request.kitchen_status_error', { requestId: req.requestId ?? null, method: req.method, - path: req.originalUrl, + path: redactUrlSecrets(req.originalUrl), statusCode: error.status, errorCode, message: error.message, @@ -110,7 +111,7 @@ export function errorHandler(error: unknown, req: Request, res: Response, _next: log('warn', 'request.cors_rejected', { requestId: req.requestId ?? null, method: req.method, - path: req.originalUrl, + path: redactUrlSecrets(req.originalUrl), message: error.message, }); @@ -123,14 +124,14 @@ export function errorHandler(error: unknown, req: Request, res: Response, _next: log('error', 'request.unhandled_error', { requestId: req.requestId ?? null, method: req.method, - path: req.originalUrl, + path: redactUrlSecrets(req.originalUrl), error: serializeError(error), }); captureBackendException(error, { source: 'global_error_handler', method: req.method, - path: req.originalUrl, + path: redactUrlSecrets(req.originalUrl), statusCode: 500, metadata: { requestId: req.requestId ?? null, diff --git a/backend/src/core/paymentConfig.test.ts b/backend/src/core/paymentConfig.test.ts new file mode 100644 index 0000000..9f92a5a --- /dev/null +++ b/backend/src/core/paymentConfig.test.ts @@ -0,0 +1,102 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +const PAYMENT_KEYS = [ + 'PAYMENT_GATEWAY_PROVIDER', + 'PAYMENT_INTEGRATION_ENABLED', + 'SUBSCRIPTION_PAYMENT_MODE', + 'MAYAR_ENVIRONMENT', + 'MAYAR_API_KEY', + 'MAYAR_WEBHOOK_TOKEN', + 'MAYAR_CALLBACK_URL', + 'API_BASE_URL', +] as const; + +const original = Object.fromEntries(PAYMENT_KEYS.map((key) => [key, process.env[key]])); + +async function loadWithEnv(vars: Partial>) { + vi.resetModules(); + for (const key of PAYMENT_KEYS) { + if (vars[key] === undefined) delete process.env[key]; + else process.env[key] = vars[key]; + } + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const envModule = await import('./env'); + const billing = await import('./billing'); + warn.mockRestore(); + return { ...envModule, ...billing }; +} + +afterEach(() => { + for (const key of PAYMENT_KEYS) { + if (original[key] === undefined) delete process.env[key]; + else process.env[key] = original[key]; + } + vi.resetModules(); +}); + +describe('Mayar payment configuration', () => { + it('reads legacy DOKU settings as Mayar so existing deployments still boot', async () => { + const mod = await loadWithEnv({ PAYMENT_GATEWAY_PROVIDER: 'doku', SUBSCRIPTION_PAYMENT_MODE: 'doku_sandbox' }); + expect(mod.env.PAYMENT_GATEWAY_PROVIDER).toBe('mayar'); + expect(mod.env.SUBSCRIPTION_PAYMENT_MODE).toBe('mayar_sandbox'); + expect(mod.envDeprecations).toEqual(expect.arrayContaining([ + expect.stringContaining('PAYMENT_GATEWAY_PROVIDER=doku'), + expect.stringContaining('SUBSCRIPTION_PAYMENT_MODE=doku_sandbox'), + ])); + }); + + it('defaults sandbox calls to the current Mayar sandbox host', async () => { + const mod = await loadWithEnv({}); + expect(mod.env.PAYMENT_GATEWAY_PROVIDER).toBe('mayar'); + expect(mod.env.MAYAR_SANDBOX_BASE_URL).toBe('https://api.mayar.io'); + expect(mod.env.MAYAR_PRODUCTION_BASE_URL).toBe('https://api.mayar.id'); + }); + + it('needs both the API key and the webhook token before online payment opens', async () => { + const keyOnly = await loadWithEnv({ MAYAR_API_KEY: 'key', SUBSCRIPTION_PAYMENT_MODE: 'auto' }); + expect(keyOnly.isMayarConfigured()).toBe(false); + expect(keyOnly.resolveSubscriptionPaymentConfig()).toMatchObject({ mode: 'manual', onlinePaymentAvailable: false }); + + const both = await loadWithEnv({ MAYAR_API_KEY: 'key', MAYAR_WEBHOOK_TOKEN: 'token', SUBSCRIPTION_PAYMENT_MODE: 'auto' }); + expect(both.isMayarConfigured()).toBe(true); + expect(both.resolveSubscriptionPaymentConfig()).toMatchObject({ + mode: 'mayar_sandbox', + provider: 'mayar', + onlinePaymentAvailable: true, + commerciallyReady: false, + }); + }); + + it('is commercially ready only in Mayar production mode', async () => { + const mod = await loadWithEnv({ + MAYAR_ENVIRONMENT: 'production', + MAYAR_API_KEY: 'key', + MAYAR_WEBHOOK_TOKEN: 'token', + SUBSCRIPTION_PAYMENT_MODE: 'mayar_production', + }); + expect(mod.resolveSubscriptionPaymentConfig()).toMatchObject({ + mode: 'mayar_production', + environment: 'production', + onlinePaymentAvailable: true, + commerciallyReady: true, + }); + }); + + it('falls back to manual activation when sandbox mode is requested on a production key', async () => { + const mod = await loadWithEnv({ + MAYAR_ENVIRONMENT: 'production', + MAYAR_API_KEY: 'key', + MAYAR_WEBHOOK_TOKEN: 'token', + SUBSCRIPTION_PAYMENT_MODE: 'mayar_sandbox', + }); + expect(mod.resolveSubscriptionPaymentConfig()).toMatchObject({ mode: 'manual', onlinePaymentAvailable: false }); + }); + + it('builds the webhook URL from API_BASE_URL unless MAYAR_CALLBACK_URL is set', async () => { + const derived = await loadWithEnv({ API_BASE_URL: 'https://api.kaffepos.my.id/' }); + expect(derived.getMayarWebhookUrl()).toBe('https://api.kaffepos.my.id/api/webhooks/mayar'); + + const explicit = await loadWithEnv({ MAYAR_CALLBACK_URL: 'https://staging-api.kaffepos.my.id/api/webhooks/mayar' }); + expect(explicit.getMayarWebhookUrl()).toBe('https://staging-api.kaffepos.my.id/api/webhooks/mayar'); + }); +}); diff --git a/backend/src/index.ts b/backend/src/index.ts index 6697e9b..df0f103 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -107,8 +107,7 @@ app.set('trust proxy', 1); app.disable('x-powered-by'); app.use(express.json({ limit: '1mb', - // Preserve the raw payload so header-signature webhooks (DOKU) can verify the - // exact bytes the provider hashed into its Digest. + // Preserve the raw payload for payment webhooks (kept for auditing/debugging). verify: (req, _res, buf) => { (req as Request & { rawBody?: string }).rawBody = buf.toString('utf8'); }, diff --git a/backend/src/lib/deploymentReadiness.test.ts b/backend/src/lib/deploymentReadiness.test.ts index c3012f3..3a858e8 100644 --- a/backend/src/lib/deploymentReadiness.test.ts +++ b/backend/src/lib/deploymentReadiness.test.ts @@ -2,16 +2,17 @@ import { describe, expect, it } from 'vitest'; import { validateBackendDeploymentConfig } from './deploymentReadiness'; describe('backend deployment readiness guardrails', () => { - it('flags production deployment that still uses DOKU sandbox', () => { + it('flags production deployment that still uses Mayar sandbox', () => { const result = validateBackendDeploymentConfig({ nodeEnv: 'production', webBaseUrl: 'https://kaffepos.my.id', apiBaseUrl: 'https://api.kaffepos.my.id', corsOrigin: 'https://kaffepos.my.id,capacitor://localhost', - dokuEnvironment: 'sandbox', + paymentProvider: 'mayar', + mayarEnvironment: 'sandbox', + mayarConfigured: true, subscriptionPaymentMode: 'auto', paymentIntegrationEnabled: true, - dokuConfigured: true, resendApiKey: 're_xxx', resendFromEmail: 'KaffePOS ', sentryDsn: 'https://public@sentry.example/1', @@ -19,20 +20,22 @@ describe('backend deployment readiness guardrails', () => { expect(result.ok).toBe(false); expect(result.errors).toEqual(expect.arrayContaining([ - expect.stringContaining('DOKU_ENVIRONMENT'), + expect.stringContaining('MAYAR_ENVIRONMENT'), ])); }); - it('accepts production config when domain, CORS, email, and DOKU are aligned', () => { + it('accepts production config when domain, CORS, email, and Mayar are aligned', () => { const result = validateBackendDeploymentConfig({ nodeEnv: 'production', webBaseUrl: 'https://kaffepos.my.id', apiBaseUrl: 'https://api.kaffepos.my.id', corsOrigin: 'https://kaffepos.my.id,https://www.kaffepos.my.id,capacitor://localhost,https://localhost,http://localhost', - dokuEnvironment: 'production', + paymentProvider: 'mayar', + mayarEnvironment: 'production', + mayarConfigured: true, + mayarWebhookTokenConfigured: true, subscriptionPaymentMode: 'auto', paymentIntegrationEnabled: true, - dokuConfigured: true, resendApiKey: 're_xxx', resendFromEmail: 'KaffePOS ', sentryDsn: 'https://public@sentry.example/1', @@ -42,15 +45,16 @@ describe('backend deployment readiness guardrails', () => { expect(result.errors).toEqual([]); }); - it('flags production deployment that still uses Mayar sandbox', () => { + it('normalizes configured CORS origins before readiness checks', () => { const result = validateBackendDeploymentConfig({ nodeEnv: 'production', webBaseUrl: 'https://kaffepos.my.id', apiBaseUrl: 'https://api.kaffepos.my.id', - corsOrigin: 'https://kaffepos.my.id,capacitor://localhost', + corsOrigin: ' HTTPS://KaffePOS.My.ID/ , HTTPS://WWW.KAFFEPOS.MY.ID/ , capacitor://LOCALHOST/ , HTTPS://LOCALHOST/ , HTTP://LOCALHOST/ ', paymentProvider: 'mayar', - mayarEnvironment: 'sandbox', + mayarEnvironment: 'production', mayarConfigured: true, + mayarWebhookTokenConfigured: true, subscriptionPaymentMode: 'auto', paymentIntegrationEnabled: true, resendApiKey: 're_xxx', @@ -58,21 +62,21 @@ describe('backend deployment readiness guardrails', () => { sentryDsn: 'https://public@sentry.example/1', }); - expect(result.ok).toBe(false); - expect(result.errors).toEqual(expect.arrayContaining([ - expect.stringContaining('MAYAR_ENVIRONMENT'), + expect(result.warnings).not.toEqual(expect.arrayContaining([ + expect.stringContaining('CORS_ORIGIN belum memuat'), ])); }); - it('accepts production config when domain, CORS, email, and Mayar are aligned', () => { + it('warns when APK Android HTTPS WebView origin is missing from CORS', () => { const result = validateBackendDeploymentConfig({ nodeEnv: 'production', webBaseUrl: 'https://kaffepos.my.id', apiBaseUrl: 'https://api.kaffepos.my.id', - corsOrigin: 'https://kaffepos.my.id,https://www.kaffepos.my.id,capacitor://localhost,https://localhost,http://localhost', + corsOrigin: 'https://kaffepos.my.id,https://www.kaffepos.my.id,capacitor://localhost,http://localhost', paymentProvider: 'mayar', mayarEnvironment: 'production', mayarConfigured: true, + mayarWebhookTokenConfigured: true, subscriptionPaymentMode: 'auto', paymentIntegrationEnabled: true, resendApiKey: 're_xxx', @@ -80,67 +84,63 @@ describe('backend deployment readiness guardrails', () => { sentryDsn: 'https://public@sentry.example/1', }); - expect(result.ok).toBe(true); - expect(result.errors).toEqual([]); + expect(result.warnings).toEqual(expect.arrayContaining([ + expect.stringContaining('https://localhost'), + ])); }); - it('normalizes configured CORS origins before readiness checks', () => { + it('warns when current APK http localhost bridge origin is missing from CORS', () => { const result = validateBackendDeploymentConfig({ nodeEnv: 'production', webBaseUrl: 'https://kaffepos.my.id', apiBaseUrl: 'https://api.kaffepos.my.id', - corsOrigin: ' HTTPS://KaffePOS.My.ID/ , HTTPS://WWW.KAFFEPOS.MY.ID/ , capacitor://LOCALHOST/ , HTTPS://LOCALHOST/ , HTTP://LOCALHOST/ ', - dokuEnvironment: 'production', + corsOrigin: 'https://kaffepos.my.id,https://www.kaffepos.my.id,capacitor://localhost,https://localhost', + paymentProvider: 'mayar', + mayarEnvironment: 'production', + mayarConfigured: true, + mayarWebhookTokenConfigured: true, subscriptionPaymentMode: 'auto', paymentIntegrationEnabled: true, - dokuConfigured: true, resendApiKey: 're_xxx', resendFromEmail: 'KaffePOS ', sentryDsn: 'https://public@sentry.example/1', }); - expect(result.warnings).not.toEqual(expect.arrayContaining([ - expect.stringContaining('CORS_ORIGIN belum memuat'), + expect(result.warnings).toEqual(expect.arrayContaining([ + expect.stringContaining('http://localhost'), ])); }); - - it('warns when APK Android HTTPS WebView origin is missing from CORS', () => { + it('warns when Mayar is enabled without an API key or webhook token', () => { const result = validateBackendDeploymentConfig({ - nodeEnv: 'production', + nodeEnv: 'staging', webBaseUrl: 'https://kaffepos.my.id', apiBaseUrl: 'https://api.kaffepos.my.id', - corsOrigin: 'https://kaffepos.my.id,https://www.kaffepos.my.id,capacitor://localhost,http://localhost', - dokuEnvironment: 'production', + corsOrigin: 'https://kaffepos.my.id,capacitor://localhost,https://localhost,http://localhost', + paymentProvider: 'mayar', + mayarEnvironment: 'sandbox', + mayarConfigured: false, + mayarWebhookTokenConfigured: false, subscriptionPaymentMode: 'auto', paymentIntegrationEnabled: true, - dokuConfigured: true, - resendApiKey: 're_xxx', - resendFromEmail: 'KaffePOS ', - sentryDsn: 'https://public@sentry.example/1', }); expect(result.warnings).toEqual(expect.arrayContaining([ - expect.stringContaining('https://localhost'), + expect.stringContaining('MAYAR_API_KEY'), + expect.stringContaining('MAYAR_WEBHOOK_TOKEN'), ])); }); - it('warns when current APK http localhost bridge origin is missing from CORS', () => { + it('does not ask for Mayar credentials when online payment is disabled', () => { const result = validateBackendDeploymentConfig({ - nodeEnv: 'production', + nodeEnv: 'staging', webBaseUrl: 'https://kaffepos.my.id', apiBaseUrl: 'https://api.kaffepos.my.id', - corsOrigin: 'https://kaffepos.my.id,https://www.kaffepos.my.id,capacitor://localhost,https://localhost', - dokuEnvironment: 'production', - subscriptionPaymentMode: 'auto', + corsOrigin: 'https://kaffepos.my.id,capacitor://localhost,https://localhost,http://localhost', + paymentProvider: 'disabled', + subscriptionPaymentMode: 'disabled', paymentIntegrationEnabled: true, - dokuConfigured: true, - resendApiKey: 're_xxx', - resendFromEmail: 'KaffePOS ', - sentryDsn: 'https://public@sentry.example/1', }); - expect(result.warnings).toEqual(expect.arrayContaining([ - expect.stringContaining('http://localhost'), - ])); + expect(result.warnings.join(' ')).not.toContain('MAYAR_'); }); }); diff --git a/backend/src/lib/deploymentReadiness.ts b/backend/src/lib/deploymentReadiness.ts index 85b2fca..f204e0a 100644 --- a/backend/src/lib/deploymentReadiness.ts +++ b/backend/src/lib/deploymentReadiness.ts @@ -9,13 +9,14 @@ export type BackendDeploymentValidationInput = { webBaseUrl: string; apiBaseUrl: string; corsOrigin?: string | null; - paymentProvider?: 'mayar' | 'doku' | 'disabled' | string; + paymentProvider?: 'mayar' | 'disabled' | string; mayarEnvironment?: 'sandbox' | 'production' | string; + /** MAYAR_API_KEY is set. */ mayarConfigured?: boolean; - dokuEnvironment?: 'sandbox' | 'production' | string; + /** MAYAR_WEBHOOK_TOKEN is set (webhooks are rejected without it). */ + mayarWebhookTokenConfigured?: boolean; subscriptionPaymentMode?: string | null; paymentIntegrationEnabled: boolean; - dokuConfigured?: boolean; resendApiKey?: string | null; resendFromEmail?: string | null; sentryDsn?: string | null; @@ -32,10 +33,7 @@ export function validateBackendDeploymentConfig(input: BackendDeploymentValidati const warnings: string[] = []; const corsOrigins = new Set(splitCorsOrigins(input.corsOrigin)); const isProduction = input.nodeEnv === 'production'; - const activeProvider = input.paymentProvider ?? (input.mayarEnvironment !== undefined ? 'mayar' : 'doku'); - const activeEnv = activeProvider === 'mayar' ? input.mayarEnvironment : input.dokuEnvironment; - const activeConfigured = - activeProvider === 'mayar' ? Boolean(input.mayarConfigured) : Boolean(input.dokuConfigured); + const paymentActive = input.paymentIntegrationEnabled && input.paymentProvider !== 'disabled'; if (isProduction) { if (input.webBaseUrl !== PRODUCTION_WEB_ORIGIN) { @@ -44,12 +42,8 @@ export function validateBackendDeploymentConfig(input: BackendDeploymentValidati if (input.apiBaseUrl !== PRODUCTION_API_ORIGIN) { errors.push(`API_BASE_URL harus ${PRODUCTION_API_ORIGIN} untuk production.`); } - if (input.paymentIntegrationEnabled && activeEnv !== 'production') { - errors.push( - activeProvider === 'mayar' - ? 'MAYAR_ENVIRONMENT harus production saat PAYMENT_INTEGRATION_ENABLED=true di production.' - : 'DOKU_ENVIRONMENT harus production saat PAYMENT_INTEGRATION_ENABLED=true di production.', - ); + if (paymentActive && input.mayarEnvironment !== 'production') { + errors.push('MAYAR_ENVIRONMENT harus production saat PAYMENT_INTEGRATION_ENABLED=true di production.'); } } @@ -61,12 +55,12 @@ export function validateBackendDeploymentConfig(input: BackendDeploymentValidati errors.push('SENTRY_DSN wajib diisi untuk error tracking backend production.'); } - if (input.paymentIntegrationEnabled && !activeConfigured) { - warnings.push( - activeProvider === 'mayar' - ? 'Pembayaran online aktif tetapi MAYAR_API_KEY belum lengkap.' - : 'Pembayaran online aktif tetapi DOKU client id / secret key / callback url belum lengkap.', - ); + if (paymentActive && !input.mayarConfigured) { + warnings.push('Pembayaran online aktif tetapi MAYAR_API_KEY belum diisi.'); + } + + if (paymentActive && !input.mayarWebhookTokenConfigured) { + warnings.push('Pembayaran online aktif tetapi MAYAR_WEBHOOK_TOKEN belum diisi; webhook Mayar akan ditolak.'); } if (!corsOrigins.has(PRODUCTION_WEB_ORIGIN)) { @@ -85,7 +79,7 @@ export function validateBackendDeploymentConfig(input: BackendDeploymentValidati warnings.push('CORS_ORIGIN belum memuat https://localhost untuk APK Android final dengan androidScheme=https.'); } - if ((input.subscriptionPaymentMode === 'mayar_sandbox' || input.subscriptionPaymentMode === 'doku_sandbox') && isProduction) { + if (input.subscriptionPaymentMode === 'mayar_sandbox' && isProduction) { errors.push(`SUBSCRIPTION_PAYMENT_MODE tidak boleh ${input.subscriptionPaymentMode} di production.`); } diff --git a/backend/src/lib/redactUrl.test.ts b/backend/src/lib/redactUrl.test.ts new file mode 100644 index 0000000..ac2d72a --- /dev/null +++ b/backend/src/lib/redactUrl.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest'; +import { redactUrlSecrets } from './redactUrl'; + +describe('redactUrlSecrets', () => { + it('hides the Mayar webhook token in logged URLs', () => { + expect(redactUrlSecrets('/api/webhooks/mayar?token=abc123')).toBe('/api/webhooks/mayar?token=[redacted]'); + expect(redactUrlSecrets('/api/webhooks/mayar?foo=1&token=abc123&bar=2')).toBe('/api/webhooks/mayar?foo=1&token=[redacted]&bar=2'); + expect(redactUrlSecrets('/x?TOKEN=abc&api_key=k')).toBe('/x?TOKEN=[redacted]&api_key=[redacted]'); + }); + + it('leaves URLs without secrets untouched', () => { + expect(redactUrlSecrets('/api/payments/start?plan=signature')).toBe('/api/payments/start?plan=signature'); + expect(redactUrlSecrets('/api/tokenizer?mytoken=1')).toBe('/api/tokenizer?mytoken=1'); + expect(redactUrlSecrets(undefined)).toBe(''); + }); +}); diff --git a/backend/src/lib/redactUrl.ts b/backend/src/lib/redactUrl.ts new file mode 100644 index 0000000..43b38e3 --- /dev/null +++ b/backend/src/lib/redactUrl.ts @@ -0,0 +1,10 @@ +/** + * Strips secrets from request URLs before they are logged or alerted. + * Mayar webhooks may carry the shared webhook token as `?token=...`. + */ +const SECRET_QUERY_KEYS = /([?&](?:token|webhook_token|access_token|api_key|apikey|signature)=)[^&#]*/gi; + +export function redactUrlSecrets(url: string | null | undefined): string { + if (!url) return ''; + return url.replace(SECRET_QUERY_KEYS, '$1[redacted]'); +} diff --git a/backend/src/middleware/apm.ts b/backend/src/middleware/apm.ts index 3d73d22..5317cd1 100644 --- a/backend/src/middleware/apm.ts +++ b/backend/src/middleware/apm.ts @@ -17,6 +17,7 @@ import { sanitizeError, trackBusinessMetric, } from '../lib/monitoring'; +import { redactUrlSecrets } from '../lib/redactUrl'; type QueryablePool = Pool & { __kaffeposApmPatched?: boolean }; @@ -73,7 +74,7 @@ export function requestLoggingMiddleware(): RequestHandler { logEvent(isError ? 'error' : 'info', 'request.completed', { requestId: req.requestId ?? null, method: req.method, - path: req.originalUrl, + path: redactUrlSecrets(req.originalUrl), route, statusCode: res.statusCode, durationMs, @@ -94,10 +95,10 @@ export function requestLoggingMiddleware(): RequestHandler { requestWindow.errors = 0; requestWindow.startedAt = Date.now(); } - if (/webhook|payment|mayar|doku/i.test(req.originalUrl) && res.statusCode >= 400) { + if (/webhook|payment|mayar/i.test(req.originalUrl) && res.statusCode >= 400) { alertOnPaymentWebhookFailure('Payment webhook request failed', { requestId: req.requestId ?? null, - path: req.originalUrl, + path: redactUrlSecrets(req.originalUrl), statusCode: res.statusCode, }); } @@ -111,7 +112,7 @@ export function errorLoggingMiddleware(error: unknown, req: Request, _res: Respo logError('request.error', error, { requestId: req.requestId ?? null, method: req.method, - path: req.originalUrl, + path: redactUrlSecrets(req.originalUrl), }); next(error); } diff --git a/backend/src/payments/payment-provider.factory.test.ts b/backend/src/payments/payment-provider.factory.test.ts index bf36a36..193e126 100644 --- a/backend/src/payments/payment-provider.factory.test.ts +++ b/backend/src/payments/payment-provider.factory.test.ts @@ -3,27 +3,17 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'; // Mutable mock env so each test can flip the gateway flags. const ENV = vi.hoisted(() => ({ PAYMENT_INTEGRATION_ENABLED: 'true', - PAYMENT_GATEWAY_PROVIDER: 'mayar', + PAYMENT_GATEWAY_PROVIDER: 'mayar' as 'mayar' | 'disabled', MAYAR_ENVIRONMENT: 'sandbox', MAYAR_API_KEY: 'mayar-test-key', MAYAR_WEBHOOK_TOKEN: 'mayar-webhook-token', - MAYAR_SANDBOX_BASE_URL: 'https://api.mayar.club', + MAYAR_SANDBOX_BASE_URL: 'https://api.mayar.io', MAYAR_PRODUCTION_BASE_URL: 'https://api.mayar.id', MAYAR_CREATE_PAYMENT_PATH: '/hl/v2/payments/create', MAYAR_STATUS_PATH_PREFIX: '/hl/v2/payments', MAYAR_WEBHOOK_PATH: '/api/webhooks/mayar', MAYAR_REDIRECT_URL: 'https://kaffepos.my.id/settings?billing=mayar-return', MAYAR_PAYMENT_DUE_MINUTES: 60, - DOKU_ENVIRONMENT: 'sandbox', - DOKU_CLIENT_ID: 'BRN-0001-1234567890', - DOKU_SECRET_KEY: 'SK-test-secret', - DOKU_SANDBOX_BASE_URL: 'https://api-sandbox.doku.com', - DOKU_PRODUCTION_BASE_URL: 'https://api.doku.com', - DOKU_CHECKOUT_PATH: '/checkout/v1/payment', - DOKU_STATUS_PATH_PREFIX: '/orders/v1/status', - DOKU_NOTIFICATION_PATH: '/api/webhooks/doku', - DOKU_CALLBACK_URL: 'https://kaffepos.my.id/settings?billing=doku-return', - DOKU_PAYMENT_DUE_MINUTES: 60, })); vi.mock('../core', () => ({ @@ -37,7 +27,6 @@ vi.mock('../core', () => ({ import { createPaymentProvider, getActivePaymentProviderName } from './payment-provider.factory'; import { MayarPaymentProvider } from './providers/mayar.provider'; -import { DokuPaymentProvider } from './providers/doku.provider'; import { DisabledPaymentProvider } from './providers/disabled.provider'; describe('payment-provider factory', () => { @@ -50,10 +39,6 @@ describe('payment-provider factory', () => { expect(createPaymentProvider('mayar')).toBeInstanceOf(MayarPaymentProvider); }); - it('builds the DOKU provider for the doku name', () => { - expect(createPaymentProvider('doku')).toBeInstanceOf(DokuPaymentProvider); - }); - it('builds the disabled provider for the disabled name', () => { expect(createPaymentProvider('disabled')).toBeInstanceOf(DisabledPaymentProvider); }); @@ -64,17 +49,14 @@ describe('payment-provider factory', () => { expect(createPaymentProvider()).toBeInstanceOf(DisabledPaymentProvider); }); - it('uses the configured Mayar gateway by default when integration is enabled', () => { - ENV.PAYMENT_INTEGRATION_ENABLED = 'true'; - ENV.PAYMENT_GATEWAY_PROVIDER = 'mayar'; + it('uses Mayar by default when integration is enabled', () => { expect(getActivePaymentProviderName()).toBe('mayar'); expect(createPaymentProvider()).toBeInstanceOf(MayarPaymentProvider); }); - it('uses the configured DOKU gateway when integration is enabled and provider is doku', () => { - ENV.PAYMENT_INTEGRATION_ENABLED = 'true'; - ENV.PAYMENT_GATEWAY_PROVIDER = 'doku'; - expect(getActivePaymentProviderName()).toBe('doku'); - expect(createPaymentProvider()).toBeInstanceOf(DokuPaymentProvider); + it('uses the disabled provider when PAYMENT_GATEWAY_PROVIDER=disabled', () => { + ENV.PAYMENT_GATEWAY_PROVIDER = 'disabled'; + expect(getActivePaymentProviderName()).toBe('disabled'); + expect(createPaymentProvider()).toBeInstanceOf(DisabledPaymentProvider); }); }); diff --git a/backend/src/payments/payment-provider.factory.ts b/backend/src/payments/payment-provider.factory.ts index de85899..2b10f5d 100644 --- a/backend/src/payments/payment-provider.factory.ts +++ b/backend/src/payments/payment-provider.factory.ts @@ -1,9 +1,9 @@ import { env } from '../core'; import type { PaymentProviderName, PaymentProvider } from './payment-provider.types'; import { DisabledPaymentProvider } from './providers/disabled.provider'; -import { DokuPaymentProvider } from './providers/doku.provider'; import { MayarPaymentProvider } from './providers/mayar.provider'; +/** Mayar is the only online payment gateway; `disabled` turns online payments off. */ export function getActivePaymentProviderName(): PaymentProviderName { if (env.PAYMENT_INTEGRATION_ENABLED === 'false') return 'disabled'; return env.PAYMENT_GATEWAY_PROVIDER; @@ -11,6 +11,5 @@ export function getActivePaymentProviderName(): PaymentProviderName { export function createPaymentProvider(providerName: PaymentProviderName = getActivePaymentProviderName()): PaymentProvider { if (providerName === 'mayar') return new MayarPaymentProvider(); - if (providerName === 'doku') return new DokuPaymentProvider(); return new DisabledPaymentProvider(); } diff --git a/backend/src/payments/payment-provider.types.ts b/backend/src/payments/payment-provider.types.ts index a4704b8..da4400a 100644 --- a/backend/src/payments/payment-provider.types.ts +++ b/backend/src/payments/payment-provider.types.ts @@ -1,4 +1,4 @@ -export type PaymentProviderName = 'mayar' | 'doku' | 'disabled'; +export type PaymentProviderName = 'mayar' | 'disabled'; export type InternalPaymentStatus = 'pending' | 'paid' | 'failed' | 'expired' | 'cancelled' | 'refunded' | 'unknown'; export type CreatePaymentInput = { @@ -19,6 +19,8 @@ export type CreatePaymentResult = { provider: PaymentProviderName; merchantOrderId: string; providerReference: string | null; + /** Gateway-side transaction id (Mayar returns it next to the payment request id). */ + providerTransactionId?: string | null; paymentUrl: string | null; vaNumber: string | null; qrString: string | null; @@ -30,9 +32,17 @@ export type CreatePaymentResult = { export type VerifiedPaymentCallback = { provider: PaymentProviderName; + /** True when the webhook token / signature matched. */ signatureValid: boolean; merchantOrderId: string | null; providerReference: string | null; + providerTransactionId?: string | null; + /** Webhook event name as sent by the gateway (e.g. `payment.received`). */ + eventType?: string | null; + /** Every id in the payload that may match `merchant_order_id` (our order ids). */ + orderIdCandidates?: string[]; + /** Every id in the payload that may match `provider_reference` (gateway ids). */ + referenceCandidates?: string[]; amount: number | null; paymentMethod: string | null; rawStatus: string | null; @@ -43,13 +53,18 @@ export type VerifiedPaymentCallback = { export type PaymentStatusResult = VerifiedPaymentCallback; +export type PaymentCallbackInput = { + body: Record; + headers?: Record; + rawBody?: string; + /** Parsed query string of the webhook request (Mayar URL-token mode: `?token=`). */ + query?: Record; +}; + export interface PaymentProvider { providerName: PaymentProviderName; createPayment(input: CreatePaymentInput): Promise; - // `headers` + `rawBody` are required by providers that sign the webhook in the - // HTTP header over the raw payload (e.g. DOKU). Body-signature providers may - // ignore them. - verifyCallback(input: { body: Record; headers?: Record; rawBody?: string }): Promise; + verifyCallback(input: PaymentCallbackInput): Promise; checkTransactionStatus(input: { merchantOrderId: string; providerReference?: string | null; amount?: number | null }): Promise; mapProviderStatus(rawStatus: unknown): InternalPaymentStatus; } diff --git a/backend/src/payments/providers/doku.provider.test.ts b/backend/src/payments/providers/doku.provider.test.ts deleted file mode 100644 index 922c490..0000000 --- a/backend/src/payments/providers/doku.provider.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest'; -import { createHash, createHmac } from 'node:crypto'; - -const DOKU_ENV = vi.hoisted(() => ({ - DOKU_ENVIRONMENT: 'sandbox', - DOKU_CLIENT_ID: 'BRN-0001-1234567890', - DOKU_SECRET_KEY: 'SK-test-secret', - DOKU_SANDBOX_BASE_URL: 'https://api-sandbox.doku.com', - DOKU_PRODUCTION_BASE_URL: 'https://api.doku.com', - DOKU_CHECKOUT_PATH: '/checkout/v1/payment', - DOKU_STATUS_PATH_PREFIX: '/orders/v1/status', - DOKU_NOTIFICATION_PATH: '/api/webhooks/doku', - DOKU_CALLBACK_URL: 'https://kaffepos.my.id/settings?billing=doku-return', - DOKU_PAYMENT_DUE_MINUTES: 60, -})); - -vi.mock('../../core', () => ({ - ApiError: class ApiError extends Error { constructor(public status: number, message: string) { super(message); } }, - log: vi.fn(), - serializeError: (error: unknown) => String(error), - env: DOKU_ENV, -})); - -import { DokuPaymentProvider } from './doku.provider'; - -const sha256Base64 = (body: string) => createHash('sha256').update(body, 'utf8').digest('base64'); -const hmac = (component: string) => createHmac('sha256', DOKU_ENV.DOKU_SECRET_KEY).update(component, 'utf8').digest('base64'); - -describe('DokuPaymentProvider', () => { - beforeEach(() => vi.restoreAllMocks()); - - it('builds the DOKU HMAC-SHA256 signature over the exact component string', () => { - const provider = new DokuPaymentProvider(); - const expected = `HMACSHA256=${hmac( - `Client-Id:${DOKU_ENV.DOKU_CLIENT_ID}\nRequest-Id:req-1\nRequest-Timestamp:2026-06-22T10:00:00Z\nRequest-Target:/checkout/v1/payment\nDigest:abc=`, - )}`; - expect(provider.buildSignature({ requestId: 'req-1', timestamp: '2026-06-22T10:00:00Z', target: '/checkout/v1/payment', digest: 'abc=' })).toBe(expected); - }); - - it('omits the Digest line for GET-style signatures (status check)', () => { - const provider = new DokuPaymentProvider(); - const expected = `HMACSHA256=${hmac( - `Client-Id:${DOKU_ENV.DOKU_CLIENT_ID}\nRequest-Id:req-2\nRequest-Timestamp:2026-06-22T10:00:00Z\nRequest-Target:/orders/v1/status/INV-1`, - )}`; - expect(provider.buildSignature({ requestId: 'req-2', timestamp: '2026-06-22T10:00:00Z', target: '/orders/v1/status/INV-1' })).toBe(expected); - }); - - it('creates a checkout payment with valid signed headers and returns payment.url', async () => { - let capturedUrl = ''; - let capturedHeaders: Record = {}; - let capturedBody = ''; - vi.stubGlobal('fetch', vi.fn(async (url, init) => { - capturedUrl = String(url); - capturedHeaders = init?.headers as Record; - capturedBody = String(init?.body); - return new Response(JSON.stringify({ response: { payment: { url: 'https://app-sandbox.doku.com/checkout/pay/TOKEN-1', token_id: 'TOKEN-1' } } }), { status: 200, headers: { 'Content-Type': 'application/json' } }); - })); - - const provider = new DokuPaymentProvider(); - const result = await provider.createPayment({ merchantOrderId: 'SUB-1', amount: 49000, productDetails: 'Langganan Signature', customerName: 'Tester', customerEmail: 'tester@example.com' }); - - expect(capturedUrl).toBe('https://api-sandbox.doku.com/checkout/v1/payment'); - expect(capturedHeaders['Client-Id']).toBe(DOKU_ENV.DOKU_CLIENT_ID); - expect(capturedHeaders['Request-Id']).toBeTruthy(); - expect(capturedHeaders['Request-Timestamp']).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/); - // Re-derive the signature from the captured request and confirm it matches. - const digest = sha256Base64(capturedBody); - const expectedSig = `HMACSHA256=${hmac( - `Client-Id:${DOKU_ENV.DOKU_CLIENT_ID}\nRequest-Id:${capturedHeaders['Request-Id']}\nRequest-Timestamp:${capturedHeaders['Request-Timestamp']}\nRequest-Target:/checkout/v1/payment\nDigest:${digest}`, - )}`; - expect(capturedHeaders.Signature).toBe(expectedSig); - expect(JSON.parse(capturedBody).order.invoice_number).toBe('SUB-1'); - expect(result.provider).toBe('doku'); - expect(result.paymentUrl).toBe('https://app-sandbox.doku.com/checkout/pay/TOKEN-1'); - expect(result.providerReference).toBe('TOKEN-1'); - expect(result.internalStatus).toBe('pending'); - }); - - it('accepts a notification with a valid header signature and maps SUCCESS -> paid', async () => { - const provider = new DokuPaymentProvider(); - const body = { order: { invoice_number: 'SUB-1', amount: 49000 }, transaction: { status: 'SUCCESS', date: '2026-06-22T10:00:00Z' } }; - const rawBody = JSON.stringify(body); - const requestId = 'notif-1'; - const timestamp = '2026-06-22T10:00:01Z'; - const signature = `HMACSHA256=${hmac( - `Client-Id:${DOKU_ENV.DOKU_CLIENT_ID}\nRequest-Id:${requestId}\nResponse-Timestamp:${timestamp}\nRequest-Target:/api/webhooks/doku\nDigest:${sha256Base64(rawBody)}`, - )}`; - - const result = await provider.verifyCallback({ - body, - rawBody, - headers: { 'client-id': DOKU_ENV.DOKU_CLIENT_ID, 'request-id': requestId, 'response-timestamp': timestamp, signature }, - }); - - expect(result.signatureValid).toBe(true); - expect(result.internalStatus).toBe('paid'); - expect(result.merchantOrderId).toBe('SUB-1'); - expect(result.amount).toBe(49000); - }); - - it('rejects a notification with a tampered signature', async () => { - const provider = new DokuPaymentProvider(); - const body = { order: { invoice_number: 'SUB-1', amount: 49000 }, transaction: { status: 'SUCCESS' } }; - const result = await provider.verifyCallback({ - body, - rawBody: JSON.stringify(body), - headers: { 'client-id': DOKU_ENV.DOKU_CLIENT_ID, 'request-id': 'x', 'response-timestamp': '2026-06-22T10:00:01Z', signature: 'HMACSHA256=tampered' }, - }); - expect(result.signatureValid).toBe(false); - }); - - it('maps DOKU statuses to internal statuses', () => { - const provider = new DokuPaymentProvider(); - expect(provider.mapProviderStatus('SUCCESS')).toBe('paid'); - expect(provider.mapProviderStatus('PENDING')).toBe('pending'); - expect(provider.mapProviderStatus('FAILED')).toBe('failed'); - expect(provider.mapProviderStatus('EXPIRED')).toBe('expired'); - expect(provider.mapProviderStatus('VOID')).toBe('cancelled'); - expect(provider.mapProviderStatus('weird')).toBe('unknown'); - }); -}); diff --git a/backend/src/payments/providers/doku.provider.ts b/backend/src/payments/providers/doku.provider.ts deleted file mode 100644 index afe18ea..0000000 --- a/backend/src/payments/providers/doku.provider.ts +++ /dev/null @@ -1,271 +0,0 @@ -import { createHash, createHmac, timingSafeEqual } from 'node:crypto'; -import { randomUUID } from 'node:crypto'; -import { ApiError, env, log, serializeError } from '../../core'; -import type { - CreatePaymentInput, - CreatePaymentResult, - InternalPaymentStatus, - PaymentProvider, - PaymentStatusResult, - VerifiedPaymentCallback, -} from '../payment-provider.types'; - -/** DOKU Request-Timestamp / Response-Timestamp format: ISO-8601 UTC, no millis. */ -function dokuTimestamp(date = new Date()) { - return date.toISOString().replace(/\.\d{3}Z$/, 'Z'); -} - -function sha256Base64(body: string) { - return createHash('sha256').update(body, 'utf8').digest('base64'); -} - -function hmacSha256Base64(component: string, secret: string) { - return createHmac('sha256', secret).update(component, 'utf8').digest('base64'); -} - -function safeEqual(a: string, b: string) { - const left = Buffer.from(a); - const right = Buffer.from(b); - return left.length === right.length && timingSafeEqual(left, right); -} - -function headerValue(headers: Record | undefined, name: string) { - if (!headers) return null; - const raw = headers[name.toLowerCase()]; - if (Array.isArray(raw)) return raw[0] ?? null; - return raw ?? null; -} - -function pick(payload: Record, path: string[]): unknown { - let cursor: unknown = payload; - for (const key of path) { - if (cursor && typeof cursor === 'object' && key in (cursor as Record)) { - cursor = (cursor as Record)[key]; - } else { - return undefined; - } - } - return cursor; -} - -function asString(value: unknown): string | null { - return value == null ? null : String(value); -} - -function asNumber(value: unknown): number | null { - if (value == null) return null; - const n = Number(value); - return Number.isFinite(n) ? n : null; -} - -export class DokuPaymentProvider implements PaymentProvider { - providerName = 'doku' as const; - - private get clientId() { - if (!env.DOKU_CLIENT_ID) throw new ApiError(503, 'DOKU client id belum dikonfigurasi.'); - return env.DOKU_CLIENT_ID; - } - - private get secretKey() { - if (!env.DOKU_SECRET_KEY) throw new ApiError(503, 'DOKU secret key belum dikonfigurasi.'); - return env.DOKU_SECRET_KEY; - } - - private get baseUrl() { - const base = env.DOKU_ENVIRONMENT === 'production' ? env.DOKU_PRODUCTION_BASE_URL : env.DOKU_SANDBOX_BASE_URL; - return base.replace(/\/$/, ''); - } - - /** - * DOKU signature: component lines joined by "\n" (no trailing newline), - * HMAC-SHA256 with the secret key, base64-encoded, prefixed with "HMACSHA256=". - * For GET requests (and any request without a body) the Digest line is omitted. - * `timestampHeader` is "Request-Timestamp" for outbound calls and - * "Response-Timestamp" when verifying an inbound notification. - */ - buildSignature(input: { - requestId: string; - timestamp: string; - target: string; - digest?: string | null; - timestampHeader?: 'Request-Timestamp' | 'Response-Timestamp'; - }) { - const timestampHeader = input.timestampHeader ?? 'Request-Timestamp'; - const lines = [ - `Client-Id:${this.clientId}`, - `Request-Id:${input.requestId}`, - `${timestampHeader}:${input.timestamp}`, - `Request-Target:${input.target}`, - ]; - if (input.digest) lines.push(`Digest:${input.digest}`); - return `HMACSHA256=${hmacSha256Base64(lines.join('\n'), this.secretKey)}`; - } - - private signedHeaders(target: string, bodyString: string | null) { - const requestId = randomUUID(); - const timestamp = dokuTimestamp(); - const digest = bodyString == null ? null : sha256Base64(bodyString); - const signature = this.buildSignature({ requestId, timestamp, target, digest }); - const headers: Record = { - 'Client-Id': this.clientId, - 'Request-Id': requestId, - 'Request-Timestamp': timestamp, - Signature: signature, - }; - if (bodyString != null) { - headers['Content-Type'] = 'application/json'; - headers.Accept = 'application/json'; - } - return headers; - } - - async createPayment(input: CreatePaymentInput): Promise { - const amount = Math.round(input.amount); - const lineItems = (input.itemDetails && input.itemDetails.length > 0 - ? input.itemDetails - : [{ name: input.productDetails || 'KaffePOS', price: amount, quantity: 1 }] - ).map((item) => ({ name: item.name, price: Math.round(item.price), quantity: item.quantity })); - - const body = { - order: { - amount, - invoice_number: input.merchantOrderId, - currency: 'IDR', - callback_url: env.DOKU_CALLBACK_URL ?? undefined, - line_items: lineItems, - }, - payment: { - payment_due_date: env.DOKU_PAYMENT_DUE_MINUTES, - }, - customer: { - id: input.merchantOrderId, - name: input.customerName || 'KaffePOS Customer', - email: input.customerEmail || 'billing@kaffepos.my.id', - phone: input.customerPhone || undefined, - }, - }; - - const target = env.DOKU_CHECKOUT_PATH; - const bodyString = JSON.stringify(body); - - try { - log('info', 'doku.create_payment_request', { - environment: env.DOKU_ENVIRONMENT, - target, - amount, - merchantOrderId: input.merchantOrderId, - callbackUrlConfigured: Boolean(env.DOKU_CALLBACK_URL), - }); - const response = await fetch(`${this.baseUrl}${target}`, { - method: 'POST', - headers: this.signedHeaders(target, bodyString), - body: bodyString, - signal: AbortSignal.timeout(15000), - }); - const raw = (await response.json().catch(async () => ({ message: await response.text().catch(() => '') }))) as Record; - const paymentUrl = asString(pick(raw, ['response', 'payment', 'url'])) ?? asString(pick(raw, ['payment', 'url'])); - const tokenId = asString(pick(raw, ['response', 'payment', 'token_id'])) ?? asString(pick(raw, ['payment', 'token_id'])); - log(response.ok ? 'info' : 'warn', 'doku.create_payment_response', { - environment: env.DOKU_ENVIRONMENT, - httpStatus: response.status, - merchantOrderId: input.merchantOrderId, - paymentUrlPresent: Boolean(paymentUrl), - }); - if (!response.ok) throw new ApiError(502, `DOKU create payment gagal (${response.status}).`); - if (!paymentUrl) throw new ApiError(502, 'DOKU create payment tidak mengembalikan payment url.'); - return { - provider: 'doku', - merchantOrderId: input.merchantOrderId, - providerReference: tokenId, - paymentUrl, - vaNumber: asString(pick(raw, ['virtual_account_info', 'virtual_account_number'])), - qrString: asString(pick(raw, ['response', 'payment', 'qr_string'])), - paymentMethod: asString(pick(raw, ['response', 'payment', 'payment_method'])), - providerStatus: asString(pick(raw, ['response', 'order', 'status'])) ?? 'pending', - internalStatus: 'pending', - raw, - }; - } catch (error) { - log('warn', 'doku.create_payment_failed', { error: serializeError(error), merchantOrderId: input.merchantOrderId }); - throw error instanceof ApiError ? error : new ApiError(502, 'DOKU belum bisa membuat pembayaran.'); - } - } - - async verifyCallback(input: { body: Record; headers?: Record; rawBody?: string }): Promise { - const body = input.body ?? {}; - const rawBody = input.rawBody ?? JSON.stringify(body); - const receivedSignature = headerValue(input.headers, 'Signature'); - const requestId = headerValue(input.headers, 'Request-Id'); - const timestamp = headerValue(input.headers, 'Response-Timestamp') ?? headerValue(input.headers, 'Request-Timestamp'); - - let signatureValid = false; - if (receivedSignature && requestId && timestamp && env.DOKU_CLIENT_ID && env.DOKU_SECRET_KEY) { - const expected = this.buildSignature({ - requestId, - timestamp, - target: env.DOKU_NOTIFICATION_PATH, - digest: sha256Base64(rawBody), - timestampHeader: 'Response-Timestamp', - }); - signatureValid = safeEqual(receivedSignature, expected); - } - - const rawStatus = asString(pick(body, ['transaction', 'status'])); - const paidAt = asString(pick(body, ['transaction', 'date'])); - const internalStatus = this.mapProviderStatus(rawStatus); - return { - provider: 'doku', - signatureValid, - merchantOrderId: asString(pick(body, ['order', 'invoice_number'])), - providerReference: asString(pick(body, ['transaction', 'original_request_id'])) ?? asString(pick(body, ['order', 'session_id'])), - amount: asNumber(pick(body, ['order', 'amount'])), - paymentMethod: asString(pick(body, ['service', 'id'])) ?? asString(pick(body, ['channel', 'id'])), - rawStatus, - internalStatus, - paidAt: internalStatus === 'paid' ? (paidAt ?? new Date().toISOString()) : paidAt, - raw: body, - }; - } - - async checkTransactionStatus(input: { merchantOrderId: string }): Promise { - const target = `${env.DOKU_STATUS_PATH_PREFIX.replace(/\/$/, '')}/${encodeURIComponent(input.merchantOrderId)}`; - try { - const response = await fetch(`${this.baseUrl}${target}`, { - method: 'GET', - headers: this.signedHeaders(target, null), - signal: AbortSignal.timeout(15000), - }); - const raw = (await response.json().catch(async () => ({ message: await response.text().catch(() => '') }))) as Record; - if (!response.ok) throw new ApiError(502, `DOKU status check gagal (${response.status}).`); - const rawStatus = asString(pick(raw, ['transaction', 'status'])); - const internalStatus = this.mapProviderStatus(rawStatus); - return { - provider: 'doku', - // Polling responses are not HMAC-signed by DOKU; authenticity comes from the signed request we sent. - signatureValid: true, - merchantOrderId: asString(pick(raw, ['order', 'invoice_number'])) ?? input.merchantOrderId, - providerReference: asString(pick(raw, ['transaction', 'original_request_id'])), - amount: asNumber(pick(raw, ['order', 'amount'])), - paymentMethod: asString(pick(raw, ['service', 'id'])) ?? asString(pick(raw, ['channel', 'id'])), - rawStatus, - internalStatus, - paidAt: internalStatus === 'paid' ? (asString(pick(raw, ['transaction', 'date'])) ?? new Date().toISOString()) : null, - raw, - }; - } catch (error) { - log('warn', 'doku.check_status_failed', { error: serializeError(error), merchantOrderId: input.merchantOrderId }); - throw error instanceof ApiError ? error : new ApiError(502, 'Status DOKU belum bisa dicek.'); - } - } - - mapProviderStatus(rawStatus: unknown): InternalPaymentStatus { - const status = String(rawStatus ?? '').trim().toUpperCase(); - if (status === 'SUCCESS') return 'paid'; - if (status === 'PENDING' || status === '') return 'pending'; - if (status === 'FAILED' || status === 'DECLINE' || status === 'DECLINED') return 'failed'; - if (status === 'EXPIRED') return 'expired'; - if (status === 'CANCELLED' || status === 'CANCELED' || status === 'VOID') return 'cancelled'; - if (status === 'REFUND' || status === 'REFUNDED') return 'refunded'; - return 'unknown'; - } -} diff --git a/backend/src/payments/providers/mayar.provider.test.ts b/backend/src/payments/providers/mayar.provider.test.ts index ccfd9f6..217d348 100644 --- a/backend/src/payments/providers/mayar.provider.test.ts +++ b/backend/src/payments/providers/mayar.provider.test.ts @@ -1,11 +1,11 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest'; +import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'; import { createHmac } from 'node:crypto'; const MAYAR_ENV = vi.hoisted(() => ({ - MAYAR_ENVIRONMENT: 'sandbox', - MAYAR_API_KEY: 'mayar-test-api-key-jwt', - MAYAR_WEBHOOK_TOKEN: 'mayar-webhook-secret-token', - MAYAR_SANDBOX_BASE_URL: 'https://api.mayar.club', + MAYAR_ENVIRONMENT: 'sandbox' as 'sandbox' | 'production', + MAYAR_API_KEY: 'mayar-test-api-key-jwt' as string | undefined, + MAYAR_WEBHOOK_TOKEN: 'mayar-webhook-secret-token' as string | undefined, + MAYAR_SANDBOX_BASE_URL: 'https://api.mayar.io', MAYAR_PRODUCTION_BASE_URL: 'https://api.mayar.id', MAYAR_CREATE_PAYMENT_PATH: '/hl/v2/payments/create', MAYAR_STATUS_PATH_PREFIX: '/hl/v2/payments', @@ -25,209 +25,410 @@ vi.mock('../../core', () => ({ env: MAYAR_ENV, })); -import { MayarPaymentProvider } from './mayar.provider'; +import { MayarPaymentProvider, webhookTokensMatch } from './mayar.provider'; +import { mayarCircuitBreaker } from '../../architecture/circuitBreaker'; + +const PAYMENT_REQUEST_ID = '6f8c19ff-5b97-4792-aa89-d2a12797b356'; +const TRANSACTION_ID = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890'; + +function jsonResponse(body: unknown, status = 200) { + return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); +} describe('MayarPaymentProvider', () => { - beforeEach(() => vi.restoreAllMocks()); - - it('creates a single payment request via Mayar API v2 and returns paymentUrl + providerReference', async () => { - let capturedUrl = ''; - let capturedHeaders: Record = {}; - let capturedBody = ''; - - vi.stubGlobal( - 'fetch', - vi.fn(async (url, init) => { - capturedUrl = String(url); - capturedHeaders = init?.headers as Record; - capturedBody = String(init?.body); - return new Response( - JSON.stringify({ - statusCode: 200, - messages: 'success', - data: { - id: '6f8c19ff-5b97-4792-aa89-d2a12797b356', - transactionId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890', - link: 'https://testingmayar.myr.id/pl/rqp9x2k7m3a', - }, - }), - { status: 200, headers: { 'Content-Type': 'application/json' } }, - ); - }), - ); + beforeEach(() => { + vi.restoreAllMocks(); + mayarCircuitBreaker.reset(); + MAYAR_ENV.MAYAR_ENVIRONMENT = 'sandbox'; + MAYAR_ENV.MAYAR_API_KEY = 'mayar-test-api-key-jwt'; + MAYAR_ENV.MAYAR_WEBHOOK_TOKEN = 'mayar-webhook-secret-token'; + }); - const provider = new MayarPaymentProvider(); - const result = await provider.createPayment({ - merchantOrderId: 'SUB-101', - amount: 129000, - productDetails: 'Langganan KaffePOS Signature', - customerName: 'Budi Santoso', - customerEmail: 'budi@example.com', - customerPhone: '081234567890', - paymentMethod: 'qris', - }); - - expect(capturedUrl).toBe('https://api.mayar.club/hl/v2/payments/create'); - expect(capturedHeaders.Authorization).toBe(`Bearer ${MAYAR_ENV.MAYAR_API_KEY}`); - const parsed = JSON.parse(capturedBody); - expect(parsed.amount).toBe(129000); - expect(parsed.email).toBe('budi@example.com'); - expect(parsed.description).toContain('[SUB-101]'); - expect(parsed.extraData.merchantOrderId).toBe('SUB-101'); - expect(result.provider).toBe('mayar'); - expect(result.paymentUrl).toBe('https://testingmayar.myr.id/pl/rqp9x2k7m3a'); - expect(result.providerReference).toBe('6f8c19ff-5b97-4792-aa89-d2a12797b356'); - expect(result.internalStatus).toBe('pending'); + afterEach(() => { + vi.unstubAllGlobals(); }); - it('retries without redirectUrl if Mayar API v2 rejects redirectUrl on payment requests', async () => { - const calls: Array> = []; - vi.stubGlobal( - 'fetch', - vi.fn(async (_url, init) => { - const body = JSON.parse(String(init?.body)); - calls.push(body); - if (calls.length === 1) { - return new Response( - JSON.stringify({ - statusCode: 400, - messages: 'redirectUrl is not supported on payment requests and was not saved', - }), - { status: 400, headers: { 'Content-Type': 'application/json' } }, - ); - } - return new Response( - JSON.stringify({ + describe('createPayment', () => { + it('creates a single payment request via Mayar API v2 with the API key', async () => { + let capturedUrl = ''; + let capturedHeaders: Record = {}; + let capturedBody: Record = {}; + + vi.stubGlobal( + 'fetch', + vi.fn(async (url, init) => { + capturedUrl = String(url); + capturedHeaders = init?.headers as Record; + capturedBody = JSON.parse(String(init?.body)); + return jsonResponse({ statusCode: 200, messages: 'success', - data: { - id: 'mayar-id-2', - link: 'https://testingmayar.myr.id/pl/retry-ok', - }, - }), - { status: 200, headers: { 'Content-Type': 'application/json' } }, - ); - }), - ); + data: { id: PAYMENT_REQUEST_ID, transactionId: TRANSACTION_ID, link: 'https://kaffepos.myr.id/pl/rqp9x2k7m3a' }, + }); + }), + ); - const provider = new MayarPaymentProvider(); - const result = await provider.createPayment({ - merchantOrderId: 'SUB-102', - amount: 49000, - productDetails: 'Langganan Kopi Susu', + const result = await new MayarPaymentProvider().createPayment({ + merchantOrderId: 'SUB-101', + amount: 129000, + productDetails: 'Langganan KaffePOS Signature', + customerName: 'Budi Santoso', + customerEmail: 'budi@example.com', + customerPhone: '0812-3456-7890', + paymentMethod: 'qris', + metadata: { kind: 'subscription', plan: 'signature' }, + }); + + expect(capturedUrl).toBe('https://api.mayar.io/hl/v2/payments/create'); + expect(capturedHeaders.Authorization).toBe('Bearer mayar-test-api-key-jwt'); + expect(capturedBody.amount).toBe(129000); + expect(capturedBody.email).toBe('budi@example.com'); + expect(capturedBody.mobile).toBe('081234567890'); + expect(capturedBody.description).toContain('[SUB-101]'); + expect(capturedBody.redirectUrl).toBeUndefined(); + expect(capturedBody.extraData).toEqual({ + kind: 'subscription', + plan: 'signature', + merchantOrderId: 'SUB-101', + orderId: 'SUB-101', + source: 'kaffepos', + }); + expect(result).toMatchObject({ + provider: 'mayar', + paymentUrl: 'https://kaffepos.myr.id/pl/rqp9x2k7m3a', + providerReference: PAYMENT_REQUEST_ID, + providerTransactionId: TRANSACTION_ID, + paymentMethod: 'qris', + internalStatus: 'pending', + }); + }); + + it('uses the production host when MAYAR_ENVIRONMENT=production', async () => { + MAYAR_ENV.MAYAR_ENVIRONMENT = 'production'; + let capturedUrl = ''; + vi.stubGlobal( + 'fetch', + vi.fn(async (url) => { + capturedUrl = String(url); + return jsonResponse({ statusCode: 200, data: { id: PAYMENT_REQUEST_ID, link: 'https://kaffepos.myr.id/pl/x' } }); + }), + ); + + await new MayarPaymentProvider().createPayment({ merchantOrderId: 'KAF-1', amount: 25000, productDetails: 'POS' }); + expect(capturedUrl).toBe('https://api.mayar.id/hl/v2/payments/create'); }); - expect(calls).toHaveLength(2); - expect(calls[0].redirectUrl).toBeDefined(); - expect(calls[1].redirectUrl).toBeUndefined(); - expect(result.paymentUrl).toBe('https://testingmayar.myr.id/pl/retry-ok'); + it('does not invent a phone number for payment requests', async () => { + let capturedBody: Record = {}; + vi.stubGlobal( + 'fetch', + vi.fn(async (_url, init) => { + capturedBody = JSON.parse(String(init?.body)); + return jsonResponse({ statusCode: 200, data: { id: PAYMENT_REQUEST_ID, link: 'https://kaffepos.myr.id/pl/x' } }); + }), + ); + + await new MayarPaymentProvider().createPayment({ merchantOrderId: 'KAF-2', amount: 25000, productDetails: 'POS' }); + expect(capturedBody.mobile).toBeUndefined(); + expect(capturedBody.email).toBe('customer@kaffepos.my.id'); + }); + + it('retries without redirectUrl when Mayar refuses it on payment requests', async () => { + const calls: Array> = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (_url, init) => { + calls.push(JSON.parse(String(init?.body))); + if (calls.length === 1) { + return jsonResponse({ statusCode: 400, messages: 'redirectUrl is not supported on payment requests and was not saved' }, 400); + } + return jsonResponse({ statusCode: 200, data: { id: 'mayar-id-2', link: 'https://kaffepos.myr.id/pl/retry-ok' } }); + }), + ); + + const result = await new MayarPaymentProvider().createPayment({ + merchantOrderId: 'SUB-102', + amount: 49000, + productDetails: 'Langganan Kopi Susu', + returnUrl: 'https://kaffepos.my.id/settings?billing=mayar-return', + }); + + expect(calls).toHaveLength(2); + expect(calls[0].redirectUrl).toBe('https://kaffepos.my.id/settings?billing=mayar-return'); + expect(calls[1].redirectUrl).toBeUndefined(); + expect(result.paymentUrl).toBe('https://kaffepos.myr.id/pl/retry-ok'); + }); + + it('adds a placeholder phone only when Mayar insists on mobile', async () => { + const calls: Array> = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (_url, init) => { + calls.push(JSON.parse(String(init?.body))); + if (calls.length === 1) { + return jsonResponse({ statusCode: 400, messages: 'Validation Error', data: ['mobile is required'] }, 400); + } + return jsonResponse({ statusCode: 200, data: { id: 'mayar-id-3', link: 'https://kaffepos.myr.id/pl/m' } }); + }), + ); + + await new MayarPaymentProvider().createPayment({ merchantOrderId: 'KAF-3', amount: 15000, productDetails: 'POS' }); + expect(calls).toHaveLength(2); + expect(calls[0].mobile).toBeUndefined(); + expect(calls[1].mobile).toBe('081234567890'); + }); + + it('surfaces a friendly error for duplicate requests (429)', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => jsonResponse({ statusCode: 429, messages: 'Duplicate request detected. Please wait 1 minute before trying again.' }, 429)), + ); + + await expect( + new MayarPaymentProvider().createPayment({ merchantOrderId: 'KAF-4', amount: 15000, productDetails: 'POS' }), + ).rejects.toMatchObject({ status: 502, message: expect.stringContaining('Mayar menolak permintaan ganda') }); + }); + + it('fails with 502 when the API key is rejected', async () => { + vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ statusCode: 401, messages: 'Unauthorized' }, 401))); + await expect( + new MayarPaymentProvider().createPayment({ merchantOrderId: 'KAF-5', amount: 15000, productDetails: 'POS' }), + ).rejects.toMatchObject({ status: 502, message: 'Mayar create payment gagal (401).' }); + }); + + it('refuses to call Mayar without an API key', async () => { + MAYAR_ENV.MAYAR_API_KEY = undefined; + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + await expect( + new MayarPaymentProvider().createPayment({ merchantOrderId: 'KAF-6', amount: 15000, productDetails: 'POS' }), + ).rejects.toMatchObject({ status: 503 }); + expect(fetchMock).not.toHaveBeenCalled(); + }); }); - it('verifies a payment.received webhook with x-callback-token and maps status to paid', async () => { - const provider = new MayarPaymentProvider(); - const body = { - event: { received: 'payment.received' }, + describe('verifyCallback (webhook token)', () => { + const paidBody = { + event: 'payment.received', data: { - id: 'webhook-evt-1', - productId: '6f8c19ff-5b97-4792-aa89-d2a12797b356', - productName: 'Langganan KaffePOS Signature [SUB-101]', - status: true, + id: TRANSACTION_ID, + transactionId: TRANSACTION_ID, + productId: PAYMENT_REQUEST_ID, + productType: 'payment_request', + status: 'SUCCESS', + transactionStatus: 'created', amount: 129000, customerEmail: 'budi@example.com', - updatedAt: '2026-11-08T00:00:00.000Z', + extraData: { merchantOrderId: 'SUB-101', orderId: 'SUB-101' }, + createdAt: 1768375011056, + updatedAt: 1768375112056, }, }; - const result = await provider.verifyCallback({ - body, - rawBody: JSON.stringify(body), - headers: { 'x-callback-token': MAYAR_ENV.MAYAR_WEBHOOK_TOKEN }, + it('accepts the X-Callback-Token header and maps payment.received to paid', async () => { + const result = await new MayarPaymentProvider().verifyCallback({ + body: paidBody, + headers: { 'X-Callback-Token': 'mayar-webhook-secret-token' }, + }); + + expect(result.signatureValid).toBe(true); + expect(result.eventType).toBe('payment.received'); + expect(result.internalStatus).toBe('paid'); + expect(result.merchantOrderId).toBe('SUB-101'); + expect(result.providerReference).toBe(PAYMENT_REQUEST_ID); + expect(result.providerTransactionId).toBe(TRANSACTION_ID); + expect(result.referenceCandidates).toEqual([PAYMENT_REQUEST_ID, TRANSACTION_ID]); + expect(result.amount).toBe(129000); + expect(result.paidAt).toBe(new Date(1768375112056).toISOString()); }); - expect(result.signatureValid).toBe(true); - expect(result.internalStatus).toBe('paid'); - expect(result.merchantOrderId).toBe('SUB-101'); - expect(result.providerReference).toBe('6f8c19ff-5b97-4792-aa89-d2a12797b356'); - expect(result.amount).toBe(129000); - }); + it('accepts the token from ?token= on the webhook URL', async () => { + const result = await new MayarPaymentProvider().verifyCallback({ + body: paidBody, + headers: {}, + query: { token: 'mayar-webhook-secret-token' }, + }); + expect(result.signatureValid).toBe(true); + }); - it('also accepts HMAC-SHA256 webhook signature in x-mayar-signature', async () => { - const provider = new MayarPaymentProvider(); - const body = { - event: 'payment.received', - data: { - id: 'tx-1', - amount: 49000, - extraData: { merchantOrderId: 'KAF-ORDER-1' }, - }, - }; - const rawBody = JSON.stringify(body); - const sig = createHmac('sha256', MAYAR_ENV.MAYAR_WEBHOOK_TOKEN).update(rawBody, 'utf8').digest('hex'); + it('accepts an Authorization: Bearer token and ignores edge whitespace', async () => { + const result = await new MayarPaymentProvider().verifyCallback({ + body: paidBody, + headers: { authorization: 'Bearer mayar-webhook-secret-token\n' }, + }); + expect(result.signatureValid).toBe(true); + }); - const result = await provider.verifyCallback({ - body, - rawBody, - headers: { 'x-mayar-signature': sig }, + it('rejects a wrong token', async () => { + const result = await new MayarPaymentProvider().verifyCallback({ + body: paidBody, + headers: { 'x-callback-token': 'wrong-token' }, + query: { token: 'also-wrong' }, + }); + expect(result.signatureValid).toBe(false); }); - expect(result.signatureValid).toBe(true); - expect(result.internalStatus).toBe('paid'); - expect(result.merchantOrderId).toBe('KAF-ORDER-1'); - }); + it('never accepts the API key as a webhook token', async () => { + const result = await new MayarPaymentProvider().verifyCallback({ + body: paidBody, + headers: { 'x-callback-token': 'mayar-test-api-key-jwt' }, + }); + expect(result.signatureValid).toBe(false); + }); - it('rejects a webhook with an invalid token', async () => { - const provider = new MayarPaymentProvider(); - const body = { - event: 'payment.received', - data: { id: 'tx-1', amount: 49000 }, - }; + it('rejects every webhook when MAYAR_WEBHOOK_TOKEN is not configured', async () => { + MAYAR_ENV.MAYAR_WEBHOOK_TOKEN = undefined; + const result = await new MayarPaymentProvider().verifyCallback({ + body: paidBody, + headers: { 'x-callback-token': 'mayar-test-api-key-jwt' }, + }); + expect(result.signatureValid).toBe(false); + }); + + it('also accepts an HMAC-SHA256 of the raw body keyed with the token', async () => { + const rawBody = JSON.stringify(paidBody); + const hex = createHmac('sha256', 'mayar-webhook-secret-token').update(rawBody, 'utf8').digest('hex'); + const base64 = createHmac('sha256', 'mayar-webhook-secret-token').update(rawBody, 'utf8').digest('base64'); + const provider = new MayarPaymentProvider(); + + const byHex = await provider.verifyCallback({ body: paidBody, rawBody, headers: { 'x-mayar-signature': hex.toUpperCase() } }); + const byBase64 = await provider.verifyCallback({ body: paidBody, rawBody, headers: { signature: `sha256=${base64}` } }); + expect(byHex.signatureValid).toBe(true); + expect(byBase64.signatureValid).toBe(true); + }); + + it('rejects an HMAC computed with another key or over another body', async () => { + const rawBody = JSON.stringify(paidBody); + const wrongKey = createHmac('sha256', 'not-the-token').update(rawBody, 'utf8').digest('hex'); + const wrongBody = createHmac('sha256', 'mayar-webhook-secret-token').update('{"tampered":true}', 'utf8').digest('hex'); + const provider = new MayarPaymentProvider(); - const result = await provider.verifyCallback({ - body, - rawBody: JSON.stringify(body), - headers: { 'x-callback-token': 'wrong-token' }, + expect((await provider.verifyCallback({ body: paidBody, rawBody, headers: { 'x-mayar-signature': wrongKey } })).signatureValid).toBe(false); + expect((await provider.verifyCallback({ body: paidBody, rawBody, headers: { 'x-mayar-signature': wrongBody } })).signatureValid).toBe(false); }); - expect(result.signatureValid).toBe(false); + it('accepts a 128-character dashboard Web Token sent in X-Callback-Token', async () => { + const webToken = 'ab'.repeat(64); + MAYAR_ENV.MAYAR_WEBHOOK_TOKEN = `${webToken}\n`; + const result = await new MayarPaymentProvider().verifyCallback({ body: paidBody, headers: { 'x-callback-token': webToken } }); + expect(result.signatureValid).toBe(true); + }); + + it('parses the nested event shape and boolean status', async () => { + const result = await new MayarPaymentProvider().verifyCallback({ + body: { + event: { received: 'payment.received' }, + data: { + productId: PAYMENT_REQUEST_ID, + productName: 'Budi', + description: 'KaffePOS checkout KAF-1700000000000-ABCD1234 [KAF-1700000000000-ABCD1234]', + status: true, + amount: '25000', + }, + }, + headers: { 'x-callback-token': 'mayar-webhook-secret-token' }, + }); + expect(result.internalStatus).toBe('paid'); + expect(result.merchantOrderId).toBe('KAF-1700000000000-ABCD1234'); + expect(result.amount).toBe(25000); + }); + + it('treats payment.reminder as pending and non-payment events as unknown', async () => { + const provider = new MayarPaymentProvider(); + const headers = { 'x-callback-token': 'mayar-webhook-secret-token' }; + const reminder = await provider.verifyCallback({ body: { event: 'payment.reminder', data: { productId: PAYMENT_REQUEST_ID } }, headers }); + const membership = await provider.verifyCallback({ body: { event: 'membership.memberExpired', data: { id: 'm-1', status: 'SUCCESS' } }, headers }); + expect(reminder.internalStatus).toBe('pending'); + expect(membership.internalStatus).toBe('unknown'); + }); + + it('compares tokens in constant time without leaking length', () => { + expect(webhookTokensMatch('abc', 'abc')).toBe(true); + expect(webhookTokensMatch('abc', 'abcd')).toBe(false); + expect(webhookTokensMatch('', 'abc')).toBe(false); + }); }); - it('checks transaction status via GET /hl/v2/payments/:id', async () => { - let capturedUrl = ''; - vi.stubGlobal( - 'fetch', - vi.fn(async (url) => { - capturedUrl = String(url); - return new Response( - JSON.stringify({ + describe('checkTransactionStatus', () => { + it('reads GET /hl/v2/payments/:id with the API key', async () => { + let capturedUrl = ''; + let capturedAuth = ''; + vi.stubGlobal( + 'fetch', + vi.fn(async (url, init) => { + capturedUrl = String(url); + capturedAuth = (init?.headers as Record).Authorization; + return jsonResponse({ statusCode: 200, messages: 'success', + data: { id: PAYMENT_REQUEST_ID, amount: 129000, status: 'paid', description: 'Langganan Signature [SUB-101]', transactions: [] }, + }); + }), + ); + + const status = await new MayarPaymentProvider().checkTransactionStatus({ + merchantOrderId: 'SUB-101', + providerReference: PAYMENT_REQUEST_ID, + }); + + expect(capturedUrl).toBe(`https://api.mayar.io/hl/v2/payments/${PAYMENT_REQUEST_ID}`); + expect(capturedAuth).toBe('Bearer mayar-test-api-key-jwt'); + expect(status.internalStatus).toBe('paid'); + expect(status.merchantOrderId).toBe('SUB-101'); + expect(status.orderIdCandidates).toEqual(['SUB-101']); + expect(status.amount).toBe(129000); + }); + + it('treats a paid entry in transactions[] as paid', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => + jsonResponse({ + statusCode: 200, data: { - id: '6f8c19ff-5b97-4792-aa89-d2a12797b356', - amount: 129000, - status: 'paid', - description: 'Langganan Signature [SUB-101]', + id: PAYMENT_REQUEST_ID, + amount: 25000, + status: 'unpaid', + transactions: [{ id: TRANSACTION_ID, status: 'paid', amount: 25000, updatedAt: 1768375112056 }], }, }), - { status: 200, headers: { 'Content-Type': 'application/json' } }, - ); - }), - ); + ), + ); - const provider = new MayarPaymentProvider(); - const status = await provider.checkTransactionStatus({ - merchantOrderId: 'SUB-101', - providerReference: '6f8c19ff-5b97-4792-aa89-d2a12797b356', + const status = await new MayarPaymentProvider().checkTransactionStatus({ merchantOrderId: 'KAF-1', providerReference: PAYMENT_REQUEST_ID }); + expect(status.internalStatus).toBe('paid'); + expect(status.providerTransactionId).toBe(TRANSACTION_ID); + expect(status.paidAt).toBe(new Date(1768375112056).toISOString()); + }); + + it('reports unpaid requests as pending', async () => { + vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ statusCode: 200, data: { id: PAYMENT_REQUEST_ID, amount: 25000, status: 'unpaid' } }))); + const status = await new MayarPaymentProvider().checkTransactionStatus({ merchantOrderId: 'KAF-1', providerReference: PAYMENT_REQUEST_ID }); + expect(status.internalStatus).toBe('pending'); + expect(status.paidAt).toBeNull(); }); - expect(capturedUrl).toBe('https://api.mayar.club/hl/v2/payments/6f8c19ff-5b97-4792-aa89-d2a12797b356'); - expect(status.internalStatus).toBe('paid'); - expect(status.merchantOrderId).toBe('SUB-101'); - expect(status.amount).toBe(129000); + it('requires a stored provider reference', async () => { + await expect(new MayarPaymentProvider().checkTransactionStatus({ merchantOrderId: 'KAF-1' })).rejects.toMatchObject({ status: 409 }); + }); + + it('maps 404 and 5xx responses to API errors', async () => { + vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ statusCode: 404, messages: 'not found' }, 404))); + await expect( + new MayarPaymentProvider().checkTransactionStatus({ merchantOrderId: 'KAF-1', providerReference: 'missing' }), + ).rejects.toMatchObject({ status: 404 }); + + vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ statusCode: 503, messages: 'down' }, 503))); + await expect( + new MayarPaymentProvider().checkTransactionStatus({ merchantOrderId: 'KAF-1', providerReference: PAYMENT_REQUEST_ID }), + ).rejects.toMatchObject({ status: 502 }); + }); }); it('maps Mayar statuses to internal statuses accurately', () => { const provider = new MayarPaymentProvider(); expect(provider.mapProviderStatus('paid')).toBe('paid'); + expect(provider.mapProviderStatus('SUCCESS')).toBe('paid'); expect(provider.mapProviderStatus('settlement')).toBe('paid'); expect(provider.mapProviderStatus(true)).toBe('paid'); expect(provider.mapProviderStatus('unpaid')).toBe('pending'); @@ -237,5 +438,6 @@ describe('MayarPaymentProvider', () => { expect(provider.mapProviderStatus('failed')).toBe('failed'); expect(provider.mapProviderStatus(false)).toBe('failed'); expect(provider.mapProviderStatus('unknown_val')).toBe('unknown'); + expect(provider.mapProviderStatus(null)).toBe('unknown'); }); }); diff --git a/backend/src/payments/providers/mayar.provider.ts b/backend/src/payments/providers/mayar.provider.ts index c8e2360..8e5b548 100644 --- a/backend/src/payments/providers/mayar.provider.ts +++ b/backend/src/payments/providers/mayar.provider.ts @@ -1,40 +1,118 @@ -import { createHmac, timingSafeEqual } from 'node:crypto'; +/** + * Mayar Headless API v2 payment provider. + * + * Docs: https://docs.mayar.id/api-reference-v2/introduction + * Production API: https://api.mayar.id/hl/v2 — API key from https://web.mayar.id/api-keys + * Sandbox API: https://api.mayar.io/hl/v2 — API key from https://web.mayar.io/api-keys + * + * KaffePOS is wired to Mayar with three things: + * 1. MAYAR_API_KEY Bearer token for every API call (create payment, status check). + * 2. MAYAR_WEBHOOK_TOKEN The "Web Token" from the Mayar dashboard. Mayar sends it in the + * `X-Callback-Token` header; `?token=` on the webhook URL also works. + * 3. Webhook URL `${API_BASE_URL}/api/webhooks/mayar` registered in + * Mayar → Integrasi → Webhook (or with `npm run mayar:connect`). + * + * Mayar does not sign webhook bodies. A `payment.received` event is therefore never + * trusted on its own: the webhook route re-reads the payment request from this API + * (see `checkTransactionStatus`) before anything is marked paid. + */ +import { createHash, createHmac, timingSafeEqual } from 'node:crypto'; import { ApiError, env, log, serializeError } from '../../core'; import { mayarCircuitBreaker } from '../../architecture/circuitBreaker'; import type { CreatePaymentInput, CreatePaymentResult, InternalPaymentStatus, + PaymentCallbackInput, PaymentProvider, PaymentStatusResult, VerifiedPaymentCallback, } from '../payment-provider.types'; -function readHeader( - headers: Record | undefined, - name: string, -): string { +/** Path prefix of the Mayar Headless API v2. */ +export const MAYAR_API_PREFIX = '/hl/v2'; +export const MAYAR_WEBHOOK_UPDATE_PATH = `${MAYAR_API_PREFIX}/webhooks/update`; +export const MAYAR_WEBHOOK_TEST_PATH = `${MAYAR_API_PREFIX}/webhooks/test`; + +/** Webhook events that describe a payment. Everything else (membership, shipping) is ignored. */ +export const MAYAR_PAYMENT_EVENTS = new Set(['payment.received', 'payment.reminder']); + +/** Headers that may carry the webhook token. `X-Callback-Token` is what Mayar sends. */ +const WEBHOOK_TOKEN_HEADERS = ['x-callback-token', 'x-mayar-callback-token', 'x-webhook-token', 'x-mayar-token']; +/** Query-string names accepted for URL-token mode (`/api/webhooks/mayar?token=...`). */ +const WEBHOOK_TOKEN_QUERY_KEYS = ['token', 'webhook_token']; +/** + * Headers that may carry an HMAC-SHA256 of the raw body keyed with the webhook token. + * Mayar documents no signature scheme; accepting one only adds a stricter way to prove + * possession of the same secret. + */ +const WEBHOOK_SIGNATURE_HEADERS = ['x-mayar-signature', 'x-callback-signature', 'x-signature', 'signature']; + +const FALLBACK_MOBILE = '081234567890'; +const FALLBACK_EMAIL = 'customer@kaffepos.my.id'; +const REQUEST_TIMEOUT_MS = 15_000; + +const PAID_STATUSES = new Set([ + 'paid', 'settled', 'settlement', 'success', 'succeeded', 'completed', 'complete', 'true', 'payment.received', +]); +const PENDING_STATUSES = new Set([ + 'unpaid', 'pending', 'created', 'active', 'waiting', 'open', 'processing', 'payment.reminder', +]); +const CANCELLED_STATUSES = new Set(['closed', 'cancelled', 'canceled', 'cancel', 'void']); +const FAILED_STATUSES = new Set(['failed', 'failure', 'fail', 'deny', 'denied', 'rejected', 'false']); + +type MayarResponse = { status: number; ok: boolean; body: Record }; + +function asRecord(value: unknown): Record { + return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record) : {}; +} + +function pickString(...values: unknown[]): string | null { + for (const value of values) { + if (typeof value === 'string' && value.trim()) return value.trim(); + } + return null; +} + +function uniqueStrings(values: Array): string[] { + return Array.from(new Set(values.filter((value): value is string => typeof value === 'string' && value.length > 0))); +} + +function readHeader(headers: Record | undefined, name: string): string { if (!headers) return ''; const target = name.toLowerCase(); for (const [key, value] of Object.entries(headers)) { if (key.toLowerCase() === target) { - return (Array.isArray(value) ? value[0] : value ?? '').trim(); + return (Array.isArray(value) ? value[0] ?? '' : value ?? '').trim(); } } return ''; } -function safeCompare(a: string, b: string): boolean { - if (!a || !b) return false; - const bufA = Buffer.from(a, 'utf8'); - const bufB = Buffer.from(b, 'utf8'); - if (bufA.length !== bufB.length) return false; - return timingSafeEqual(bufA, bufB); +function readQueryValue(query: Record | undefined, name: string): string { + if (!query) return ''; + const value = query[name]; + if (typeof value === 'string') return value.trim(); + if (Array.isArray(value) && typeof value[0] === 'string') return value[0].trim(); + return ''; } -function normalizePhone(phone?: string | null): string { +/** + * Constant-time token comparison. Both sides are hashed first so neither the + * comparison time nor an early length check leaks anything about the secret. + */ +export function webhookTokensMatch(candidate: string, secret: string): boolean { + const left = candidate.trim(); + const right = secret.trim(); + if (!left || !right) return false; + const a = createHash('sha256').update(left, 'utf8').digest(); + const b = createHash('sha256').update(right, 'utf8').digest(); + return timingSafeEqual(a, b); +} + +function normalizePhone(phone?: string | null): string | null { const cleaned = (phone ?? '').replace(/[^\d+]/g, '').trim(); - return cleaned.length >= 8 ? cleaned : '081234567890'; + return cleaned.replace(/\D/g, '').length >= 10 ? cleaned : null; } function extractBracketOrderId(text: unknown): string | null { @@ -49,97 +127,152 @@ function parseTimestamp(value: unknown): string | null { return new Date(ms).toISOString(); } if (typeof value === 'string' && value.trim()) { - const parsed = Date.parse(value.trim()); + const trimmed = value.trim(); + if (/^\d+$/.test(trimmed)) return parseTimestamp(Number(trimmed)); + const parsed = Date.parse(trimmed); if (!Number.isNaN(parsed)) return new Date(parsed).toISOString(); } return null; } +function parseAmount(...values: unknown[]): number | null { + for (const value of values) { + if (value === null || value === undefined || value === '') continue; + const amount = Number(value); + if (Number.isFinite(amount)) return Math.round(amount); + } + return null; +} + +/** + * Mayar returns `messages` (or `message`); validation errors add an array of + * details in `data`. All of them are joined so callers can match on any part. + */ +export function extractMayarMessage(body: Record): string | null { + const parts: string[] = []; + for (const candidate of [body.messages, body.message, body.data]) { + if (typeof candidate === 'string' && candidate.trim()) { + parts.push(candidate.trim()); + } else if (Array.isArray(candidate)) { + for (const entry of candidate) { + const text = typeof entry === 'string' ? entry : pickString(asRecord(entry).message, asRecord(entry).msg); + if (text) parts.push(text.trim()); + } + } + } + return parts.length ? Array.from(new Set(parts)).join('; ') : null; +} + +/** Event name from either `{ event: "payment.received" }` or `{ event: { received: "payment.received" } }`. */ +export function extractMayarEventName(body: Record): string | null { + if (typeof body.event === 'string' && body.event.trim()) return body.event.trim().toLowerCase(); + const eventObject = asRecord(body.event); + const nested = pickString(eventObject.received, eventObject.name, eventObject.type); + if (nested) return nested.toLowerCase(); + const fallback = pickString(body.type, body.eventType, body.event_type); + return fallback ? fallback.toLowerCase() : null; +} + export class MayarPaymentProvider implements PaymentProvider { readonly providerName = 'mayar' as const; - private get apiKey() { - if (!env.MAYAR_API_KEY) { + get baseUrl(): string { + const base = env.MAYAR_ENVIRONMENT === 'production' ? env.MAYAR_PRODUCTION_BASE_URL : env.MAYAR_SANDBOX_BASE_URL; + return base.replace(/\/+$/, ''); + } + + /** Webhook token configured for this deployment, or null when it is missing. */ + get webhookToken(): string | null { + const token = env.MAYAR_WEBHOOK_TOKEN?.trim(); + return token ? token : null; + } + + private get apiKey(): string { + const key = env.MAYAR_API_KEY?.trim(); + if (!key) { throw new ApiError(503, 'Mayar API key belum dikonfigurasi.'); } - return env.MAYAR_API_KEY; + return key; } - private get webhookSecret() { - const secret = env.MAYAR_WEBHOOK_TOKEN || env.MAYAR_API_KEY; - if (!secret) { - throw new ApiError(503, 'Mayar webhook token / API key belum dikonfigurasi.'); - } - return secret; + private resolvePath(path: string): string { + const trimmed = path.trim(); + return trimmed.startsWith('/') ? trimmed : `/${trimmed}`; } - private get baseUrl() { - const base = - env.MAYAR_ENVIRONMENT === 'production' - ? env.MAYAR_PRODUCTION_BASE_URL - : env.MAYAR_SANDBOX_BASE_URL; - return base.replace(/\/$/, ''); + /** + * Authenticated call to the Mayar API. Network errors and 5xx responses count + * against the circuit breaker; 4xx responses are returned to the caller. + */ + private async request(method: 'GET' | 'POST', path: string, payload?: Record): Promise { + const url = `${this.baseUrl}${this.resolvePath(path)}`; + const apiKey = this.apiKey; + return mayarCircuitBreaker.execute(async () => { + const response = await fetch(url, { + method, + headers: { + Authorization: `Bearer ${apiKey}`, + Accept: 'application/json', + ...(payload ? { 'Content-Type': 'application/json' } : {}), + }, + ...(payload ? { body: JSON.stringify(payload) } : {}), + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + const body = asRecord(await response.json().catch(() => ({}))); + if (response.status >= 500) { + throw new ApiError(502, `Mayar sedang tidak bisa dihubungi (${response.status}).`); + } + return { status: response.status, ok: response.ok, body }; + }); } - private mapPaymentMethodChannel(method?: string | null): string | undefined { + /** Mayar payment channel id for a KaffePOS payment method id (informational only). */ + mapPaymentMethodChannel(method?: string | null): string | undefined { const normalized = (method ?? '').trim().toLowerCase(); if (!normalized) return undefined; if (normalized === 'qris') return 'qris'; if (normalized === 'bni_va' || normalized === 'va/bni') return 'va/bni'; if (normalized === 'bri_va' || normalized === 'va/bri') return 'va/bri'; - if (normalized === 'mandiri_bill' || normalized === 'va/mandiri') return 'va/mandiri'; + if (normalized === 'mandiri_bill' || normalized === 'mandiri_va' || normalized === 'va/mandiri') return 'va/mandiri'; if (normalized === 'cimb_va' || normalized === 'va/cimb') return 'va/cimb'; if (normalized === 'permata_va' || normalized === 'va/permata') return 'va/permata'; + if (normalized === 'bjb_va' || normalized === 'va/bjb') return 'va/bjb'; if (normalized === 'bsi_va' || normalized === 'va/bsi') return 'va/bsi'; return undefined; } - verifyWebhookSignature(params: { - headers?: Record; - rawBody?: string; - body: Record; - }): boolean { - let secret = ''; - try { - secret = this.webhookSecret; - } catch { - return false; - } - - const bearerRaw = readHeader(params.headers, 'authorization'); - const bearerToken = bearerRaw.toLowerCase().startsWith('bearer ') - ? bearerRaw.slice(7).trim() - : bearerRaw; - + /** + * Checks the webhook against MAYAR_WEBHOOK_TOKEN (the dashboard "Web Token"). + * Accepts the `X-Callback-Token` header (and a few aliases), `Authorization: Bearer`, + * `?token=` on the webhook URL, or an HMAC-SHA256 of the raw body keyed with the token. + * The API key is never accepted as a webhook token. + */ + verifyWebhookToken(params: Pick): boolean { + const secret = this.webhookToken; + if (!secret) return false; + + const authorization = readHeader(params.headers, 'authorization'); + const bearer = /^bearer\s+/i.test(authorization) ? authorization.replace(/^bearer\s+/i, '').trim() : ''; + const signatures = WEBHOOK_SIGNATURE_HEADERS.map((name) => + readHeader(params.headers, name).replace(/^(sha256|hmacsha256|hmac-sha256)=/i, '').trim(), + ).filter(Boolean); const candidates = [ - readHeader(params.headers, 'x-callback-token'), - readHeader(params.headers, 'x-mayar-token'), - readHeader(params.headers, 'x-webhook-token'), - readHeader(params.headers, 'x-mayar-signature'), - readHeader(params.headers, 'signature'), - bearerToken, - typeof params.body.webhookToken === 'string' ? params.body.webhookToken.trim() : '', + ...WEBHOOK_TOKEN_HEADERS.map((name) => readHeader(params.headers, name)), + bearer, + ...WEBHOOK_TOKEN_QUERY_KEYS.map((name) => readQueryValue(params.query, name)), + ...signatures, ].filter(Boolean); - if (candidates.length === 0) return false; - - const rawBody = params.rawBody ?? JSON.stringify(params.body); - const hmacHex = createHmac('sha256', secret).update(rawBody, 'utf8').digest('hex'); - const hmacBase64 = createHmac('sha256', secret).update(rawBody, 'utf8').digest('base64'); - - for (const candidate of candidates) { - if ( - safeCompare(candidate, secret) || - safeCompare(candidate, hmacHex) || - safeCompare(candidate, hmacBase64) || - safeCompare(candidate, `HMACSHA256=${hmacBase64}`) || - (env.MAYAR_API_KEY && safeCompare(candidate, env.MAYAR_API_KEY)) - ) { - return true; - } - } + if (candidates.some((candidate) => webhookTokensMatch(candidate, secret))) return true; + if (signatures.length === 0) return false; - return false; + const rawBody = params.rawBody ?? (params.body ? JSON.stringify(params.body) : ''); + if (!rawBody) return false; + const hex = createHmac('sha256', secret).update(rawBody, 'utf8').digest('hex'); + const base64 = createHmac('sha256', secret).update(rawBody, 'utf8').digest('base64'); + return signatures.some( + (signature) => webhookTokensMatch(signature.toLowerCase(), hex) || webhookTokensMatch(signature, base64), + ); } async createPayment(input: CreatePaymentInput): Promise { @@ -148,24 +281,29 @@ export class MayarPaymentProvider implements PaymentProvider { } const amount = Math.round(input.amount); - const expiredAt = new Date( - Date.now() + env.MAYAR_PAYMENT_DUE_MINUTES * 60_000, - ).toISOString(); - const redirectUrl = input.returnUrl ?? env.MAYAR_REDIRECT_URL ?? undefined; - const isInvoiceEndpoint = env.MAYAR_CREATE_PAYMENT_PATH.includes('/invoices/'); - - const basePayload: Record = { - name: (input.customerName || input.productDetails || input.merchantOrderId).slice(0, 100), + const expiredAt = new Date(Date.now() + env.MAYAR_PAYMENT_DUE_MINUTES * 60_000).toISOString(); + const redirectUrl = input.returnUrl?.trim() || undefined; + const createPath = this.resolvePath(env.MAYAR_CREATE_PAYMENT_PATH); + const isInvoiceEndpoint = createPath.includes('/invoices/'); + const mobile = normalizePhone(input.customerPhone); + const title = (input.customerName || input.productDetails || input.merchantOrderId).slice(0, 100); + const description = `${(input.productDetails || input.merchantOrderId).slice(0, 180)} [${input.merchantOrderId}]`; + + const payload: Record = { + name: title, amount, - email: input.customerEmail || 'customer@kaffepos.my.id', - mobile: normalizePhone(input.customerPhone), - description: `${(input.productDetails || input.merchantOrderId).slice(0, 180)} [${input.merchantOrderId}]`, + email: input.customerEmail || FALLBACK_EMAIL, + // Invoices require a phone number; payment requests do not, so we only + // send a placeholder where Mayar insists on one. + ...(mobile ? { mobile } : isInvoiceEndpoint ? { mobile: FALLBACK_MOBILE } : {}), + description, expiredAt, ...(redirectUrl ? { redirectUrl } : {}), extraData: { + ...(input.metadata ?? {}), merchantOrderId: input.merchantOrderId, orderId: input.merchantOrderId, - ...(input.metadata ?? {}), + source: 'kaffepos', }, ...(isInvoiceEndpoint ? { @@ -176,94 +314,64 @@ export class MayarPaymentProvider implements PaymentProvider { rate: Math.round(item.price), quantity: item.quantity, })) - : [ - { - description: (input.productDetails || input.merchantOrderId).slice(0, 100), - rate: amount, - quantity: 1, - }, - ], + : [{ description: (input.productDetails || input.merchantOrderId).slice(0, 100), rate: amount, quantity: 1 }], } : {}), }; - const targetPath = env.MAYAR_CREATE_PAYMENT_PATH.startsWith('/') - ? env.MAYAR_CREATE_PAYMENT_PATH - : `/${env.MAYAR_CREATE_PAYMENT_PATH}`; - const url = `${this.baseUrl}${targetPath}`; - - const sendCreateRequest = async (payloadObj: Record) => { - return mayarCircuitBreaker.execute(async () => { - const response = await fetch(url, { - method: 'POST', - headers: { - Authorization: `Bearer ${this.apiKey}`, - Accept: 'application/json', - 'Content-Type': 'application/json', - }, - body: JSON.stringify(payloadObj), - signal: AbortSignal.timeout(15_000), - }); - const body = (await response.json().catch(() => ({}))) as Record; - return { response, body }; - }); - }; - try { log('info', 'mayar.create_payment_request', { environment: env.MAYAR_ENVIRONMENT, baseUrl: this.baseUrl, - target: targetPath, + target: createPath, merchantOrderId: input.merchantOrderId, amount, redirectUrlConfigured: Boolean(redirectUrl), }); - let { response, body } = await sendCreateRequest(basePayload); - - // Mayar /hl/v2/payments/create rejects redirectUrl with 400 if the account/record - // does not persist redirectUrl; retry cleanly without redirectUrl when that happens. - if ( - !response.ok && - response.status === 400 && - redirectUrl && - typeof body.messages === 'string' && - body.messages.toLowerCase().includes('redirecturl') - ) { - const retryPayload = { ...basePayload }; - delete retryPayload.redirectUrl; - ({ response, body } = await sendCreateRequest(retryPayload)); + let { status, ok, body } = await this.request('POST', createPath, payload); + + // Mayar rejects some optional fields depending on the account/endpoint: + // - payment requests may refuse `redirectUrl` ("redirectUrl is not supported ...") + // - some endpoints insist on `mobile` + // Retry once per field with the payload adjusted. + for (let attempt = 0; attempt < 2 && !ok && status === 400; attempt += 1) { + const message = (extractMayarMessage(body) ?? '').toLowerCase(); + if (payload.redirectUrl && message.includes('redirecturl')) { + delete payload.redirectUrl; + } else if (!payload.mobile && message.includes('mobile')) { + payload.mobile = FALLBACK_MOBILE; + } else { + break; + } + ({ status, ok, body } = await this.request('POST', createPath, payload)); } - const data = (body.data ?? body) as Record; - const paymentUrl = - typeof data.link === 'string' - ? data.link - : typeof data.linkPayment === 'string' - ? data.linkPayment - : typeof data.paymentUrl === 'string' - ? data.paymentUrl - : typeof data.linkUrl === 'string' - ? data.linkUrl - : null; - const providerReference = - typeof data.id === 'string' - ? data.id - : typeof data.transactionId === 'string' - ? data.transactionId - : null; - - log(response.ok ? 'info' : 'warn', 'mayar.create_payment_response', { + const data = asRecord(body.data ?? body); + const paymentUrl = pickString(data.link, data.linkPayment, data.paymentUrl, data.linkUrl, data.url); + const providerReference = pickString(data.id, data.paymentRequestId, data.invoiceId); + const providerTransactionId = pickString(data.transactionId, data.transaction_id); + const message = extractMayarMessage(body); + + log(ok ? 'info' : 'warn', 'mayar.create_payment_response', { environment: env.MAYAR_ENVIRONMENT, - status: response.status, + status, merchantOrderId: input.merchantOrderId, hasPaymentUrl: Boolean(paymentUrl), providerReference, - message: typeof body.messages === 'string' ? body.messages : null, + providerTransactionId, + message, + hint: + status === 401 || status === 403 + ? 'Periksa MAYAR_API_KEY dan pastikan MAYAR_ENVIRONMENT cocok dengan asal key (sandbox vs production).' + : undefined, }); - if (!response.ok) { - throw new ApiError(502, `Mayar create payment gagal (${response.status}).`); + if (status === 429) { + throw new ApiError(502, 'Mayar menolak permintaan ganda. Tunggu 1 menit lalu coba lagi.'); + } + if (!ok) { + throw new ApiError(502, `Mayar create payment gagal (${status}).`); } if (!paymentUrl) { throw new ApiError(502, 'Mayar create payment tidak mengembalikan link pembayaran.'); @@ -272,12 +380,13 @@ export class MayarPaymentProvider implements PaymentProvider { return { provider: 'mayar', merchantOrderId: input.merchantOrderId, - providerReference, + providerReference: providerReference ?? providerTransactionId, + providerTransactionId, paymentUrl, - vaNumber: typeof data.vaNumber === 'string' ? data.vaNumber : null, - qrString: typeof data.qrString === 'string' ? data.qrString : null, + vaNumber: pickString(data.vaNumber, data.va_number), + qrString: pickString(data.qrString, data.qr_string, data.qrisString), paymentMethod: this.mapPaymentMethodChannel(input.paymentMethod) ?? input.paymentMethod ?? 'MAYAR_CHECKOUT', - providerStatus: typeof body.messages === 'string' ? body.messages : 'PENDING', + providerStatus: 'PENDING', internalStatus: 'pending', raw: body, }; @@ -286,94 +395,62 @@ export class MayarPaymentProvider implements PaymentProvider { merchantOrderId: input.merchantOrderId, error: serializeError(error), }); - throw error instanceof ApiError - ? error - : new ApiError(502, 'Gagal menghubungi gateway pembayaran Mayar.'); + throw error instanceof ApiError ? error : new ApiError(502, 'Gagal menghubungi gateway pembayaran Mayar.'); } } - async verifyCallback(input: { - body: Record; - headers?: Record; - rawBody?: string; - }): Promise { - const body = input.body ?? {}; - const data = ((body.data && typeof body.data === 'object' ? body.data : body) ?? {}) as Record< - string, - unknown - >; - const extraData = ((data.extraData && typeof data.extraData === 'object' - ? data.extraData - : body.extraData && typeof body.extraData === 'object' - ? body.extraData - : {}) ?? {}) as Record; - - const eventObj = body.event && typeof body.event === 'object' ? (body.event as Record) : null; - const eventName = - typeof body.event === 'string' - ? body.event - : typeof eventObj?.received === 'string' - ? eventObj.received - : null; - - const signatureValid = this.verifyWebhookSignature({ - headers: input.headers, - rawBody: input.rawBody, - body, - }); - - const explicitOrderId = - typeof extraData.merchantOrderId === 'string' - ? extraData.merchantOrderId - : typeof extraData.orderId === 'string' - ? extraData.orderId - : typeof data.merchantOrderId === 'string' - ? data.merchantOrderId - : typeof body.merchantOrderId === 'string' - ? body.merchantOrderId - : extractBracketOrderId(data.productName) ?? - extractBracketOrderId(data.description) ?? - extractBracketOrderId(data.name); - - const providerReference = - typeof data.productId === 'string' - ? data.productId - : typeof data.paymentLinkId === 'string' - ? data.paymentLinkId - : typeof data.invoiceId === 'string' - ? data.invoiceId - : typeof data.id === 'string' - ? data.id - : typeof data.transactionId === 'string' - ? data.transactionId - : null; - - const merchantOrderId = explicitOrderId ?? providerReference; + /** + * Authenticates and parses a Mayar webhook. This only proves the request came + * from someone holding the webhook token — callers must still confirm a paid + * status with `checkTransactionStatus` before settling anything. + */ + async verifyCallback(input: PaymentCallbackInput): Promise { + const body = asRecord(input.body); + const data = Object.keys(asRecord(body.data)).length > 0 ? asRecord(body.data) : body; + const extraData = Object.keys(asRecord(data.extraData)).length > 0 ? asRecord(data.extraData) : asRecord(body.extraData); + const eventType = extractMayarEventName(body); + const signatureValid = this.verifyWebhookToken({ headers: input.headers, query: input.query, rawBody: input.rawBody, body }); + + const orderIdCandidates = uniqueStrings([ + pickString(extraData.merchantOrderId), + pickString(extraData.orderId), + pickString(data.merchantOrderId), + pickString(body.merchantOrderId), + extractBracketOrderId(data.description), + extractBracketOrderId(data.productDescription), + extractBracketOrderId(data.productName), + extractBracketOrderId(data.name), + ]); + + // `productId` is the payment request / invoice id that `createPayment` stored as + // provider_reference. The other ids are kept as lookup fallbacks. + const providerReference = pickString(data.productId, data.paymentRequestId, data.paymentLinkId, data.invoiceId); + const providerTransactionId = pickString(data.transactionId, data.transaction_id); + const referenceCandidates = uniqueStrings([providerReference, providerTransactionId, pickString(data.id)]); let rawStatus: string | null = null; if (typeof data.status === 'boolean') { rawStatus = data.status ? 'PAID' : 'FAILED'; - } else if (typeof data.status === 'string' && data.status.trim()) { - rawStatus = data.status.trim(); - } else if (typeof data.transactionStatus === 'string' && data.transactionStatus.trim()) { - rawStatus = data.transactionStatus.trim(); - } else if (eventName) { - rawStatus = eventName; + } else if (pickString(data.status)) { + rawStatus = pickString(data.status); + } else if (eventType) { + rawStatus = eventType; } - const internalStatus = - eventName === 'payment.received' && data.status !== false - ? 'paid' - : this.mapProviderStatus(rawStatus); - - const amountRaw = Number(data.amount ?? body.amount ?? NaN); - const amount = Number.isFinite(amountRaw) ? Math.round(amountRaw) : null; - const paymentMethod = - typeof data.paymentMethod === 'string' - ? data.paymentMethod - : typeof data.paymentType === 'string' - ? data.paymentType - : 'MAYAR'; + let internalStatus: InternalPaymentStatus; + if (eventType === 'payment.received') { + const statusMapping = rawStatus && rawStatus !== eventType ? this.mapProviderStatus(rawStatus) : 'paid'; + internalStatus = statusMapping === 'failed' || statusMapping === 'cancelled' || statusMapping === 'expired' ? statusMapping : 'paid'; + } else if (eventType === 'payment.reminder') { + internalStatus = 'pending'; + } else if (eventType && !MAYAR_PAYMENT_EVENTS.has(eventType)) { + // membership.*, shipper.status, testing events: not a payment state change. + internalStatus = 'unknown'; + } else { + internalStatus = this.mapProviderStatus(rawStatus); + } + + const amount = parseAmount(data.amount, body.amount); const paidAt = internalStatus === 'paid' ? parseTimestamp(data.paidAt ?? data.updatedAt ?? data.createdAt) ?? new Date().toISOString() @@ -382,10 +459,14 @@ export class MayarPaymentProvider implements PaymentProvider { return { provider: 'mayar', signatureValid, - merchantOrderId, - providerReference, + eventType, + merchantOrderId: orderIdCandidates[0] ?? null, + providerReference: providerReference ?? providerTransactionId ?? pickString(data.id), + providerTransactionId, + orderIdCandidates, + referenceCandidates, amount, - paymentMethod, + paymentMethod: pickString(data.paymentMethod, data.paymentType, data.paymentChannel) ?? 'MAYAR', rawStatus, internalStatus, paidAt, @@ -393,66 +474,71 @@ export class MayarPaymentProvider implements PaymentProvider { }; } + /** + * Reads a payment request from Mayar (`GET /hl/v2/payments/{id}`) — the source of + * truth used to confirm webhooks and manual "cek status" requests. + */ async checkTransactionStatus(input: { merchantOrderId: string; providerReference?: string | null; amount?: number | null; }): Promise { - const lookupId = input.providerReference?.trim() || input.merchantOrderId; - const prefix = env.MAYAR_STATUS_PATH_PREFIX.replace(/\/$/, ''); - const targetPath = `${prefix.startsWith('/') ? prefix : `/${prefix}`}/${encodeURIComponent(lookupId)}`; - const { body } = await mayarCircuitBreaker.execute(async () => { - const res = await fetch(`${this.baseUrl}${targetPath}`, { - method: 'GET', - headers: { - Authorization: `Bearer ${this.apiKey}`, - Accept: 'application/json', - }, - signal: AbortSignal.timeout(15_000), - }); - if (!res.ok) { - throw new ApiError(502, `Mayar check status gagal (${res.status}).`); - } - const parsed = (await res.json().catch(() => ({}))) as Record; - return { response: res, body: parsed }; - }); + const lookupId = input.providerReference?.trim(); + if (!lookupId) { + throw new ApiError(409, 'Referensi pembayaran Mayar belum tersedia untuk order ini.'); + } + const prefix = this.resolvePath(env.MAYAR_STATUS_PATH_PREFIX).replace(/\/+$/, ''); + let response: MayarResponse; + try { + response = await this.request('GET', `${prefix}/${encodeURIComponent(lookupId)}`); + } catch (error) { + log('warn', 'mayar.check_status_unreachable', { merchantOrderId: input.merchantOrderId, error: serializeError(error) }); + throw error instanceof ApiError ? error : new ApiError(502, 'Gagal menghubungi Mayar untuk cek status pembayaran.'); + } + const { status, ok, body } = response; + if (status === 404) { + throw new ApiError(404, 'Pembayaran tidak ditemukan di Mayar.'); + } + if (!ok) { + log('warn', 'mayar.check_status_failed', { status, merchantOrderId: input.merchantOrderId, message: extractMayarMessage(body) }); + throw new ApiError(502, `Mayar check status gagal (${status}).`); + } + + const data = asRecord(body.data ?? body); + const extraData = asRecord(data.extraData); + const transactions = Array.isArray(data.transactions) ? data.transactions.map(asRecord) : []; + const paidTransaction = transactions.find((entry) => this.mapProviderStatus(entry.status) === 'paid'); + + let rawStatus = pickString(data.status, body.status); + let internalStatus = this.mapProviderStatus(rawStatus); + if (internalStatus !== 'paid' && paidTransaction) { + rawStatus = pickString(paidTransaction.status) ?? 'paid'; + internalStatus = 'paid'; + } - const data = ((body.data && typeof body.data === 'object' ? body.data : body) ?? {}) as Record< - string, - unknown - >; - const extraData = ((data.extraData && typeof data.extraData === 'object' ? data.extraData : {}) ?? - {}) as Record; - const rawStatus = - typeof data.status === 'string' - ? data.status - : typeof body.status === 'string' - ? body.status - : null; - const internalStatus = this.mapProviderStatus(rawStatus); - const amountRaw = Number(data.amount ?? input.amount ?? NaN); const merchantOrderId = - (typeof extraData.merchantOrderId === 'string' ? extraData.merchantOrderId : null) ?? + pickString(extraData.merchantOrderId, extraData.orderId) ?? extractBracketOrderId(data.description) ?? extractBracketOrderId(data.name) ?? - input.merchantOrderId; - const providerReference = - typeof data.id === 'string' - ? data.id - : typeof data.transactionId === 'string' - ? data.transactionId - : input.providerReference ?? null; + null; return { provider: 'mayar', signatureValid: true, - merchantOrderId, - providerReference, - amount: Number.isFinite(amountRaw) ? Math.round(amountRaw) : null, - paymentMethod: typeof data.paymentMethod === 'string' ? data.paymentMethod : 'MAYAR', + eventType: 'status_check', + merchantOrderId: merchantOrderId ?? input.merchantOrderId, + providerReference: pickString(data.id) ?? lookupId, + providerTransactionId: pickString(paidTransaction?.id, data.transactionId), + orderIdCandidates: uniqueStrings([merchantOrderId]), + referenceCandidates: uniqueStrings([pickString(data.id), lookupId]), + amount: parseAmount(data.amount, paidTransaction?.amount, input.amount), + paymentMethod: pickString(paidTransaction?.paymentMethod, data.paymentMethod) ?? 'MAYAR', rawStatus, internalStatus, - paidAt: internalStatus === 'paid' ? new Date().toISOString() : null, + paidAt: + internalStatus === 'paid' + ? parseTimestamp(paidTransaction?.updatedAt ?? paidTransaction?.createdAt ?? data.updatedAt) ?? new Date().toISOString() + : null, raw: body, }; } @@ -461,48 +547,13 @@ export class MayarPaymentProvider implements PaymentProvider { if (rawStatus === true) return 'paid'; if (rawStatus === false) return 'failed'; const normalized = String(rawStatus ?? '').trim().toLowerCase(); - if ( - normalized === 'paid' || - normalized === 'settled' || - normalized === 'settlement' || - normalized === 'success' || - normalized === 'completed' || - normalized === 'true' || - normalized === 'payment.received' - ) { - return 'paid'; - } - if ( - normalized === 'unpaid' || - normalized === 'pending' || - normalized === 'created' || - normalized === 'active' || - normalized === 'waiting' || - normalized === 'open' || - normalized === 'payment.reminder' - ) { - return 'pending'; - } + if (!normalized) return 'unknown'; + if (PAID_STATUSES.has(normalized)) return 'paid'; + if (PENDING_STATUSES.has(normalized)) return 'pending'; if (normalized === 'expired' || normalized === 'expire') return 'expired'; - if ( - normalized === 'closed' || - normalized === 'cancelled' || - normalized === 'canceled' || - normalized === 'cancel' || - normalized === 'void' - ) { - return 'cancelled'; - } + if (CANCELLED_STATUSES.has(normalized)) return 'cancelled'; if (normalized === 'refunded' || normalized === 'refund') return 'refunded'; - if ( - normalized === 'failed' || - normalized === 'failure' || - normalized === 'deny' || - normalized === 'rejected' || - normalized === 'false' - ) { - return 'failed'; - } + if (FAILED_STATUSES.has(normalized)) return 'failed'; return 'unknown'; } } diff --git a/backend/src/routes/__tests__/webhooks.test.ts b/backend/src/routes/__tests__/webhooks.test.ts index d6749f6..3854051 100644 --- a/backend/src/routes/__tests__/webhooks.test.ts +++ b/backend/src/routes/__tests__/webhooks.test.ts @@ -1,30 +1,39 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; -import { randomUUID } from 'node:crypto'; + +const mocks = vi.hoisted(() => ({ + poolQuery: vi.fn(), + clientQuery: vi.fn(), + tokenConfigured: vi.fn(() => true), + verifyCallback: vi.fn(), + checkTransactionStatus: vi.fn(), +})); vi.mock('../../core', async () => { const actual = await vi.importActual('../../core'); return { ...actual, - withTransaction: vi.fn(async (cb) => cb({ query: vi.fn().mockResolvedValue({ rows: [] }), release: vi.fn() })), + pool: { query: mocks.poolQuery }, + withTransaction: vi.fn(async (cb) => cb({ query: mocks.clientQuery, release: vi.fn() })), ApiError: class ApiError extends Error { constructor(public status: number, message: string) { super(message); } }, log: vi.fn(), serializeError: vi.fn((e: unknown) => String(e)), insertNotification: vi.fn(), broadcastKitchenEvent: vi.fn(), - activatePaidSubscription: vi.fn(), + activatePaidSubscription: vi.fn().mockResolvedValue(null), sendPaymentSuccessEmail: vi.fn(), + isMayarWebhookTokenConfigured: mocks.tokenConfigured, }; }); vi.mock('../../services/PaymentService', () => ({ PaymentService: { - finalizePaidOrder: vi.fn().mockResolvedValue({ transactionId: null, kitchenOrder: null }), + finalizePaidOrder: vi.fn().mockResolvedValue({ transactionId: 'tx-1', kitchenOrder: null }), voidCompletedOrderTransaction: vi.fn(), }, })); vi.mock('../../services/CommissionService', () => ({ - CommissionService: { createFromSubscriptionPayment: vi.fn() }, + CommissionService: vi.fn(), })); vi.mock('../../lib/config/feature-flags', () => ({ @@ -37,141 +46,249 @@ vi.mock('../../lib/alerting', () => ({ vi.mock('../../payments/payment-provider.factory', () => ({ createPaymentProvider: vi.fn(() => ({ - verifyCallback: vi.fn().mockResolvedValue({ - signatureValid: true, - merchantOrderId: `ORDER-${randomUUID()}`, - internalStatus: 'paid', - rawStatus: 'SUCCESS', - amount: 50000, - provider: 'doku', - providerReference: 'DOKU-REF-001', - paymentMethod: 'QRIS', - paidAt: new Date().toISOString(), - raw: {}, - }), + providerName: 'mayar', + verifyCallback: mocks.verifyCallback, + checkTransactionStatus: mocks.checkTransactionStatus, })), })); -import { createPaymentProvider } from '../../payments/payment-provider.factory'; +import router from '../webhooks'; +import { activatePaidSubscription } from '../../core'; +import { PaymentService } from '../../services/PaymentService'; import { alertOnPaymentWebhookFailure } from '../../lib/alerting'; -describe('DOKU webhook handler', () => { - const makeReq = (overrides?: Record) => ({ - body: { order: { invoice_number: `ORDER-${randomUUID()}` }, transaction: { status: 'SUCCESS' } }, - headers: { 'signature': 'test-sig' }, - rawBody: '{}', +const PAYMENT_REQUEST_ID = '6f8c19ff-5b97-4792-aa89-d2a12797b356'; + +function findHandler(path: string, method: 'get' | 'post') { + const layer = (router as any).stack?.find((l: any) => l.route?.path === path && l.route?.methods?.[method]); + return layer?.route?.stack?.[0]?.handle as ((req: any, res: any, next: any) => Promise) | undefined; +} + +function webhookResult(overrides: Record = {}) { + return { + provider: 'mayar', + signatureValid: true, + eventType: 'payment.received', + merchantOrderId: 'KAF-1700000000000-ABCD1234', + providerReference: PAYMENT_REQUEST_ID, + providerTransactionId: 'trx-1', + orderIdCandidates: ['KAF-1700000000000-ABCD1234'], + referenceCandidates: [PAYMENT_REQUEST_ID, 'trx-1'], + amount: 25000, + paymentMethod: 'QRIS', + rawStatus: 'SUCCESS', + internalStatus: 'paid', + paidAt: '2026-11-16T03:00:00.000Z', + raw: { event: 'payment.received' }, ...overrides, - }); + }; +} - const makeRes = () => { - const res = { status: vi.fn(), json: vi.fn() }; - res.status.mockReturnValue(res); - return res; +function confirmedResult(overrides: Record = {}) { + return { + provider: 'mayar', + signatureValid: true, + eventType: 'status_check', + merchantOrderId: 'KAF-1700000000000-ABCD1234', + providerReference: PAYMENT_REQUEST_ID, + orderIdCandidates: ['KAF-1700000000000-ABCD1234'], + referenceCandidates: [PAYMENT_REQUEST_ID], + amount: 25000, + paymentMethod: 'MAYAR', + rawStatus: 'paid', + internalStatus: 'paid', + paidAt: '2026-11-16T03:00:01.000Z', + raw: { data: { status: 'paid' } }, + ...overrides, }; +} - const next = vi.fn(); +const posOrderRow = { + id: 'po-1', + merchant_order_id: 'KAF-1700000000000-ABCD1234', + provider_reference: PAYMENT_REQUEST_ID, + amount: 25000, + status: 'pending', +}; + +const makeReq = (overrides: Record = {}) => ({ + body: { event: 'payment.received', data: { productId: PAYMENT_REQUEST_ID } }, + headers: { 'x-callback-token': 'secret' }, + query: {}, + rawBody: '{}', + ...overrides, +}); + +const makeRes = () => { + const res = { status: vi.fn(), json: vi.fn() }; + res.status.mockReturnValue(res); + return res; +}; + +describe('Mayar webhook route', () => { + const handler = findHandler('/api/webhooks/mayar', 'post')!; beforeEach(() => { vi.clearAllMocks(); + for (const mock of [mocks.poolQuery, mocks.clientQuery, mocks.verifyCallback, mocks.checkTransactionStatus]) { + mock.mockReset(); + } + mocks.tokenConfigured.mockReturnValue(true); + mocks.poolQuery.mockResolvedValue({ rows: [] }); + mocks.clientQuery.mockResolvedValue({ rows: [] }); }); - it('registers POST /api/webhooks/mayar and POST /api/webhooks/doku routes', async () => { - const webhooksModule = await import('../webhooks'); - const router = webhooksModule.default; - const mayarRoute = (router as any).stack?.find((l: any) => l.route?.path === '/api/webhooks/mayar' && l.route?.methods?.post); - const dokuRoute = (router as any).stack?.find((l: any) => l.route?.path === '/api/webhooks/doku' && l.route?.methods?.post); - expect(mayarRoute).toBeDefined(); - expect(dokuRoute).toBeDefined(); + it('registers GET + POST /api/webhooks/mayar and no DOKU route', () => { + expect(findHandler('/api/webhooks/mayar', 'post')).toBeDefined(); + expect(findHandler('/api/webhooks/mayar', 'get')).toBeDefined(); + expect(findHandler('/api/webhooks/doku', 'post')).toBeUndefined(); }); - it('rejects Mayar webhook with invalid signature/token', async () => { - vi.mocked(createPaymentProvider).mockReturnValueOnce({ - verifyCallback: vi.fn().mockResolvedValue({ - signatureValid: false, - merchantOrderId: 'MAYAR-ORDER-INVALID', - internalStatus: 'unknown', - rawStatus: 'INVALID', - amount: null, - provider: 'mayar', - providerReference: null, - paymentMethod: null, - paidAt: null, - raw: {}, - }), - } as any); - - const webhooksModule = await import('../webhooks'); - const router = webhooksModule.default; - const mayarRoute = (router as any).stack?.find((l: any) => l.route?.path === '/api/webhooks/mayar' && l.route?.methods?.post); - const handler = mayarRoute?.route?.stack?.[0]?.handle; - - if (!handler) { - expect(true).toBe(true); - return; - } + it('reports whether the webhook token is configured on GET', async () => { + const res = makeRes(); + await findHandler('/api/webhooks/mayar', 'get')!({}, res, vi.fn()); + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ ok: true, provider: 'mayar', webhookTokenConfigured: true })); + }); - const req = makeReq() as any; - const res = makeRes() as any; + it('answers 503 (so Mayar retries) when MAYAR_WEBHOOK_TOKEN is missing', async () => { + mocks.tokenConfigured.mockReturnValue(false); + const next = vi.fn(); + await handler(makeReq(), makeRes(), next); + expect(next).toHaveBeenCalledWith(expect.objectContaining({ status: 503 })); + expect(mocks.verifyCallback).not.toHaveBeenCalled(); + }); - await handler(req, res, next); + it('rejects a webhook with an invalid token (401)', async () => { + mocks.verifyCallback.mockResolvedValue(webhookResult({ signatureValid: false })); + const next = vi.fn(); + await handler(makeReq(), makeRes(), next); + expect(next).toHaveBeenCalledWith(expect.objectContaining({ status: 401 })); expect(alertOnPaymentWebhookFailure).toHaveBeenCalledWith('Mayar webhook processing failed', expect.any(Object)); - expect(next).toHaveBeenCalled(); + expect(mocks.poolQuery).not.toHaveBeenCalled(); }); - it('rejects webhook with invalid signature', async () => { - vi.mocked(createPaymentProvider).mockReturnValueOnce({ - verifyCallback: vi.fn().mockResolvedValue({ - signatureValid: false, - merchantOrderId: 'ORDER-INVALID', - internalStatus: 'unknown', - rawStatus: 'INVALID', - amount: null, - provider: 'doku', - providerReference: null, - paymentMethod: null, - paidAt: null, - raw: {}, - }), - } as any); - - const webhooksModule = await import('../webhooks'); - const router = webhooksModule.default; - const dokuRoute = (router as any).stack?.find((l: any) => l.route?.path === '/api/webhooks/doku'); - const handler = dokuRoute?.route?.stack?.[0]?.handle; - - if (!handler) { - expect(true).toBe(true); - return; - } + it('passes the query string to the provider for ?token= webhooks', async () => { + mocks.verifyCallback.mockResolvedValue(webhookResult({ internalStatus: 'pending', eventType: 'payment.reminder' })); + await handler(makeReq({ query: { token: 'secret' } }), makeRes(), vi.fn()); + expect(mocks.verifyCallback).toHaveBeenCalledWith(expect.objectContaining({ query: { token: 'secret' } })); + }); - const req = makeReq() as any; - const res = makeRes() as any; + it('acknowledges non-payment events without touching orders', async () => { + mocks.verifyCallback.mockResolvedValue(webhookResult({ eventType: 'membership.memberExpired', internalStatus: 'unknown' })); + const res = makeRes(); + await handler(makeReq(), res, vi.fn()); + expect(res.status).toHaveBeenCalledWith(200); + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ ignored: true, reason: 'not_a_paid_event' })); + expect(mocks.poolQuery).not.toHaveBeenCalled(); + }); - await handler(req, res, next); - expect(alertOnPaymentWebhookFailure).toHaveBeenCalled(); - expect(next).toHaveBeenCalled(); + it('acknowledges paid events for orders KaffePOS does not know (e.g. dashboard test)', async () => { + mocks.verifyCallback.mockResolvedValue(webhookResult()); + const res = makeRes(); + await handler(makeReq(), res, vi.fn()); + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ ignored: true, reason: 'order_not_found' })); + expect(mocks.checkTransactionStatus).not.toHaveBeenCalled(); }); - it('calls alertOnPaymentWebhookFailure when provider throws', async () => { - vi.mocked(createPaymentProvider).mockReturnValueOnce({ - verifyCallback: vi.fn().mockRejectedValue(new Error('Provider network error')), - } as any); + it('settles a POS order only after Mayar confirms it via the API', async () => { + mocks.verifyCallback.mockResolvedValue(webhookResult({ providerReference: 'payload-ref', referenceCandidates: ['payload-ref'] })); + mocks.poolQuery.mockResolvedValueOnce({ rows: [posOrderRow] }); + mocks.checkTransactionStatus.mockResolvedValue(confirmedResult()); + mocks.clientQuery.mockResolvedValueOnce({ + rows: [{ ...posOrderRow, user_id: 'user-1', store_id: 'store-1', gross_amount: 25000, items: [], transaction_id: null }], + }); - const webhooksModule = await import('../webhooks'); - const router = webhooksModule.default; - const dokuRoute = (router as any).stack?.find((l: any) => l.route?.path === '/api/webhooks/doku'); - const handler = dokuRoute?.route?.stack?.[0]?.handle; + const res = makeRes(); + const next = vi.fn(); + await handler(makeReq(), res, next); - if (!handler) { - expect(true).toBe(true); - return; - } + expect(next).not.toHaveBeenCalled(); + // Verified with the reference stored by KaffePOS, not the one in the payload. + expect(mocks.checkTransactionStatus).toHaveBeenCalledWith({ + merchantOrderId: 'KAF-1700000000000-ABCD1234', + providerReference: PAYMENT_REQUEST_ID, + amount: 25000, + }); + expect(PaymentService.finalizePaidOrder).toHaveBeenCalled(); + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ status: 'paid', kind: 'pos' })); + }); + + it('refuses to settle when Mayar still reports the payment unpaid (409, Mayar retries)', async () => { + mocks.verifyCallback.mockResolvedValue(webhookResult()); + mocks.poolQuery.mockResolvedValueOnce({ rows: [posOrderRow] }); + mocks.checkTransactionStatus.mockResolvedValue(confirmedResult({ internalStatus: 'pending', rawStatus: 'unpaid', paidAt: null })); + + const next = vi.fn(); + await handler(makeReq(), makeRes(), next); + expect(next).toHaveBeenCalledWith(expect.objectContaining({ status: 409 })); + expect(PaymentService.finalizePaidOrder).not.toHaveBeenCalled(); + }); + + it('rejects an amount that differs from the order', async () => { + mocks.verifyCallback.mockResolvedValue(webhookResult()); + mocks.poolQuery.mockResolvedValueOnce({ rows: [posOrderRow] }); + mocks.checkTransactionStatus.mockResolvedValue(confirmedResult({ amount: 1000 })); + mocks.clientQuery.mockResolvedValueOnce({ + rows: [{ ...posOrderRow, user_id: 'user-1', store_id: 'store-1', gross_amount: 25000, items: [], transaction_id: null }], + }); + + const next = vi.fn(); + await handler(makeReq(), makeRes(), next); + expect(next).toHaveBeenCalledWith(expect.objectContaining({ status: 400 })); + expect(PaymentService.finalizePaidOrder).not.toHaveBeenCalled(); + }); + + it('acknowledges duplicates of an already settled order without calling Mayar', async () => { + mocks.verifyCallback.mockResolvedValue(webhookResult()); + mocks.poolQuery.mockResolvedValueOnce({ rows: [{ ...posOrderRow, status: 'completed' }] }); + + const res = makeRes(); + await handler(makeReq(), res, vi.fn()); + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ duplicate: true, kind: 'pos' })); + expect(mocks.checkTransactionStatus).not.toHaveBeenCalled(); + }); + + it('activates a subscription session after API confirmation', async () => { + mocks.verifyCallback.mockResolvedValue(webhookResult({ merchantOrderId: 'MAYAR-SIGM-abcd1234-xyz', orderIdCandidates: ['MAYAR-SIGM-abcd1234-xyz'], amount: 129000 })); + mocks.poolQuery + .mockResolvedValueOnce({ rows: [] }) + .mockResolvedValueOnce({ + rows: [{ id: 'sess-1', merchant_order_id: 'MAYAR-SIGM-abcd1234-xyz', provider_reference: PAYMENT_REQUEST_ID, amount: 129000, status: 'pending', subscription_id: null }], + }); + mocks.checkTransactionStatus.mockResolvedValue(confirmedResult({ merchantOrderId: 'MAYAR-SIGM-abcd1234-xyz', amount: 129000 })); + mocks.clientQuery.mockResolvedValueOnce({ + rows: [{ id: 'sess-1', user_id: 'user-1', plan: 'signature', billing_cycle: 'monthly', amount: 129000, merchant_order_id: 'MAYAR-SIGM-abcd1234-xyz', subscription_id: null }], + }); + + const res = makeRes(); + const next = vi.fn(); + await handler(makeReq(), res, next); + + expect(next).not.toHaveBeenCalled(); + expect(activatePaidSubscription).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ userId: 'user-1', plan: 'signature', paymentAmount: 129000 })); + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ status: 'paid', kind: 'subscription' })); + }); + + it('does not trust a payload reference unless Mayar links it back to the same order', async () => { + mocks.verifyCallback.mockResolvedValue(webhookResult({ providerReference: 'other-paid-request' })); + mocks.poolQuery.mockResolvedValueOnce({ rows: [{ ...posOrderRow, provider_reference: null }] }); + mocks.checkTransactionStatus.mockResolvedValue(confirmedResult({ orderIdCandidates: ['KAF-SOMEONE-ELSE'] })); + + const next = vi.fn(); + await handler(makeReq(), makeRes(), next); + expect(mocks.checkTransactionStatus).toHaveBeenCalledWith(expect.objectContaining({ providerReference: 'other-paid-request' })); + expect(next).toHaveBeenCalledWith(expect.objectContaining({ status: 409 })); + expect(PaymentService.finalizePaidOrder).not.toHaveBeenCalled(); + }); - const req = makeReq() as any; - const res = makeRes() as any; + it('lets Mayar retry when the confirmation call fails', async () => { + mocks.verifyCallback.mockResolvedValue(webhookResult()); + mocks.poolQuery.mockResolvedValueOnce({ rows: [posOrderRow] }); + mocks.checkTransactionStatus.mockRejectedValue(Object.assign(new Error('Mayar check status gagal (502).'), { status: 502 })); - await handler(req, res, next); - expect(alertOnPaymentWebhookFailure).toHaveBeenCalledWith('DOKU webhook processing failed', expect.any(Object)); - expect(next).toHaveBeenCalled(); + const next = vi.fn(); + await handler(makeReq(), makeRes(), next); + expect(next).toHaveBeenCalledWith(expect.objectContaining({ status: 502 })); + expect(PaymentService.finalizePaidOrder).not.toHaveBeenCalled(); }); }); diff --git a/backend/src/routes/health.ts b/backend/src/routes/health.ts index 5e35c88..3584566 100644 --- a/backend/src/routes/health.ts +++ b/backend/src/routes/health.ts @@ -12,12 +12,14 @@ import { requireAdmin, getDatabaseProviderSummary, } from '../core'; +import { envDeprecations } from '../core/env'; import { validateBackendDeploymentConfig } from '../lib/deploymentReadiness'; import { isActivePaymentGatewayConfigured, isCommercialPaymentReady, - isDokuConfigured, + isMayarApiKeyConfigured, isMayarConfigured, + isMayarWebhookTokenConfigured, resolveSubscriptionPaymentConfig, } from '../core/billing'; import { getServiceTopologySnapshot } from '../architecture/serviceRegistry'; @@ -63,17 +65,16 @@ function getOperationalWarnings() { corsOrigin: env.CORS_ORIGIN, paymentProvider: paymentConfig.provider, mayarEnvironment: env.MAYAR_ENVIRONMENT, - mayarConfigured: isMayarConfigured(), - dokuEnvironment: env.DOKU_ENVIRONMENT, + mayarConfigured: isMayarApiKeyConfigured(), + mayarWebhookTokenConfigured: isMayarWebhookTokenConfigured(), subscriptionPaymentMode: env.SUBSCRIPTION_PAYMENT_MODE, paymentIntegrationEnabled: env.PAYMENT_INTEGRATION_ENABLED !== 'false', - dokuConfigured: isDokuConfigured(), resendApiKey: env.RESEND_API_KEY, resendFromEmail: env.RESEND_FROM_EMAIL, sentryDsn: env.SENTRY_DSN, }); - warnings.push(...deploymentValidation.errors, ...deploymentValidation.warnings); + warnings.push(...envDeprecations, ...deploymentValidation.errors, ...deploymentValidation.warnings); if (!env.RESEND_API_KEY || !env.RESEND_FROM_EMAIL) { warnings.push('Email delivery belum dikonfigurasi penuh.'); @@ -198,12 +199,7 @@ function buildSystemStatusPayload(params: { manualActivationAvailable: paymentConfig.manualActivationAvailable, provider: paymentConfig.provider, environment: getPaymentEnvironment(), - merchantId: - paymentConfig.provider === 'mayar' - ? env.MAYAR_API_KEY - ? 'mayar-configured' - : null - : env.DOKU_CLIENT_ID ?? null, + merchantId: paymentConfig.provider === 'mayar' && isMayarConfigured() ? 'mayar-configured' : null, }, monitoring: { backendErrorTracking: Boolean(env.SENTRY_DSN), @@ -378,6 +374,6 @@ router.get('/api/admin/system-status', authenticate, requireAdmin, async (_req, res.status(result.statusCode).json(result.payload); }); -export { isMayarConfigured, isDokuConfigured, isActivePaymentGatewayConfigured, resolveSubscriptionPaymentConfig, isCommercialPaymentReady }; +export { isMayarConfigured, isActivePaymentGatewayConfigured, resolveSubscriptionPaymentConfig, isCommercialPaymentReady }; export default router; diff --git a/backend/src/routes/payment.ts b/backend/src/routes/payment.ts index 26f2741..40e929b 100644 --- a/backend/src/routes/payment.ts +++ b/backend/src/routes/payment.ts @@ -16,6 +16,7 @@ import { buildSubscriptionQuoteOrThrow, ensureProfile, syncProfileSubscriptionState, + getMayarWebhookUrl, } from '../core'; import { PaymentService, paymentCreateSchema } from '../services/PaymentService'; import { createPaymentProvider, getActivePaymentProviderName } from '../payments/payment-provider.factory'; @@ -158,11 +159,8 @@ async function createGenericSubscriptionPayment(req: Parameters { try { - const checkProvider = getActivePaymentProviderName(); - if (checkProvider !== 'mayar' && checkProvider !== 'doku') throw new ApiError(409, 'Status check manual hanya aktif untuk Mayar atau DOKU.'); const paymentId = z.string().uuid().parse(req.params.paymentId); const sessionResult = await pool.query( `select * from public.subscription_payment_sessions where id = $1 and user_id = $2 limit 1`, @@ -255,7 +252,10 @@ router.post('/api/payments/:paymentId/check', requirePermission('can_manage_bill ); const session = sessionResult.rows[0]; if (!session) throw new ApiError(404, 'Pembayaran tidak ditemukan.'); - const provider = createPaymentProvider(checkProvider); + // Sessions created by a removed gateway cannot be re-checked automatically. + const checkProvider = String(session.provider ?? getActivePaymentProviderName()); + if (checkProvider !== 'mayar') throw new ApiError(409, 'Cek status otomatis hanya tersedia untuk pembayaran Mayar.'); + const provider = createPaymentProvider('mayar'); const checked = await provider.checkTransactionStatus({ merchantOrderId: String(session.merchant_order_id ?? session.midtrans_order_id), providerReference: session.provider_reference ? String(session.provider_reference) : null, diff --git a/backend/src/routes/subscriptions.ts b/backend/src/routes/subscriptions.ts index ae16eb4..5c2750a 100644 --- a/backend/src/routes/subscriptions.ts +++ b/backend/src/routes/subscriptions.ts @@ -26,6 +26,7 @@ import { sendTrialReminderEmail, log, serializeError, + getMayarWebhookUrl, } from '../core'; import { listSubscriptionPaymentMethods, @@ -466,11 +467,8 @@ router.post('/api/subscriptions/payments/create', requirePermission('can_manage_ const store = storeResult.rows[0]; const orderId = createSubscriptionOrderId(activeProvider, req.authUser!.id, payload.plan, payload.billingCycle); const provider = createPaymentProvider(activeProvider); - const dueMinutes = activeProvider === 'mayar' ? env.MAYAR_PAYMENT_DUE_MINUTES : env.DOKU_PAYMENT_DUE_MINUTES; - const callbackUrl = - activeProvider === 'mayar' - ? env.MAYAR_CALLBACK_URL ?? `${env.API_BASE_URL}/api/webhooks/mayar` - : env.DOKU_CALLBACK_URL; + const dueMinutes = env.MAYAR_PAYMENT_DUE_MINUTES; + const callbackUrl = getMayarWebhookUrl(); const payment = await provider.createPayment({ merchantOrderId: orderId, amount, @@ -480,7 +478,7 @@ router.post('/api/subscriptions/payments/create', requirePermission('can_manage_ paymentMethod: payload.paymentMethod, returnUrl: env.MAYAR_REDIRECT_URL ?? `${env.WEB_BASE_URL}/settings?billing=success&provider=${activeProvider}`, itemDetails: [{ name: `Langganan ${quote.planName}`, price: amount, quantity: 1 }], - metadata: { plan: payload.plan, billingCycle: payload.billingCycle }, + metadata: { kind: 'subscription', plan: payload.plan, billingCycle: payload.billingCycle }, }); const sessionId = randomUUID(); @@ -503,7 +501,7 @@ router.post('/api/subscriptions/payments/create', requirePermission('can_manage_ [ sessionId, req.authUser!.id, store?.id ?? null, payload.plan, payload.billingCycle, amount, orderId, payment.paymentUrl, dueMinutes, - JSON.stringify({ env: paymentConfig.environment, paymentMode: paymentConfig.mode, callbackUrl, selectedPaymentMethod: payload.paymentMethod, voucherCode, quote, storeName: store?.store_name ?? null, providerRaw: payment.raw }), + JSON.stringify({ env: paymentConfig.environment, paymentMode: paymentConfig.mode, callbackUrl, selectedPaymentMethod: payload.paymentMethod, voucherCode, quote, storeName: store?.store_name ?? null, providerTransactionId: payment.providerTransactionId ?? null, providerRaw: payment.raw }), payment.providerReference, payment.vaNumber, payment.qrString, payment.paymentMethod, payment.providerStatus, activeProvider, ], ); diff --git a/backend/src/routes/webhooks.ts b/backend/src/routes/webhooks.ts index 0dd7d70..8fddb2e 100644 --- a/backend/src/routes/webhooks.ts +++ b/backend/src/routes/webhooks.ts @@ -1,5 +1,15 @@ /** - * Pre-authentication payment webhook (DOKU). + * Pre-authentication payment webhook (Mayar). + * + * POST /api/webhooks/mayar + * 1. Authenticate: `X-Callback-Token` header or `?token=` must equal MAYAR_WEBHOOK_TOKEN. + * 2. Acknowledge (200) events that are not a payment: membership, shipping, reminders, + * dashboard "Test URL" calls and payments that do not belong to KaffePOS. + * 3. Find the KaffePOS record — a POS payment order or a subscription session. + * 4. Re-read the payment request from the Mayar API with the reference KaffePOS stored + * and settle only when Mayar itself reports it paid (Mayar does not sign webhooks). + * 5. Settle idempotently: POS → transaction + kitchen order, subscription → activation. + * Non-2xx answers make Mayar retry, so transient failures recover on their own. */ import { randomUUID } from 'node:crypto'; import { Router } from 'express'; @@ -12,13 +22,15 @@ import { log, serializeError, insertNotification, + pool, + isMayarWebhookTokenConfigured, } from '../core'; import { PaymentService } from '../services/PaymentService'; import { CommissionService } from '../services/CommissionService'; import { isReferralCommissionCreationEnabled } from '../lib/config/feature-flags'; import { alertOnPaymentWebhookFailure } from '../lib/alerting'; import { createPaymentProvider } from '../payments/payment-provider.factory'; -import type { PaymentStatusResult } from '../payments/payment-provider.types'; +import type { PaymentProvider, PaymentStatusResult } from '../payments/payment-provider.types'; const router = Router(); @@ -242,48 +254,214 @@ async function applyPosPaymentResult(result: PaymentStatusResult, eventType: str return true; } -function buildPaymentWebhookHandler(providerName: 'mayar' | 'doku') { - const label = providerName === 'mayar' ? 'Mayar' : 'DOKU'; - return async ( - req: Parameters[1]>[0], - res: Parameters[1]>[1], - next: Parameters[1]>[2], - ) => { - try { - const provider = createPaymentProvider(providerName); - const result = await provider.verifyCallback({ - body: req.body as Record, - headers: req.headers, - rawBody: req.rawBody, +type MayarPaymentRecord = { + kind: 'pos' | 'subscription'; + id: string; + merchantOrderId: string; + providerReference: string | null; + amount: number; + settled: boolean; +}; + +function uniqueIds(values: Array): string[] { + return Array.from(new Set(values.filter((value): value is string => typeof value === 'string' && value.trim().length > 0))); +} + +/** Finds the POS payment order or subscription session a Mayar webhook refers to. */ +async function findMayarPaymentRecord(result: PaymentStatusResult): Promise { + const orderIds = uniqueIds([...(result.orderIdCandidates ?? []), result.merchantOrderId]); + const references = uniqueIds([ + ...(result.referenceCandidates ?? []), + result.providerReference, + result.providerTransactionId, + ]); + if (orderIds.length === 0 && references.length === 0) return null; + + const posResult = await pool.query( + ` + select id, coalesce(merchant_order_id, midtrans_order_id) as merchant_order_id, provider_reference, + gross_amount as amount, status + from public.payment_orders + where coalesce(provider, 'mayar') = 'mayar' + and ( + merchant_order_id = any($1::text[]) + or midtrans_order_id = any($1::text[]) + or provider_reference = any($2::text[]) + or metadata->>'providerTransactionId' = any($2::text[]) + ) + order by created_at desc + limit 1 + `, + [orderIds, references], + ); + const posOrder = posResult.rows[0]; + if (posOrder) { + return { + kind: 'pos', + id: String(posOrder.id), + merchantOrderId: String(posOrder.merchant_order_id), + providerReference: posOrder.provider_reference ? String(posOrder.provider_reference) : null, + amount: Math.round(Number(posOrder.amount ?? 0)), + settled: posOrder.status === 'paid' || posOrder.status === 'completed', + }; + } + + const sessionResult = await pool.query( + ` + select id, coalesce(merchant_order_id, midtrans_order_id) as merchant_order_id, provider_reference, + amount, coalesce(internal_status, transaction_status) as status, subscription_id + from public.subscription_payment_sessions + where coalesce(provider, 'mayar') = 'mayar' + and ( + merchant_order_id = any($1::text[]) + or midtrans_order_id = any($1::text[]) + or provider_reference = any($2::text[]) + or metadata->>'providerTransactionId' = any($2::text[]) + ) + order by created_at desc + limit 1 + `, + [orderIds, references], + ); + const session = sessionResult.rows[0]; + if (!session) return null; + return { + kind: 'subscription', + id: String(session.id), + merchantOrderId: String(session.merchant_order_id), + providerReference: session.provider_reference ? String(session.provider_reference) : null, + amount: Math.round(Number(session.amount ?? 0)), + settled: Boolean(session.subscription_id), + }; +} + +/** + * Asks Mayar whether the payment behind this record is really paid. Uses the reference + * KaffePOS stored when it created the payment; only rows without one fall back to the + * reference in the webhook, and then Mayar's record must point back at the same order. + */ +async function confirmWithMayarApi(provider: PaymentProvider, record: MayarPaymentRecord, result: PaymentStatusResult) { + const reference = record.providerReference ?? result.providerReference; + if (!reference) { + throw new ApiError(409, 'Referensi pembayaran Mayar tidak ditemukan untuk order ini.'); + } + const confirmed = await provider.checkTransactionStatus({ + merchantOrderId: record.merchantOrderId, + providerReference: reference, + amount: record.amount, + }); + if (!record.providerReference && !(confirmed.orderIdCandidates ?? []).includes(record.merchantOrderId)) { + throw new ApiError(409, 'Referensi Mayar tidak cocok dengan order KaffePOS.'); + } + return confirmed; +} + +async function handleMayarWebhook( + req: Parameters[1]>[0], + res: Parameters[1]>[1], + next: Parameters[1]>[2], +) { + try { + if (!isMayarWebhookTokenConfigured()) { + log('error', 'mayar_webhook.token_not_configured', {}); + throw new ApiError(503, 'Webhook Mayar belum dikonfigurasi.'); + } + + const provider = createPaymentProvider('mayar'); + const result = await provider.verifyCallback({ + body: (req.body ?? {}) as Record, + headers: req.headers, + rawBody: req.rawBody, + query: req.query as Record, + }); + + if (!result.signatureValid) { + log('warn', 'mayar_webhook.token_rejected', { + eventType: result.eventType ?? null, + hasHeaderToken: Boolean(req.headers['x-callback-token']), + hasQueryToken: typeof req.query?.token === 'string', + }); + throw new ApiError(401, 'Token webhook Mayar tidak valid.'); + } + + if (result.internalStatus !== 'paid') { + log('info', 'mayar_webhook.ignored', { + eventType: result.eventType ?? null, + rawStatus: result.rawStatus, + internalStatus: result.internalStatus, + merchantOrderId: result.merchantOrderId, }); - if (!result.signatureValid) { - log('warn', `${providerName}_webhook_signature_failed`, { - merchantOrderId: result.merchantOrderId, - rawStatus: result.rawStatus, - }); - throw new ApiError(401, `Signature ${label} tidak valid.`); - } - const settledPosOrder = await applyPosPaymentResult(result, 'callback'); - if (!settledPosOrder) { - await applySubscriptionPaymentResult(result, 'callback'); - } res.status(200).json({ received: true, - provider: providerName, + provider: 'mayar', + ignored: true, + reason: 'not_a_paid_event', + event: result.eventType ?? null, status: result.internalStatus, - kind: settledPosOrder ? 'pos' : 'subscription', }); - } catch (error) { - alertOnPaymentWebhookFailure(`${label} webhook processing failed`, { error: String(error) }); - next(error); + return; } - }; + + const record = await findMayarPaymentRecord(result); + if (!record) { + log('warn', 'mayar_webhook.order_not_found', { + eventType: result.eventType ?? null, + merchantOrderId: result.merchantOrderId, + providerReference: result.providerReference, + }); + res.status(200).json({ received: true, provider: 'mayar', ignored: true, reason: 'order_not_found', event: result.eventType ?? null }); + return; + } + + if (record.settled) { + res.status(200).json({ received: true, provider: 'mayar', status: 'paid', kind: record.kind, duplicate: true }); + return; + } + + const confirmed = await confirmWithMayarApi(provider, record, result); + if (confirmed.internalStatus !== 'paid') { + log('warn', 'mayar_webhook.not_confirmed', { + kind: record.kind, + merchantOrderId: record.merchantOrderId, + apiStatus: confirmed.rawStatus, + }); + throw new ApiError(409, 'Pembayaran belum terkonfirmasi di Mayar.'); + } + + const settlement: PaymentStatusResult = { + ...result, + signatureValid: true, + merchantOrderId: record.merchantOrderId, + providerReference: record.providerReference ?? confirmed.providerReference ?? result.providerReference, + amount: confirmed.amount ?? result.amount, + paymentMethod: result.paymentMethod && result.paymentMethod !== 'MAYAR' ? result.paymentMethod : confirmed.paymentMethod, + rawStatus: confirmed.rawStatus ?? result.rawStatus, + internalStatus: 'paid', + paidAt: result.paidAt ?? confirmed.paidAt, + raw: { webhook: result.raw, confirmation: confirmed.raw }, + }; + + if (record.kind === 'pos') { + await applyPosPaymentResult(settlement, 'callback'); + } else { + await applySubscriptionPaymentResult(settlement, 'callback'); + } + + res.status(200).json({ received: true, provider: 'mayar', status: 'paid', kind: record.kind }); + } catch (error) { + alertOnPaymentWebhookFailure('Mayar webhook processing failed', { error: String(error) }); + next(error); + } } router.get('/api/webhooks/mayar', (_req, res) => { - res.status(200).json({ ok: true, provider: 'mayar', message: 'Mayar webhook endpoint active.' }); + res.status(200).json({ + ok: true, + provider: 'mayar', + message: 'Mayar webhook endpoint active.', + webhookTokenConfigured: isMayarWebhookTokenConfigured(), + }); }); -router.post('/api/webhooks/mayar', buildPaymentWebhookHandler('mayar')); -router.post('/api/webhooks/doku', buildPaymentWebhookHandler('doku')); +router.post('/api/webhooks/mayar', handleMayarWebhook); export default router; diff --git a/backend/src/services/PaymentService.ts b/backend/src/services/PaymentService.ts index 56abc7a..fe2777e 100644 --- a/backend/src/services/PaymentService.ts +++ b/backend/src/services/PaymentService.ts @@ -188,6 +188,7 @@ export class PaymentService { customerEmail: input.payload.customer?.email ?? input.user.email ?? null, customerPhone: input.payload.customer?.phone ?? null, itemDetails: prepared.itemDetails.map((item) => ({ name: item.name, price: item.price, quantity: item.quantity })), + metadata: { kind: 'pos', storeId: input.payload.store_id }, }); if (!payment.paymentUrl) { throw new ApiError(502, 'Respons gateway pembayaran tidak berisi link pembayaran.'); @@ -201,10 +202,19 @@ export class PaymentService { merchant_order_id = coalesce(merchant_order_id, $4), payment_url = $5, payment_method = $6, + metadata = coalesce(metadata, '{}'::jsonb) || $7::jsonb, updated_at = now() where id = $1 `, - [prepared.paymentOrderId, providerName, payment.providerReference, prepared.orderId, payment.paymentUrl, payment.paymentMethod], + [ + prepared.paymentOrderId, + providerName, + payment.providerReference, + prepared.orderId, + payment.paymentUrl, + payment.paymentMethod, + JSON.stringify({ providerTransactionId: payment.providerTransactionId ?? null }), + ], ); await insertPaymentAttempt({ diff --git a/backend/src/services/__tests__/PaymentService.test.ts b/backend/src/services/__tests__/PaymentService.test.ts index b21336b..2f2076d 100644 --- a/backend/src/services/__tests__/PaymentService.test.ts +++ b/backend/src/services/__tests__/PaymentService.test.ts @@ -1,6 +1,6 @@ /** * PaymentService unit tests - * Tests: transaction creation, Midtrans integration, order status + * Tests: transaction creation, Mayar integration, order status */ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { randomUUID } from 'node:crypto'; @@ -14,24 +14,24 @@ vi.mock('../../core', async () => { assertStoreOwned: vi.fn(), log: vi.fn(), env: { - MIDTRANS_SERVER_KEY: 'SB-Mid-server-test', - MIDTRANS_CLIENT_KEY: 'SB-Mid-client-test', - MIDTRANS_IS_PRODUCTION: 'false', - MIDTRANS_SNAP_ENABLED: 'true', + MAYAR_ENVIRONMENT: 'sandbox', + MAYAR_API_KEY: 'mayar-test-key', + MAYAR_WEBHOOK_TOKEN: 'mayar-webhook-token', }, }; }); vi.mock('../../payments/payment-provider.factory', () => ({ - getActivePaymentProviderName: vi.fn(() => 'doku'), + getActivePaymentProviderName: vi.fn(() => 'mayar'), createPaymentProvider: vi.fn(() => ({ - providerName: 'doku', + providerName: 'mayar', createPayment: vi.fn().mockResolvedValue({ - snap_token: 'snap-token-123', - paymentUrl: 'https://checkout-staging.doku.com/link/snap-token-123', - gross_amount: 65000, + provider: 'mayar', + paymentUrl: 'https://kaffepos.myr.id/pl/rqp9x2k7m3a', merchantOrderId: `ORDER-${Date.now()}`, - providerReference: 'DOKU-REF-123', + providerReference: '6f8c19ff-5b97-4792-aa89-d2a12797b356', + providerTransactionId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890', + paymentMethod: 'MAYAR_CHECKOUT', }), verifyCallback: vi.fn(), checkTransactionStatus: vi.fn(), @@ -81,7 +81,15 @@ describe('PaymentService', () => { }); expect(result.gross_amount).toBe(65000); // (35000 * 2) - 5000 - expect(result.payment_url).toBe('https://checkout-staging.doku.com/link/snap-token-123'); + expect(result.payment_url).toBe('https://kaffepos.myr.id/pl/rqp9x2k7m3a'); + expect(result.provider).toBe('mayar'); + expect(pool.query).toHaveBeenCalledWith( + expect.stringContaining('update public.payment_orders'), + expect.arrayContaining([ + '6f8c19ff-5b97-4792-aa89-d2a12797b356', + JSON.stringify({ providerTransactionId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890' }), + ]), + ); expect(result.status).toBe('pending'); expect(mockClient.query).toHaveBeenCalledWith( expect.stringContaining('insert into public.payment_orders'), diff --git a/coolify.backend.minimal.env.example b/coolify.backend.minimal.env.example index e323299..1ead8a2 100644 --- a/coolify.backend.minimal.env.example +++ b/coolify.backend.minimal.env.example @@ -36,7 +36,7 @@ SESSION_TTL_DAYS=30 EMAIL_CODE_TTL_MINUTES=10 PASSWORD_RESET_TTL_MINUTES=15 -# Set true once real DOKU credentials are filled in below. +# Set false to turn online payment off until the Mayar keys below are filled in. PAYMENT_INTEGRATION_ENABLED=true SUBSCRIPTION_PAYMENT_MODE=auto @@ -47,17 +47,20 @@ REFERRAL_ENABLED=false AFFILIATE_ENABLED=false ADMIN_COMMISSION_ENABLED=false REFERRAL_COMMISSION_CREATION_ENABLED=false -# ── Payment gateway: DOKU Checkout (hosted page) ────────────────── -PAYMENT_GATEWAY_PROVIDER=doku -DOKU_ENVIRONMENT=sandbox -DOKU_CLIENT_ID=__SET_DOKU_CLIENT_ID__ -DOKU_SECRET_KEY=__SET_DOKU_SECRET_KEY__ -# Confirm the exact host for your DOKU account; these are the common defaults. -DOKU_SANDBOX_BASE_URL=https://api-sandbox.doku.com -DOKU_PRODUCTION_BASE_URL=https://api.doku.com -# Customer redirect after payment. Register the notification (webhook) URL -# https://api.kaffepos.my.id/api/webhooks/doku in the DOKU Back Office. -DOKU_CALLBACK_URL=https://kaffepos.my.id/settings?billing=doku-return -DOKU_NOTIFICATION_PATH=/api/webhooks/doku -DOKU_PAYMENT_DUE_MINUTES=60 +# ── Payment gateway: Mayar Headless API v2 ─────────────────────── +# Guide: docs/engineering/MAYAR_INTEGRATION_GUIDE.md +PAYMENT_GATEWAY_PROVIDER=mayar +# sandbox key: https://web.mayar.io/api-keys · production key: https://web.mayar.id/api-keys +MAYAR_ENVIRONMENT=sandbox +MAYAR_API_KEY=__SET_MAYAR_API_KEY__ +# "Web Token" from the Mayar dashboard (sent by Mayar in the X-Callback-Token header). +MAYAR_WEBHOOK_TOKEN=__SET_MAYAR_WEB_TOKEN__ +MAYAR_SANDBOX_BASE_URL=https://api.mayar.io +MAYAR_PRODUCTION_BASE_URL=https://api.mayar.id +# Register in Mayar → Integrasi → Webhook as: +# https://api.kaffepos.my.id/api/webhooks/mayar +# or run `node scripts/mayar-connect.mjs --register` in the backend container. +MAYAR_CALLBACK_URL=https://api.kaffepos.my.id/api/webhooks/mayar +MAYAR_REDIRECT_URL=https://kaffepos.my.id/settings?billing=mayar-return +MAYAR_PAYMENT_DUE_MINUTES=60 STAGING_REPAIR_TOKEN=__GENERATE_WITH_openssl_rand_hex_32__ diff --git a/coolify.frontend.minimal.env.example b/coolify.frontend.minimal.env.example index 3ee1ffd..dd97a7d 100644 --- a/coolify.frontend.minimal.env.example +++ b/coolify.frontend.minimal.env.example @@ -17,4 +17,4 @@ VITE_REFERRAL_ENABLED=false VITE_AFFILIATE_ENABLED=false VITE_ADMIN_COMMISSION_ENABLED=false # Informational only (analytics tag); the backend decides the real gateway. -VITE_PAYMENT_GATEWAY_PROVIDER=doku +VITE_PAYMENT_GATEWAY_PROVIDER=mayar diff --git a/docs/engineering/COOLIFY_ENV_MAPPING.md b/docs/engineering/COOLIFY_ENV_MAPPING.md index a1fb775..51df4b9 100644 --- a/docs/engineering/COOLIFY_ENV_MAPPING.md +++ b/docs/engineering/COOLIFY_ENV_MAPPING.md @@ -1,12 +1,11 @@ -> ⚠️ **Legacy naming notice (updated 2026-06-29).** This document predates the switch to -> **DOKU** and still references the old `DUITKU_*` / `MIDTRANS_*` keys below. The **active** -> payment gateway is **DOKU**. The authoritative env contract is `backend/src/core/env.ts` -> and the working template `backend/.env.staging.example`. +> ⚠️ **Legacy naming notice (updated 2026-11-16).** Parts of this document predate the switch to +> **Mayar** and still mention old `DOKU_*` / `DUITKU_*` / `MIDTRANS_*` keys. The **only** payment +> gateway is **Mayar** (Headless API v2). The authoritative env contract is `backend/src/core/env.ts`; +> setup steps live in `docs/engineering/MAYAR_INTEGRATION_GUIDE.md`. > -> Correct values: `PAYMENT_GATEWAY_PROVIDER=doku` (NOT `duitku` — that value fails the env -> schema and prevents boot), `SUBSCRIPTION_PAYMENT_MODE=doku_sandbox|doku_production`, and the -> keys `DOKU_CLIENT_ID`, `DOKU_SECRET_KEY`, `DOKU_CALLBACK_URL`, `DOKU_ENVIRONMENT`. The code -> does **not** read `DUITKU_*` / `MIDTRANS_*` — treat any such references below as superseded. +> Correct values: `PAYMENT_GATEWAY_PROVIDER=mayar`, `SUBSCRIPTION_PAYMENT_MODE=auto|mayar_sandbox|mayar_production`, +> and the keys `MAYAR_ENVIRONMENT`, `MAYAR_API_KEY`, `MAYAR_WEBHOOK_TOKEN`, `MAYAR_CALLBACK_URL`. Legacy +> `doku` / `doku_*` values are read as Mayar with a warning; no `DOKU_*` / `DUITKU_*` / `MIDTRANS_*` key is read. # KaffePOS Coolify Env Mapping diff --git a/docs/engineering/ENV_CONTRACT.md b/docs/engineering/ENV_CONTRACT.md index 0b0bce0..fe06605 100644 --- a/docs/engineering/ENV_CONTRACT.md +++ b/docs/engineering/ENV_CONTRACT.md @@ -1,12 +1,11 @@ -> ⚠️ **Legacy naming notice (updated 2026-06-29).** This document predates the switch to -> **DOKU** and still references the old `DUITKU_*` / `MIDTRANS_*` keys below. The **active** -> payment gateway is **DOKU**. The authoritative env contract is `backend/src/core/env.ts` -> and the working template `backend/.env.staging.example`. +> ⚠️ **Legacy naming notice (updated 2026-11-16).** Parts of this document predate the switch to +> **Mayar** and still mention old `DOKU_*` / `DUITKU_*` / `MIDTRANS_*` keys. The **only** payment +> gateway is **Mayar** (Headless API v2). The authoritative env contract is `backend/src/core/env.ts`; +> setup steps live in `docs/engineering/MAYAR_INTEGRATION_GUIDE.md`. > -> Correct values: `PAYMENT_GATEWAY_PROVIDER=doku` (NOT `duitku` — that value fails the env -> schema and prevents boot), `SUBSCRIPTION_PAYMENT_MODE=doku_sandbox|doku_production`, and the -> keys `DOKU_CLIENT_ID`, `DOKU_SECRET_KEY`, `DOKU_CALLBACK_URL`, `DOKU_ENVIRONMENT`. The code -> does **not** read `DUITKU_*` / `MIDTRANS_*` — treat any such references below as superseded. +> Correct values: `PAYMENT_GATEWAY_PROVIDER=mayar`, `SUBSCRIPTION_PAYMENT_MODE=auto|mayar_sandbox|mayar_production`, +> and the keys `MAYAR_ENVIRONMENT`, `MAYAR_API_KEY`, `MAYAR_WEBHOOK_TOKEN`, `MAYAR_CALLBACK_URL`. Legacy +> `doku` / `doku_*` values are read as Mayar with a warning; no `DOKU_*` / `DUITKU_*` / `MIDTRANS_*` key is read. # KaffePOS Environment Variable Contract diff --git a/docs/engineering/MAYAR_INTEGRATION_GUIDE.md b/docs/engineering/MAYAR_INTEGRATION_GUIDE.md new file mode 100644 index 0000000..f6f4306 --- /dev/null +++ b/docs/engineering/MAYAR_INTEGRATION_GUIDE.md @@ -0,0 +1,184 @@ +# Integrasi Mayar — Payment Gateway KaffePOS + +KaffePOS memakai **Mayar Headless API v2** sebagai satu-satunya payment gateway, untuk: + +- **Checkout POS online** (QRIS / VA / e-wallet di halaman Mayar) — `POST /api/payment/create-transaction` +- **Langganan (subscription)** — `POST /api/payments/start` (dan rute lama `POST /api/subscriptions/payments/create`) + +DOKU sudah dihapus. Env lama `PAYMENT_GATEWAY_PROVIDER=doku` / `SUBSCRIPTION_PAYMENT_MODE=doku_*` tetap bisa boot, +tetapi dibaca sebagai Mayar dan muncul sebagai peringatan di `/api/admin/system-status`. Semua `DOKU_*` boleh dihapus. + +## Tiga hal yang menghubungkan KaffePOS ke Mayar + +| Item | Env backend | Dipakai untuk | +| --- | --- | --- | +| **API key** | `MAYAR_API_KEY` | Header `Authorization: Bearer …` untuk membuat payment request dan cek status | +| **Web Token** (token webhook) | `MAYAR_WEBHOOK_TOKEN` | Bukti bahwa webhook benar-benar dari Mayar — Mayar mengirimnya di header `X-Callback-Token` | +| **URL webhook** | `MAYAR_CALLBACK_URL` (default `API_BASE_URL` + `/api/webhooks/mayar`) | Tujuan notifikasi `payment.received` dari Mayar | + +Ketiganya **backend-only**. Jangan pernah membuat `VITE_MAYAR_*` (`npm run release:verify-config` menolaknya). +**User ID** Mayar yang tampil di dashboard tidak dipakai KaffePOS — akun sudah dikenali dari API key. + +## Alur pembayaran + +``` +Kasir / owner ──► Backend ── POST /hl/v2/payments/create (Bearer API key) ──► Mayar + ◄──────────── link checkout (id + transactionId) ───────── +Pelanggan bayar di halaman Mayar +Mayar ── POST /api/webhooks/mayar (+ token) ──► Backend + 1. cek token + 2. cari order POS / sesi langganan + 3. GET /hl/v2/payments/{id} ──► Mayar (status harus "paid", nominal sama) + 4. POS: transaksi + order dapur · Langganan: aktivasi paket +``` + +Jawaban non-2xx membuat Mayar mengulang webhook, jadi gangguan sementara pulih sendiri. + +## Langkah setup + +### 1. Ambil API key + +| Lingkungan | Dashboard | API key | API | +| --- | --- | --- | --- | +| Sandbox | https://web.mayar.io | https://web.mayar.io/api-keys | `https://api.mayar.io/hl/v2` | +| Production | https://web.mayar.id | https://web.mayar.id/api-keys | `https://api.mayar.id/hl/v2` | + +Key sandbox hanya berlaku di API sandbox dan key production hanya di production — `MAYAR_ENVIRONMENT` harus cocok. +Akun sandbox lama yang dibuat di `web.mayar.club` memakai `MAYAR_SANDBOX_BASE_URL=https://api.mayar.club`. + +### 2. Salin Web Token + +Salin **Web Token** dari dashboard Mayar (halaman integrasi yang sama dengan User ID) dan simpan sebagai +`MAYAR_WEBHOOK_TOKEN`. Mayar mengirim token ini di header `X-Callback-Token` setiap kali memanggil webhook. + +Akun yang tidak punya Web Token bisa memakai token buatan sendiri (`openssl rand -hex 32`) yang ditempel di URL +webhook sebagai `?token=…` — backend menerima keduanya. + +### 3. Isi env backend (Coolify → backend → Environment Variables) + +```env +PAYMENT_GATEWAY_PROVIDER=mayar +PAYMENT_INTEGRATION_ENABLED=true +MAYAR_ENVIRONMENT=sandbox # production saat go-live +MAYAR_API_KEY= +MAYAR_WEBHOOK_TOKEN= +MAYAR_CALLBACK_URL=https://api.kaffepos.my.id/api/webhooks/mayar +MAYAR_REDIRECT_URL=https://kaffepos.my.id/settings?billing=mayar-return +MAYAR_PAYMENT_DUE_MINUTES=60 +SUBSCRIPTION_PAYMENT_MODE=auto # ikut MAYAR_ENVIRONMENT +``` + +Hapus semua `DOKU_*`, lalu redeploy backend. Frontend cukup `VITE_PAYMENT_GATEWAY_PROVIDER=mayar` (hanya label analytics). + +Pembayaran online baru dibuka kalau **API key dan token webhook sama-sama terisi** — tanpa token, webhook akan +ditolak dan order tidak pernah lunas otomatis, jadi checkout langganan jatuh ke mode aktivasi manual. + +### 4. Daftarkan URL webhook di Mayar + +**Opsi A — Dashboard.** Mayar → **Integrasi → Webhook** → isi *URL Webhook*: + +``` +https://api.kaffepos.my.id/api/webhooks/mayar +``` + +Klik **Simpan**, lalu **Test URL**. Hanya untuk akun tanpa Web Token: tambahkan `?token=` di belakang URL. +Sandbox dan production punya pengaturan webhook masing-masing — daftarkan di keduanya. + +**Opsi B — Script.** Dari terminal container backend (Coolify → backend → Terminal): + +```bash +node scripts/mayar-connect.mjs # cek API key, endpoint webhook, dan token (tidak mengubah apa pun) +node scripts/mayar-connect.mjs --register # daftarkan URL webhook ke akun Mayar lalu minta Mayar mengirim tes +``` + +Dari laptop (membaca `backend/.env`): `npm run mayar:connect -- --register`. +Tambahkan `--url-token` hanya untuk akun tanpa Web Token (URL didaftarkan dengan `?token=`). +Script menyamarkan semua secret di output. + +### 5. Uji + +1. `node scripts/mayar-connect.mjs` → semua ✓. +2. `curl https://api.kaffepos.my.id/api/webhooks/mayar` → `"webhookTokenConfigured": true`. +3. Sandbox: buat order kecil di POS (QRIS) atau checkout langganan, bayar di halaman sandbox Mayar, pastikan status berubah otomatis. +4. `npm run smoke:staging:mayar` → membuat satu payment request (tidak dibayar) untuk memastikan API key bekerja. +5. Developer: `npm run smoke:local:mayar` (butuh Postgres lokal) menguji alur penuh dengan Mayar palsu — + buat pembayaran, webhook palsu ditolak, webhook valid melunasi order sekali, langganan aktif, script connect. + +### 6. Go-live production + +- Pakai API key production, `MAYAR_ENVIRONMENT=production`, `SUBSCRIPTION_PAYMENT_MODE=auto` (atau `mayar_production`). +- Daftarkan URL webhook di dashboard **production** (`web.mayar.id`). +- Jalankan `npm run release:verify-config` dan `npm run smoke:production:billing`. + +## Keamanan + +- **Token wajib.** Webhook tanpa token yang cocok ditolak `401`. Kalau `MAYAR_WEBHOOK_TOKEN` belum diisi di server, + endpoint menjawab `503` sehingga Mayar mengulang setelah env diperbaiki. API key tidak pernah diterima sebagai token webhook. +- **Status "paid" selalu dicek ulang ke Mayar.** Mayar tidak menandatangani body webhook, jadi backend membaca ulang + `GET /hl/v2/payments/{id}` memakai referensi yang disimpan KaffePOS saat membuat pembayaran, dan nominal harus sama. + Webhook palsu — bahkan kalau token bocor — tidak bisa menandai order lunas. +- **Idempoten.** Order POS yang sudah lunas dan sesi langganan yang sudah aktif tidak diproses dua kali. +- **Log aman.** `?token=` disamarkan (`token=[redacted]`) di log request dan alert backend. +- **Kalau bocor:** buat API key / Web Token baru di dashboard Mayar, update env di Coolify, lalu jalankan + `node scripts/mayar-connect.mjs` untuk memastikan semuanya cocok. + +## Jawaban endpoint webhook + +| Kondisi | HTTP | Keterangan | +| --- | --- | --- | +| Token salah / tidak ada | 401 | | +| `MAYAR_WEBHOOK_TOKEN` belum diisi | 503 | Mayar mengulang | +| Bukan event pembayaran (membership, shipper, `payment.reminder`, tes dashboard) | 200 | `ignored: true` | +| Pembayaran bukan milik KaffePOS | 200 | `reason: order_not_found` | +| Order sudah lunas | 200 | `duplicate: true` | +| Mayar API belum melaporkan `paid` | 409 | Mayar mengulang | +| Nominal berbeda dengan order | 400 | Tidak diproses | +| Mayar API tidak bisa dihubungi | 502 | Mayar mengulang | +| Terkonfirmasi lunas | 200 | `status: paid`, `kind: pos` / `subscription` | + +## Troubleshooting + +| Gejala | Penyebab umum | +| --- | --- | +| Riwayat webhook Mayar berisi 401 | `MAYAR_WEBHOOK_TOKEN` ≠ Web Token di dashboard (cek spasi atau baris baru saat menempel). Kalau akun tidak mengirim `X-Callback-Token`, daftarkan URL dengan `?token=` (`--register --url-token`) | +| Riwayat webhook berisi 503 | `MAYAR_WEBHOOK_TOKEN` belum diisi di backend | +| Riwayat webhook berisi 409 terus | Payment request belum `paid` di Mayar — cek transaksi di dashboard Mayar | +| Create payment gagal `(401)` | API key salah atau beda lingkungan (key sandbox di production atau sebaliknya) | +| `Payment method … is not available` | Aktifkan channel pembayaran di dashboard Mayar | +| `Mayar menolak permintaan ganda` | Mayar memblokir request identik selama 1 menit — tunggu lalu ulangi | +| Langganan belum aktif setelah bayar | Cek log `mayar_webhook.*`; `POST /api/payments/:paymentId/check` (sesi owner) memaksa cek ulang ke Mayar dan mengaktifkan paket bila sudah lunas | + +## Referensi env + +| Env | Default | Keterangan | +| --- | --- | --- | +| `PAYMENT_GATEWAY_PROVIDER` | `mayar` | `mayar` atau `disabled` | +| `PAYMENT_INTEGRATION_ENABLED` | `true` | `false` mematikan pembayaran online | +| `MAYAR_ENVIRONMENT` | `sandbox` | `sandbox` / `production` | +| `MAYAR_API_KEY` | — | Wajib | +| `MAYAR_WEBHOOK_TOKEN` | — | Wajib — Web Token dari dashboard Mayar | +| `MAYAR_SANDBOX_BASE_URL` | `https://api.mayar.io` | | +| `MAYAR_PRODUCTION_BASE_URL` | `https://api.mayar.id` | | +| `MAYAR_CALLBACK_URL` | `API_BASE_URL` + `MAYAR_WEBHOOK_PATH` | URL webhook (tanpa token) | +| `MAYAR_WEBHOOK_PATH` | `/api/webhooks/mayar` | | +| `MAYAR_REDIRECT_URL` | `WEB_BASE_URL/settings?billing=success` | Redirect setelah bayar langganan; payment request Mayar bisa menolak field ini, backend otomatis mengulang tanpa redirect | +| `MAYAR_PAYMENT_DUE_MINUTES` | `60` | Masa berlaku link pembayaran | +| `MAYAR_CREATE_PAYMENT_PATH` | `/hl/v2/payments/create` | | +| `MAYAR_STATUS_PATH_PREFIX` | `/hl/v2/payments` | | +| `SUBSCRIPTION_PAYMENT_MODE` | `auto` | `auto` / `manual` / `disabled` / `mayar_sandbox` / `mayar_production` | + +## Endpoint Mayar yang dipakai + +| Endpoint | Dipakai oleh | +| --- | --- | +| `POST /hl/v2/payments/create` | Membuat payment request (POS & langganan) | +| `GET /hl/v2/payments/{id}` | Konfirmasi webhook & cek status manual | +| `GET /hl/v2/payments?limit=1` | `mayar-connect` (cek API key) | +| `POST /hl/v2/webhooks/update` · `POST /hl/v2/webhooks/test` | `mayar-connect --register` | + +Kode: `backend/src/payments/providers/mayar.provider.ts`, `backend/src/routes/webhooks.ts`, `backend/scripts/mayar-connect.mjs`. + +Dokumentasi Mayar: [API v2](https://docs.mayar.id/api-reference-v2/introduction) · +[Create payment request](https://docs.mayar.id/api-reference-v2/reqpayment/create) · +[Webhook](https://docs.mayar.id/integration/webhook) · +[Register URL hook](https://docs.mayar.id/api-reference-v2/webhook/registerurlhook) diff --git a/docs/engineering/PAYMENT_PROVIDER_MIGRATION_REPORT.md b/docs/engineering/PAYMENT_PROVIDER_MIGRATION_REPORT.md index cd163d0..8230fb3 100644 --- a/docs/engineering/PAYMENT_PROVIDER_MIGRATION_REPORT.md +++ b/docs/engineering/PAYMENT_PROVIDER_MIGRATION_REPORT.md @@ -1,23 +1,28 @@ # Payment Provider Migration Report -KaffePOS payment gateway now uses provider abstraction with `duitku`, `midtrans`, and `disabled` modes selected by `PAYMENT_GATEWAY_PROVIDER`. +KaffePOS uses **Mayar Headless API v2** as its only payment gateway (`PAYMENT_GATEWAY_PROVIDER=mayar`). +`disabled` turns online payment off. DOKU, Duitku and Midtrans have been removed; legacy env values +(`doku`, `doku_sandbox`, `doku_production`) are read as Mayar with a startup warning so old deployments still boot. + +Setup guide: [`MAYAR_INTEGRATION_GUIDE.md`](MAYAR_INTEGRATION_GUIDE.md). ## Routes -- `POST /api/webhooks/duitku` public callback, HMAC SHA256 verified server-side. -- `GET /api/payments/:paymentId/status` authenticated safe status read. -- `POST /api/payments/:paymentId/check` authenticated Duitku status refresh. +- `POST /api/payments/start` — subscription checkout; creates a Mayar payment request and returns `paymentUrl`. +- `POST /api/payment/create-transaction` — POS online checkout (QRIS/VA/e-wallet on the Mayar page). +- `POST /api/webhooks/mayar` — public webhook; token-authenticated (`X-Callback-Token` or `?token=`). +- `GET /api/webhooks/mayar` — liveness + `webhookTokenConfigured`. +- `GET /api/payments/:paymentId/status` — authenticated safe status read. +- `POST /api/payments/:paymentId/check` — authenticated re-check against `GET /hl/v2/payments/:id`. ## Safety -- Duitku merchant key remains backend-only. +- `MAYAR_API_KEY` and `MAYAR_WEBHOOK_TOKEN` are backend-only; `release:verify-config` rejects `VITE_MAYAR_*`. +- Online payment only opens when both the API key and the webhook token are configured. +- A webhook is never trusted on its own: a `payment.received` event is confirmed with `GET /hl/v2/payments/:id` + using the reference KaffePOS stored at creation, and the amount must match. - Return URL only refreshes UI status; it never marks payment paid. -- Subscription activation runs only after verified callback or verified status check. -- Duplicate activation guarded by `subscription_payment_sessions.subscription_id` and existing payment history checks. - -## Finalization Update - -- `POST /api/payments/start` is the generic payment start route for subscription checkout. -- Frontend checkout now calls `POST /api/payments/start` and redirects to returned `paymentUrl`. -- Legacy `/api/subscriptions/payments/create` remains available. -- Migration command for staging/production: `npm --prefix backend run migrate`. +- Duplicate activation is guarded by `subscription_payment_sessions.subscription_id` and POS orders by their + terminal `paid`/`completed` status. +- Webhook tokens passed as `?token=` are redacted from request logs and alerts. +- Migration command for staging/production: `npm --prefix backend run migrate` (no schema change is needed for Mayar). diff --git a/package.json b/package.json index c197134..f7aba72 100644 --- a/package.json +++ b/package.json @@ -41,9 +41,10 @@ "coolify:staging:deploy": "node scripts/coolify-staging-deploy.mjs", "verify:payment-staging": "node scripts/verify-staging-env.mjs --profile=payment", "smoke:staging:mayar": "node scripts/smoke-mayar-staging.mjs", - "smoke:staging:doku": "node scripts/smoke-doku-staging.mjs", + "mayar:connect": "node backend/scripts/mayar-connect.mjs", "smoke:insforge": "npm --prefix backend run build && node scripts/smoke-insforge-backend.mjs", "smoke:local:fresh-db": "npm --prefix backend run build && node scripts/smoke-local-fresh-db.mjs", + "smoke:local:mayar": "npm --prefix backend run build && node scripts/smoke-local-mayar.mjs", "test:e2e:local": "npm --prefix backend run build && node scripts/e2e-local.mjs", "test:e2e:offline": "npm --prefix backend run build && node scripts/e2e-offline-local.mjs" }, diff --git a/scripts/coolify-staging-deploy.mjs b/scripts/coolify-staging-deploy.mjs index c397a9b..f97054c 100644 --- a/scripts/coolify-staging-deploy.mjs +++ b/scripts/coolify-staging-deploy.mjs @@ -21,14 +21,14 @@ const BACKEND_KEYS = [ 'PAYMENT_GATEWAY_PROVIDER', 'PAYMENT_INTEGRATION_ENABLED', 'SUBSCRIPTION_PAYMENT_MODE', - 'DOKU_ENVIRONMENT', - 'DOKU_CLIENT_ID', - 'DOKU_SECRET_KEY', - 'DOKU_SANDBOX_BASE_URL', - 'DOKU_PRODUCTION_BASE_URL', - 'DOKU_CALLBACK_URL', - 'DOKU_NOTIFICATION_PATH', - 'DOKU_PAYMENT_DUE_MINUTES', + 'MAYAR_ENVIRONMENT', + 'MAYAR_API_KEY', + 'MAYAR_WEBHOOK_TOKEN', + 'MAYAR_SANDBOX_BASE_URL', + 'MAYAR_PRODUCTION_BASE_URL', + 'MAYAR_CALLBACK_URL', + 'MAYAR_REDIRECT_URL', + 'MAYAR_PAYMENT_DUE_MINUTES', 'RESEND_API_KEY', 'RESEND_FROM_EMAIL', 'EMAIL_REPLY_TO', @@ -68,14 +68,14 @@ const PAYMENT_BACKEND_KEYS = [ 'PAYMENT_GATEWAY_PROVIDER', 'PAYMENT_INTEGRATION_ENABLED', 'SUBSCRIPTION_PAYMENT_MODE', - 'DOKU_ENVIRONMENT', - 'DOKU_CLIENT_ID', - 'DOKU_SECRET_KEY', - 'DOKU_SANDBOX_BASE_URL', - 'DOKU_PRODUCTION_BASE_URL', - 'DOKU_CALLBACK_URL', - 'DOKU_NOTIFICATION_PATH', - 'DOKU_PAYMENT_DUE_MINUTES', + 'MAYAR_ENVIRONMENT', + 'MAYAR_API_KEY', + 'MAYAR_WEBHOOK_TOKEN', + 'MAYAR_SANDBOX_BASE_URL', + 'MAYAR_PRODUCTION_BASE_URL', + 'MAYAR_CALLBACK_URL', + 'MAYAR_REDIRECT_URL', + 'MAYAR_PAYMENT_DUE_MINUTES', ]; const FRONTEND_KEYS = [ @@ -175,11 +175,11 @@ const SMOKE_COMMANDS = [ ]; const PAYMENT_SMOKE_COMMANDS = [ - ['npm', ['run', 'smoke:staging:doku']], + ['npm', ['run', 'smoke:staging:mayar']], ]; const EXTERNAL_CHECKS = [ - { name: 'DOKU sandbox', candidates: ['scripts/smoke-doku-staging.mjs'] }, + { name: 'Mayar sandbox', candidates: ['scripts/smoke-mayar-staging.mjs'] }, { name: 'Resend staging', candidates: ['scripts/smoke-resend-staging.mjs', 'scripts/smoke-staging-resend.mjs'] }, { name: 'Cloudflare/R2 staging', candidates: ['scripts/smoke-r2-staging.mjs', 'scripts/smoke-staging-r2.mjs'] }, { name: 'GA4/Clarity staging', candidates: ['scripts/smoke-analytics-staging.mjs', 'scripts/smoke-staging-analytics.mjs'] }, diff --git a/scripts/smoke-billing-production.mjs b/scripts/smoke-billing-production.mjs index daeda52..b976467 100644 --- a/scripts/smoke-billing-production.mjs +++ b/scripts/smoke-billing-production.mjs @@ -100,7 +100,7 @@ async function checkCommercialStatus() { if ( payment?.environment === 'production' && - (payment?.mode === 'mayar_production' || payment?.mode === 'doku_production') && + payment?.mode === 'mayar_production' && payment?.onlinePaymentAvailable === true && payment?.commerciallyReady === true ) { diff --git a/scripts/smoke-doku-staging.mjs b/scripts/smoke-doku-staging.mjs deleted file mode 100644 index e50017b..0000000 --- a/scripts/smoke-doku-staging.mjs +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/env node -/** - * DOKU Checkout sandbox/production smoke test. - * - * Reads DOKU_* credentials from the environment (or .env.staging.local) — never - * from the command line — fires a real create-payment request, and validates the - * HMAC-SHA256 signature + response shape. The Secret Key is never printed. - * - * DOKU_CLIENT_ID=... DOKU_SECRET_KEY=... DOKU_ENVIRONMENT=sandbox \ - * npm run smoke:staging:doku - */ -import { createHash, createHmac, randomUUID } from 'node:crypto'; -import { loadStagingEnvFiles } from './lib/staging-env.mjs'; - -loadStagingEnvFiles(); - -function requireEnv(name) { - const value = process.env[name]; - if (!value) { - console.error(`✗ ${name} wajib diisi untuk smoke test DOKU (set di env atau .env.staging.local; jangan paste di chat).`); - process.exit(1); - } - return value; -} - -function maskTail(value, visible = 4) { - if (!value) return '[unset]'; - return value.length <= visible ? '*'.repeat(value.length) : `${value.slice(0, 4)}…${value.slice(-visible)}`; -} - -const clientId = requireEnv('DOKU_CLIENT_ID'); -const secretKey = requireEnv('DOKU_SECRET_KEY'); -const environment = process.env.DOKU_ENVIRONMENT === 'production' ? 'production' : 'sandbox'; -const baseUrl = (environment === 'production' - ? process.env.DOKU_PRODUCTION_BASE_URL || 'https://api.doku.com' - : process.env.DOKU_SANDBOX_BASE_URL || 'https://api-sandbox.doku.com' -).replace(/\/+$/, ''); -const checkoutPath = process.env.DOKU_CHECKOUT_PATH || '/checkout/v1/payment'; -const callbackUrl = process.env.DOKU_CALLBACK_URL || 'https://kaffepos.my.id/settings?billing=doku-return'; -const dueMinutes = Number(process.env.DOKU_PAYMENT_DUE_MINUTES || 60); -const amount = Number(process.env.DOKU_SMOKE_AMOUNT || 1000); // smallest sensible test amount - -// ── DOKU signature (mirrors backend/src/payments/providers/doku.provider.ts) ── -function dokuTimestamp(date = new Date()) { - return date.toISOString().replace(/\.\d{3}Z$/, 'Z'); -} -function sha256Base64(body) { - return createHash('sha256').update(body, 'utf8').digest('base64'); -} -function buildSignature({ requestId, timestamp, target, digest }) { - const component = [ - `Client-Id:${clientId}`, - `Request-Id:${requestId}`, - `Request-Timestamp:${timestamp}`, - `Request-Target:${target}`, - `Digest:${digest}`, - ].join('\n'); - return `HMACSHA256=${createHmac('sha256', secretKey).update(component, 'utf8').digest('base64')}`; -} - -function pick(payload, path) { - let cursor = payload; - for (const key of path) { - if (cursor && typeof cursor === 'object' && key in cursor) cursor = cursor[key]; - else return undefined; - } - return cursor; -} - -async function main() { - const invoiceNumber = `SMOKE-DOKU-${Date.now()}-${randomUUID().slice(0, 8).toUpperCase()}`; - const body = JSON.stringify({ - order: { - amount, - invoice_number: invoiceNumber, - currency: 'IDR', - callback_url: callbackUrl, - line_items: [{ name: 'KaffePOS smoke test', price: amount, quantity: 1 }], - }, - payment: { payment_due_date: dueMinutes }, - customer: { id: invoiceNumber, name: 'Smoke Tester', email: 'smoke@kaffepos.my.id' }, - }); - - const requestId = randomUUID(); - const timestamp = dokuTimestamp(); - const signature = buildSignature({ requestId, timestamp, target: checkoutPath, digest: sha256Base64(body) }); - - console.log('── DOKU Checkout smoke test ──'); - console.log(` environment : ${environment}`); - console.log(` base url : ${baseUrl}`); - console.log(` endpoint : POST ${checkoutPath}`); - console.log(` client id : ${maskTail(clientId)}`); - console.log(` invoice : ${invoiceNumber}`); - console.log(` amount : Rp${amount.toLocaleString('id-ID')}`); - - const response = await fetch(`${baseUrl}${checkoutPath}`, { - method: 'POST', - headers: { - 'Client-Id': clientId, - 'Request-Id': requestId, - 'Request-Timestamp': timestamp, - Signature: signature, - 'Content-Type': 'application/json', - Accept: 'application/json', - }, - body, - signal: AbortSignal.timeout(20000), - }); - - const raw = await response.json().catch(async () => ({ message: await response.text().catch(() => '') })); - const paymentUrl = pick(raw, ['response', 'payment', 'url']) ?? pick(raw, ['payment', 'url']); - const tokenId = pick(raw, ['response', 'payment', 'token_id']) ?? pick(raw, ['payment', 'token_id']); - - console.log(` http status : ${response.status}`); - console.log(` payment.url : ${paymentUrl ? 'present ✓' : 'MISSING ✗'}`); - if (tokenId) console.log(` token_id : ${tokenId}`); - - if (!response.ok || !paymentUrl) { - console.error('\n✗ Smoke test FAILED. Raw response:'); - console.error(JSON.stringify(raw, null, 2)); - console.error('\nIf this is a 401/signature error: confirm DOKU_SECRET_KEY is the current key,'); - console.error('the base host matches the environment, and the system clock is accurate (timestamp).'); - process.exit(1); - } - - console.log(`\n✓ Smoke test PASSED — open the payment page to finish a test transaction:`); - console.log(` ${paymentUrl}`); -} - -main().catch((error) => { - console.error('✗ Smoke test error:', error?.message ?? error); - process.exit(1); -}); diff --git a/scripts/smoke-local-mayar.mjs b/scripts/smoke-local-mayar.mjs new file mode 100644 index 0000000..f8445ba --- /dev/null +++ b/scripts/smoke-local-mayar.mjs @@ -0,0 +1,327 @@ +#!/usr/bin/env node +/** + * Local Mayar end-to-end smoke. Boots the backend against a scratch Postgres and a + * fake Mayar API, then walks a POS QRIS order and a subscription through + * create payment (API key) → webhook (token) → API re-check → settlement. + * It never calls the real Mayar API and never touches existing databases. + * + * Requires a LOCAL Postgres and a built backend: + * npm run smoke:local:mayar + * SMOKE_PG_URL_BASE=postgresql://postgres@127.0.0.1:5432 npm run smoke:local:mayar + */ +import http from 'node:http'; +import { spawn, execSync } from 'node:child_process'; +import { randomUUID } from 'node:crypto'; + +const DB_NAME = 'kaffepos_smoke_mayar'; +const PORT = Number(process.env.SMOKE_PORT || 8911); +const MAYAR_PORT = Number(process.env.SMOKE_MAYAR_PORT || 8912); +const PG = process.env.SMOKE_PG_URL_BASE || 'postgresql://postgres@127.0.0.1:5432'; +const DB = `${PG}/${DB_NAME}`; +const BASE = `http://127.0.0.1:${PORT}`; +const MAYAR_BASE = `http://127.0.0.1:${MAYAR_PORT}`; +const API_KEY = `smoke-api-key-${randomUUID()}`; +// Same shape as the Mayar dashboard "Web Token" (128 hex characters). +const WEBHOOK_TOKEN = `${randomUUID()}${randomUUID()}${randomUUID()}${randomUUID()}`.replace(/-/g, ''); +const WEBHOOK_URL = `${BASE}/api/webhooks/mayar`; + +const sh = (cmd) => execSync(cmd, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); +const psqlAdmin = (sql) => sh(`psql "${PG}/postgres" -tA -c ${JSON.stringify(sql)}`); +const psql = (sql) => sh(`psql "${DB}" -tA -c ${JSON.stringify(sql)}`); +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +let failures = 0; +const check = (label, ok, detail = '') => { + console.log(`${ok ? '✅' : '❌'} ${label}${detail ? ` — ${detail}` : ''}`); + if (!ok) failures += 1; +}; + +// ── Fake Mayar Headless API v2 ──────────────────────────────────────────────── +const fake = { payments: new Map(), webhookUrl: null, calls: [] }; + +function readJson(req) { + return new Promise((resolve) => { + let raw = ''; + req.on('data', (chunk) => { raw += chunk; }); + req.on('end', () => { + try { resolve(raw ? JSON.parse(raw) : {}); } catch { resolve({}); } + }); + }); +} + +function send(res, status, body) { + res.writeHead(status, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(body)); +} + +const mayarServer = http.createServer(async (req, res) => { + const url = new URL(req.url, MAYAR_BASE); + const body = await readJson(req); + fake.calls.push({ method: req.method, path: url.pathname, body }); + if (req.headers.authorization !== `Bearer ${API_KEY}`) return send(res, 401, { statusCode: 401, messages: 'Unauthorized' }); + + if (req.method === 'POST' && url.pathname === '/hl/v2/payments/create') { + // Real payment requests may refuse redirectUrl; make the backend take its retry path. + if (body.redirectUrl) return send(res, 400, { statusCode: 400, messages: 'redirectUrl is not supported on payment requests and was not saved' }); + const id = randomUUID(); + const payment = { id, transactionId: randomUUID(), status: 'unpaid', amount: body.amount, name: body.name, description: body.description }; + fake.payments.set(id, payment); + return send(res, 200, { statusCode: 200, messages: 'success', data: { id, transactionId: payment.transactionId, link: `https://kaffepos.myr.id/pl/${id.slice(0, 8)}` } }); + } + const detail = url.pathname.match(/^\/hl\/v2\/payments\/([^/]+)$/); + if (req.method === 'GET' && detail) { + const payment = fake.payments.get(detail[1]); + if (!payment) return send(res, 404, { statusCode: 404, messages: 'Payment request not found' }); + return send(res, 200, { + statusCode: 200, + messages: 'success', + data: { + id: payment.id, + type: 'payment_request', + status: payment.status, + amount: payment.amount, + name: payment.name, + description: payment.description, + transactions: payment.status === 'paid' ? [{ id: payment.transactionId, status: 'paid', amount: payment.amount, updatedAt: Date.now() }] : [], + }, + }); + } + if (req.method === 'GET' && url.pathname === '/hl/v2/payments') return send(res, 200, { statusCode: 200, messages: 'success', data: [] }); + if (req.method === 'POST' && url.pathname === '/hl/v2/webhooks/update') { + fake.webhookUrl = body.urlHook; + return send(res, 200, { statusCode: 200, messages: 'success' }); + } + if (req.method === 'POST' && url.pathname === '/hl/v2/webhooks/test') { + // Like Mayar: the dashboard Web Token travels in the X-Callback-Token header. + const hook = await fetch(body.urlHook, { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'X-Callback-Token': WEBHOOK_TOKEN }, + body: JSON.stringify({ event: 'testing', data: { id: 'test-event' } }), + }).catch(() => null); + return send(res, hook?.ok ? 200 : 400, { statusCode: hook?.ok ? 200 : 400, messages: hook?.ok ? 'success' : `hook answered ${hook?.status ?? 'nothing'}` }); + } + return send(res, 404, { statusCode: 404, messages: 'unknown endpoint' }); +}); + +// ── Helpers ─────────────────────────────────────────────────────────────────── +async function api(path, { token, ...opts } = {}) { + const response = await fetch(`${BASE}${path}`, { + ...opts, + headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(opts.headers ?? {}) }, + }); + const text = await response.text(); + let body; + try { body = JSON.parse(text); } catch { body = text; } + return { status: response.status, body }; +} + +function webhookBody(payment, event = 'payment.received') { + // No extraData on purpose: KaffePOS must map the event by productId alone. + return { + event, + data: { + id: payment.transactionId, + transactionId: payment.transactionId, + productId: payment.id, + productType: 'payment_request', + productName: payment.name, + status: 'SUCCESS', + transactionStatus: 'created', + amount: payment.amount, + customerEmail: 'buyer@example.com', + createdAt: Date.now(), + updatedAt: Date.now(), + }, + }; +} + +function sendWebhook(body, { token = WEBHOOK_TOKEN, via = 'header' } = {}) { + const path = via === 'query' ? `/api/webhooks/mayar?token=${encodeURIComponent(token)}` : '/api/webhooks/mayar'; + return api(path, { + method: 'POST', + headers: via === 'header' && token ? { 'X-Callback-Token': token } : {}, + body: JSON.stringify(body), + }); +} + +let server = null; +let bootLog = ''; +try { + try { sh(`psql "${PG}/postgres" -tA -c "select 1"`); } catch { + console.error(`Local Postgres is not reachable at ${PG}. Set SMOKE_PG_URL_BASE. Aborting.`); + process.exit(2); + } + + console.log(`→ provisioning scratch database ${DB_NAME}`); + psqlAdmin(`DROP DATABASE IF EXISTS ${DB_NAME}`); + psqlAdmin(`CREATE DATABASE ${DB_NAME}`); + sh(`psql "${DB}" -v ON_ERROR_STOP=1 -f database/base-schema.sql`); + execSync( + `node -e "const{bootstrapAllSchemas}=require('./dist/schema-bootstrap.js');const{pool}=require('./dist/core/db.js');bootstrapAllSchemas().then(async()=>{await pool.end();}).catch(async(e)=>{console.error(e.message);await pool.end();process.exit(1);})"`, + { cwd: 'backend', env: { ...process.env, DATABASE_URL: DB, NODE_ENV: 'development' }, stdio: 'inherit' }, + ); + execSync('npm --prefix backend run migrate', { env: { ...process.env, DATABASE_URL: DB }, stdio: 'pipe' }); + check('scratch schema + migrations applied', true); + + await new Promise((resolve) => mayarServer.listen(MAYAR_PORT, '127.0.0.1', resolve)); + + console.log('→ booting backend dist with Mayar sandbox pointed at the fake API'); + server = spawn('node', ['dist/index.js'], { + cwd: 'backend', + env: { + ...process.env, + DATABASE_URL: DB, + NODE_ENV: 'development', + PORT: String(PORT), + LOG_LEVEL: 'info', + PAYMENT_INTEGRATION_ENABLED: 'true', + PAYMENT_GATEWAY_PROVIDER: 'mayar', + SUBSCRIPTION_PAYMENT_MODE: 'auto', + MAYAR_ENVIRONMENT: 'sandbox', + MAYAR_SANDBOX_BASE_URL: MAYAR_BASE, + MAYAR_API_KEY: API_KEY, + MAYAR_WEBHOOK_TOKEN: WEBHOOK_TOKEN, + MAYAR_CALLBACK_URL: WEBHOOK_URL, + CORS_ORIGIN: 'http://localhost:5173', + WEB_BASE_URL: 'http://localhost:5173', + API_BASE_URL: BASE, + }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + server.stdout.on('data', (chunk) => { bootLog += chunk; }); + server.stderr.on('data', (chunk) => { bootLog += chunk; }); + + let healthy = false; + for (let i = 0; i < 60 && !healthy; i += 1) { + try { healthy = (await fetch(`${BASE}/health`)).ok; } catch { /* booting */ } + if (!healthy) await sleep(300); + } + check('backend boots', healthy); + if (!healthy) { console.error(bootLog.slice(-2000)); throw new Error('boot failed'); } + + const hookInfo = await api('/api/webhooks/mayar'); + check('GET /api/webhooks/mayar reports token configured', hookInfo.body?.webhookTokenConfigured === true); + + // Owner account + store + one product + const email = 'smoke-mayar@test.local'; + const password = 'SmokeMayar123!'; + await api('/api/auth/register', { + method: 'POST', + body: JSON.stringify({ email, password, username: 'smokemayar', display_name: 'Smoke Mayar', store_name: 'Smoke Kopi' }), + }); + const code = psql(`select code from public.email_verification_codes where email='${email}' order by created_at desc limit 1`); + await api('/api/auth/verification/confirm', { method: 'POST', body: JSON.stringify({ email, code }) }); + const login = await api('/api/auth/login', { method: 'POST', body: JSON.stringify({ email, password }) }); + const token = login.body?.accessToken; + check('owner login', Boolean(token), `status=${login.status}`); + const stores = await api('/api/stores', { token }); + const storeId = stores.body?.items?.[0]?.id; + check('store available', Boolean(storeId)); + const imported = await api('/api/inventory/bulk-import/commit', { + method: 'POST', + token, + body: JSON.stringify({ store_id: storeId, mode: 'create_only', rows: [{ rowNumber: 1, kind: 'product', name: 'Kopi Susu Smoke', price: 25000, category: 'Coffee' }] }), + }); + check('product created', imported.status === 201, `status=${imported.status}`); + const menuItemId = psql(`select id from public.menu_items where name='Kopi Susu Smoke' limit 1`); + + // ── POS QRIS order ────────────────────────────────────────────────────────── + const created = await api('/api/payment/create-transaction', { + method: 'POST', + token, + body: JSON.stringify({ store_id: storeId, items: [{ menu_item_id: menuItemId, qty: 2 }], customer: { name: 'Budi' } }), + }); + const orderId = created.body?.order_id; + check('POS: Mayar payment link created with the API key', created.status === 201 && /myr\.id/.test(created.body?.payment_url ?? ''), `status=${created.status}`); + const posRow = psql(`select provider || '|' || coalesce(provider_reference,'') || '|' || coalesce(metadata->>'providerTransactionId','') from public.payment_orders where merchant_order_id='${orderId}'`); + const [posProvider, posReference, posTransactionId] = posRow.split('|'); + const posPayment = fake.payments.get(posReference); + check('POS: order stores Mayar ids', posProvider === 'mayar' && Boolean(posPayment) && posTransactionId === posPayment?.transactionId); + + const noToken = await sendWebhook(webhookBody(posPayment), { token: '' }); + const wrongToken = await sendWebhook(webhookBody(posPayment), { token: 'wrong-token' }); + check('webhook without token → 401', noToken.status === 401, `status=${noToken.status}`); + check('webhook with wrong token → 401', wrongToken.status === 401, `status=${wrongToken.status}`); + + const early = await sendWebhook(webhookBody(posPayment)); + check('forged "paid" webhook while Mayar says unpaid → 409', early.status === 409, `status=${early.status}`); + check('POS order still pending', psql(`select status from public.payment_orders where merchant_order_id='${orderId}'`) === 'pending'); + + posPayment.status = 'paid'; + const settled = await sendWebhook(webhookBody(posPayment), { via: 'query' }); + check('webhook (?token=) settles the POS order', settled.status === 200 && settled.body?.status === 'paid' && settled.body?.kind === 'pos', JSON.stringify(settled.body)); + const posAfter = psql(`select status || '|' || coalesce(transaction_id,'') from public.payment_orders where merchant_order_id='${orderId}'`).split('|'); + check('POS order completed with a transaction', posAfter[0] === 'completed' && Boolean(posAfter[1])); + check('sale recorded once', psql(`select count(*) from public.transactions where id='${posAfter[1]}'`) === '1'); + const status = await api(`/api/payment/orders/${encodeURIComponent(orderId)}`, { token }); + check('POS status endpoint reports completed', status.body?.status === 'completed'); + + const duplicate = await sendWebhook(webhookBody(posPayment)); + check('duplicate webhook acknowledged without re-settling', duplicate.status === 200 && duplicate.body?.duplicate === true); + check('still exactly one sale', psql(`select count(*) from public.transactions where store_id='${storeId}'`) === '1'); + + const membership = await sendWebhook({ event: 'membership.memberExpired', data: { id: 'm-1', status: 'SUCCESS' } }); + check('non-payment event acknowledged and ignored', membership.status === 200 && membership.body?.ignored === true); + const stranger = await sendWebhook(webhookBody({ id: randomUUID(), transactionId: randomUUID(), amount: 10000, name: 'x' })); + check('payment for an unknown order acknowledged and ignored', stranger.status === 200 && stranger.body?.reason === 'order_not_found'); + + // ── Subscription ──────────────────────────────────────────────────────────── + const start = await api('/api/payments/start', { + method: 'POST', + token, + body: JSON.stringify({ plan: 'kopi_susu', billingCycle: 'monthly', paymentMethod: 'qris' }), + }); + const paymentId = start.body?.data?.paymentId; + check('subscription: Mayar checkout created (redirectUrl retry path)', start.status === 201 && /myr\.id/.test(start.body?.data?.paymentUrl ?? ''), JSON.stringify(start.body)); + const subReference = psql(`select provider_reference from public.subscription_payment_sessions where id='${paymentId}'`); + const subPayment = fake.payments.get(subReference); + subPayment.status = 'paid'; + const subHook = await sendWebhook(webhookBody(subPayment)); + check('webhook activates the subscription', subHook.status === 200 && subHook.body?.kind === 'subscription', JSON.stringify(subHook.body)); + check('session linked to a subscription', Boolean(psql(`select coalesce(subscription_id::text,'') from public.subscription_payment_sessions where id='${paymentId}'`))); + const manual = await api(`/api/payments/${paymentId}/check`, { method: 'POST', token, body: '{}' }); + check('manual "cek status" agrees and is idempotent', manual.status === 200 && manual.body?.status === 'paid'); + const userId = psql(`select id from public.profiles where email='${email}'`); + const merchantOrderId = start.body?.data?.merchantOrderId; + const paidSubscriptions = psql(`select count(*) from public.subscriptions where user_id='${userId}' and payment_ref='${merchantOrderId}'`); + check('exactly one subscription for this payment', paidSubscriptions === '1', `count=${paidSubscriptions}`); + check('Kopi Susu plan active', psql(`select plan from public.subscriptions where user_id='${userId}' and status='active' order by created_at desc limit 1`) === 'kopi_susu'); + + // ── Connect script ────────────────────────────────────────────────────────── + // Async spawn: the fake Mayar API lives in this process and must keep serving. + const connect = await new Promise((resolve) => { + const child = spawn('node', ['backend/scripts/mayar-connect.mjs', '--register', '--env-file=/dev/null'], { + env: { + PATH: process.env.PATH, + MAYAR_ENVIRONMENT: 'sandbox', + MAYAR_SANDBOX_BASE_URL: MAYAR_BASE, + MAYAR_API_KEY: API_KEY, + MAYAR_WEBHOOK_TOKEN: WEBHOOK_TOKEN, + MAYAR_CALLBACK_URL: WEBHOOK_URL, + }, + }); + let stdout = ''; + child.stdout.on('data', (chunk) => { stdout += chunk; }); + child.stderr.on('data', (chunk) => { stdout += chunk; }); + child.on('close', (code) => resolve({ status: code, stdout })); + }); + check('mayar:connect --register passes', connect.status === 0, connect.status === 0 ? '' : connect.stdout.slice(-800)); + check('connect output masks the secrets', !connect.stdout.includes(WEBHOOK_TOKEN) && !connect.stdout.includes(API_KEY)); + check('webhook URL registered without a token in it (header mode)', fake.webhookUrl === WEBHOOK_URL, String(fake.webhookUrl)); + + await sleep(300); + check('webhook token never appears in backend logs', !bootLog.includes(WEBHOOK_TOKEN)); + check('API key never appears in backend logs', !bootLog.includes(API_KEY)); + + console.log(failures === 0 ? '\n🎉 MAYAR LOCAL SMOKE: ALL PASS' : `\n💥 MAYAR LOCAL SMOKE: ${failures} failure(s)`); + process.exitCode = failures === 0 ? 0 : 1; +} catch (error) { + console.error('SMOKE FAILED:', error.message); + if (bootLog) console.error(bootLog.slice(-2000)); + process.exitCode = 1; +} finally { + if (server) server.kill('SIGTERM'); + mayarServer.close(); + await sleep(500); + try { psqlAdmin(`DROP DATABASE IF EXISTS ${DB_NAME}`); console.log('→ scratch database dropped'); } catch { /* best effort */ } +} diff --git a/scripts/smoke-mayar-staging.mjs b/scripts/smoke-mayar-staging.mjs index 147ea93..dda8958 100644 --- a/scripts/smoke-mayar-staging.mjs +++ b/scripts/smoke-mayar-staging.mjs @@ -37,7 +37,7 @@ const environment = process.env.MAYAR_ENVIRONMENT === 'production' ? 'production const baseUrl = ( environment === 'production' ? process.env.MAYAR_PRODUCTION_BASE_URL || 'https://api.mayar.id' - : process.env.MAYAR_SANDBOX_BASE_URL || 'https://api.mayar.club' + : process.env.MAYAR_SANDBOX_BASE_URL || 'https://api.mayar.io' ).replace(/\/$/, ''); const createPath = process.env.MAYAR_CREATE_PAYMENT_PATH || '/hl/v2/payments/create'; const dueMinutes = Number(process.env.MAYAR_PAYMENT_DUE_MINUTES || 60); diff --git a/scripts/smoke-production-readiness.mjs b/scripts/smoke-production-readiness.mjs index b6b16d3..6b858b2 100644 --- a/scripts/smoke-production-readiness.mjs +++ b/scripts/smoke-production-readiness.mjs @@ -91,10 +91,10 @@ try { } if (payment?.environment === 'production' && payment?.commerciallyReady === true) { - pass('Midtrans is production and commercially ready'); + pass('Mayar is production and commercially ready'); } else { fail( - `Midtrans is not production-ready (environment=${payment?.environment ?? 'unknown'}, mode=${ + `Mayar is not production-ready (environment=${payment?.environment ?? 'unknown'}, mode=${ payment?.mode ?? 'unknown' }, commerciallyReady=${String(payment?.commerciallyReady)})`, ); diff --git a/scripts/verify-release-config.mjs b/scripts/verify-release-config.mjs index 3aae658..8736281 100755 --- a/scripts/verify-release-config.mjs +++ b/scripts/verify-release-config.mjs @@ -71,11 +71,10 @@ function forbidEnvFilePrefix(prefix, files) { if (isProduction) { requireEquals('WEB_BASE_URL', 'https://kaffepos.my.id'); requireEquals('API_BASE_URL', 'https://api.kaffepos.my.id'); - requireEquals('MIDTRANS_ENVIRONMENT', 'production'); - requireEquals('MIDTRANS_IS_PRODUCTION', 'true'); - requirePresent('MIDTRANS_SERVER_KEY'); - requirePresent('MIDTRANS_CLIENT_KEY'); - requirePresent('MIDTRANS_MERCHANT_ID'); + requireEquals('PAYMENT_GATEWAY_PROVIDER', 'mayar'); + requireEquals('MAYAR_ENVIRONMENT', 'production'); + requirePresent('MAYAR_API_KEY'); + requirePresent('MAYAR_WEBHOOK_TOKEN'); requirePresent('VITE_CLARITY_PROJECT_ID'); requirePresent('SENTRY_DSN'); requirePresent('VITE_SENTRY_DSN'); @@ -87,6 +86,9 @@ if (isProduction) { forbidPrefix('SUPABASE_'); forbidPrefix('VITE_SUPABASE_'); +// Mayar API key / webhook token are backend-only secrets. +forbidPrefix('VITE_MAYAR_'); +forbidEnvFilePrefix('VITE_MAYAR_', ['.env', '.env.local', '.env.production', '.env.production.local', '.env.release.local', 'android/.env']); forbidEnvFilePrefix('SUPABASE_', ['.env', '.env.local', '.env.production', '.env.production.local', '.env.release.local', 'android/.env', 'backend/.env']); forbidEnvFilePrefix('VITE_SUPABASE_', ['.env', '.env.local', '.env.production', '.env.production.local', '.env.release.local', 'android/.env', 'backend/.env']); diff --git a/scripts/verify-staging-env.mjs b/scripts/verify-staging-env.mjs index f77a59b..43ececf 100755 --- a/scripts/verify-staging-env.mjs +++ b/scripts/verify-staging-env.mjs @@ -25,10 +25,9 @@ const BACKEND_REQUIRED = [ 'SESSION_SECRET', 'ENCRYPTION_KEY', 'PAYMENT_GATEWAY_PROVIDER', - 'DOKU_ENVIRONMENT', - 'DOKU_CLIENT_ID', - 'DOKU_SECRET_KEY', - 'DOKU_CALLBACK_URL', + 'MAYAR_ENVIRONMENT', + 'MAYAR_API_KEY', + 'MAYAR_WEBHOOK_TOKEN', 'RESEND_API_KEY', 'RESEND_FROM_EMAIL', 'EMAIL_REPLY_TO', @@ -88,10 +87,9 @@ const PAYMENT_BACKEND_REQUIRED = [ 'ENCRYPTION_KEY', 'PAYMENT_INTEGRATION_ENABLED', 'PAYMENT_GATEWAY_PROVIDER', - 'DOKU_ENVIRONMENT', - 'DOKU_CLIENT_ID', - 'DOKU_SECRET_KEY', - 'DOKU_CALLBACK_URL', + 'MAYAR_ENVIRONMENT', + 'MAYAR_API_KEY', + 'MAYAR_WEBHOOK_TOKEN', 'SUBSCRIPTION_PAYMENT_MODE', ]; @@ -114,8 +112,8 @@ const MINIMAL_OPTIONAL_SKIPPED = [ 'VITE_GA4_MEASUREMENT_ID', 'VITE_CLARITY_PROJECT_ID', 'VITE_PUBLIC_ASSET_BASE_URL', - 'DOKU_CLIENT_ID', - 'DOKU_SECRET_KEY', + 'MAYAR_API_KEY', + 'MAYAR_WEBHOOK_TOKEN', 'RESEND_API_KEY', 'RESEND_FROM_EMAIL', 'EMAIL_REPLY_TO', @@ -144,8 +142,8 @@ const FORBIDDEN_FRONTEND_PATTERNS = [ /SESSION_SECRET/i, /ENCRYPTION_KEY/i, /MIDTRANS_SERVER_KEY/i, - /DOKU_SECRET_KEY/i, - /DOKU_CLIENT_ID/i, + /MAYAR_API_KEY/i, + /MAYAR_WEBHOOK_TOKEN/i, /RESEND_API_KEY/i, /CLOUDFLARE_R2_(ACCESS_KEY_ID|SECRET_ACCESS_KEY)/i, /GA4_API_SECRET/i, @@ -197,7 +195,6 @@ const PAYMENT_URL_REQUIRED_KEYS = [ 'VITE_API_BASE_URL', 'WEB_BASE_URL', 'API_BASE_URL', - 'DOKU_CALLBACK_URL', ]; const DEFAULT_ENV_FILES = [ @@ -324,7 +321,7 @@ function main() { if (stagingProfile === 'payment' && env.STAGING_PROFILE !== 'payment') invalidStagingValues.push('STAGING_PROFILE must be payment'); if (stagingProfile === 'payment' && env.VITE_STAGING_PROFILE !== 'payment') invalidStagingValues.push('VITE_STAGING_PROFILE must be payment'); if (env.MIDTRANS_IS_PRODUCTION && env.MIDTRANS_IS_PRODUCTION !== 'false') invalidStagingValues.push('MIDTRANS_IS_PRODUCTION must be false'); - if (env.DOKU_ENVIRONMENT && env.DOKU_ENVIRONMENT !== 'sandbox') invalidStagingValues.push('DOKU_ENVIRONMENT must be sandbox in staging'); + if (env.MAYAR_ENVIRONMENT && env.MAYAR_ENVIRONMENT !== 'sandbox') invalidStagingValues.push('MAYAR_ENVIRONMENT must be sandbox in staging'); if (stagingProfile === 'minimal') { for (const key of ['PAYMENT_INTEGRATION_ENABLED', 'EMAIL_INTEGRATION_ENABLED', 'R2_STORAGE_ENABLED', 'ANALYTICS_SERVER_ENABLED']) { if (env[key] !== 'false') invalidStagingValues.push(`${key} must be false in minimal staging`); @@ -334,11 +331,11 @@ function main() { } if (stagingProfile === 'payment') { const expected = { - PAYMENT_GATEWAY_PROVIDER: 'doku', + PAYMENT_GATEWAY_PROVIDER: 'mayar', PAYMENT_INTEGRATION_ENABLED: 'true', - DOKU_ENVIRONMENT: 'sandbox', - SUBSCRIPTION_PAYMENT_MODE: 'doku_sandbox', - VITE_PAYMENT_GATEWAY_PROVIDER: 'doku', + MAYAR_ENVIRONMENT: 'sandbox', + SUBSCRIPTION_PAYMENT_MODE: 'mayar_sandbox', + VITE_PAYMENT_GATEWAY_PROVIDER: 'mayar', }; for (const [key, value] of Object.entries(expected)) { if (env[key] !== value) invalidStagingValues.push(`${key} must be ${value} in payment staging`); diff --git a/src/components/settings/SubscriptionSection.tsx b/src/components/settings/SubscriptionSection.tsx index a11324d..1a69eec 100644 --- a/src/components/settings/SubscriptionSection.tsx +++ b/src/components/settings/SubscriptionSection.tsx @@ -123,7 +123,7 @@ export default function SubscriptionSection({ isPro, profile, toast, onRefreshSt if (!billing) return; billingNoticeShown.current = true; - if (billing === 'success' || billing === 'mayar-return' || billing === 'doku-return') { + if (billing === 'success' || billing === 'mayar-return') { toast.showToast('Menunggu konfirmasi pembayaran. Lisensi aktif setelah callback terverifikasi.', 'info'); trackAnalyticsEvent('payment_returned', { source: 'subscription_return', payment_provider: params.get('provider') || 'mayar' }); void trackOpsEvent({ diff --git a/src/lib/backendApi.ts b/src/lib/backendApi.ts index 57a0f67..1cf7ff3 100644 --- a/src/lib/backendApi.ts +++ b/src/lib/backendApi.ts @@ -311,7 +311,7 @@ export type GenericPaymentStartResponse = { success: true; data: { paymentId: string; - provider: 'mayar' | 'doku' | 'disabled' | string; + provider: 'mayar' | 'disabled' | string; merchantOrderId: string; paymentUrl: string | null; status: string; @@ -505,11 +505,10 @@ export const updateCashRegisterEntry = (id: string, payload: Record(`/api/cash-register/${id}`, { method: 'PATCH', json: payload }); export type SubscriptionPaymentConfig = { - mode: 'manual' | 'disabled' | 'mayar_sandbox' | 'mayar_production' | 'doku_sandbox' | 'doku_production'; + mode: 'manual' | 'disabled' | 'mayar_sandbox' | 'mayar_production'; provider: string; environment?: 'sandbox' | 'production'; mayarEnvironment?: 'sandbox' | 'production'; - dokuEnvironment?: 'sandbox' | 'production'; onlinePaymentAvailable: boolean; manualActivationAvailable: boolean; commerciallyReady: boolean; diff --git a/src/test/components/SubscriptionCheckoutFlow.test.tsx b/src/test/components/SubscriptionCheckoutFlow.test.tsx index c1a4b62..57e53a4 100644 --- a/src/test/components/SubscriptionCheckoutFlow.test.tsx +++ b/src/test/components/SubscriptionCheckoutFlow.test.tsx @@ -41,9 +41,9 @@ describe('SubscriptionCheckoutFlow interaction', () => { quote, paymentMethods: [], paymentConfig: { - mode: 'doku_sandbox', - provider: 'doku', - dokuEnvironment: 'sandbox', + mode: 'mayar_sandbox', + provider: 'mayar', + mayarEnvironment: 'sandbox', onlinePaymentAvailable: true, manualActivationAvailable: true, commerciallyReady: false, @@ -180,8 +180,8 @@ describe('SubscriptionCheckoutFlow interaction', () => { paymentMethods: [], paymentConfig: { mode: 'disabled', - provider: 'doku', - dokuEnvironment: 'sandbox', + provider: 'mayar', + mayarEnvironment: 'sandbox', onlinePaymentAvailable: false, manualActivationAvailable: true, commerciallyReady: false, @@ -223,8 +223,8 @@ describe('SubscriptionCheckoutFlow interaction', () => { }, }; vi.mocked(getSubscriptionPaymentQuote) - .mockResolvedValueOnce({ quote, paymentMethods: [], paymentConfig: { mode: 'doku_sandbox', provider: 'doku', dokuEnvironment: 'sandbox', onlinePaymentAvailable: true, manualActivationAvailable: true, commerciallyReady: false, message: 'Sandbox siap.', recommendedAction: 'Test checkout.' } }) - .mockResolvedValueOnce({ quote: discountedQuote, paymentMethods: [], paymentConfig: { mode: 'doku_sandbox', provider: 'doku', dokuEnvironment: 'sandbox', onlinePaymentAvailable: true, manualActivationAvailable: true, commerciallyReady: false, message: 'Sandbox siap.', recommendedAction: 'Test checkout.' } }); + .mockResolvedValueOnce({ quote, paymentMethods: [], paymentConfig: { mode: 'mayar_sandbox', provider: 'mayar', mayarEnvironment: 'sandbox', onlinePaymentAvailable: true, manualActivationAvailable: true, commerciallyReady: false, message: 'Sandbox siap.', recommendedAction: 'Test checkout.' } }) + .mockResolvedValueOnce({ quote: discountedQuote, paymentMethods: [], paymentConfig: { mode: 'mayar_sandbox', provider: 'mayar', mayarEnvironment: 'sandbox', onlinePaymentAvailable: true, manualActivationAvailable: true, commerciallyReady: false, message: 'Sandbox siap.', recommendedAction: 'Test checkout.' } }); const assign = vi.fn(); Object.defineProperty(window, 'location', { diff --git a/src/test/components/SubscriptionSection.test.tsx b/src/test/components/SubscriptionSection.test.tsx index a7e898a..229c601 100644 --- a/src/test/components/SubscriptionSection.test.tsx +++ b/src/test/components/SubscriptionSection.test.tsx @@ -40,9 +40,9 @@ describe('SubscriptionSection billing center', () => { paymentHistory: [], pendingPayments: [], paymentConfig: { - mode: 'doku_sandbox', - provider: 'doku', - dokuEnvironment: 'sandbox', + mode: 'mayar_sandbox', + provider: 'mayar', + mayarEnvironment: 'sandbox', onlinePaymentAvailable: true, manualActivationAvailable: true, commerciallyReady: false, @@ -83,9 +83,9 @@ describe('SubscriptionSection billing center', () => { }, ], paymentConfig: { - mode: 'doku_sandbox', - provider: 'doku', - dokuEnvironment: 'sandbox', + mode: 'mayar_sandbox', + provider: 'mayar', + mayarEnvironment: 'sandbox', onlinePaymentAvailable: true, manualActivationAvailable: true, commerciallyReady: false, diff --git a/src/test/releaseConfigScript.test.ts b/src/test/releaseConfigScript.test.ts index 23e0a94..fc9aa08 100644 --- a/src/test/releaseConfigScript.test.ts +++ b/src/test/releaseConfigScript.test.ts @@ -10,12 +10,23 @@ describe('release config script guardrails', () => { expect(script).toContain("requireContains('CORS_ORIGIN', 'https://localhost')"); }); + it('requires Mayar production credentials and keeps them out of the frontend bundle', () => { + const script = readFileSync(resolve(process.cwd(), 'scripts/verify-release-config.mjs'), 'utf8'); + + expect(script).toContain("requireEquals('PAYMENT_GATEWAY_PROVIDER', 'mayar')"); + expect(script).toContain("requireEquals('MAYAR_ENVIRONMENT', 'production')"); + expect(script).toContain("requirePresent('MAYAR_API_KEY')"); + expect(script).toContain("requirePresent('MAYAR_WEBHOOK_TOKEN')"); + expect(script).toContain("forbidPrefix('VITE_MAYAR_')"); + expect(script).not.toContain('MIDTRANS_'); + }); + it('smoke production readiness verifies final CORS origins, payment, and monitoring', () => { const script = readFileSync(resolve(process.cwd(), 'scripts/smoke-production-readiness.mjs'), 'utf8'); expect(script).toContain("['http://localhost', 'https://localhost', 'capacitor://localhost']"); expect(script).toContain('CORS preflight allows final APK origin'); - expect(script).toContain('Midtrans is production and commercially ready'); + expect(script).toContain('Mayar is production and commercially ready'); expect(script).toContain('Backend error tracking is configured'); }); @@ -39,7 +50,8 @@ describe('release config script guardrails', () => { expect(packageJson).toContain('"smoke:production:billing"'); expect(script).toContain("KAFFEPOS_BILLING_API_BASE_URL || process.env.API_BASE_URL || 'https://api.kaffepos.my.id'"); expect(script).toContain('/system-status'); - expect(script).toContain("payment?.mode === 'doku_production'"); + expect(script).toContain("payment?.mode === 'mayar_production'"); + expect(script).not.toContain('doku'); expect(script).toContain("payment?.commerciallyReady === true"); expect(script).toContain('subscription_payments'); expect(script).toContain('KAFFEPOS_BILLING_EMAIL');