diff --git a/src/helpers/hubtel-status.ts b/src/helpers/hubtel-status.ts new file mode 100644 index 0000000..b80dc4a --- /dev/null +++ b/src/helpers/hubtel-status.ts @@ -0,0 +1,28 @@ +type StoredPayment = { reference: string; amount: number; currency: string }; + +function record(value: unknown): Record { + return value !== null && typeof value === "object" ? (value as Record) : {}; +} + +export function verifiedHubtelStatus( + payload: unknown, + payment: StoredPayment, +): "SUCCESS" | "PENDING" | null { + const result = record(payload); + const data = record(result.data); + if (result.responseCode !== "0000" || data.clientReference !== payment.reference) return null; + if (payment.currency !== "GHS") return null; + if (data.currencyCode != null && data.currencyCode !== payment.currency) return null; + if (data.status === "Unpaid") return "PENDING"; + if (data.status !== "Paid") return null; + if ( + typeof data.amount !== "number" || + !Number.isFinite(data.amount) || + !Number.isFinite(payment.amount) || + payment.amount <= 0 || + Math.abs(data.amount - payment.amount) > 0.000001 + ) { + return null; + } + return "SUCCESS"; +} diff --git a/src/middleware/hubtel-callback.ts b/src/middleware/hubtel-callback.ts index 7a8ac53..6c1d985 100644 --- a/src/middleware/hubtel-callback.ts +++ b/src/middleware/hubtel-callback.ts @@ -1,47 +1,62 @@ import { Request, Response, NextFunction } from "express"; import { getHubtelStatusClient } from "../config/hubtel.js"; +import { prisma } from "../config/prisma.js"; import { fail, ok } from "../helpers/response.js"; +import { verifiedHubtelStatus } from "../helpers/hubtel-status.js"; -/** - * Middleware to verify Hubtel payment callbacks. - * Validates payload structure and verifies the transaction status with Hubtel's API - * before allowing the callback to be processed. - */ +/** Treat callbacks as notifications; independently verify the stored collection. */ export default async function verifyHubtelCallback( req: Request, res: Response, next: NextFunction, ) { try { - const { ResponseCode, Data } = req.body; - - if (!ResponseCode || !Data) { + const { ResponseCode, Data } = req.body ?? {}; + if ( + typeof ResponseCode !== "string" || + typeof Data?.ClientReference !== "string" || + !Data.ClientReference + ) { return fail(res, 400, "Invalid callback payload"); } - - if (!Data.ClientReference || !Data.TransactionId) { - return fail(res, 400, "Missing transaction identifiers"); + const payment = await prisma.payment.findUnique({ + where: { reference: Data.ClientReference }, + }); + if (!payment || payment.provider !== "HUBTEL") { + return fail(res, 404, "Payment not found"); } - - // Verify the transaction with Hubtel's Transaction Status API - try { - const hubtelStatusClient = await getHubtelStatusClient(); - const statusResponse = await hubtelStatusClient.get(`/${Data.TransactionId}`); - const statusData = statusResponse.data; - - // If Hubtel reports the transaction as failed, reject the callback - if (statusData.Status === "FAILED") { - return ok(res, null, "Transaction confirmed as failed by Hubtel"); - } - } catch (_e) { - // If the status check fails, reject the callback — Hubtel will retry - console.error("Failed to verify transaction status with Hubtel API, rejecting callback"); - return fail(res, 502, "Unable to verify transaction with Hubtel"); + if (["SUCCESS", "REFUNDED", "PARTIALLY_REFUNDED"].includes(payment.status)) { + return ok(res, null, "Payment already processed"); } - + const client = await getHubtelStatusClient(); + const response = await client.get("", { params: { clientReference: payment.reference } }); + const status = verifiedHubtelStatus(response.data, payment); + if (status === null) return fail(res, 502, "Unable to verify transaction"); + if (status !== "SUCCESS") return fail(res, 409, "Payment not yet confirmed"); + // Downstream legacy handlers consume PascalCase fields. Derive the success + // indicator and financial fields from the independently verified response. + const verified = response.data.data; + req.body = { + ResponseCode: "0000", + Status: "SUCCESS", + Message: "Payment verified", + Data: { + ClientReference: payment.reference, + Amount: verified.amount, + Charges: verified.charges ?? 0, + AmountAfterCharges: verified.amountAfterCharges ?? verified.amount, + AmountCharged: verified.amount, + TransactionId: verified.transactionId, + ExternalTransactionId: verified.externalTransactionId, + SalesInvoiceId: verified.transactionId, + Description: "Payment verified", + responseCode: "0000", + DeliveryFee: 0, + }, + }; next(); } catch (error) { console.error("Hubtel callback verification error:", error); - return fail(res, 500, "Callback verification failed"); + return fail(res, 502, "Unable to verify transaction with Hubtel"); } } diff --git a/tests/hubtel-status.test.ts b/tests/hubtel-status.test.ts new file mode 100644 index 0000000..a711b62 --- /dev/null +++ b/tests/hubtel-status.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vitest"; +import { verifiedHubtelStatus } from "../src/helpers/hubtel-status.js"; + +describe("Hubtel collection verification", () => { + const payment = { reference: "ORDER-1", amount: 50, currency: "GHS" }; + const data = { clientReference: "ORDER-1", amount: 50, status: "Paid" }; + const payload = { responseCode: "0000", data }; + + it("accepts only the matching paid collection", () => { + expect(verifiedHubtelStatus(payload, payment)).toBe("SUCCESS"); + const wrongAmount = { ...payload, data: { ...data, amount: 49 } }; + expect(verifiedHubtelStatus(wrongAmount, payment)).toBeNull(); + const wrongReference = { ...payload, data: { ...data, clientReference: "OTHER" } }; + expect(verifiedHubtelStatus(wrongReference, payment)).toBeNull(); + }); + + it("does not interpret successful API responses as successful payments", () => { + const unpaid = { ...payload, data: { ...data, status: "Unpaid" } }; + expect(verifiedHubtelStatus(unpaid, payment)).toBe("PENDING"); + const invalid = { ...payload, data: { ...data, status: "Refunded" } }; + expect(verifiedHubtelStatus(invalid, payment)).toBeNull(); + expect(verifiedHubtelStatus({ responseCode: "0000" }, payment)).toBeNull(); + }); + + it("rejects invalid amounts and unsupported currencies", () => { + const invalid = { ...payload, data: { ...data, amount: NaN } }; + expect(verifiedHubtelStatus(invalid, payment)).toBeNull(); + expect(verifiedHubtelStatus(payload, { ...payment, currency: "USD" })).toBeNull(); + }); +});