Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"scripts": {
"dev": "node src/server.js",
"start": "node src/server.js",
"test": "node --test src/tests"
"test": "node --test src/tests/*.test.js"
},
"dependencies": {
"cors": "^2.8.5",
Expand All @@ -14,6 +14,7 @@
"helmet": "^7.1.0",
"jsonwebtoken": "^9.0.2",
"multer": "^2.1.1",
"stripe": "^22.1.1",
"zod": "^3.23.8"
}
}
14 changes: 11 additions & 3 deletions apps/api/src/controllers/paymentController.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { ok } from "../utils/response.js";
import { createPaymentIntent } from "../services/paymentService.js";
import { fail, ok } from "../utils/response.js";
import { createPaymentIntent, PaymentServiceError } from "../services/paymentService.js";

export async function createPayment(req, res) {
return ok(res, await createPaymentIntent(req.body), 201);
try {
return ok(res, await createPaymentIntent(req.body), 201);
} catch (error) {
if (error instanceof PaymentServiceError) {
return fail(res, error.message, error.statusCode);
}

throw error;
}
}
120 changes: 112 additions & 8 deletions apps/api/src/services/paymentService.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,113 @@
export async function createPaymentIntent(payload) {
// TODO: integrate Stripe SDK and return client secret.
return {
paymentId: `pay_${Date.now()}`,
amount: payload.amount,
currency: payload.currency ?? "usd",
provider: "stripe"
};
import Stripe from "stripe";
import { env } from "../config/env.js";

let stripeClient;

export class PaymentServiceError extends Error {
constructor(message, statusCode = 400) {
super(message);
this.name = "PaymentServiceError";
this.statusCode = statusCode;
}
}

export function setStripeClientForTest(client) {
stripeClient = client;
}

export function resetStripeClientForTest() {
stripeClient = undefined;
}

function getStripeClient() {
if (stripeClient) {
return stripeClient;
}

if (!env.stripeSecretKey) {
throw new PaymentServiceError("STRIPE_SECRET_KEY is required to create payment intents", 500);
}

stripeClient = new Stripe(env.stripeSecretKey);
return stripeClient;
}

function validateAmount(amount) {
if (!Number.isInteger(amount) || amount <= 0) {
throw new PaymentServiceError("amount is required and must be a positive integer");
}
return amount;
}

function validateCurrency(currency) {
const requestedCurrency = currency ?? "usd";

if (typeof requestedCurrency !== "string") {
throw new PaymentServiceError("currency must be a valid three-letter currency code");
}

const normalizedCurrency = requestedCurrency.toLowerCase();

if (!/^[a-z]{3}$/.test(normalizedCurrency)) {
throw new PaymentServiceError("currency must be a valid three-letter currency code");
}

return normalizedCurrency;
}

function validateMetadata(metadata) {
if (metadata === undefined) {
return undefined;
}

if (!metadata || Array.isArray(metadata) || typeof metadata !== "object") {
throw new PaymentServiceError("metadata must be an object when provided");
}

return Object.fromEntries(
Object.entries(metadata).map(([key, value]) => {
if (value === null || value === undefined || typeof value === "object") {
throw new PaymentServiceError("metadata values must be strings, numbers, or booleans");
}

return [key, String(value)];
})
);
}

function toStripeError(error) {
const type = error?.type ?? error?.raw?.type ?? "";
if (type.startsWith("Stripe") && error?.message) {
return new PaymentServiceError(error.message, 502);
}

return new PaymentServiceError("Unable to create payment intent", 502);
}

export async function createPaymentIntent(payload = {}) {
const amount = validateAmount(payload.amount);
const currency = validateCurrency(payload.currency);
const metadata = validateMetadata(payload.metadata);

try {
const paymentIntent = await getStripeClient().paymentIntents.create({
amount,
currency,
...(metadata ? { metadata } : {})
});

return {
paymentId: paymentIntent.id,
clientSecret: paymentIntent.client_secret,
amount,
currency,
provider: "stripe"
};
} catch (error) {
if (error instanceof PaymentServiceError) {
throw error;
}

throw toStripeError(error);
}
}
140 changes: 140 additions & 0 deletions apps/api/src/tests/paymentService.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
createPaymentIntent,
resetStripeClientForTest,
setStripeClientForTest
} from "../services/paymentService.js";

test.afterEach(() => {
resetStripeClientForTest();
});

test("createPaymentIntent validates positive integer amounts", async () => {
await assert.rejects(
() => createPaymentIntent({ amount: 0 }),
/amount is required and must be a positive integer/
);

await assert.rejects(
() => createPaymentIntent({ amount: 12.5 }),
/amount is required and must be a positive integer/
);
});

test("createPaymentIntent validates currency values", async () => {
await assert.rejects(
() => createPaymentIntent({ amount: 2500, currency: 123 }),
/currency must be a valid three-letter currency code/
);

await assert.rejects(
() => createPaymentIntent({ amount: 2500, currency: "usdollar" }),
/currency must be a valid three-letter currency code/
);
});

test("createPaymentIntent creates a Stripe payment intent with default currency", async () => {
const calls = [];
setStripeClientForTest({
paymentIntents: {
create: async (params) => {
calls.push(params);
return {
id: "pi_test_123",
client_secret: "pi_test_123_secret_abc"
};
}
}
});

const result = await createPaymentIntent({ amount: 2500 });

assert.deepEqual(calls, [{ amount: 2500, currency: "usd" }]);
assert.deepEqual(result, {
paymentId: "pi_test_123",
clientSecret: "pi_test_123_secret_abc",
amount: 2500,
currency: "usd",
provider: "stripe"
});
});

test("createPaymentIntent normalizes currency and metadata before calling Stripe", async () => {
const calls = [];
setStripeClientForTest({
paymentIntents: {
create: async (params) => {
calls.push(params);
return {
id: "pi_test_456",
client_secret: "pi_test_456_secret_def"
};
}
}
});

await createPaymentIntent({
amount: 5000,
currency: "EUR",
metadata: {
jobId: 42,
urgent: true,
source: "checkout"
}
});

assert.deepEqual(calls, [
{
amount: 5000,
currency: "eur",
metadata: {
jobId: "42",
urgent: "true",
source: "checkout"
}
}
]);
});

test("createPaymentIntent preserves Stripe error messages", async () => {
setStripeClientForTest({
paymentIntents: {
create: async () => {
const error = new Error("No such customer: cus_missing");
error.type = "StripeInvalidRequestError";
throw error;
}
}
});

await assert.rejects(
() => createPaymentIntent({ amount: 5000 }),
/No such customer: cus_missing/
);
});

test("createPaymentIntent live Stripe smoke test", { skip: shouldSkipStripeSmoke() }, async () => {
const result = await createPaymentIntent({
amount: 100,
currency: "usd",
metadata: {
smoke: "true"
}
});

assert.match(result.paymentId, /^pi_/);
assert.match(result.clientSecret, /^pi_.*_secret_/);
});

function shouldSkipStripeSmoke() {
if (process.env.STRIPE_PAYMENT_SMOKE !== "true") {
return "set STRIPE_PAYMENT_SMOKE=true to run the live Stripe smoke test";
}

if (!process.env.STRIPE_SECRET_KEY) {
return "set STRIPE_SECRET_KEY to run the live Stripe smoke test";
}

return false;
}
23 changes: 20 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading