mirror of
https://github.com/bitbaum/paykit.git
synced 2026-12-04 05:30:36 +01:00
* Add a Stripe provider: cards, TWINT and wallets (0.4.0) `@bitbaum/paykit/stripe` implements PaymentProvider against Stripe's hosted Checkout: a one-time session for a plan, the session read back for status, and the Stripe-Signature webhook check. No payment_method_types is sent, so which methods a buyer sees (TWINT for a CHF price, cards, wallets) is the seller's Stripe Dashboard. No SDK and no new dependency. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmteJuDGFouA1itJ5tM * StripeError without a parameter property, so the source also runs under type stripping Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmteJuDGFouA1itJ5tM * Stripe provider: sendReference, to tell Stripe nothing about the buyer An app that keeps its accounts to itself can turn off client_reference_id. Settling never needed it: the stored checkout is the link back. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmteJuDGFouA1itJ5tM --------- Co-authored-by: Claude <noreply@anthropic.com>
204 lines
11 KiB
JavaScript
204 lines
11 KiB
JavaScript
import assert from 'node:assert/strict';
|
|
import { createHmac } from 'node:crypto';
|
|
import test from 'node:test';
|
|
import { applySettlement } from '../dist/checkout/index.js';
|
|
import { StripeError, signStripePayload, stripeProvider, verifyStripeSignature } from '../dist/stripe/index.js';
|
|
|
|
const secret = 'whsec_test';
|
|
const now = new Date('2026-11-26T08:00:00Z');
|
|
const month = { id: 'month', days: 30, price: { amount: 1200, currency: 'CHF' }, providerRef: 'pass-30' };
|
|
const urls = { successUrl: 'https://app.example/pass/checkout/{CHECKOUT_SESSION_ID}', cancelUrl: 'https://app.example/pass' };
|
|
|
|
function json(status, body) {
|
|
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
|
}
|
|
const session = (over = {}) => ({
|
|
id: 'cs_test_1',
|
|
object: 'checkout.session',
|
|
url: 'https://checkout.stripe.com/c/pay/cs_test_1',
|
|
expires_at: Math.floor(now.getTime() / 1000) + 86_400,
|
|
status: 'open',
|
|
payment_status: 'unpaid',
|
|
amount_total: 1200,
|
|
currency: 'chf',
|
|
client_reference_id: 'user-1',
|
|
...over,
|
|
});
|
|
const completed = (over = {}, type = 'checkout.session.completed') =>
|
|
JSON.stringify({ id: 'evt_1', type, data: { object: session({ status: 'complete', payment_status: 'paid', ...over }) } });
|
|
|
|
test('the signature is HMAC-SHA-256 over `${t}.${rawBody}`, as Stripe signs it', () => {
|
|
const body = completed();
|
|
const t = Math.floor(now.getTime() / 1000);
|
|
const byHand = `t=${t},v1=${createHmac('sha256', secret).update(`${t}.${body}`).digest('hex')}`;
|
|
assert.equal(signStripePayload(body, secret, now), byHand);
|
|
assert.deepEqual(verifyStripeSignature(body, secret, byHand, { now }), { valid: true });
|
|
});
|
|
|
|
test('a wrong secret, a changed body, an old timestamp and a broken header are each refused', () => {
|
|
const body = completed();
|
|
const header = signStripePayload(body, secret, now);
|
|
assert.equal(verifyStripeSignature(body, 'other', header, { now }).reason, 'signature_mismatch');
|
|
assert.equal(verifyStripeSignature(body + ' ', secret, header, { now }).reason, 'signature_mismatch');
|
|
assert.equal(verifyStripeSignature(body, secret, header, { now: new Date(now.getTime() + 301_000) }).reason, 'timestamp_outside_tolerance');
|
|
assert.equal(verifyStripeSignature(body, secret, header, { now: new Date(now.getTime() + 300_000) }).valid, true);
|
|
assert.equal(verifyStripeSignature(body, secret, null, { now }).reason, 'malformed_header');
|
|
assert.equal(verifyStripeSignature(body, secret, 'v1=abc', { now }).reason, 'malformed_header');
|
|
assert.equal(verifyStripeSignature(body, secret, `t=${Math.floor(now.getTime() / 1000)},v0=abc`, { now }).reason, 'unknown_scheme');
|
|
});
|
|
|
|
test('while a secret is rolled two v1 signatures arrive, and either one is enough', () => {
|
|
const body = completed();
|
|
const t = Math.floor(now.getTime() / 1000);
|
|
const good = createHmac('sha256', secret).update(`${t}.${body}`).digest('hex');
|
|
const other = createHmac('sha256', 'whsec_old').update(`${t}.${body}`).digest('hex');
|
|
assert.equal(verifyStripeSignature(body, secret, `t=${t},v1=${other},v1=${good},v0=ignored`, { now }).valid, true);
|
|
});
|
|
|
|
test('createCheckout asks for a one-time hosted payment and names no payment method', async () => {
|
|
const calls = [];
|
|
const provider = stripeProvider({
|
|
...urls,
|
|
secretKey: 'sk_test_x',
|
|
locale: 'de',
|
|
productName: (plan) => `Heidi pass, ${plan.days} days`,
|
|
now: () => now,
|
|
fetch: async (url, init) => {
|
|
calls.push({ url, init });
|
|
return json(200, session());
|
|
},
|
|
});
|
|
const checkout = await provider.createCheckout({ plan: month, reference: 'user-1' });
|
|
|
|
assert.equal(calls[0].url, 'https://api.stripe.com/v1/checkout/sessions');
|
|
assert.equal(calls[0].init.method, 'POST');
|
|
assert.equal(calls[0].init.headers.authorization, 'Bearer sk_test_x');
|
|
const form = Object.fromEntries(new URLSearchParams(calls[0].init.body));
|
|
assert.deepEqual(form, {
|
|
mode: 'payment',
|
|
client_reference_id: 'user-1',
|
|
success_url: urls.successUrl,
|
|
cancel_url: urls.cancelUrl,
|
|
'metadata[plan_id]': 'month',
|
|
'line_items[0][quantity]': '1',
|
|
'line_items[0][price_data][currency]': 'chf',
|
|
'line_items[0][price_data][unit_amount]': '1200',
|
|
'line_items[0][price_data][product_data][name]': 'Heidi pass, 30 days',
|
|
locale: 'de',
|
|
});
|
|
// Which methods are offered is the seller's Dashboard: TWINT appears there, not here.
|
|
assert.equal(calls[0].init.body.includes('payment_method_types'), false);
|
|
assert.deepEqual(checkout, {
|
|
provider: 'stripe',
|
|
id: 'cs_test_1',
|
|
reference: 'user-1',
|
|
planId: 'month',
|
|
amount: { amount: 1200, currency: 'CHF' },
|
|
payUrl: 'https://checkout.stripe.com/c/pay/cs_test_1',
|
|
expiresAt: new Date(now.getTime() + 86_400_000).toISOString(),
|
|
});
|
|
assert.equal('invoice' in checkout, false);
|
|
});
|
|
|
|
test('with sendReference off, Stripe is told nothing about who is buying', async () => {
|
|
let body = '';
|
|
const provider = stripeProvider({ ...urls, secretKey: 'sk_test_x', sendReference: false, fetch: async (_url, init) => ((body = init.body), json(200, session())) });
|
|
const checkout = await provider.createCheckout({ plan: month, reference: 'user-1' });
|
|
assert.equal(body.includes('user-1'), false);
|
|
assert.equal(new URLSearchParams(body).has('client_reference_id'), false);
|
|
// The app still knows whose it is: the checkout it stores.
|
|
assert.equal(checkout.reference, 'user-1');
|
|
});
|
|
|
|
test('a plan whose providerRef is a Stripe price charges that price', async () => {
|
|
let body = '';
|
|
const provider = stripeProvider({ ...urls, secretKey: 'sk_test_x', fetch: async (_url, init) => ((body = init.body), json(200, session())) });
|
|
await provider.createCheckout({ plan: { ...month, providerRef: 'price_123' }, reference: 'user-1' });
|
|
const form = Object.fromEntries(new URLSearchParams(body));
|
|
assert.equal(form['line_items[0][price]'], 'price_123');
|
|
assert.equal(Object.keys(form).some((k) => k.includes('price_data')), false);
|
|
});
|
|
|
|
test('no key, a fractional amount and a currency that is not one are refused before any call', async () => {
|
|
let called = 0;
|
|
const fetch = async () => (called++, json(200, session()));
|
|
await assert.rejects(stripeProvider({ ...urls, fetch }).createCheckout({ plan: month, reference: 'u' }), StripeError);
|
|
const provider = stripeProvider({ ...urls, secretKey: 'sk_test_x', fetch });
|
|
await assert.rejects(provider.createCheckout({ plan: { ...month, price: { amount: 12.5, currency: 'CHF' } }, reference: 'u' }), StripeError);
|
|
await assert.rejects(provider.createCheckout({ plan: { ...month, price: { amount: 0, currency: 'CHF' } }, reference: 'u' }), StripeError);
|
|
await assert.rejects(provider.createCheckout({ plan: { ...month, price: { amount: 1200, currency: 'francs' } }, reference: 'u' }), StripeError);
|
|
assert.equal(called, 0);
|
|
});
|
|
|
|
test("Stripe's own error sentence reaches the caller, with the status", async () => {
|
|
const provider = stripeProvider({ ...urls, secretKey: 'sk_test_x', fetch: async () => json(401, { error: { type: 'invalid_request_error', message: 'Invalid API Key provided: sk_test_x' } }) });
|
|
await assert.rejects(provider.createCheckout({ plan: month, reference: 'u' }), (error) => error instanceof StripeError && error.status === 401 && /Invalid API Key/.test(error.message));
|
|
const mute = stripeProvider({ ...urls, secretKey: 'sk_test_x', fetch: async () => new Response('gateway', { status: 502 }) });
|
|
await assert.rejects(mute.createCheckout({ plan: month, reference: 'u' }), (error) => error.message === 'Stripe answered 502');
|
|
});
|
|
|
|
test('status reads the session: paid is payment_status, not a finished session', async () => {
|
|
const answers = [session(), session({ status: 'complete', payment_status: 'unpaid' }), session({ status: 'complete', payment_status: 'paid' }), session({ status: 'expired' })];
|
|
const seen = [];
|
|
const provider = stripeProvider({ ...urls, secretKey: 'sk_test_x', now: () => now, fetch: async (url, init) => (seen.push([url, init.method]), json(200, answers.shift())) });
|
|
assert.deepEqual(await provider.status({ id: 'cs_test_1' }), { state: 'pending', paidAt: null });
|
|
assert.deepEqual(await provider.status({ id: 'cs_test_1' }), { state: 'pending', paidAt: null });
|
|
assert.deepEqual(await provider.status({ id: 'cs_test_1' }), { state: 'paid', paidAt: now.toISOString() });
|
|
assert.deepEqual(await provider.status({ id: 'cs_test_1' }), { state: 'expired', paidAt: null });
|
|
assert.deepEqual(seen[0], ['https://api.stripe.com/v1/checkout/sessions/cs_test_1', 'GET']);
|
|
});
|
|
|
|
test('verifyWebhook turns a paid session into a settlement and nothing else into one', () => {
|
|
const provider = stripeProvider({ ...urls, webhookSecret: secret, now: () => now });
|
|
const sign = (body) => ({ 'Stripe-Signature': signStripePayload(body, secret, now) });
|
|
|
|
const paid = completed();
|
|
assert.deepEqual(provider.verifyWebhook(paid, sign(paid)), {
|
|
ok: true,
|
|
event: { provider: 'stripe', externalId: 'cs_test_1', amount: { amount: 1200, currency: 'CHF' }, providerRef: null, eventId: 'evt_1' },
|
|
});
|
|
const later = completed({}, 'checkout.session.async_payment_succeeded');
|
|
assert.equal(provider.verifyWebhook(later, sign(later)).event.externalId, 'cs_test_1');
|
|
|
|
// Finished but the money is not there yet: the async event follows.
|
|
const waiting = completed({ payment_status: 'unpaid' });
|
|
assert.deepEqual(provider.verifyWebhook(waiting, sign(waiting)), { ok: true, event: null });
|
|
const other = JSON.stringify({ id: 'evt_2', type: 'charge.refunded', data: { object: {} } });
|
|
assert.deepEqual(provider.verifyWebhook(other, sign(other)), { ok: true, event: null });
|
|
|
|
assert.deepEqual(provider.verifyWebhook(paid, { 'Stripe-Signature': signStripePayload(paid, 'whsec_other', now) }), { ok: false, reason: 'signature_mismatch' });
|
|
assert.deepEqual(provider.verifyWebhook(paid, {}), { ok: false, reason: 'malformed_header' });
|
|
assert.deepEqual(provider.verifyWebhook('not json', sign('not json')), { ok: false, reason: 'malformed_body' });
|
|
const empty = JSON.stringify({ id: 'evt_3', type: 'checkout.session.completed', data: {} });
|
|
assert.deepEqual(provider.verifyWebhook(empty, sign(empty)), { ok: false, reason: 'malformed_body' });
|
|
assert.deepEqual(stripeProvider(urls).verifyWebhook(paid, sign(paid)), { ok: false, reason: 'no_webhook_secret' });
|
|
});
|
|
|
|
test('a Stripe settlement grants once, and a session paid short of the stored price grants nothing', async () => {
|
|
const provider = stripeProvider({ ...urls, webhookSecret: secret, now: () => now });
|
|
const stored = { id: 'cs_test_1', reference: 'user-1', planId: 'month', amount: { amount: 1200, currency: 'CHF' } };
|
|
let settled = false;
|
|
let entitlement = null;
|
|
const store = {
|
|
findCheckout: async (id) => (id === stored.id ? stored : null),
|
|
settleOnce: async (_checkout, grant) => {
|
|
if (settled) return null;
|
|
settled = true;
|
|
return (entitlement = grant(entitlement));
|
|
},
|
|
};
|
|
const deliver = async (body) => {
|
|
const verdict = provider.verifyWebhook(body, { 'stripe-signature': signStripePayload(body, secret, now) });
|
|
return applySettlement({ event: verdict.event, plans: [month], store, paidAt: now });
|
|
};
|
|
|
|
assert.equal((await deliver(completed({ amount_total: 600 }))).outcome, 'underpaid');
|
|
assert.equal((await deliver(completed({ currency: 'eur' }))).outcome, 'underpaid');
|
|
assert.equal(settled, false);
|
|
|
|
const first = await deliver(completed());
|
|
assert.equal(first.outcome, 'granted');
|
|
assert.equal(first.entitlement.expiresAt, new Date(now.getTime() + 30 * 86_400_000).toISOString());
|
|
assert.equal((await deliver(completed())).outcome, 'duplicate');
|
|
});
|