Skip to content
Closed
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/*.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": "^16.12.0",
"zod": "^3.23.8"
}
}
59 changes: 54 additions & 5 deletions apps/api/src/services/paymentService.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,58 @@
export async function createPaymentIntent(payload) {
// TODO: integrate Stripe SDK and return client secret.
import Stripe from "stripe";

let stripeClient;

function getStripeClient() {
if (!process.env.STRIPE_SECRET_KEY) {
throw new Error("STRIPE_SECRET_KEY is required to create payment intents");
}

stripeClient ??= new Stripe(process.env.STRIPE_SECRET_KEY);
return stripeClient;
}

function validatePaymentPayload(payload = {}) {
if (!Number.isInteger(payload.amount) || payload.amount <= 0) {
throw new Error("amount must be a positive integer in the smallest currency unit");
}

const currency = payload.currency ?? "usd";
if (typeof currency !== "string" || currency.trim() === "") {
throw new Error("currency must be a non-empty string");
}

return {
paymentId: `pay_${Date.now()}`,
amount: payload.amount,
currency: payload.currency ?? "usd",
provider: "stripe"
currency: currency.toLowerCase(),
metadata: payload.metadata
};
}

export async function createPaymentIntent(payload) {
const { amount, currency, metadata } = validatePaymentPayload(payload);

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?.type?.startsWith("Stripe")) {
throw new Error(error.message);
}
throw error;
}
}

export function __setStripeClientForTest(client) {
stripeClient = client;
}
147 changes: 147 additions & 0 deletions apps/api/src/tests/paymentService.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import test from "node:test";
import assert from "node:assert/strict";
import { createApp } from "../app.js";
import { createPaymentIntent, __setStripeClientForTest } from "../services/paymentService.js";

async function withServer(assertions) {
const app = createApp();
const server = app.listen(0);

await new Promise((resolve, reject) => {
server.once("listening", resolve);
server.once("error", reject);
});

try {
const { port } = server.address();
await assertions(`http://127.0.0.1:${port}`);
} finally {
await new Promise((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
});
}
}

test.afterEach(() => {
__setStripeClientForTest(undefined);
delete process.env.STRIPE_SECRET_KEY;
});

test("createPaymentIntent creates a Stripe PaymentIntent", async () => {
process.env.STRIPE_SECRET_KEY = "sk_test_example";
const calls = [];

__setStripeClientForTest({
paymentIntents: {
async create(payload) {
calls.push(payload);
return {
id: "pi_123",
client_secret: "pi_123_secret_456"
};
}
}
});

const result = await createPaymentIntent({
amount: 2500,
currency: "USD",
metadata: { jobId: "job_1" }
});

assert.deepEqual(calls, [
{
amount: 2500,
currency: "usd",
metadata: { jobId: "job_1" }
}
]);
assert.deepEqual(result, {
paymentId: "pi_123",
clientSecret: "pi_123_secret_456",
amount: 2500,
currency: "usd",
provider: "stripe"
});
});

test("createPaymentIntent defaults currency to usd", async () => {
process.env.STRIPE_SECRET_KEY = "sk_test_example";
let stripePayload;

__setStripeClientForTest({
paymentIntents: {
async create(payload) {
stripePayload = payload;
return { id: "pi_123", client_secret: "secret" };
}
}
});

await createPaymentIntent({ amount: 100 });

assert.equal(stripePayload.currency, "usd");
});

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

test("createPaymentIntent preserves Stripe error messages", async () => {
process.env.STRIPE_SECRET_KEY = "sk_test_example";
__setStripeClientForTest({
paymentIntents: {
async create() {
const error = new Error("Your card was declined.");
error.type = "StripeCardError";
throw error;
}
}
});

await assert.rejects(
() => createPaymentIntent({ amount: 100 }),
/Your card was declined\./
);
});

test("createPaymentIntent requires STRIPE_SECRET_KEY", async () => {
await assert.rejects(
() => createPaymentIntent({ amount: 100 }),
/STRIPE_SECRET_KEY is required/
);
});

test("POST /api/payments returns Stripe payment data", async () => {
process.env.STRIPE_SECRET_KEY = "sk_test_example";
__setStripeClientForTest({
paymentIntents: {
async create() {
return { id: "pi_route", client_secret: "pi_route_secret" };
}
}
});

await withServer(async (baseUrl) => {
const response = await fetch(`${baseUrl}/api/payments`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ amount: 500, currency: "usd" })
});
const payload = await response.json();

assert.equal(response.status, 201);
assert.equal(payload.success, true);
assert.equal(payload.data.paymentId, "pi_route");
assert.equal(payload.data.clientSecret, "pi_route_secret");
});
});

test("createPaymentIntent live Stripe smoke test", { skip: process.env.STRIPE_LIVE_SMOKE !== "1" }, async () => {
const result = await createPaymentIntent({ amount: 100, currency: "usd" });
assert.match(result.paymentId, /^pi_/);
assert.equal(typeof result.clientSecret, "string");
});
16 changes: 14 additions & 2 deletions package-lock.json

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