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
1 change: 1 addition & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"helmet": "^7.1.0",
"jsonwebtoken": "^9.0.2",
"multer": "^2.1.1",
"stripe": "^16.0.0",
"zod": "^3.23.8"
}
}
67 changes: 60 additions & 7 deletions apps/api/src/services/paymentService.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,62 @@
import Stripe from "stripe";

let _stripe = null;

/**
* Initialise (or replace) the Stripe singleton.
* Call once at app startup with the real key.
*
* @param {string} [secretKey] - Stripe secret key. Falls back to STRIPE_SECRET_KEY env var.
* @param {import("stripe").default} [stripeInstance] - Optional pre-configured Stripe instance
* (useful for testing without real API calls).
*/
export function initStripe(secretKey, stripeInstance) {
if (stripeInstance) {
_stripe = stripeInstance;
return _stripe;
}
const key = secretKey ?? process.env.STRIPE_SECRET_KEY;
if (!key) throw new Error("STRIPE_SECRET_KEY environment variable is not set");
_stripe = new Stripe(key, { apiVersion: "2024-06-20" });
return _stripe;
}

function getStripe() {
if (!_stripe) {
initStripe();
}
return _stripe;
}

/**
* Create a Stripe PaymentIntent.
*
* @param {{ amount: number, currency?: string }} payload
* @returns {{ paymentId: string, clientSecret: string, amount: number, currency: string, provider: string }}
*/
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"
};
if (!payload.amount || typeof payload.amount !== "number" || payload.amount <= 0) {
throw new Error(
"payload.amount is required and must be a positive integer (smallest currency unit, e.g. cents)"
);
}

const currency = payload.currency ?? "usd";

try {
const paymentIntent = await getStripe().paymentIntents.create({
amount: payload.amount,
currency,
});

return {
paymentId: paymentIntent.id,
clientSecret: paymentIntent.client_secret,
amount: paymentIntent.amount,
currency: paymentIntent.currency,
provider: "stripe",
};
} catch (err) {
throw new Error(err.message);
}
}
114 changes: 114 additions & 0 deletions apps/api/src/tests/payment.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import test from "node:test";
import assert from "node:assert/strict";
import { createPaymentIntent, initStripe } from "../services/paymentService.js";

test("createPaymentIntent throws when amount is missing", async () => {
await assert.rejects(
() => createPaymentIntent({}),
/payload.amount is required/
);
});

test("createPaymentIntent throws when amount is zero", async () => {
await assert.rejects(
() => createPaymentIntent({ amount: 0 }),
/payload.amount is required/
);
});

test("createPaymentIntent throws when amount is negative", async () => {
await assert.rejects(
() => createPaymentIntent({ amount: -100 }),
/payload.amount is required/
);
});

test("createPaymentIntent throws when amount is not a number", async () => {
await assert.rejects(
() => createPaymentIntent({ amount: "100" }),
/payload.amount is required/
);
});

test("createPaymentIntent returns correct shape and maps fields from PaymentIntent", async () => {
const mockStripe = {
paymentIntents: {
create: async (args) => ({
id: `pi_${Date.now()}`,
client_secret: `pi_${Date.now()}_secret_${args.currency}`,
amount: args.amount,
currency: args.currency,
}),
},
};
initStripe(undefined, mockStripe);

const result = await createPaymentIntent({ amount: 2000, currency: "usd" });

assert.equal(typeof result.paymentId, "string");
assert.equal(result.paymentId.startsWith("pi_"), true, "paymentId starts with pi_");
assert.equal(typeof result.clientSecret, "string");
assert.ok(result.clientSecret.includes("_secret_"), "clientSecret contains _secret_");
assert.equal(result.amount, 2000);
assert.equal(result.currency, "usd");
assert.equal(result.provider, "stripe");
});

test("createPaymentIntent uses default currency 'usd' when not provided", async () => {
const mockStripe = {
paymentIntents: {
create: async (args) => ({
id: "pi_fixed",
client_secret: "pi_fixed_secret_xyz",
amount: args.amount,
currency: args.currency,
}),
},
};
initStripe(undefined, mockStripe);

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

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

test("createPaymentIntent passes amount and currency to Stripe paymentIntents.create", async () => {
let capturedArgs = null;
const mockStripe = {
paymentIntents: {
create: async (args) => {
capturedArgs = args;
return {
id: "pi_fixed",
client_secret: "pi_fixed_secret_xyz",
amount: args.amount,
currency: args.currency,
};
},
},
};
initStripe(undefined, mockStripe);

await createPaymentIntent({ amount: 3450, currency: "eur" });

assert.equal(capturedArgs.amount, 3450);
assert.equal(capturedArgs.currency, "eur");
});

test("createPaymentIntent throws and preserves Stripe error message", async () => {
const mockStripe = {
paymentIntents: {
create: async () => {
const err = new Error("Your card was declined");
err.type = "StripeCardError";
throw err;
},
},
};
initStripe(undefined, mockStripe);

await assert.rejects(
() => createPaymentIntent({ amount: 1000 }),
/Your card was declined/
);
});
20 changes: 18 additions & 2 deletions package-lock.json

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

Loading