Skip to content

Commit ac2607c

Browse files
committed
Stripe: mirror refunds and track the refunded amount on payments
1 parent 738209f commit ac2607c

7 files changed

Lines changed: 189 additions & 1 deletion

File tree

‎modules/spacetime-stripe-ts/README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ spacetime call --server http://127.0.0.1:3000 stripe-ts get_stripe_config_status
128128
| `stripe_checkout_session` | `stripe_checkout_session_id` | customer |
129129
| `stripe_invoice` | `stripe_invoice_id` | customer, subscription, org, user |
130130
| `stripe_payment` | `stripe_payment_intent_id` | customer, org, user |
131+
| `stripe_refund` | `stripe_refund_id` | PaymentIntent |
131132

132133
- `stripe_webhook_event`: idempotency log holding each event's payload (not its
133134
signature header). The scheduled `prune_webhook_events` reducer deletes events
@@ -232,6 +233,8 @@ invoice.paid invoice.payment_succeeded
232233
invoice.payment_failed invoice_payment.paid
233234
payment_intent.succeeded
234235
payment_intent.payment_failed
236+
refund.created refund.updated
237+
refund.failed charge.refund.updated
235238
```
236239

237240
Other event types are accepted and stored with status `Ignored`.
@@ -329,6 +332,10 @@ shapes:
329332
Endpoints on `2025-03-31.basil` or later must subscribe to
330333
`invoice_payment.paid`. Exclude rows with `stripeInvoiceId` when totaling
331334
payments alongside `stripe_invoice`.
335+
- `stripe_refund` mirrors refunds by PaymentIntent. `stripe_payment.amountRefunded`
336+
is the sum of its refunds that are not `failed` or `canceled`, so a payment
337+
is fully refunded when `amountRefunded` equals `amount`. Refunds without a
338+
PaymentIntent are stored as `Ignored`.
332339
- An invoice row takes `userId` and `orgId` from its subscription row, or from
333340
`invoice.parent.subscription_details.metadata` when the invoice arrives
334341
before the subscription.

‎modules/spacetime-stripe-ts/example/src/module_bindings/app/stripe/types.ts‎

Lines changed: 13 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎modules/spacetime-stripe-ts/scripts/test-stripe-smoke.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -769,6 +769,64 @@ async function main() {
769769
if (!recoveredPayment.includes('"succeeded"'))
770770
throw new Error(`payment regressed: ${recoveredPayment}`);
771771

772+
step('refunds sum onto the payment; late and failed refunds do not count');
773+
const refunded = async () => {
774+
const result = await run('spacetime', [
775+
'sql',
776+
'--server',
777+
opts.server,
778+
opts.database,
779+
"select amount_refunded from stripe_payment where stripe_payment_intent_id = 'pi_failure_test'",
780+
]);
781+
return result.stdout.trim().split('\n').at(-1)?.trim();
782+
};
783+
for (const [
784+
eventId,
785+
eventType,
786+
refundId,
787+
status,
788+
amount,
789+
offset,
790+
expected,
791+
] of [
792+
['evt_refund_ok', 'refund.updated', 're_smoke_1', 'succeeded', 30, 5, '30'],
793+
['evt_refund_late', 'refund.created', 're_smoke_1', 'pending', 30, 4, '30'],
794+
['evt_refund_2', 'refund.created', 're_smoke_2', 'pending', 20, 6, '50'],
795+
[
796+
'evt_refund_2_failed',
797+
'refund.failed',
798+
're_smoke_2',
799+
'failed',
800+
20,
801+
7,
802+
'30',
803+
],
804+
] as const) {
805+
await ingest(opts, {
806+
eventId,
807+
eventType,
808+
payload: {
809+
id: eventId,
810+
type: eventType,
811+
created: EVENT_CREATED + offset,
812+
data: {
813+
object: {
814+
id: refundId,
815+
amount,
816+
currency: 'usd',
817+
status,
818+
payment_intent: 'pi_failure_test',
819+
},
820+
},
821+
},
822+
});
823+
const actual = await refunded();
824+
if (actual !== expected)
825+
throw new Error(
826+
`${eventId}: amount_refunded ${actual}, expected ${expected}`
827+
);
828+
}
829+
772830
step('setup checkout stores setup state without a payment');
773831
await ingest(opts, {
774832
eventId: 'evt_setup',

‎modules/spacetime-stripe-ts/scripts/type-alignment.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,11 @@ type _StripeEvents = Assert<
2525
| Stripe.InvoicePaymentSucceededEvent
2626
| Stripe.InvoicePaymentFailedEvent
2727
| Stripe.InvoicePaymentPaidEvent
28-
| Stripe.PaymentIntentSucceededEvent,
28+
| Stripe.PaymentIntentSucceededEvent
29+
| Stripe.RefundCreatedEvent
30+
| Stripe.RefundUpdatedEvent
31+
| Stripe.RefundFailedEvent
32+
| Stripe.ChargeRefundUpdatedEvent,
2933
ParsedStripeEvent
3034
>
3135
>;

‎modules/spacetime-stripe-ts/src/submodule/event-order.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,14 @@ export function invoiceStatusRank(status: string): number {
3535
}
3636
}
3737

38+
// Refunds move from `pending` or `requires_action` to `succeeded`, and can
39+
// still fail or be canceled after that.
40+
export function refundStatusRank(status: string): number {
41+
if (status === 'pending' || status === 'requires_action') return 0;
42+
if (status === 'succeeded') return 1;
43+
return 2;
44+
}
45+
3846
// Checkout `payment_status` moves from `unpaid` to `paid`,
3947
// `no_payment_required`, or `failed` (recorded for
4048
// `checkout.session.async_payment_failed`). A paid session never moves to

‎modules/spacetime-stripe-ts/src/submodule/operations.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
checkoutPaymentStatusRank,
2828
invoiceStatusRank,
2929
isStale,
30+
refundStatusRank,
3031
subscriptionStatusRank,
3132
} from './event-order.js';
3233
import { buildStripeHttpRequest } from './http.js';
@@ -319,6 +320,16 @@ export function upsertCheckoutSession(
319320
ctx.db.stripeCheckoutSession.stripeCheckoutSessionId.update(row);
320321
}
321322

323+
function refundedAmount(ctx: WriteCtx, stripePaymentIntentId: string): bigint {
324+
let total = 0n;
325+
for (const refund of ctx.db.stripeRefund.byPaymentIntent.filter(
326+
stripePaymentIntentId
327+
))
328+
if (refund.status !== 'failed' && refund.status !== 'canceled')
329+
total += refund.amount;
330+
return total;
331+
}
332+
322333
export function upsertPayment(
323334
ctx: WriteCtx,
324335
now: ModuleTimestamp,
@@ -343,6 +354,7 @@ export function upsertPayment(
343354
stripeCustomerId: args.stripeCustomerId ?? existing?.stripeCustomerId,
344355
stripeInvoiceId: args.stripeInvoiceId ?? existing?.stripeInvoiceId,
345356
amount: args.amount,
357+
amountRefunded: refundedAmount(ctx, args.stripePaymentIntentId),
346358
currency: args.currency,
347359
status: args.status,
348360
createdUnix: args.createdUnix,
@@ -809,6 +821,52 @@ function dispatchEvent(
809821
});
810822
return WebhookEventStatus.Processed;
811823
}
824+
case 'refund.created':
825+
case 'refund.updated':
826+
case 'refund.failed':
827+
case 'charge.refund.updated': {
828+
const obj = event.data.object;
829+
const paymentIntentId =
830+
obj.payment_intent === undefined
831+
? null
832+
: extractExpandableIdOrNull(obj.payment_intent);
833+
if (paymentIntentId === null) return WebhookEventStatus.Ignored;
834+
const status =
835+
event.type === 'refund.failed' ? 'failed' : (obj.status ?? 'pending');
836+
const existing = ctx.db.stripeRefund.stripeRefundId.find(obj.id);
837+
if (
838+
existing &&
839+
isStale(
840+
{
841+
createdUnix: existing.eventCreatedUnix,
842+
rank: refundStatusRank(existing.status),
843+
},
844+
{ createdUnix: eventCreatedUnix, rank: refundStatusRank(status) }
845+
)
846+
)
847+
return WebhookEventStatus.Ignored;
848+
const row = {
849+
stripeRefundId: obj.id,
850+
stripePaymentIntentId: paymentIntentId,
851+
amount: BigInt(obj.amount),
852+
currency: obj.currency,
853+
status,
854+
eventCreatedUnix,
855+
insertedAt: existing?.insertedAt ?? ctx.timestamp,
856+
updatedAt: ctx.timestamp,
857+
};
858+
if (existing) ctx.db.stripeRefund.stripeRefundId.update(row);
859+
else ctx.db.stripeRefund.insert(row);
860+
const payment =
861+
ctx.db.stripePayment.stripePaymentIntentId.find(paymentIntentId);
862+
if (payment)
863+
ctx.db.stripePayment.stripePaymentIntentId.update({
864+
...payment,
865+
amountRefunded: refundedAmount(ctx, paymentIntentId),
866+
updatedAt: ctx.timestamp,
867+
});
868+
return WebhookEventStatus.Processed;
869+
}
812870
default:
813871
return assertExhaustive(event);
814872
}

‎modules/spacetime-stripe-ts/src/submodule/schema.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ export const stripePaymentRow = {
9292
stripeCustomerId: t.option(t.string()),
9393
stripeInvoiceId: t.option(t.string()),
9494
amount: t.i64(),
95+
amountRefunded: t.i64(),
9596
currency: t.string(),
9697
status: t.string(),
9798
createdUnix: t.i64(),
@@ -102,6 +103,17 @@ export const stripePaymentRow = {
102103
updatedAt: t.timestamp(),
103104
};
104105

106+
export const stripeRefundRow = {
107+
stripeRefundId: t.string().primaryKey(),
108+
stripePaymentIntentId: t.string(),
109+
amount: t.i64(),
110+
currency: t.string(),
111+
status: t.string(),
112+
eventCreatedUnix: t.i64(),
113+
insertedAt: t.timestamp(),
114+
updatedAt: t.timestamp(),
115+
};
116+
105117
export const stripeInvoiceRow = {
106118
stripeInvoiceId: t.string().primaryKey(),
107119
stripeCustomerId: t.string(),
@@ -202,6 +214,20 @@ const stripePaymentOptions = {
202214
export const stripePaymentTable: ReturnType<
203215
typeof table<typeof stripePaymentRow, typeof stripePaymentOptions>
204216
> = table(stripePaymentOptions, stripePaymentRow);
217+
const stripeRefundOptions = {
218+
name: 'stripe_refund',
219+
public: false,
220+
indexes: [
221+
{
222+
accessor: 'byPaymentIntent',
223+
algorithm: 'btree',
224+
columns: ['stripePaymentIntentId'],
225+
} as const,
226+
],
227+
};
228+
export const stripeRefundTable: ReturnType<
229+
typeof table<typeof stripeRefundRow, typeof stripeRefundOptions>
230+
> = table(stripeRefundOptions, stripeRefundRow);
205231
const stripeInvoiceOptions = {
206232
name: 'stripe_invoice',
207233
public: false,
@@ -292,6 +318,7 @@ const tables: {
292318
stripeSubscription: typeof stripeSubscriptionTable;
293319
stripeCheckoutSession: typeof stripeCheckoutSessionTable;
294320
stripePayment: typeof stripePaymentTable;
321+
stripeRefund: typeof stripeRefundTable;
295322
stripeInvoice: typeof stripeInvoiceTable;
296323
stripeWebhookEvent: typeof stripeWebhookEventTable;
297324
stripeWebhookPruneTick: typeof stripeWebhookPruneTickTable;
@@ -302,6 +329,7 @@ const tables: {
302329
stripeSubscription: stripeSubscriptionTable,
303330
stripeCheckoutSession: stripeCheckoutSessionTable,
304331
stripePayment: stripePaymentTable,
332+
stripeRefund: stripeRefundTable,
305333
stripeInvoice: stripeInvoiceTable,
306334
stripeWebhookEvent: stripeWebhookEventTable,
307335
stripeWebhookPruneTick: stripeWebhookPruneTickTable,
@@ -444,6 +472,14 @@ const vInvoicePaymentObject = v.object({
444472
payment: v.object({ payment_intent: v.optional(vExpandableId) }),
445473
});
446474

475+
const vRefundObject = v.object({
476+
id: v.string(),
477+
amount: v.number(),
478+
currency: v.string(),
479+
status: v.union([v.string(), v.null()]),
480+
payment_intent: v.optional(vExpandableIdOrNull),
481+
});
482+
447483
function vEvent<const T extends string, const O extends v.GenericSchema>(
448484
type: T,
449485
object: O
@@ -475,6 +511,10 @@ export const vStripeEvent = v.variant('type', [
475511
vEvent('invoice_payment.paid', vInvoicePaymentObject),
476512
vEvent('payment_intent.succeeded', vPaymentIntentObject),
477513
vEvent('payment_intent.payment_failed', vPaymentIntentObject),
514+
vEvent('refund.created', vRefundObject),
515+
vEvent('refund.updated', vRefundObject),
516+
vEvent('refund.failed', vRefundObject),
517+
vEvent('charge.refund.updated', vRefundObject),
478518
]);
479519

480520
export type ParsedStripeEvent = v.InferOutput<typeof vStripeEvent>;

0 commit comments

Comments
 (0)