Phase 5 Xendit: Stages 1-7 (XENDIT_ENABLED=false; Stage 8 pending creds)
Backend - payment_sessions → payment_requests rename across DB schema + 29 files - payment.service.js becomes product-agnostic owner: EventEmitter + Xendit wrapper + requestPayment / confirmPayment public API; legacy aliases retained for existing chat callers - Webhook handler at POST /api/shared/payment/webhooks/xendit, with constant-time token verification (8 vitest cases) - Server-driven pairing: payment.service emits payment_request.confirmed → pairing subscriber starts the blast. Legacy POST /chat/request still works during the cutover. - Reconciliation sweeper extended (re-emits events for confirmed rows with no chat session) - SIGTERM drain + startup reconciliation pass in server.js Customer app - waiting_payment_screen opens xendit_invoice_url via LaunchMode.inAppBrowserView - searching / no-bestie / targeted-waiting / pairing-notifier updated to consume the new payment_request_id contract - pending_payments_provider + bestie-unavailable dialog migrated Dev / testing - XENDIT_ENABLED=false is the safe default; .env.example documents the four new vars - backend/.dev/xendit-fake-webhook.sh exercises the handler without ngrok - 90/92 backend tests pass (two pre-existing session-timer flakes, unrelated); client_app analyzer clean - requirement/phase5-xendit-plan.md is the canonical reference Stage 8 (live E2E) blocked on Xendit test-mode keys. The dashboard's single-webhook-URL constraint will be worked around via a self-poll script next session. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -48,7 +48,7 @@ export const internalTestRoutes = async (fastify) => {
|
||||
await sql`DELETE FROM chat_request_notifications WHERE session_id IN (SELECT id FROM chat_sessions WHERE customer_id = ${id})`
|
||||
await sql`DELETE FROM customer_transactions WHERE customer_id = ${id}`
|
||||
await sql`DELETE FROM chat_sessions WHERE customer_id = ${id}`
|
||||
await sql`DELETE FROM payment_sessions WHERE customer_id = ${id}`
|
||||
await sql`DELETE FROM payment_requests WHERE customer_id = ${id}`
|
||||
await sql`DELETE FROM auth_sessions WHERE user_id = ${id} AND user_type = 'customer'`
|
||||
}
|
||||
await sql`DELETE FROM customers WHERE phone = ${phone}`
|
||||
@@ -65,7 +65,7 @@ export const internalTestRoutes = async (fastify) => {
|
||||
let target
|
||||
if (latest === true) {
|
||||
const [row] = await sql`
|
||||
SELECT id FROM payment_sessions
|
||||
SELECT id FROM payment_requests
|
||||
WHERE status = 'pending'
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
@@ -78,7 +78,7 @@ export const internalTestRoutes = async (fastify) => {
|
||||
return reply.code(400).send({ error: 'latest:true required in body' })
|
||||
}
|
||||
const [updated] = await sql`
|
||||
UPDATE payment_sessions
|
||||
UPDATE payment_requests
|
||||
SET status = 'confirmed', confirmed_at = NOW()
|
||||
WHERE id = ${target} AND status = 'pending'
|
||||
RETURNING id, customer_id, status, mode, duration_minutes, is_first_session_discount, targeted_mitra_id
|
||||
@@ -105,7 +105,7 @@ export const internalTestRoutes = async (fastify) => {
|
||||
let target
|
||||
if (latest === true) {
|
||||
const [row] = await sql`
|
||||
SELECT id FROM payment_sessions
|
||||
SELECT id FROM payment_requests
|
||||
WHERE status = 'pending'
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
@@ -120,7 +120,7 @@ export const internalTestRoutes = async (fastify) => {
|
||||
return reply.code(400).send({ error: 'payment_id or latest:true required in body' })
|
||||
}
|
||||
const [updated] = await sql`
|
||||
UPDATE payment_sessions
|
||||
UPDATE payment_requests
|
||||
SET status = 'expired', expires_at = NOW() - INTERVAL '1 minute'
|
||||
WHERE id = ${target} AND status = 'pending'
|
||||
RETURNING id, status
|
||||
@@ -168,7 +168,7 @@ export const internalTestRoutes = async (fastify) => {
|
||||
const [linked] = await sql`
|
||||
SELECT ps.targeted_mitra_id
|
||||
FROM chat_sessions cs
|
||||
LEFT JOIN payment_sessions ps ON ps.id = cs.payment_session_id
|
||||
LEFT JOIN payment_requests ps ON ps.id = cs.payment_request_id
|
||||
WHERE cs.id = ${target}
|
||||
LIMIT 1
|
||||
`
|
||||
@@ -268,7 +268,7 @@ export const internalTestRoutes = async (fastify) => {
|
||||
return { ok: true, session_id: session.id, mitra_id: mitra.id, mitra_name: mitra.display_name }
|
||||
})
|
||||
|
||||
// Seed a payment_sessions row in `pending` status for the customer linked
|
||||
// Seed a payment_requests row in `pending` status for the customer linked
|
||||
// to `phone`, with expires_at safely in the future. Used by Maestro Stage
|
||||
// 10 flow (09_chat_tab.yaml) to populate the Pembayaran sub-tab without
|
||||
// walking the multi-screen S6 paywall → method → duration → method flow.
|
||||
@@ -297,7 +297,7 @@ export const internalTestRoutes = async (fastify) => {
|
||||
return reply.code(404).send({ error: 'no_customer_for_phone', phone })
|
||||
}
|
||||
const [row] = await sql`
|
||||
INSERT INTO payment_sessions (
|
||||
INSERT INTO payment_requests (
|
||||
customer_id, amount, duration_minutes, is_first_session_discount,
|
||||
is_extension, status, mode, expires_at
|
||||
) VALUES (
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
getEarlyEndConfig, setEarlyEndConfig,
|
||||
getMitraPingConfig, setMitraPingConfig, getMitraHeartbeatCadenceSeconds,
|
||||
getSensitivityConfig, setSensitivityConfig,
|
||||
getPaymentSessionTimeoutMinutes, setPaymentSessionTimeoutMinutes,
|
||||
getPaymentRequestTimeoutMinutes, setPaymentRequestTimeoutMinutes,
|
||||
getReturningChatConfirmationTimeoutSeconds, setReturningChatConfirmationTimeoutSeconds,
|
||||
getExtensionDefaultActionOnTimeout, setExtensionDefaultActionOnTimeout,
|
||||
getPairingBlastTimeoutSeconds, setPairingBlastTimeoutSeconds,
|
||||
@@ -247,21 +247,21 @@ export const internalConfigRoutes = async (app) => {
|
||||
app.get('/payment-session-timeout', {
|
||||
preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
|
||||
}, async (_req, reply) => {
|
||||
return reply.send({ success: true, data: await getPaymentSessionTimeoutMinutes() })
|
||||
return reply.send({ success: true, data: await getPaymentRequestTimeoutMinutes() })
|
||||
})
|
||||
|
||||
app.patch('/payment-session-timeout', {
|
||||
preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
|
||||
}, async (request, reply) => {
|
||||
const { payment_session_timeout_minutes } = request.body ?? {}
|
||||
if (typeof payment_session_timeout_minutes !== 'number' || payment_session_timeout_minutes < 1) {
|
||||
const { payment_request_timeout_minutes } = request.body ?? {}
|
||||
if (typeof payment_request_timeout_minutes !== 'number' || payment_request_timeout_minutes < 1) {
|
||||
return reply.code(422).send({
|
||||
success: false,
|
||||
error: { code: 'VALIDATION_ERROR', message: 'payment_session_timeout_minutes must be a number >= 1' },
|
||||
error: { code: 'VALIDATION_ERROR', message: 'payment_request_timeout_minutes must be a number >= 1' },
|
||||
})
|
||||
}
|
||||
const config = await setPaymentSessionTimeoutMinutes(payment_session_timeout_minutes)
|
||||
await publishConfigInvalidate('payment_session_timeout_minutes')
|
||||
const config = await setPaymentRequestTimeoutMinutes(payment_request_timeout_minutes)
|
||||
await publishConfigInvalidate('payment_request_timeout_minutes')
|
||||
return reply.send({ success: true, data: config })
|
||||
})
|
||||
|
||||
|
||||
@@ -47,16 +47,16 @@ export const clientChatRoutes = async (app) => {
|
||||
/**
|
||||
* Start a general-blast pairing search.
|
||||
*
|
||||
* Body MUST include `payment_session_id` (a confirmed payment_session owned by the caller).
|
||||
* Body MUST include `payment_request_id` (a confirmed payment_request owned by the caller).
|
||||
* Pricing/duration/free-trial values are sourced from the payment session, NOT from the client.
|
||||
*/
|
||||
app.post('/request', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
|
||||
const { payment_session_id, topic_sensitivity } = request.body ?? {}
|
||||
const { payment_request_id, topic_sensitivity } = request.body ?? {}
|
||||
|
||||
if (!payment_session_id) {
|
||||
if (!payment_request_id) {
|
||||
return reply.code(400).send({
|
||||
success: false,
|
||||
error: { code: 'BAD_REQUEST', message: 'payment_session_id is required' },
|
||||
error: { code: 'BAD_REQUEST', message: 'payment_request_id is required' },
|
||||
})
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ export const clientChatRoutes = async (app) => {
|
||||
}
|
||||
|
||||
const session = await createPairingRequest(request.customer.id, {
|
||||
paymentSessionId: payment_session_id,
|
||||
paymentRequestId: payment_request_id,
|
||||
topic_sensitivity,
|
||||
})
|
||||
return reply.code(201).send({ success: true, data: session })
|
||||
@@ -77,18 +77,18 @@ export const clientChatRoutes = async (app) => {
|
||||
/**
|
||||
* Start a targeted "Curhat lagi" pairing request.
|
||||
*
|
||||
* Body: { payment_session_id, mitra_id, topic_sensitivity? }
|
||||
* Body: { payment_request_id, mitra_id, topic_sensitivity? }
|
||||
* Returns 409 with reason: 'targeted_mitra_offline' if the targeted mitra is unreachable
|
||||
* or at capacity. The payment session stays `confirmed` in that case so the customer
|
||||
* can fall back to general blast on the same payment.
|
||||
*/
|
||||
app.post('/chat-requests/returning', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
|
||||
const { payment_session_id, mitra_id, topic_sensitivity } = request.body ?? {}
|
||||
const { payment_request_id, mitra_id, topic_sensitivity } = request.body ?? {}
|
||||
|
||||
if (!payment_session_id) {
|
||||
if (!payment_request_id) {
|
||||
return reply.code(400).send({
|
||||
success: false,
|
||||
error: { code: 'BAD_REQUEST', message: 'payment_session_id is required' },
|
||||
error: { code: 'BAD_REQUEST', message: 'payment_request_id is required' },
|
||||
})
|
||||
}
|
||||
if (!mitra_id) {
|
||||
@@ -103,7 +103,7 @@ export const clientChatRoutes = async (app) => {
|
||||
: TopicSensitivity.REGULAR
|
||||
|
||||
const session = await createTargetedPairingRequest(request.customer.id, {
|
||||
paymentSessionId: payment_session_id,
|
||||
paymentRequestId: payment_request_id,
|
||||
targetedMitraId: mitra_id,
|
||||
topic_sensitivity: resolvedTopic,
|
||||
})
|
||||
@@ -113,26 +113,26 @@ export const clientChatRoutes = async (app) => {
|
||||
/**
|
||||
* Customer-initiated cancel during searching/waiting.
|
||||
*
|
||||
* Body: { payment_session_id }
|
||||
* Terminal — payment session moves to failed_pairing with cause = customer_cancelled.
|
||||
* Body: { payment_request_id }
|
||||
* Terminal — payment session moves to failed_delivery with cause = customer_cancelled.
|
||||
*/
|
||||
app.post('/chat-requests/cancel', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
|
||||
const { payment_session_id } = request.body ?? {}
|
||||
if (!payment_session_id) {
|
||||
const { payment_request_id } = request.body ?? {}
|
||||
if (!payment_request_id) {
|
||||
return reply.code(400).send({
|
||||
success: false,
|
||||
error: { code: 'BAD_REQUEST', message: 'payment_session_id is required' },
|
||||
error: { code: 'BAD_REQUEST', message: 'payment_request_id is required' },
|
||||
})
|
||||
}
|
||||
const result = await cancelPaymentSearch(payment_session_id, request.customer.id)
|
||||
const result = await cancelPaymentSearch(payment_request_id, request.customer.id)
|
||||
return reply.send({ success: true, data: result })
|
||||
})
|
||||
|
||||
/**
|
||||
* After a returning-chat fail, customer taps "Chat dengan bestie lain".
|
||||
* Reuses the same payment_session_id (no double-charge), runs general blast.
|
||||
* Reuses the same payment_request_id (no double-charge), runs general blast.
|
||||
*/
|
||||
app.post('/chat-requests/:paymentSessionId/fallback-to-blast', {
|
||||
app.post('/chat-requests/:paymentRequestId/fallback-to-blast', {
|
||||
preHandler: [authenticate, resolveCustomer],
|
||||
}, async (request, reply) => {
|
||||
const { topic_sensitivity } = request.body ?? {}
|
||||
@@ -140,7 +140,7 @@ export const clientChatRoutes = async (app) => {
|
||||
? TopicSensitivity.SENSITIVE
|
||||
: TopicSensitivity.REGULAR
|
||||
const session = await fallbackToGeneralBlast(
|
||||
request.params.paymentSessionId,
|
||||
request.params.paymentRequestId,
|
||||
request.customer.id,
|
||||
{ topic_sensitivity: resolvedTopic },
|
||||
)
|
||||
@@ -150,7 +150,7 @@ export const clientChatRoutes = async (app) => {
|
||||
/**
|
||||
* Cancel-by-session-id retained for in-flight chat_session cancels (e.g. cancel
|
||||
* during the 20s targeted wait after a chat_session has been created). Customer cancel
|
||||
* via payment_session_id should prefer POST /chat-requests/cancel above.
|
||||
* via payment_request_id should prefer POST /chat-requests/cancel above.
|
||||
*/
|
||||
app.post('/request/:sessionId/cancel', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
|
||||
const session = await cancelPairingRequest(request.params.sessionId, request.customer.id)
|
||||
@@ -173,17 +173,17 @@ export const clientChatRoutes = async (app) => {
|
||||
})
|
||||
|
||||
/**
|
||||
* Extension request REQUIRES `extension_payment_session_id`.
|
||||
* Extension request REQUIRES `extension_payment_request_id`.
|
||||
* The payment session must be is_extension=true and is_first_session_discount=false.
|
||||
* Pricing/duration come from the payment session via the extension service.
|
||||
*/
|
||||
app.post('/session/:sessionId/extend', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
|
||||
const { duration_minutes, price, extension_payment_session_id } = request.body ?? {}
|
||||
const { duration_minutes, price, extension_payment_request_id } = request.body ?? {}
|
||||
|
||||
if (!extension_payment_session_id) {
|
||||
if (!extension_payment_request_id) {
|
||||
return reply.code(400).send({
|
||||
success: false,
|
||||
error: { code: 'BAD_REQUEST', message: 'extension_payment_session_id is required' },
|
||||
error: { code: 'BAD_REQUEST', message: 'extension_payment_request_id is required' },
|
||||
})
|
||||
}
|
||||
if (!duration_minutes || price === undefined) {
|
||||
@@ -196,7 +196,7 @@ export const clientChatRoutes = async (app) => {
|
||||
const extension = await requestExtension(request.params.sessionId, request.customer.id, {
|
||||
duration_minutes,
|
||||
price,
|
||||
extension_payment_session_id,
|
||||
extension_payment_request_id,
|
||||
})
|
||||
return reply.send({ success: true, data: extension })
|
||||
})
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { authenticate } from '../../plugins/auth.js'
|
||||
import { getCustomerById } from '../../services/customer.service.js'
|
||||
import {
|
||||
createPaymentSession,
|
||||
confirmPaymentSession,
|
||||
abandonPaymentSession,
|
||||
getPaymentSession,
|
||||
requestPayment,
|
||||
confirmPaymentForCustomer,
|
||||
cancelPayment,
|
||||
getPayment,
|
||||
getCustomerPendingPayments,
|
||||
} from '../../services/payment.service.js'
|
||||
import {
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
findTier,
|
||||
readFirstSessionDiscountConfig,
|
||||
} from '../../services/pricing.service.js'
|
||||
import { getXenditConfig } from '../../services/config.service.js'
|
||||
import { UserType, SessionMode } from '../../constants.js'
|
||||
|
||||
const resolveCustomer = async (request, reply) => {
|
||||
@@ -35,10 +36,10 @@ const resolveCustomer = async (request, reply) => {
|
||||
/**
|
||||
* Payment session lifecycle (mocked — no Xendit yet).
|
||||
*
|
||||
* POST /api/client/payment-sessions
|
||||
* POST /api/client/payment-sessions/:id/confirm
|
||||
* POST /api/client/payment-sessions/:id/cancel
|
||||
* GET /api/client/payment-sessions/:id
|
||||
* POST /api/client/payment-requests
|
||||
* POST /api/client/payment-requests/:id/confirm
|
||||
* POST /api/client/payment-requests/:id/cancel
|
||||
* GET /api/client/payment-requests/:id
|
||||
*/
|
||||
export const clientPaymentRoutes = async (app) => {
|
||||
// Create a payment session (status = pending). First-session-discount is server-authoritative:
|
||||
@@ -103,7 +104,11 @@ export const clientPaymentRoutes = async (app) => {
|
||||
}
|
||||
}
|
||||
|
||||
const session = await createPaymentSession({
|
||||
// Phase 5: payment.service.js handles the Xendit invoice creation internally
|
||||
// when XENDIT_ENABLED=true. The row comes back with xendit_invoice_url populated;
|
||||
// when off, invoice_url is null and the dev/Maestro stub plays the webhook role.
|
||||
const session = await requestPayment({
|
||||
productType: 'chat_session',
|
||||
customerId: request.customer.id,
|
||||
durationMinutes: duration_minutes,
|
||||
amount,
|
||||
@@ -125,12 +130,21 @@ export const clientPaymentRoutes = async (app) => {
|
||||
targeted_mitra_id: session.targeted_mitra_id,
|
||||
expires_at: session.expires_at,
|
||||
status: session.status,
|
||||
invoice_url: session.xendit_invoice_url ?? null,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
app.post('/:id/confirm', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
|
||||
const session = await confirmPaymentSession(request.params.id, request.customer.id)
|
||||
// Phase 5 D9: when Xendit is live, only the webhook can confirm. The dev/Maestro
|
||||
// stub at /internal/_test/force-confirm-payment bypasses this gate (internal listener).
|
||||
if (getXenditConfig().enabled) {
|
||||
return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'FORBIDDEN', message: 'Confirmation must come from Xendit webhook' },
|
||||
})
|
||||
}
|
||||
const session = await confirmPaymentForCustomer(request.params.id, request.customer.id)
|
||||
return reply.send({
|
||||
success: true,
|
||||
data: {
|
||||
@@ -142,7 +156,7 @@ export const clientPaymentRoutes = async (app) => {
|
||||
})
|
||||
|
||||
app.post('/:id/cancel', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
|
||||
const session = await abandonPaymentSession(request.params.id, request.customer.id)
|
||||
const session = await cancelPayment(request.params.id, request.customer.id)
|
||||
return reply.send({
|
||||
success: true,
|
||||
data: {
|
||||
@@ -160,19 +174,34 @@ export const clientPaymentRoutes = async (app) => {
|
||||
})
|
||||
|
||||
app.get('/:id', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
|
||||
const session = await getPaymentSession(request.params.id)
|
||||
const session = await getPayment(request.params.id)
|
||||
if (!session) {
|
||||
return reply.code(404).send({
|
||||
success: false,
|
||||
error: { code: 'NOT_FOUND', message: 'Payment session not found' },
|
||||
error: { code: 'NOT_FOUND', message: 'Payment request not found' },
|
||||
})
|
||||
}
|
||||
if (session.customer_id !== request.customer.id) {
|
||||
return reply.code(403).send({
|
||||
success: false,
|
||||
error: { code: 'FORBIDDEN', message: 'Payment session does not belong to this customer' },
|
||||
error: { code: 'FORBIDDEN', message: 'Payment request does not belong to this customer' },
|
||||
})
|
||||
}
|
||||
return reply.send({ success: true, data: session })
|
||||
// Phase 5: surface chat_session_id (and status) when the server-driven pairing
|
||||
// subscriber has already started pairing for this confirmed payment. Lets the
|
||||
// app skip its legacy POST /chat/request call and just move to the searching state.
|
||||
const { getDb } = await import('../../db/client.js')
|
||||
const sqlClient = getDb()
|
||||
const [chat] = await sqlClient`
|
||||
SELECT id, status FROM chat_sessions WHERE payment_request_id = ${session.id} LIMIT 1
|
||||
`
|
||||
return reply.send({
|
||||
success: true,
|
||||
data: {
|
||||
...session,
|
||||
chat_session_id: chat?.id ?? null,
|
||||
chat_session_status: chat?.status ?? null,
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
92
backend/src/routes/public/shared.payment-webhooks.routes.js
Normal file
92
backend/src/routes/public/shared.payment-webhooks.routes.js
Normal file
@@ -0,0 +1,92 @@
|
||||
// Phase 5 — Payment provider webhooks.
|
||||
//
|
||||
// Endpoint: POST /api/shared/payment/webhooks/xendit
|
||||
//
|
||||
// Public route (Xendit cannot present a JWT) authenticated by the
|
||||
// `x-callback-token` header verified against env XENDIT_WEBHOOK_TOKEN.
|
||||
//
|
||||
// Body shape from Xendit Invoice callback (relevant fields only):
|
||||
// { id, external_id, status, amount, payment_method, paid_at, ... }
|
||||
//
|
||||
// Handled statuses: PAID (→ confirmPayment), EXPIRED (→ expirePayment).
|
||||
// Anything else ACKs with `{ ok: true, ignored: <status> }` for forward-compat.
|
||||
//
|
||||
// All state transitions go through payment.service.js — this handler is just
|
||||
// the entry point. Events emit from inside the service, not from here.
|
||||
|
||||
import { confirmPayment, expirePayment, getPayment, verifyWebhookToken } from '../../services/payment.service.js'
|
||||
|
||||
export const paymentWebhookRoutes = async (app) => {
|
||||
app.post('/webhooks/xendit', async (request, reply) => {
|
||||
const headerToken = request.headers['x-callback-token']
|
||||
if (!verifyWebhookToken(headerToken)) {
|
||||
request.log.warn('xendit webhook: bad token')
|
||||
return reply.code(401).send({ error: 'invalid_token' })
|
||||
}
|
||||
|
||||
const body = request.body ?? {}
|
||||
const invoiceId = body.id
|
||||
const paymentRequestId = body.external_id
|
||||
const status = body.status
|
||||
const amount = typeof body.amount === 'number' ? body.amount : null
|
||||
const paymentMethod = body.payment_method ?? null
|
||||
|
||||
request.log.info(
|
||||
{ paymentRequestId, invoiceId, status, amount, paymentMethod },
|
||||
'xendit webhook received',
|
||||
)
|
||||
|
||||
if (!paymentRequestId) {
|
||||
// Forward-compat: future Xendit event types may not carry external_id
|
||||
return reply.send({ ok: true, ignored: 'no_external_id' })
|
||||
}
|
||||
|
||||
const existing = await getPayment(paymentRequestId)
|
||||
if (!existing) {
|
||||
// Unknown payment — could be stale orphan from a wiped dev DB. ACK so Xendit
|
||||
// stops retrying; warn so we notice if this becomes common in prod.
|
||||
request.log.warn({ paymentRequestId, invoiceId }, 'unknown payment_request — ACKing')
|
||||
return reply.send({ ok: true, ignored: 'unknown_payment_request' })
|
||||
}
|
||||
|
||||
if (status === 'PAID') {
|
||||
// Defensive: amount mismatch = either tampering or config drift. Refuse to confirm.
|
||||
if (amount !== null && amount !== existing.amount) {
|
||||
request.log.error(
|
||||
{ paymentRequestId, expected: existing.amount, got: amount },
|
||||
'xendit webhook: amount mismatch',
|
||||
)
|
||||
return reply.code(409).send({ error: 'amount_mismatch' })
|
||||
}
|
||||
|
||||
try {
|
||||
await confirmPayment(paymentRequestId, { invoiceId, paymentMethod, amount })
|
||||
} catch (err) {
|
||||
// INVALID_STATE = already confirmed/consumed (Xendit retry); CONFLICT = race lost. ACK.
|
||||
// EXPIRED = customer paid AFTER our sweeper expired the row — painful, manual recovery
|
||||
// needed. Log loud so we notice. (D5 alignment should keep this rare.)
|
||||
if (err.code === 'INVALID_STATE' || err.code === 'CONFLICT') {
|
||||
request.log.info(
|
||||
{ paymentRequestId, code: err.code, prevStatus: existing.status },
|
||||
'xendit webhook: already in terminal state, ACKing',
|
||||
)
|
||||
} else if (err.code === 'EXPIRED') {
|
||||
request.log.error(
|
||||
{ paymentRequestId, expiredAt: existing.expires_at },
|
||||
'xendit webhook: PAID after expiry — manual recovery needed',
|
||||
)
|
||||
} else {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
return reply.send({ ok: true })
|
||||
}
|
||||
|
||||
if (status === 'EXPIRED') {
|
||||
await expirePayment(paymentRequestId)
|
||||
return reply.send({ ok: true })
|
||||
}
|
||||
|
||||
return reply.send({ ok: true, ignored: status })
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user