Skip to content

Commit 2c2abac

Browse files
cheddarfoxclaude
andcommitted
feat(billing): wire Stripe checkout webhook to credit ledger [REN-79]
Replace the TODO stub in the checkout.session.completed handler with actual credit allocation via the ledger service. The webhook now extracts user UUID from client_reference_id and SKU from session metadata, then calls allocate_credits() with the checkout session ID as the idempotency key so Stripe retries are safe. Also registers the Stripe webhook router in the API v1 router and adds six test cases covering happy path, idempotency, unknown SKU, missing metadata, missing signature, and invalid signature. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent d5d21fd commit 2c2abac

3 files changed

Lines changed: 349 additions & 7 deletions

File tree

‎core/api/v1/router.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
from core.api.v1.auth import router as auth_router
2424
from core.api.v1.health import router as health_router
25+
from core.billing.stripe.stripe_webhook import router as stripe_webhook_router
2526

2627
api_v1_router = APIRouter(prefix="/api/v1")
2728

@@ -30,3 +31,6 @@
3031

3132
# Authentication
3233
api_v1_router.include_router(auth_router, tags=["auth"])
34+
35+
# Billing webhooks
36+
api_v1_router.include_router(stripe_webhook_router, tags=["billing"])

‎core/billing/stripe/stripe_webhook.py‎

Lines changed: 75 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,21 @@
3838

3939
from __future__ import annotations
4040

41+
from decimal import Decimal
42+
from typing import TYPE_CHECKING
43+
from uuid import UUID
44+
4145
import stripe
4246
import structlog
43-
from fastapi import APIRouter, HTTPException, Request, status
47+
from fastapi import APIRouter, Depends, HTTPException, Request, status
4448

4549
from core.config import get_settings
50+
from core.database import get_db_session
51+
from core.ledger.service import allocate_credits
52+
from core.models.base import TransactionSource
53+
54+
if TYPE_CHECKING:
55+
from sqlalchemy.ext.asyncio import AsyncSession
4656

4757
logger = structlog.get_logger(__name__)
4858

@@ -54,7 +64,10 @@
5464

5565

5666
@router.post("/webhooks/stripe")
57-
async def stripe_hook(req: Request) -> dict[str, object]:
67+
async def stripe_hook(
68+
req: Request,
69+
session: AsyncSession = Depends(get_db_session),
70+
) -> dict[str, object]:
5871
"""Handle incoming Stripe webhook events.
5972
6073
Verifies the webhook signature using the endpoint secret,
@@ -63,6 +76,10 @@ async def stripe_hook(req: Request) -> dict[str, object]:
6376
retries for successfully received (but possibly unhandled)
6477
event types.
6578
79+
Credit allocation for ``checkout.session.completed`` events is
80+
idempotent -- Stripe retries are safe because the ledger service
81+
uses the checkout session ID as a deduplication key.
82+
6683
Returns:
6784
dict: ``{"received": True}`` on successful processing.
6885
@@ -112,10 +129,61 @@ async def stripe_hook(req: Request) -> dict[str, object]:
112129

113130
# -- 4. Route to event-specific handlers --
114131
if event["type"] == "checkout.session.completed":
115-
logger.info("stripe_checkout_completed", event_id=event["id"])
116-
# TODO(REN-79): Implement credit allocation via event handler.
117-
# The previous implementation used `from ledger.credit import credit`
118-
# which no longer exists. Credit allocation with idempotency
119-
# checks will be implemented in REN-79.
132+
await _handle_checkout_completed(event, session)
120133

121134
return {"received": True}
135+
136+
137+
async def _handle_checkout_completed(
138+
event: dict[str, object],
139+
session: AsyncSession,
140+
) -> None:
141+
"""Allocate credits after a successful Stripe checkout session.
142+
143+
Extracts the user UUID from ``client_reference_id`` and the credit
144+
SKU from session metadata, then delegates to the ledger service.
145+
Unknown or missing SKUs are logged as warnings but do NOT cause
146+
the webhook to fail (Stripe would retry indefinitely).
147+
"""
148+
sess_obj: dict[str, object] = event["data"]["object"] # type: ignore[index]
149+
checkout_session_id: str = sess_obj.get("id", "") # type: ignore[assignment]
150+
151+
# Extract user ID from Stripe's client_reference_id field.
152+
client_reference_id = sess_obj.get("client_reference_id")
153+
if not client_reference_id:
154+
logger.warning(
155+
"stripe_checkout_missing_client_reference_id",
156+
event_id=event["id"],
157+
)
158+
return
159+
160+
# Determine the credit SKU from session metadata.
161+
metadata: dict[str, str] = sess_obj.get("metadata") or {} # type: ignore[assignment]
162+
sku = metadata.get("sku")
163+
if not sku or sku not in CREDIT_MAP:
164+
logger.warning(
165+
"stripe_checkout_unknown_sku",
166+
event_id=event["id"],
167+
sku=sku,
168+
)
169+
return
170+
171+
credit_amount = CREDIT_MAP[sku]
172+
173+
logger.info(
174+
"stripe_checkout_completed",
175+
event_id=event["id"],
176+
sku=sku,
177+
credit_amount=credit_amount,
178+
user_id=client_reference_id,
179+
)
180+
181+
await allocate_credits(
182+
session=session,
183+
user_id=UUID(str(client_reference_id)),
184+
amount=Decimal(credit_amount),
185+
source=TransactionSource.STRIPE,
186+
reference_id=str(checkout_session_id),
187+
description=f"Stripe checkout: {sku}",
188+
)
189+
await session.commit()

‎tests/test_stripe_webhook.py‎

Lines changed: 270 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,270 @@
1+
# Copyright 2025 ByBren, LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Tests for the Stripe webhook handler (REN-79).
16+
17+
Verifies credit allocation wiring between the Stripe checkout.session.completed
18+
event and the credit ledger service. All tests mock
19+
``stripe.Webhook.construct_event`` since real Stripe signatures cannot be
20+
generated in tests.
21+
"""
22+
23+
from __future__ import annotations
24+
25+
from decimal import Decimal
26+
from typing import TYPE_CHECKING
27+
from unittest.mock import patch
28+
29+
import pytest
30+
import stripe
31+
32+
from core.models.base import CreditLedgerEntry, TransactionDirection, TransactionSource
33+
34+
if TYPE_CHECKING:
35+
from httpx import AsyncClient
36+
from sqlalchemy.ext.asyncio import AsyncSession
37+
38+
from core.models.base import User
39+
40+
WEBHOOK_URL = "/api/v1/webhooks/stripe"
41+
42+
43+
def _checkout_event(
44+
*,
45+
event_id: str = "evt_test_123",
46+
session_id: str = "cs_test_abc",
47+
client_reference_id: str | None = "00000000-0000-0000-0000-000000000001",
48+
sku: str | None = "cred10",
49+
) -> dict:
50+
"""Build a minimal checkout.session.completed event payload."""
51+
metadata = {}
52+
if sku is not None:
53+
metadata["sku"] = sku
54+
55+
session_obj: dict = {
56+
"id": session_id,
57+
"client_reference_id": client_reference_id,
58+
"metadata": metadata,
59+
}
60+
61+
return {
62+
"id": event_id,
63+
"type": "checkout.session.completed",
64+
"data": {"object": session_obj},
65+
}
66+
67+
68+
# ---------------------------------------------------------------------------
69+
# Happy path: credit allocation
70+
# ---------------------------------------------------------------------------
71+
72+
73+
@pytest.mark.asyncio
74+
async def test_checkout_completed_allocates_credits(
75+
client: AsyncClient,
76+
test_user: User,
77+
db_session: AsyncSession,
78+
) -> None:
79+
"""A valid checkout.session.completed event allocates credits."""
80+
event = _checkout_event(
81+
client_reference_id=str(test_user.id),
82+
sku="cred10",
83+
session_id="cs_alloc_001",
84+
)
85+
86+
with patch("stripe.Webhook.construct_event", return_value=event):
87+
response = await client.post(
88+
WEBHOOK_URL,
89+
content=b"{}",
90+
headers={"stripe-signature": "t=1,v1=sig"},
91+
)
92+
93+
assert response.status_code == 200
94+
assert response.json() == {"received": True}
95+
96+
# Verify a ledger entry was created with the correct values.
97+
from sqlalchemy import select
98+
99+
result = await db_session.execute(
100+
select(CreditLedgerEntry).where(
101+
CreditLedgerEntry.reference_id == "cs_alloc_001",
102+
)
103+
)
104+
entry = result.scalar_one_or_none()
105+
assert entry is not None
106+
assert entry.user_id == test_user.id
107+
assert entry.amount == Decimal("100")
108+
assert entry.direction == TransactionDirection.CREDIT
109+
assert entry.source == TransactionSource.STRIPE
110+
assert entry.description == "Stripe checkout: cred10"
111+
112+
113+
# ---------------------------------------------------------------------------
114+
# Idempotency: same event twice
115+
# ---------------------------------------------------------------------------
116+
117+
118+
@pytest.mark.asyncio
119+
async def test_checkout_completed_idempotent(
120+
client: AsyncClient,
121+
test_user: User,
122+
db_session: AsyncSession,
123+
) -> None:
124+
"""Replaying the same event does not create a duplicate ledger entry."""
125+
event = _checkout_event(
126+
client_reference_id=str(test_user.id),
127+
sku="cred10",
128+
session_id="cs_idemp_001",
129+
)
130+
131+
with patch("stripe.Webhook.construct_event", return_value=event):
132+
r1 = await client.post(
133+
WEBHOOK_URL,
134+
content=b"{}",
135+
headers={"stripe-signature": "t=1,v1=sig"},
136+
)
137+
r2 = await client.post(
138+
WEBHOOK_URL,
139+
content=b"{}",
140+
headers={"stripe-signature": "t=1,v1=sig"},
141+
)
142+
143+
assert r1.status_code == 200
144+
assert r2.status_code == 200
145+
146+
# Only one ledger entry should exist for this reference_id.
147+
from sqlalchemy import func, select
148+
149+
result = await db_session.execute(
150+
select(func.count()).where(
151+
CreditLedgerEntry.reference_id == "cs_idemp_001",
152+
)
153+
)
154+
assert result.scalar_one() == 1
155+
156+
157+
# ---------------------------------------------------------------------------
158+
# Unknown SKU
159+
# ---------------------------------------------------------------------------
160+
161+
162+
@pytest.mark.asyncio
163+
async def test_checkout_completed_unknown_sku(
164+
client: AsyncClient,
165+
test_user: User,
166+
db_session: AsyncSession,
167+
) -> None:
168+
"""An unknown SKU logs a warning but still returns received: True."""
169+
event = _checkout_event(
170+
client_reference_id=str(test_user.id),
171+
sku="cred_unknown",
172+
session_id="cs_unknown_001",
173+
)
174+
175+
with patch("stripe.Webhook.construct_event", return_value=event):
176+
response = await client.post(
177+
WEBHOOK_URL,
178+
content=b"{}",
179+
headers={"stripe-signature": "t=1,v1=sig"},
180+
)
181+
182+
assert response.status_code == 200
183+
assert response.json() == {"received": True}
184+
185+
# No ledger entry should have been created.
186+
from sqlalchemy import func, select
187+
188+
result = await db_session.execute(
189+
select(func.count()).where(
190+
CreditLedgerEntry.reference_id == "cs_unknown_001",
191+
)
192+
)
193+
assert result.scalar_one() == 0
194+
195+
196+
# ---------------------------------------------------------------------------
197+
# Missing metadata / SKU
198+
# ---------------------------------------------------------------------------
199+
200+
201+
@pytest.mark.asyncio
202+
async def test_checkout_completed_missing_metadata(
203+
client: AsyncClient,
204+
test_user: User,
205+
db_session: AsyncSession,
206+
) -> None:
207+
"""Missing metadata/sku logs a warning but still returns received: True."""
208+
event = _checkout_event(
209+
client_reference_id=str(test_user.id),
210+
sku=None,
211+
session_id="cs_nometa_001",
212+
)
213+
214+
with patch("stripe.Webhook.construct_event", return_value=event):
215+
response = await client.post(
216+
WEBHOOK_URL,
217+
content=b"{}",
218+
headers={"stripe-signature": "t=1,v1=sig"},
219+
)
220+
221+
assert response.status_code == 200
222+
assert response.json() == {"received": True}
223+
224+
# No ledger entry should have been created.
225+
from sqlalchemy import func, select
226+
227+
result = await db_session.execute(
228+
select(func.count()).where(
229+
CreditLedgerEntry.reference_id == "cs_nometa_001",
230+
)
231+
)
232+
assert result.scalar_one() == 0
233+
234+
235+
# ---------------------------------------------------------------------------
236+
# Missing stripe-signature header
237+
# ---------------------------------------------------------------------------
238+
239+
240+
@pytest.mark.asyncio
241+
async def test_missing_signature_returns_400(client: AsyncClient) -> None:
242+
"""A request without a stripe-signature header is rejected with 400."""
243+
response = await client.post(
244+
WEBHOOK_URL,
245+
content=b"{}",
246+
)
247+
assert response.status_code == 400
248+
assert "Missing stripe-signature" in response.json()["detail"]
249+
250+
251+
# ---------------------------------------------------------------------------
252+
# Invalid signature
253+
# ---------------------------------------------------------------------------
254+
255+
256+
@pytest.mark.asyncio
257+
async def test_invalid_signature_returns_400(client: AsyncClient) -> None:
258+
"""An invalid Stripe signature is rejected with 400."""
259+
with patch(
260+
"stripe.Webhook.construct_event",
261+
side_effect=stripe.error.SignatureVerificationError("bad sig", "sig_header"),
262+
):
263+
response = await client.post(
264+
WEBHOOK_URL,
265+
content=b"{}",
266+
headers={"stripe-signature": "t=1,v1=badsig"},
267+
)
268+
269+
assert response.status_code == 400
270+
assert "Invalid signature" in response.json()["detail"]

0 commit comments

Comments
 (0)