diff --git a/.env.example b/.env.example index b1048c5..99b3a0b 100644 --- a/.env.example +++ b/.env.example @@ -27,3 +27,23 @@ TERMII_SENDER_ID= UPLOAD_DIR=.local/evidence UPLOAD_STORAGE=database SEED_DEVELOPMENT=false + +SMSPOOL_API_KEY= +FIVESIM_API_KEY= + +BOOSTERO_API_KEY= +SMMKINGS_API_KEY= + +PRESTMIT_API_KEY= +PRESTMIT_API_SECRET= +PRESTMIT_WEBHOOK_SECRET= + +FINCRA_SECRET_KEY= +FINCRA_BUSINESS_ID= +FINCRA_WEBHOOK_SECRET= + +GIFT_BUY_MARKUP_BPS=300 +GIFT_SELL_MARGIN_BPS=200 +VIRTUAL_NUMBER_MARKUP_BPS=2000 +SOCIAL_BOOST_MARKUP_BPS=3000 +EXCHANGE_MARKUP_BPS=100 diff --git a/apps/api/src/app/api/v1/gift-cards/purchases/route.ts b/apps/api/src/app/api/v1/gift-cards/purchases/route.ts index 3195c1c..9f229ea 100644 --- a/apps/api/src/app/api/v1/gift-cards/purchases/route.ts +++ b/apps/api/src/app/api/v1/gift-cards/purchases/route.ts @@ -1,8 +1,4 @@ import { endpoint } from "@quickpay/server/shared/infrastructure/http"; -import { identity } from "@quickpay/server/shared/auth"; -import { giftCardBuyer } from "@quickpay/server/v1/modules/gift-cards/providers/purchase-provider"; -import { json } from "@quickpay/server/shared/infrastructure/http"; -export const POST = endpoint(async (req) => { - await identity(req); - return json(await giftCardBuyer.catalog()); -}); +import { purchases } from "@quickpay/server/v1/modules/gift-cards/routes/purchases"; +export const GET = endpoint(purchases); +export const POST = endpoint(purchases); diff --git a/apps/api/src/shared/infrastructure/env.ts b/apps/api/src/shared/infrastructure/env.ts index 03c95d6..2ef808a 100644 --- a/apps/api/src/shared/infrastructure/env.ts +++ b/apps/api/src/shared/infrastructure/env.ts @@ -2,6 +2,10 @@ import "dotenv/config"; import { z } from "zod"; import { ConfigurationError } from "../errors"; const schema = z.object({ + SMSPOOL_API_KEY: z.string().default(""), + FIVESIM_API_KEY: z.string().default(""), + BOOSTERO_API_KEY: z.string().default(""), + SMMKINGS_API_KEY: z.string().default(""), DATABASE_URL: z.url(), WEB_ORIGIN: z.url().default("http://localhost:3000"), API_ORIGIN: z.url().default("http://localhost:3001"), diff --git a/apps/api/src/v1/modules/admin/routes/handler.ts b/apps/api/src/v1/modules/admin/routes/handler.ts index 5518e16..b8b840d 100644 --- a/apps/api/src/v1/modules/admin/routes/handler.ts +++ b/apps/api/src/v1/modules/admin/routes/handler.ts @@ -1,3 +1,4 @@ +import { env } from "../../../../shared/infrastructure/env"; import { z } from "zod"; import { atomic, pool, enqueue } from "@quickpay/database"; import { authorized } from "../../../../shared/auth"; @@ -263,10 +264,16 @@ async function reviewGift(req: Request) { const { rows: [sale], } = await c.query( - "SELECT s.*,q.amount,e.status evidence_status FROM gift_sales s JOIN gift_quotes q ON q.id=s.quote_id JOIN evidence e ON e.id=s.evidence_id WHERE s.id=$1 FOR UPDATE OF s", + "SELECT s.*,q.amount,p.sandbox_only,e.status evidence_status FROM gift_sales s JOIN gift_quotes q ON q.id=s.quote_id JOIN gift_products p ON p.id=q.product_id JOIN evidence e ON e.id=s.evidence_id WHERE s.id=$1 FOR UPDATE OF s", [v.id], ); assert(sale, "NOT_FOUND", "Sale not found.", 404); + assert( + !sale.sandbox_only || env().PAYMENT_MODE === "sandbox", + "SANDBOX_ONLY", + "Sandbox cards can only be reviewed in sandbox mode.", + 409, + ); assert( sale.user_id !== s.user.id, "SELF_REVIEW", diff --git a/apps/api/src/v1/modules/digital-services/providers/clients.ts b/apps/api/src/v1/modules/digital-services/providers/clients.ts new file mode 100644 index 0000000..612e43a --- /dev/null +++ b/apps/api/src/v1/modules/digital-services/providers/clients.ts @@ -0,0 +1,138 @@ +import { env } from "../../../../shared/infrastructure/env"; +import { DomainError } from "../../../../shared/errors"; + +type Payload = Record; +async function request( + url: string, + key: string, + options: { + method: "GET" | "POST"; + data?: Payload; + authorization: "bearer" | "form"; + }, +) { + if (!key) + throw new DomainError( + "PROVIDER_UNCONFIGURED", + "This service is currently unavailable.", + 503, + ); + let response: Response; + try { + response = await fetch(url, { + method: options.method, + headers: { + Accept: "application/json", + ...(options.authorization === "bearer" + ? { Authorization: `Bearer ${key}` } + : {}), + ...(options.data + ? { "Content-Type": "application/x-www-form-urlencoded" } + : {}), + }, + ...(options.data ? { body: new URLSearchParams(options.data) } : {}), + signal: AbortSignal.timeout(20000), + redirect: "error", + }); + } catch { + throw new DomainError( + "PROVIDER_UNAVAILABLE", + "The provider could not complete this request. Please check the order status before retrying.", + 503, + ); + } + if (!response.ok) + throw new DomainError( + "PROVIDER_UNAVAILABLE", + "The provider could not complete this request. Please check the order status before retrying.", + 503, + ); + let result: unknown; + try { + result = await response.json(); + } catch { + throw new DomainError( + "PROVIDER_UNAVAILABLE", + "The provider returned an unreadable response. Please check the order status before retrying.", + 503, + ); + } + if ( + typeof result !== "object" || + result === null || + ("error" in result && !!result.error) || + ("success" in result && + [false, 0, "0", "false"].includes(result.success as never)) + ) + throw new DomainError( + "PROVIDER_REJECTED", + "The provider could not complete this request.", + 409, + ); + return result; +} +export const smsPool = { + call(path: string, data: Payload = {}) { + const key = env().SMSPOOL_API_KEY; + return request(`https://api.smspool.net/${path}`, key, { + method: "POST", + authorization: "form", + data: { ...data, key }, + }); + }, + countries: () => smsPool.call("country/retrieve_all"), + services: () => smsPool.call("service/retrieve_all"), + price: (country: string, service: string) => + smsPool.call("request/price", { country, service }), + purchase: (country: string, service: string, maxPrice: string) => + smsPool.call("purchase/sms", { country, service, max_price: maxPrice }), + status: (orderid: string) => smsPool.call("sms/check", { orderid }), + cancel: (orderid: string) => smsPool.call("sms/cancel", { orderid }), +}; +export const fiveSim = { + call(path: string, method: "GET" | "POST" = "GET") { + return request(`https://5sim.net/v1/${path}`, env().FIVESIM_API_KEY, { + method, + authorization: "bearer", + ...(method === "POST" ? { data: {} } : {}), + }); + }, + prices: () => fiveSim.call("guest/prices"), + purchase: (country: string, operator: string, service: string) => + fiveSim.call( + `user/buy/activation/${encodeURIComponent(country)}/${encodeURIComponent(operator)}/${encodeURIComponent(service)}`, + "POST", + ), + status: (id: string) => fiveSim.call(`user/check/${encodeURIComponent(id)}`), + cancel: (id: string) => + fiveSim.call(`user/cancel/${encodeURIComponent(id)}`, "POST"), + finish: (id: string) => + fiveSim.call(`user/finish/${encodeURIComponent(id)}`, "POST"), +}; +export type BoostProvider = "boostero" | "smmkings"; +export function boosting(provider: BoostProvider) { + const call = (action: string, data: Payload = {}) => { + const key = + provider === "boostero" ? env().BOOSTERO_API_KEY : env().SMMKINGS_API_KEY; + return request( + provider === "boostero" + ? "https://boostero.com/api/v2" + : "https://smmkings.com/api/v2", + key, + { + method: "POST", + authorization: "form", + data: { ...data, key, action }, + }, + ); + }; + return { + services: () => call("services"), + purchase: (service: string, link: string, quantity: string) => + call("add", { service, link, quantity }), + status: (order: string) => call("status", { order }), + cancel: (orders: string) => call("cancel", { orders }), + refill: (order: string) => call("refill", { order }), + balance: () => call("balance"), + }; +} diff --git a/apps/api/src/v1/modules/digital-services/providers/config.ts b/apps/api/src/v1/modules/digital-services/providers/config.ts new file mode 100644 index 0000000..8dc7122 --- /dev/null +++ b/apps/api/src/v1/modules/digital-services/providers/config.ts @@ -0,0 +1,57 @@ +import { z } from "zod"; +import { ConfigurationError, DomainError } from "../../../../shared/errors"; + +const basisPoints = (value: number) => + z.coerce.number().int().min(0).max(10000).default(value); +const schema = z.object({ + PAYMENT_MODE: z.enum(["disabled", "sandbox", "live"]).default("disabled"), + PRESTMIT_API_KEY: z.string().trim().default(""), + PRESTMIT_API_SECRET: z.string().trim().default(""), + PRESTMIT_WEBHOOK_SECRET: z.string().trim().default(""), + FINCRA_SECRET_KEY: z.string().trim().default(""), + FINCRA_BUSINESS_ID: z.string().trim().default(""), + FINCRA_WEBHOOK_SECRET: z.string().trim().default(""), + GIFT_BUY_MARKUP_BPS: basisPoints(300), + GIFT_SELL_MARGIN_BPS: basisPoints(200), + VIRTUAL_NUMBER_MARKUP_BPS: basisPoints(2000), + SOCIAL_BOOST_MARKUP_BPS: basisPoints(3000), + EXCHANGE_MARKUP_BPS: basisPoints(100), +}); +export function supplierSettings( + values: Record = process.env, +) { + const parsed = schema.safeParse(values); + if (!parsed.success) + throw new ConfigurationError([ + ...new Set(parsed.error.issues.map((issue) => String(issue.path[0]))), + ]); + return parsed.data; +} +export function supplierEndpoint( + provider: "prestmit" | "fincra", + mode: "disabled" | "sandbox" | "live", +) { + if (mode === "disabled") + throw new DomainError( + "SERVICE_UNAVAILABLE", + "This service is currently unavailable.", + 503, + ); + if (provider === "prestmit") + return mode === "live" + ? "https://api.prestmit.io/partners/v1" + : "https://dev-api.prestmit.io/partners/v1"; + return mode === "live" + ? "https://api.fincra.com" + : "https://sandboxapi.fincra.com"; +} +export function markedUpCost(costMinor: bigint, markupBps: number) { + if ( + costMinor <= 0n || + !Number.isInteger(markupBps) || + markupBps < 0 || + markupBps > 10000 + ) + throw new Error("Invalid price parameters"); + return (costMinor * BigInt(10000 + markupBps) + 9999n) / 10000n; +} diff --git a/apps/api/src/v1/modules/digital-services/providers/partner-clients.ts b/apps/api/src/v1/modules/digital-services/providers/partner-clients.ts new file mode 100644 index 0000000..b7141a8 --- /dev/null +++ b/apps/api/src/v1/modules/digital-services/providers/partner-clients.ts @@ -0,0 +1,125 @@ +import { createHmac, timingSafeEqual } from "node:crypto"; +import { DomainError } from "../../../../shared/errors"; +import { supplierEndpoint, supplierSettings } from "./config"; + +type Fields = Record; +async function responseJson(response: Response): Promise { + if (!response.ok) + throw new DomainError( + "PROVIDER_UNAVAILABLE", + "The service could not complete this request. Check its status before retrying.", + 503, + ); + const data: unknown = await response.json(); + if ( + typeof data !== "object" || + data === null || + ("success" in data && data.success === false) + ) + throw new DomainError( + "PROVIDER_REJECTED", + "The service could not complete this request.", + 409, + ); + return data; +} +function requireCredentials(...values: string[]) { + if (values.some((value) => !value)) + throw new DomainError( + "PROVIDER_UNCONFIGURED", + "This service is currently unavailable.", + 503, + ); +} +export function prestmitSignature(key: string, secret: string, fields: Fields) { + return createHmac("sha256", secret) + .update(`${key}:${JSON.stringify(fields)}`) + .digest("hex"); +} +export function validPrestmitWebhook( + rawBody: string, + signature: string | null, + secret: string, +) { + if (!secret || !signature) return false; + const expected = createHmac("sha256", secret) + .update(rawBody) + .digest("base64"); + const received = Buffer.from(signature); + const wanted = Buffer.from(expected); + return received.length === wanted.length && timingSafeEqual(received, wanted); +} +async function prestmitGet(path: string, fields: Fields = {}) { + const config = supplierSettings(); + requireCredentials(config.PRESTMIT_API_KEY, config.PRESTMIT_API_SECRET); + const url = new URL( + `${supplierEndpoint("prestmit", config.PAYMENT_MODE)}${path}`, + ); + for (const [key, value] of Object.entries(fields)) + url.searchParams.set(key, value); + return responseJson( + await fetch(url, { + headers: { + "API-KEY": config.PRESTMIT_API_KEY, + "API-Hash": prestmitSignature( + config.PRESTMIT_API_KEY, + config.PRESTMIT_API_SECRET, + fields, + ), + Accept: "application/json", + }, + signal: AbortSignal.timeout(20000), + redirect: "error", + }), + ); +} +export const prestmit = { + availability: () => prestmitGet("/general/service-availability"), + buyCatalog: (page = "1") => + prestmitGet("/giftcard-trade/buy/fetch-buyable-giftcards", { page }), + buyConfiguration: () => prestmitGet("/giftcard-trade/buy/config"), + sellRates: () => prestmitGet("/giftcard-trade/sell/rate-calculator-data"), + wallet: () => prestmitGet("/wallet/fiat/details"), +}; +export async function fincraQuote( + sourceCurrency: "NGN" | "USD" | "EUR" | "GBP", + destinationCurrency: "NGN" | "USD" | "EUR" | "GBP", + amount: string, +) { + if ( + sourceCurrency === destinationCurrency || + !/^(?:0|[1-9]\d{0,11})(?:\.\d{1,2})?$/.test(amount) || + Number(amount) <= 0 + ) + throw new DomainError( + "INVALID_AMOUNT", + "Choose different currencies and a positive amount.", + 400, + ); + const config = supplierSettings(); + requireCredentials(config.FINCRA_SECRET_KEY, config.FINCRA_BUSINESS_ID); + return responseJson( + await fetch( + `${supplierEndpoint("fincra", config.PAYMENT_MODE)}/quotes/generate`, + { + method: "POST", + headers: { + "api-key": config.FINCRA_SECRET_KEY, + "Content-Type": "application/json", + Accept: "application/json", + }, + body: JSON.stringify({ + sourceCurrency, + destinationCurrency, + amount, + business: config.FINCRA_BUSINESS_ID, + action: "send", + transactionType: "conversion", + paymentDestination: "fliqpay_wallet", + }), + signal: AbortSignal.timeout(20000), + redirect: "error", + }, + ), + ); +} diff --git a/apps/api/src/v1/modules/exchanges/routes/handler.ts b/apps/api/src/v1/modules/exchanges/routes/handler.ts index 612b36e..89d603c 100644 --- a/apps/api/src/v1/modules/exchanges/routes/handler.ts +++ b/apps/api/src/v1/modules/exchanges/routes/handler.ts @@ -1,10 +1,20 @@ import { identity } from "../../../../shared/auth"; +import { pool } from "@quickpay/database"; import { json } from "../../../../shared/infrastructure/http"; export async function exchanges(req: Request) { await identity(req); + const { rows } = await pool.query<{ + id: string; + source: string; + target: string; + enabled: boolean; + }>( + "SELECT id,source,target,enabled FROM exchange_pairs WHERE enabled=true ORDER BY source,target", + ); return json({ - pairs: [], - message: - "Currency exchanges are not available yet. Supported gift-card sales are quoted in naira in Gift cards.", + pairs: rows, + message: rows.length + ? "Exchange availability can change. Request a current quote before confirming any conversion." + : "Currency exchanges are not available yet. Supported gift-card sales are quoted in naira in Gift cards.", }); } diff --git a/apps/api/src/v1/modules/gift-cards/routes/handler.ts b/apps/api/src/v1/modules/gift-cards/routes/handler.ts index 5f01182..bcd8931 100644 --- a/apps/api/src/v1/modules/gift-cards/routes/handler.ts +++ b/apps/api/src/v1/modules/gift-cards/routes/handler.ts @@ -12,10 +12,12 @@ export async function products(req: Request) { return json({ products: ( await pool.query( - "SELECT * FROM gift_products WHERE enabled=true AND sell_enabled=true ORDER BY brand", + "SELECT * FROM gift_products WHERE enabled=true AND sell_enabled=true AND (sandbox_only=false OR $1) ORDER BY brand", + [env().PAYMENT_MODE === "sandbox"], ) ).rows, - buyingAvailable: false, + buyingAvailable: env().PAYMENT_MODE === "sandbox", + sandbox: env().PAYMENT_MODE === "sandbox", }); } export async function quote(req: Request) { @@ -30,8 +32,8 @@ export async function quote(req: Request) { const { rows: [p], } = await pool.query( - "SELECT * FROM gift_products WHERE id=$1 AND enabled=true AND sell_enabled=true", - [v.productId], + "SELECT * FROM gift_products WHERE id=$1 AND enabled=true AND sell_enabled=true AND (sandbox_only=false OR $2)", + [v.productId, env().PAYMENT_MODE === "sandbox"], ); assert(p, "GIFT_UNAVAILABLE", "This gift card is not available yet.", 503); const units = BigInt(v.units); @@ -193,11 +195,14 @@ export async function sales(req: Request) { const { rows: [q], } = await c.query( - "SELECT * FROM gift_quotes WHERE id=$1 AND user_id=$2 FOR UPDATE", + "SELECT q.*,p.sandbox_only FROM gift_quotes q JOIN gift_products p ON p.id=q.product_id WHERE q.id=$1 AND q.user_id=$2 FOR UPDATE OF q", [v.quoteId, s.user.id], ); assert( - q && !q.used && new Date(q.expires_at) > new Date(), + q && + !q.used && + new Date(q.expires_at) > new Date() && + (!q.sandbox_only || env().PAYMENT_MODE === "sandbox"), "QUOTE_EXPIRED", "Your quote expired. Request a new quote.", 409, diff --git a/apps/api/src/v1/modules/gift-cards/routes/purchases.ts b/apps/api/src/v1/modules/gift-cards/routes/purchases.ts new file mode 100644 index 0000000..8832ddb --- /dev/null +++ b/apps/api/src/v1/modules/gift-cards/routes/purchases.ts @@ -0,0 +1,102 @@ +import { z } from "zod"; +import { atomic, pool } from "@quickpay/database"; +import { identity } from "../../../../shared/auth"; +import { body, json, rateLimit } from "../../../../shared/infrastructure/http"; +import { env } from "../../../../shared/infrastructure/env"; +import { assert } from "../../../../shared/errors"; + +export async function purchases(req: Request) { + const session = await identity(req); + assert( + env().PAYMENT_MODE === "sandbox", + "GIFT_PURCHASE_UNAVAILABLE", + "Gift-card buying is not available yet. Please check back.", + 503, + ); + if (req.method === "GET") { + const products = await pool.query( + "SELECT * FROM gift_products WHERE sandbox_only=true AND enabled=true AND buy_enabled=true ORDER BY brand", + ); + const history = await pool.query( + "SELECT b.*,p.brand FROM sandbox_gift_purchases b JOIN gift_products p ON p.id=b.product_id WHERE b.user_id=$1 AND b.status='successful' ORDER BY b.created_at DESC LIMIT 100", + [session.user.id], + ); + return json({ products: products.rows, purchases: history.rows }); + } + await rateLimit(`gift-buy:${session.user.id}`, 20); + const value = await body( + req, + z.discriminatedUnion("action", [ + z.object({ + action: z.literal("quote"), + productId: z.string(), + units: z.string().regex(/^[1-9]\d{0,5}$/), + }), + z.object({ action: z.literal("confirm"), quoteId: z.string().uuid() }), + ]), + ); + const purchase = await atomic(async (client) => { + if (value.action === "quote") { + const { + rows: [product], + } = await client.query( + "SELECT * FROM gift_products WHERE id=$1 AND sandbox_only=true AND enabled=true AND buy_enabled=true", + [value.productId], + ); + assert( + product, + "GIFT_UNAVAILABLE", + "Choose an available sandbox card.", + 400, + ); + const units = BigInt(value.units); + assert( + units >= BigInt(product.min_units) && + units <= BigInt(product.max_units), + "QUOTE_LIMIT", + "Choose a value within the card limits.", + ); + const { + rows: [quote], + } = await client.query( + "INSERT INTO sandbox_gift_purchases(id,user_id,product_id,units,amount,expires_at) VALUES($1,$2,$3,$4,$5,now()+interval '10 minutes') RETURNING *", + [ + crypto.randomUUID(), + session.user.id, + product.id, + value.units, + (units * BigInt(product.rate_kobo)).toString(), + ], + ); + return quote; + } + const { + rows: [quote], + } = await client.query( + "SELECT * FROM sandbox_gift_purchases WHERE id=$1 AND user_id=$2 FOR UPDATE", + [value.quoteId, session.user.id], + ); + assert(quote, "NOT_FOUND", "Purchase quote not found.", 404); + if (quote.status === "successful") return quote; + assert( + new Date(quote.expires_at) > new Date(), + "QUOTE_EXPIRED", + "Your quote expired. Request a new quote.", + 409, + ); + const { + rows: [completed], + } = await client.query( + "UPDATE sandbox_gift_purchases SET status='successful' WHERE id=$1 RETURNING *", + [quote.id], + ); + return completed; + }); + return json({ + purchase, + demoCode: + purchase.status === "successful" + ? `DEMO-NOT-REDEEMABLE-${purchase.id}` + : null, + }); +} diff --git a/apps/mobile/src/features/bills/screens/PaymentsScreen.tsx b/apps/mobile/src/features/bills/screens/PaymentsScreen.tsx index eefb339..1ef964c 100644 --- a/apps/mobile/src/features/bills/screens/PaymentsScreen.tsx +++ b/apps/mobile/src/features/bills/screens/PaymentsScreen.tsx @@ -1,3 +1,4 @@ +import { ComingSoon } from "../../coming-soon/ComingSoon"; import { router } from "expo-router"; import { categories, type Service } from "@quickpay/contracts"; import { Screen } from "../../../components/layout/screen"; @@ -66,6 +67,7 @@ export function PaymentsScreen() { title="Exchanges" onPress={() => router.push("/(customer)/exchanges")} /> + ); } diff --git a/apps/mobile/src/features/coming-soon/ComingSoon.tsx b/apps/mobile/src/features/coming-soon/ComingSoon.tsx new file mode 100644 index 0000000..ad28b27 --- /dev/null +++ b/apps/mobile/src/features/coming-soon/ComingSoon.tsx @@ -0,0 +1,38 @@ +import { Pressable, Text, View } from "react-native"; + +export function ComingSoon() { + return ( + + + Coming soon + + + Virtual numbers + Coming soon + + Explore numbers for supported services such as WhatsApp and Telegram. + Availability will depend on country and service support. + + + + + Social media boosting + + Coming soon + + Planned services for X, YouTube, Facebook, TikTok, Instagram and more. + + + + ); +} diff --git a/apps/mobile/src/features/dashboard/screens/DashboardScreen.tsx b/apps/mobile/src/features/dashboard/screens/DashboardScreen.tsx index 64effb5..8689380 100644 --- a/apps/mobile/src/features/dashboard/screens/DashboardScreen.tsx +++ b/apps/mobile/src/features/dashboard/screens/DashboardScreen.tsx @@ -1,3 +1,4 @@ +import { ComingSoon } from "../../coming-soon/ComingSoon"; import { Pressable, Text, View } from "react-native"; import { router } from "expo-router"; import { @@ -86,6 +87,7 @@ export function DashboardScreen() { ))} + ("/gift-cards/evidence", { method: "POST", body: data, diff --git a/apps/mobile/src/features/gift-cards/components/BuyCards.tsx b/apps/mobile/src/features/gift-cards/components/BuyCards.tsx new file mode 100644 index 0000000..513afbd --- /dev/null +++ b/apps/mobile/src/features/gift-cards/components/BuyCards.tsx @@ -0,0 +1,136 @@ +import { useState } from "react"; +import { Text } from "react-native"; +import { mutation } from "@quickpay/api-client"; +import { + formatMoney, + type GiftProduct, + type GiftPurchase, + type GiftPurchaseResult, +} from "@quickpay/contracts"; +import { api } from "../../../services/api"; +import { useResource } from "../../../services/api/use-resource"; +import { Button } from "../../../components/ui/button"; +import { Input } from "../../../components/ui/input"; +import { Choice } from "../../../components/ui/choice/Choice"; +import { + Notice, + LoadingState, + ErrorState, + EmptyState, +} from "../../../components/feedback/Feedback"; +import { Card, Row } from "../../../components/ui/card/Card"; + +export function BuyCards() { + const catalog = useResource<{ + products: GiftProduct[]; + purchases: GiftPurchase[]; + }>("/gift-cards/purchases"); + const [product, setProduct] = useState(""); + const [units, setUnits] = useState(""); + const [result, setResult] = useState(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + async function submit() { + if (busy) return; + setBusy(true); + setError(""); + try { + setResult( + await api( + "/gift-cards/purchases", + mutation( + result + ? { action: "confirm", quoteId: result.purchase.id } + : { action: "quote", productId: product, units }, + ), + ), + ); + await catalog.refetch(); + } catch (e) { + setError(e instanceof Error ? e.message : "Please try again."); + } finally { + setBusy(false); + } + } + return ( + <> + + No money will be charged and no redeemable card will be delivered in + this environment. + + {catalog.isPending ? ( + + ) : catalog.error ? ( + void catalog.refetch()} + /> + ) : result ? ( + + + + {result.demoCode ? ( + + Purchase preview completed. No redeemable code issued. + + ) : ( + <> + + Quote expires{" "} + {new Date(result.purchase.expires_at).toLocaleString()}. + + + ))} {user.role === "admin" && ( ("/exchanges"); + const r = useApi<{ + message: string; + pairs?: { id: string; source: string; target: string; enabled?: boolean }[]; + }>("/exchanges"); return ( -
-

Supported exchanges

-
- -

- Clear value. Confirmed support. -

- {r.loading ? ( - - ) : r.error ? ( - - ) : ( -

- {r.data?.message} +

+
+
+
+
+
+ + Exchange desk + +

+ Move value with clarity. +

+

+ Review supported markets, understand your quote, and keep each + exchange easy to track. +

+
+
+ + + + + + + +
+
+
+ +
+
+
+
+

Available markets

+

+ Configured pairs are shown with current availability state. +

+
+ {r.data?.pairs?.length ? ( + + {r.data.pairs.length} markets + + ) : null} +
+ {r.loading ? ( +
+ +
+ ) : r.error ? ( + + ) : r.data?.pairs?.some((pair) => pair.enabled !== false) ? ( +
+ {r.data.pairs + .filter((pair) => pair.enabled !== false) + .map((pair) => ( +
+
+ + + + + Enabled pair + +
+

+ Exchange pair +

+

+ {pair.source} →{" "} + {pair.target} +

+

+ This pair is configured. Quotes and conversions are not + available in this release yet. +

+ +
+ ))} +
+ ) : ( +
+
+ + + +
+

+ No currency pairs are open yet +

+

+ {r.data?.message ?? + "We will show supported currencies and current exchange details here when markets are available."} +

+

+ No rate or settlement is shown until a supported provider + and market are available. +

+
+
+
+ {[ + ["Clear quote", "See the rate and fees first."], + ["Your review", "Check details before confirming."], + ["Track progress", "Keep the exchange status close."], + ].map(([title, text]) => ( +
+

{title}

+

{text}

+
+ ))} +
+
+ )} +
+
+

Have a gift card to exchange?

+

+ Get a naira quote and follow the review from your Gift cards + page. +

+
+ + Open gift cards + +
+
+ +
); diff --git a/apps/web/src/features/gift-cards/BuyCards.tsx b/apps/web/src/features/gift-cards/BuyCards.tsx new file mode 100644 index 0000000..9138798 --- /dev/null +++ b/apps/web/src/features/gift-cards/BuyCards.tsx @@ -0,0 +1,273 @@ +"use client"; +import { useState } from "react"; +import { + ArrowRight, + BadgeCheck, + Clock3, + Gift, + ShieldCheck, + Sparkles, +} from "lucide-react"; +import { api, mutation } from "@quickpay/api-client"; +import { + formatMoney, + type GiftPurchase, + type GiftPurchaseResult, +} from "@quickpay/contracts"; +import { useApi } from "../../lib/use-api"; +import { Button } from "../../components/ui/button"; +import { Field } from "../../components/ui/form-field"; +import { + EmptyState, + ErrorState, + LoadingState, +} from "../../components/feedback"; + +export function BuyCards() { + const catalog = useApi<{ + products: { + id: string; + brand: string; + region: string; + card_type: string; + rate_kobo: string; + min_units: string; + max_units: string; + }[]; + purchases: GiftPurchase[]; + }>("/gift-cards/purchases"); + const [product, setProduct] = useState(""); + const [units, setUnits] = useState(""); + const [result, setResult] = useState(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const selectedProduct = catalog.data?.products.find( + (item) => item.id === product, + ); + const estimate = + selectedProduct && + /^[1-9]\d{0,5}$/.test(units) && + BigInt(units) >= BigInt(selectedProduct.min_units) && + BigInt(units) <= BigInt(selectedProduct.max_units) + ? formatMoney( + (BigInt(units) * BigInt(selectedProduct.rate_kobo)).toString(), + ) + : null; + + async function submit(e: React.FormEvent) { + e.preventDefault(); + if (busy) return; + if (!product) { + setError("Choose a gift card to continue."); + return; + } + setBusy(true); + setError(""); + try { + setResult( + await api( + "/gift-cards/purchases", + mutation( + result + ? { action: "confirm", quoteId: result.purchase.id } + : { action: "quote", productId: product, units }, + ), + ), + ); + await catalog.refresh(); + } catch (e) { + setError(e instanceof Error ? e.message : "Please try again."); + } finally { + setBusy(false); + } + } + + return ( +
+
+ +

+ Purchase preview + + No money will be charged and no redeemable card will be delivered in + this environment. + +

+
+ {error && } + {catalog.loading ? ( + + ) : catalog.error ? ( + + ) : result ? ( +
+ + + {result.demoCode ? "Preview complete" : "Quote ready"} + +

+ {result.demoCode + ? "Purchase preview completed" + : "Review purchase quote"} +

+
+
+

Face value

+

{result.purchase.units} units

+
+
+

Estimated price

+

+ {formatMoney(result.purchase.amount)} +

+
+
+ {result.demoCode ? ( +

+ No redeemable code was issued in this preview. +

+ ) : ( + <> +

+ + Expires {new Date(result.purchase.expires_at).toLocaleString()} +

+ + + )} + +
+ ) : !catalog.data?.products.length ? ( + + ) : ( +
+
+ + Buy a gift card + +

Choose your card

+

+ Pick a brand and enter its face value to see a price preview. +

+
+
+ Available brands +
+ {catalog.data.products.map((item) => ( + + ))} +
+
+ setUnits(e.target.value)} + inputMode="numeric" + pattern="[1-9][0-9]{0,5}" + /> + {selectedProduct && ( +

+ + Face value must be between {selectedProduct.min_units} and{" "} + {selectedProduct.max_units} units. +

+ )} + {estimate && ( +
+ + Price preview + + The final amount is confirmed by your quote. + + + {estimate} +
+ )} + + + )} + {catalog.data?.purchases.length ? ( +
+
+
+

Your purchases

+

+ Your recent purchase previews. +

+
+ + {catalog.data.purchases.length} + +
+ {catalog.data.purchases.map((purchase) => ( +
+
+ + + + + + {purchase.brand ?? "Gift card"} + + + {purchase.units} units · Preview + + +
+ + + {formatMoney(purchase.amount)} + + + Not delivered + + +
+ ))} +
+ ) : null} +
+ ); +} diff --git a/apps/web/src/features/gift-cards/GiftCardsPage.tsx b/apps/web/src/features/gift-cards/GiftCardsPage.tsx index 17fe7ae..9976fd3 100644 --- a/apps/web/src/features/gift-cards/GiftCardsPage.tsx +++ b/apps/web/src/features/gift-cards/GiftCardsPage.tsx @@ -1,4 +1,5 @@ "use client"; +import { BuyCards } from "./BuyCards"; import { useState } from "react"; import Link from "next/link"; import { toast } from "sonner"; @@ -9,6 +10,16 @@ import { Field } from "../../components/ui/form-field"; import { inputClass } from "../../components/ui/password-input"; import { Button } from "../../components/ui/button"; import { StatusBadge } from "../../components/ui/status-badge"; +import { + ArrowDownToLine, + ArrowRight, + ArrowUpFromLine, + BadgeCheck, + Clock3, + Gift, + ShieldCheck, + Sparkles, +} from "lucide-react"; import { EmptyState, LoadingState, @@ -31,12 +42,18 @@ type Quote = { cardType: string; }; export function GiftCardsPage() { - const products = useApi<{ products: Product[] }>("/gift-cards/products"), + const products = useApi<{ + products: Product[]; + buyingAvailable: boolean; + sandbox: boolean; + }>("/gift-cards/products"), sales = useApi<{ sales: { id: string; status: string; brand: string; + region: string; + card_type: string; amount: string; reason: string | null; created_at: string; @@ -49,6 +66,7 @@ export function GiftCardsPage() { [evidence, setEvidence] = useState(""), [busy, setBusy] = useState(false), [error, setError] = useState(""); + const selectedProduct = products.data?.products.find((p) => p.id === product); async function getQuote(e: React.FormEvent) { e.preventDefault(); setBusy(true); @@ -102,156 +120,336 @@ export function GiftCardsPage() { } } return ( -
-
-

Gift cards

-

- Clear quotes. Careful checks. Naira settlement after review. -

+
+
+
+
+
+
+ + Gift card marketplace + +

+ Your gift cards, put to work. +

+

+ See the value up front, follow every step, and keep your sales and + purchases together in one place. +

+
+
+ {[ + ["01", "Choose a card"], + ["02", "Review the quote"], + ["03", "Track the result"], + ].map(([step, label]) => ( +
+ {step} +

+ {label} +

+
+ ))} +
+
-
- {["sell", "buy", "history"].map((t) => ( - - ))} + +
+
+

+ What would you like to do? +

+

+ Choose a flow to see its rates and requirements. +

+
+
+ {(["sell", "buy", "history"] as const).map((t) => { + const Icon = + t === "sell" + ? ArrowUpFromLine + : t === "buy" + ? ArrowDownToLine + : Clock3; + return ( + + ); + })} +
+ {error && } -
- {tab === "buy" ? ( - - ) : tab === "history" ? ( - sales.loading ? ( - - ) : sales.error ? ( - - ) : sales.data?.sales.length ? ( -
- {sales.data.sales.map((s) => ( -
-
-

- {s.brand} · {formatMoney(s.amount)} -

- +
+
+ {tab === "buy" ? ( + products.loading ? ( + + ) : products.error ? ( + + ) : products.data?.buyingAvailable ? ( + + ) : ( +
+ + + +

+ Buying is being prepared +

+

+ Gift card purchases will appear here when this service is + available. +

+
+ ) + ) : tab === "history" ? ( + sales.loading ? ( + + ) : sales.error ? ( + + ) : sales.data?.sales.length ? ( +
+
+
+

Your sales

+

+ Follow each card from review to settlement. +

- {s.reason && ( -

{s.reason}

- )} - - Ask about this sale - + + {sales.data.sales.length} records +
- ))} -
- ) : ( - - ) - ) : products.loading ? ( - - ) : products.error ? ( - - ) : !products.data?.products.length ? ( - - ) : quote ? ( -
-

Review your quote

-

- {quote.brand} · {quote.region} · {quote.cardType} -

-

- {formatMoney(quote.amount)} -

-

- Expires{" "} - {new Date(quote.expiresAt).toLocaleString("en-NG", { - timeZone: "Africa/Lagos", - })} - . Subject to verification of card value. -

- - { - if (e.target.files?.[0]) void upload(e.target.files[0]); - }} - className={inputClass} + {sales.data.sales.map((s) => ( +
+
+
+ + + +
+

{s.brand}

+

+ {s.region} · {s.card_type} +

+
+
+ +
+
+
+

Quoted payout

+

+ {formatMoney(s.amount)} +

+
+

+ {new Date(s.created_at).toLocaleDateString("en-NG", { + day: "numeric", + month: "short", + year: "numeric", + timeZone: "Africa/Lagos", + })} +

+
+ {s.reason && ( +

{s.reason}

+ )} + + Ask about this sale + +
+ ))} +
+ ) : ( +
+ + + +

Your activity will show here

+

+ Once you submit a card for review, you can follow its status + from this page. +

+
+ ) + ) : products.loading ? ( + + ) : products.error ? ( + + ) : !products.data?.products.length ? ( + -

- Your evidence is private and held for a safety check. Uploading a - file does not add money to your wallet. Rejected cards receive a - reason and a support path. -

- - -
- ) : ( -
-
-
+
); diff --git a/packages/contracts/src/gift-purchases.ts b/packages/contracts/src/gift-purchases.ts new file mode 100644 index 0000000..7418ae6 --- /dev/null +++ b/packages/contracts/src/gift-purchases.ts @@ -0,0 +1,13 @@ +export type GiftPurchase = { + id: string; + product_id: string; + units: string; + amount: string; + status: "quoted" | "successful"; + expires_at: string; + brand?: string; +}; +export type GiftPurchaseResult = { + purchase: GiftPurchase; + demoCode: string | null; +}; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 585b560..db36ef3 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -270,3 +270,4 @@ export function shouldRefreshTransaction( Date.now() - new Date(t.createdAt).getTime() < 7 * 24 * 60 * 60 * 1000) ); } +export type { GiftPurchase, GiftPurchaseResult } from "./gift-purchases"; diff --git a/packages/database/migrations/0015_sandbox_gift_cards.sql b/packages/database/migrations/0015_sandbox_gift_cards.sql new file mode 100644 index 0000000..7219962 --- /dev/null +++ b/packages/database/migrations/0015_sandbox_gift_cards.sql @@ -0,0 +1,15 @@ +ALTER TABLE gift_products ADD COLUMN sandbox_only boolean NOT NULL DEFAULT false; +INSERT INTO gift_products(id,brand,region,card_type,enabled,buy_enabled,sell_enabled,rate_kobo,min_units,max_units,sandbox_only) +VALUES ('sandbox-apple-us','Apple (Sandbox)','US','digital',true,true,true,100000,10,500,true), +('sandbox-amazon-us','Amazon (Sandbox)','US','digital',true,true,true,100000,10,500,true), +('sandbox-steam-us','Steam (Sandbox)','US','digital',true,true,true,100000,10,500,true); +CREATE TABLE sandbox_gift_purchases ( + id uuid PRIMARY KEY, + user_id text NOT NULL REFERENCES users(id), + product_id text NOT NULL REFERENCES gift_products(id), + units bigint NOT NULL CHECK(units BETWEEN 10 AND 500), + amount bigint NOT NULL CHECK(amount>0), + status text NOT NULL DEFAULT 'quoted' CHECK(status IN ('quoted','successful')), + expires_at timestamptz NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); diff --git a/packages/database/migrations/0016_gift_card_display_names.sql b/packages/database/migrations/0016_gift_card_display_names.sql new file mode 100644 index 0000000..ce42186 --- /dev/null +++ b/packages/database/migrations/0016_gift_card_display_names.sql @@ -0,0 +1 @@ +UPDATE gift_products SET brand=replace(brand,' (Sandbox)','') WHERE sandbox_only=true; diff --git a/scripts/check-config.ts b/scripts/check-config.ts index cba085f..7b521c8 100644 --- a/scripts/check-config.ts +++ b/scripts/check-config.ts @@ -1,3 +1,4 @@ +import { supplierSettings } from "../apps/api/src/v1/modules/digital-services/providers/config"; import { env } from "../apps/api/src/shared/infrastructure/env"; import { ConfigurationError } from "../apps/api/src/shared/errors"; import { config } from "dotenv"; @@ -7,6 +8,7 @@ const envPath = fileURLToPath(new URL("../.env", import.meta.url)); config({ path: envPath, override: true, quiet: true }); try { const settings = env(); + supplierSettings(); console.log( `Server configuration is valid. PAYMENT_MODE=${settings.PAYMENT_MODE}. Source: ${envPath}`, ); diff --git a/tests/financial.test.ts b/tests/financial.test.ts index d1bcf8a..a447672 100644 --- a/tests/financial.test.ts +++ b/tests/financial.test.ts @@ -1,3 +1,5 @@ +import { purchases as giftPurchases } from "../apps/api/src/v1/modules/gift-cards/routes/purchases"; +import { products as giftProducts } from "../apps/api/src/v1/modules/gift-cards/routes/handler"; import { beforeAll, afterAll, describe, it, expect, vi } from "vitest"; import { readFile, readdir } from "node:fs/promises"; import pg from "pg"; @@ -1861,3 +1863,110 @@ describe("deposit checkout recovery", () => { } }); }); + +describe("sandbox gift-card checkout", () => { + it("quotes and confirms once without a wallet debit, isolates owners, expires quotes and hides demos outside sandbox", async () => { + const config = env(), + previous = config.PAYMENT_MODE; + const buyer = crypto.randomUUID(), + stranger = crypto.randomUUID(); + await user(buyer); + await user(stranger); + const login = await auth().api.signInEmail({ + body: { email: `${buyer}@quickpay.test`, password: testPassword }, + }); + const other = await auth().api.signInEmail({ + body: { email: `${stranger}@quickpay.test`, password: testPassword }, + }); + const req = (payload?: unknown, token = login.token) => + new Request("http://localhost:3001/api/v1/gift-cards/purchases", { + method: payload ? "POST" : "GET", + headers: { + authorization: `Bearer ${token}`, + "content-type": "application/json", + }, + ...(payload ? { body: JSON.stringify(payload) } : {}), + }); + try { + config.PAYMENT_MODE = "sandbox"; + const catalog = await (await giftProducts(req())).json(); + expect(catalog.buyingAvailable).toBe(true); + expect( + catalog.products.some( + (p: { id: string }) => p.id === "sandbox-apple-us", + ), + ).toBe(true); + await expect( + giftPurchases( + req({ action: "quote", productId: "sandbox-apple-us", units: "501" }), + ), + ).rejects.toThrow("within the card limits"); + const quoted = await ( + await giftPurchases( + req({ action: "quote", productId: "sandbox-apple-us", units: "10" }), + ) + ).json(); + expect(quoted.purchase.amount).toBe("1000000"); + const confirmation = { action: "confirm", quoteId: quoted.purchase.id }; + await expect( + giftPurchases(req(confirmation, other.token)), + ).rejects.toThrow("not found"); + const results = await Promise.all([ + giftPurchases(req(confirmation)), + giftPurchases(req(confirmation)), + ]); + for (const result of results) + expect((await result.json()).demoCode).toContain( + "DEMO-NOT-REDEEMABLE-", + ); + expect( + (await (await giftPurchases(req())).json()).purchases, + ).toHaveLength(1); + expect(await balance(buyer)).toBe(0n); + const expired = await ( + await giftPurchases( + req({ action: "quote", productId: "sandbox-apple-us", units: "10" }), + ) + ).json(); + await pool.query( + "UPDATE sandbox_gift_purchases SET expires_at=now()-interval '1 minute' WHERE id=$1", + [expired.purchase.id], + ); + await expect( + giftPurchases(req({ action: "confirm", quoteId: expired.purchase.id })), + ).rejects.toThrow("expired"); + const saleQuote = await ( + await giftQuote(req({ productId: "sandbox-apple-us", units: "10" })) + ).json(); + const evidenceId = crypto.randomUUID(); + await pool.query( + "INSERT INTO evidence(id,user_id,file_path,mime,size) VALUES($1,$2,'sandbox-sample','image/png',100)", + [evidenceId, buyer], + ); + const sale = await ( + await giftSales(req({ quoteId: saleQuote.id, evidenceId })) + ).json(); + expect(sale.id).toBeTruthy(); + expect( + ( + await pool.query("SELECT status FROM gift_sales WHERE id=$1", [ + sale.id, + ]) + ).rows[0].status, + ).toBe("review"); + expect(await balance(buyer)).toBe(0n); + config.PAYMENT_MODE = "disabled"; + expect( + (await (await giftProducts(req())).json()).products.every( + (p: { sandbox_only: boolean }) => !p.sandbox_only, + ), + ).toBe(true); + await expect(giftPurchases(req())).rejects.toThrow("not available"); + await expect( + giftQuote(req({ productId: "sandbox-apple-us", units: "10" })), + ).rejects.toThrow("not available"); + } finally { + config.PAYMENT_MODE = previous; + } + }); +}); diff --git a/tests/partner-clients.test.ts b/tests/partner-clients.test.ts new file mode 100644 index 0000000..2a61034 --- /dev/null +++ b/tests/partner-clients.test.ts @@ -0,0 +1,102 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { createHmac } from "node:crypto"; +import { + supplierEndpoint, + supplierSettings, + markedUpCost, +} from "../apps/api/src/v1/modules/digital-services/providers/config"; +import { + prestmit, + fincraQuote, + validPrestmitWebhook, +} from "../apps/api/src/v1/modules/digital-services/providers/partner-clients"; +afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); +}); +it("chooses fixed environment hosts and refuses disabled requests", () => { + expect(supplierEndpoint("prestmit", "sandbox")).toBe( + "https://dev-api.prestmit.io/partners/v1", + ); + expect(supplierEndpoint("prestmit", "live")).toBe( + "https://api.prestmit.io/partners/v1", + ); + expect(supplierEndpoint("fincra", "live")).toBe("https://api.fincra.com"); + expect(() => supplierEndpoint("fincra", "disabled")).toThrow(); +}); +it("rejects invalid margins and rounds purchase prices upward in minor units", () => { + expect(markedUpCost(101n, 300)).toBe(105n); + expect(markedUpCost(100000n, 2000)).toBe(120000n); + expect(() => supplierSettings({ GIFT_BUY_MARKUP_BPS: "-1" })).toThrow(); + expect(() => markedUpCost(1n, 0.5)).toThrow(); +}); +it("authenticates exact Prestmit query fields with HMAC", async () => { + vi.stubEnv("PAYMENT_MODE", "sandbox"); + vi.stubEnv("PRESTMIT_API_KEY", "test-key"); + vi.stubEnv("PRESTMIT_API_SECRET", "test-secret"); + const fetcher = vi.fn().mockResolvedValue(Response.json({ success: true })); + vi.stubGlobal("fetch", fetcher); + await prestmit.buyCatalog("2"); + const [url, init] = fetcher.mock.calls[0]; + expect(String(url)).toBe( + "https://dev-api.prestmit.io/partners/v1/giftcard-trade/buy/fetch-buyable-giftcards?page=2", + ); + expect(init.headers["API-Hash"]).toBe( + createHmac("sha256", "test-secret") + .update('test-key:{"page":"2"}') + .digest("hex"), + ); + expect(init.redirect).toBe("error"); +}); +it("authenticates Fincra quotes with business ID and conversion destination", async () => { + vi.stubEnv("PAYMENT_MODE", "sandbox"); + vi.stubEnv("FINCRA_SECRET_KEY", "test-secret"); + vi.stubEnv("FINCRA_BUSINESS_ID", "business-test"); + const fetcher = vi.fn().mockResolvedValue(Response.json({ success: true })); + vi.stubGlobal("fetch", fetcher); + await fincraQuote("NGN", "USD", "10000.00"); + const [url, init] = fetcher.mock.calls[0]; + expect(url).toBe("https://sandboxapi.fincra.com/quotes/generate"); + expect(init.headers["api-key"]).toBe("test-secret"); + expect(JSON.parse(init.body)).toMatchObject({ + business: "business-test", + paymentDestination: "fliqpay_wallet", + amount: "10000.00", + transactionType: "conversion", + }); +}); +it("rejects unsupported amount representations before any request", async () => { + const fetcher = vi.fn(); + vi.stubGlobal("fetch", fetcher); + await expect(fincraQuote("NGN", "USD", "1e5")).rejects.toThrow(); + await expect(fincraQuote("NGN", "NGN", "1")).rejects.toThrow(); + expect(fetcher).not.toHaveBeenCalled(); +}); +it("validates webhook signatures against raw bytes and requires a secret", () => { + const body = '{ "status": "APPROVED" }'; + const signature = createHmac("sha256", "secret") + .update(body) + .digest("base64"); + expect(validPrestmitWebhook(body, signature, "secret")).toBe(true); + expect( + validPrestmitWebhook(JSON.stringify(JSON.parse(body)), signature, "secret"), + ).toBe(false); + expect(validPrestmitWebhook(body, signature, "")).toBe(false); + expect(validPrestmitWebhook(body, "bad", "secret")).toBe(false); +}); +it("redacts provider error details", async () => { + vi.stubEnv("PAYMENT_MODE", "sandbox"); + vi.stubEnv("PRESTMIT_API_KEY", "key"); + vi.stubEnv("PRESTMIT_API_SECRET", "secret"); + vi.stubGlobal( + "fetch", + vi + .fn() + .mockResolvedValue( + Response.json({ error: "secret credential" }, { status: 401 }), + ), + ); + await expect(prestmit.availability()).rejects.toThrow( + "Check its status before retrying", + ); +});