ai-lls-lib 1.1.0__py3-none-any.whl → 1.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,486 @@
1
+ """Stripe API management with metadata conventions."""
2
+
3
+ import os
4
+ from typing import List, Optional, Dict, Any
5
+ import logging
6
+
7
+ try:
8
+ import stripe
9
+ except ImportError:
10
+ stripe = None # Handle gracefully for testing
11
+
12
+ from .models import Plan
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class StripeManager:
18
+ """
19
+ Manages Stripe resources with metadata conventions.
20
+ Uses metadata to discover and filter products/prices.
21
+ """
22
+
23
+ METADATA_SCHEMA = {
24
+ "product_type": "landline_scrubber",
25
+ "environment": None, # Set at runtime
26
+ "tier": None,
27
+ "credits": None,
28
+ "active": "true"
29
+ }
30
+
31
+ def __init__(self, api_key: Optional[str] = None, environment: Optional[str] = None):
32
+ """Initialize with Stripe API key and environment."""
33
+ if not stripe:
34
+ raise ImportError("stripe package not installed. Run: pip install stripe")
35
+
36
+ self.api_key = api_key or os.environ.get("STRIPE_SECRET_KEY")
37
+ if not self.api_key:
38
+ raise ValueError("Stripe API key not provided and STRIPE_SECRET_KEY not set")
39
+
40
+ stripe.api_key = self.api_key
41
+ self.environment = environment or os.environ.get("ENVIRONMENT", "staging")
42
+
43
+ def list_plans(self) -> List[Plan]:
44
+ """
45
+ Fetch active plans from Stripe using metadata.
46
+ Returns list of Plan objects sorted by price.
47
+ """
48
+ try:
49
+ # Fetch all active prices with expanded product data
50
+ prices = stripe.Price.list(
51
+ active=True,
52
+ expand=["data.product"],
53
+ limit=100
54
+ )
55
+
56
+ plans = []
57
+ for price in prices.data:
58
+ metadata = price.metadata or {}
59
+
60
+ # Filter by our metadata conventions
61
+ if (metadata.get("product_type") == "landline_scrubber" and
62
+ metadata.get("environment") == self.environment and
63
+ metadata.get("active") == "true"):
64
+
65
+ # Convert to Plan object
66
+ plan = Plan.from_stripe_price(price, price.product)
67
+ plans.append(plan)
68
+
69
+ # Sort by price amount
70
+ plans.sort(key=lambda p: p.plan_amount)
71
+
72
+ logger.info(f"Found {len(plans)} active plans for environment {self.environment}")
73
+ return plans
74
+
75
+ except stripe.error.StripeError as e:
76
+ logger.error(f"Stripe error listing plans: {e}")
77
+ # Return mock data for development/testing
78
+ return self._get_mock_plans()
79
+
80
+ def create_setup_intent(self, user_id: str) -> Dict[str, str]:
81
+ """
82
+ Create a SetupIntent for secure payment method collection.
83
+ Frontend will confirm this with Stripe Elements.
84
+ """
85
+ try:
86
+ # Get or create customer
87
+ customer = self._get_or_create_customer(user_id)
88
+
89
+ # Create SetupIntent
90
+ setup_intent = stripe.SetupIntent.create(
91
+ customer=customer.id,
92
+ metadata={
93
+ "user_id": user_id,
94
+ "environment": self.environment
95
+ }
96
+ )
97
+
98
+ return {
99
+ "client_secret": setup_intent.client_secret,
100
+ "setup_intent_id": setup_intent.id
101
+ }
102
+
103
+ except stripe.error.StripeError as e:
104
+ logger.error(f"Stripe error creating setup intent: {e}")
105
+ raise
106
+
107
+ def attach_payment_method(self, user_id: str, payment_method_id: str, billing_details: Dict[str, Any]) -> Dict[str, Any]:
108
+ """
109
+ Attach a payment method to customer (legacy path).
110
+ Returns whether this is the first card.
111
+ """
112
+ try:
113
+ # Get or create customer
114
+ customer = self._get_or_create_customer(user_id)
115
+
116
+ # Attach payment method to customer
117
+ payment_method = stripe.PaymentMethod.attach(
118
+ payment_method_id,
119
+ customer=customer.id
120
+ )
121
+
122
+ # Update billing details if provided
123
+ if billing_details:
124
+ stripe.PaymentMethod.modify(
125
+ payment_method_id,
126
+ billing_details=billing_details
127
+ )
128
+
129
+ # Check if this is the first payment method
130
+ payment_methods = stripe.PaymentMethod.list(
131
+ customer=customer.id,
132
+ type="card"
133
+ )
134
+
135
+ first_card = len(payment_methods.data) == 1
136
+
137
+ # Set as default if first card
138
+ if first_card:
139
+ stripe.Customer.modify(
140
+ customer.id,
141
+ invoice_settings={"default_payment_method": payment_method_id}
142
+ )
143
+
144
+ return {
145
+ "payment_method_id": payment_method_id,
146
+ "first_card": first_card,
147
+ "customer_id": customer.id
148
+ }
149
+
150
+ except stripe.error.StripeError as e:
151
+ logger.error(f"Stripe error attaching payment method: {e}")
152
+ raise
153
+
154
+ def verify_payment_method(self, user_id: str, payment_method_id: str) -> Dict[str, Any]:
155
+ """
156
+ Perform $1 verification charge on new payment method.
157
+ """
158
+ try:
159
+ customer = self._get_or_create_customer(user_id)
160
+
161
+ # Create $1 verification charge
162
+ payment_intent = stripe.PaymentIntent.create(
163
+ amount=100, # $1.00 in cents
164
+ currency="usd",
165
+ customer=customer.id,
166
+ payment_method=payment_method_id,
167
+ off_session=True,
168
+ confirm=True,
169
+ description="Card verification - $1 charge",
170
+ metadata={
171
+ "user_id": user_id,
172
+ "type": "verification",
173
+ "environment": self.environment
174
+ }
175
+ )
176
+
177
+ return {
178
+ "status": payment_intent.status,
179
+ "payment_intent_id": payment_intent.id
180
+ }
181
+
182
+ except stripe.error.StripeError as e:
183
+ logger.error(f"Stripe error verifying payment method: {e}")
184
+ raise
185
+
186
+ def charge_prepaid(self, user_id: str, reference_code: str, amount: Optional[float] = None) -> Dict[str, Any]:
187
+ """
188
+ Charge saved payment method for credit purchase.
189
+ Supports both fixed-price and metadata-based variable-amount plans.
190
+ """
191
+ try:
192
+ customer = self._get_or_create_customer(user_id)
193
+
194
+ # Look up price from Stripe
195
+ prices = stripe.Price.list(active=True, limit=100, expand=["data.product"])
196
+ price = None
197
+
198
+ for p in prices.data:
199
+ metadata = p.metadata or {}
200
+ # Match by price ID or plan_reference in metadata
201
+ if (p.id == reference_code or
202
+ metadata.get("plan_reference") == reference_code or
203
+ (metadata.get("tier") == reference_code and
204
+ metadata.get("environment") == self.environment)):
205
+ price = p
206
+ break
207
+
208
+ if not price:
209
+ raise ValueError(f"Invalid plan reference: {reference_code}")
210
+
211
+ price_metadata = price.metadata or {}
212
+
213
+ # Check if this is a variable amount plan
214
+ if price_metadata.get("variable_amount") == "true":
215
+ # Variable amount plan - validate amount
216
+ if not amount:
217
+ raise ValueError("Amount required for variable-amount plan")
218
+
219
+ # Get validation rules from metadata
220
+ min_amount = float(price_metadata.get("min_amount", "5"))
221
+ if amount < min_amount:
222
+ raise ValueError(f"Amount ${amount} is below minimum ${min_amount}")
223
+
224
+ # Check against default amounts if specified
225
+ default_amounts_str = price_metadata.get("default_amounts", "")
226
+ if default_amounts_str:
227
+ allowed_amounts = [float(x.strip()) for x in default_amounts_str.split(",")]
228
+ # Allow default amounts OR any amount >= minimum
229
+ if amount not in allowed_amounts and amount < max(allowed_amounts):
230
+ logger.info(f"Amount ${amount} not in defaults {allowed_amounts}, but allowed as >= ${min_amount}")
231
+
232
+ # Calculate credits based on credits_per_dollar
233
+ credits_per_dollar = float(price_metadata.get("credits_per_dollar", "285"))
234
+ credits_to_add = int(amount * credits_per_dollar)
235
+ charge_amount = int(amount * 100) # Convert to cents
236
+
237
+ else:
238
+ # Fixed price plan
239
+ charge_amount = price.unit_amount
240
+ credits_str = price_metadata.get("credits", "0")
241
+ if credits_str.lower() == "unlimited":
242
+ credits_to_add = 0 # Subscription handles this differently
243
+ else:
244
+ credits_to_add = int(credits_str)
245
+
246
+ # Get default payment method
247
+ default_pm = customer.invoice_settings.get("default_payment_method")
248
+ if not default_pm:
249
+ # Try to get first payment method
250
+ payment_methods = stripe.PaymentMethod.list(
251
+ customer=customer.id,
252
+ type="card",
253
+ limit=1
254
+ )
255
+ if not payment_methods.data:
256
+ raise ValueError("No payment method on file")
257
+ default_pm = payment_methods.data[0].id
258
+
259
+ # Create payment intent
260
+ payment_intent = stripe.PaymentIntent.create(
261
+ amount=charge_amount,
262
+ currency="usd",
263
+ customer=customer.id,
264
+ payment_method=default_pm,
265
+ off_session=True,
266
+ confirm=True,
267
+ description=f"Credit purchase - {credits_to_add} credits",
268
+ metadata={
269
+ "user_id": user_id,
270
+ "credits": credits_to_add,
271
+ "reference_code": reference_code,
272
+ "environment": self.environment
273
+ }
274
+ )
275
+
276
+ return {
277
+ "id": payment_intent.id,
278
+ "status": payment_intent.status,
279
+ "credits_added": credits_to_add,
280
+ "amount_charged": charge_amount / 100 # Convert back to dollars
281
+ }
282
+
283
+ except stripe.error.StripeError as e:
284
+ logger.error(f"Stripe error processing payment: {e}")
285
+ raise
286
+
287
+ def customer_has_payment_method(self, stripe_customer_id: str) -> bool:
288
+ """
289
+ Check if customer has any saved payment methods.
290
+ """
291
+ try:
292
+ payment_methods = stripe.PaymentMethod.list(
293
+ customer=stripe_customer_id,
294
+ type="card",
295
+ limit=1
296
+ )
297
+ return len(payment_methods.data) > 0
298
+ except stripe.error.StripeError as e:
299
+ logger.error(f"Stripe error checking payment methods: {e}")
300
+ return False
301
+
302
+ def list_payment_methods(self, stripe_customer_id: str) -> Dict[str, Any]:
303
+ """
304
+ List all payment methods for a customer.
305
+ """
306
+ try:
307
+ # Get customer to find default payment method
308
+ customer = stripe.Customer.retrieve(stripe_customer_id)
309
+ default_pm_id = customer.invoice_settings.get("default_payment_method")
310
+
311
+ # List all payment methods
312
+ payment_methods = stripe.PaymentMethod.list(
313
+ customer=stripe_customer_id,
314
+ type="card"
315
+ )
316
+
317
+ items = []
318
+ for pm in payment_methods.data:
319
+ items.append({
320
+ "id": pm.id,
321
+ "brand": pm.card.brand,
322
+ "last4": pm.card.last4,
323
+ "exp_month": pm.card.exp_month,
324
+ "exp_year": pm.card.exp_year,
325
+ "is_default": pm.id == default_pm_id
326
+ })
327
+
328
+ return {
329
+ "items": items,
330
+ "default_payment_method_id": default_pm_id
331
+ }
332
+
333
+ except stripe.error.StripeError as e:
334
+ logger.error(f"Stripe error listing payment methods: {e}")
335
+ return {"items": [], "default_payment_method_id": None}
336
+
337
+ def _get_or_create_customer(self, user_id: str, email: Optional[str] = None) -> Any:
338
+ """
339
+ Get existing Stripe customer or create new one.
340
+ First checks by user_id in metadata, then by email if provided.
341
+ """
342
+ try:
343
+ # First try to find by user_id in metadata
344
+ customers = stripe.Customer.search(
345
+ query=f'metadata["user_id"]:"{user_id}"',
346
+ limit=1
347
+ )
348
+
349
+ if customers.data:
350
+ return customers.data[0]
351
+
352
+ # If email provided, try to find by email
353
+ if email:
354
+ customers = stripe.Customer.list(email=email, limit=1)
355
+ if customers.data:
356
+ # Update metadata with user_id
357
+ customer = customers.data[0]
358
+ stripe.Customer.modify(
359
+ customer.id,
360
+ metadata={"user_id": user_id}
361
+ )
362
+ return customer
363
+
364
+ # Create new customer
365
+ return stripe.Customer.create(
366
+ email=email,
367
+ metadata={
368
+ "user_id": user_id,
369
+ "environment": self.environment
370
+ }
371
+ )
372
+
373
+ except stripe.error.StripeError as e:
374
+ logger.error(f"Stripe error getting/creating customer: {e}")
375
+ raise
376
+
377
+ def create_subscription(self, user_id: str, email: str, price_id: str) -> Dict[str, Any]:
378
+ """Create a subscription for unlimited access."""
379
+ try:
380
+ # Create or retrieve customer
381
+ customers = stripe.Customer.list(email=email, limit=1)
382
+ if customers.data:
383
+ customer = customers.data[0]
384
+ else:
385
+ customer = stripe.Customer.create(
386
+ email=email,
387
+ metadata={"user_id": user_id}
388
+ )
389
+
390
+ # Create subscription
391
+ subscription = stripe.Subscription.create(
392
+ customer=customer.id,
393
+ items=[{"price": price_id}],
394
+ metadata={
395
+ "user_id": user_id,
396
+ "environment": self.environment
397
+ }
398
+ )
399
+
400
+ return {
401
+ "subscription_id": subscription.id,
402
+ "status": subscription.status,
403
+ "customer_id": customer.id
404
+ }
405
+
406
+ except stripe.error.StripeError as e:
407
+ logger.error(f"Stripe error creating subscription: {e}")
408
+ raise
409
+
410
+ def pause_subscription(self, subscription_id: str) -> Dict[str, str]:
411
+ """Pause a subscription."""
412
+ try:
413
+ subscription = stripe.Subscription.modify(
414
+ subscription_id,
415
+ pause_collection={"behavior": "mark_uncollectible"}
416
+ )
417
+ return {"message": "Subscription paused", "status": "paused"}
418
+ except stripe.error.StripeError as e:
419
+ logger.error(f"Stripe error pausing subscription: {e}")
420
+ raise
421
+
422
+ def resume_subscription(self, subscription_id: str) -> Dict[str, str]:
423
+ """Resume a paused subscription."""
424
+ try:
425
+ subscription = stripe.Subscription.modify(
426
+ subscription_id,
427
+ pause_collection="" # Remove pause
428
+ )
429
+ return {"message": "Subscription resumed", "status": "active"}
430
+ except stripe.error.StripeError as e:
431
+ logger.error(f"Stripe error resuming subscription: {e}")
432
+ raise
433
+
434
+ def cancel_subscription(self, subscription_id: str) -> Dict[str, str]:
435
+ """Cancel a subscription."""
436
+ try:
437
+ subscription = stripe.Subscription.delete(subscription_id)
438
+ return {"message": "Subscription cancelled", "status": "cancelled"}
439
+ except stripe.error.StripeError as e:
440
+ logger.error(f"Stripe error cancelling subscription: {e}")
441
+ raise
442
+
443
+ def _get_mock_plans(self) -> List[Plan]:
444
+ """Return mock plans for development/testing."""
445
+ return [
446
+ Plan(
447
+ plan_reference="79541679412215",
448
+ plan_type="prepaid",
449
+ plan_name="STANDARD",
450
+ plan_subtitle="One-time purchase",
451
+ plan_amount=10.0,
452
+ plan_credits=5000,
453
+ plan_credits_text="5,000 credits",
454
+ percent_off=""
455
+ ),
456
+ Plan(
457
+ plan_reference="79541679412216",
458
+ plan_type="prepaid",
459
+ plan_name="POWER",
460
+ plan_subtitle="Best value",
461
+ plan_amount=50.0,
462
+ plan_credits=28500,
463
+ plan_credits_text="28,500 credits",
464
+ percent_off="12.5% OFF"
465
+ ),
466
+ Plan(
467
+ plan_reference="79541679412217",
468
+ plan_type="prepaid",
469
+ plan_name="ELITE",
470
+ plan_subtitle="Maximum savings",
471
+ plan_amount=100.0,
472
+ plan_credits=66666,
473
+ plan_credits_text="66,666 credits",
474
+ percent_off="25% OFF"
475
+ ),
476
+ Plan(
477
+ plan_reference="price_unlimited",
478
+ plan_type="postpaid",
479
+ plan_name="UNLIMITED",
480
+ plan_subtitle="Monthly subscription",
481
+ plan_amount=299.0,
482
+ plan_credits=None,
483
+ plan_credits_text="Unlimited",
484
+ percent_off=""
485
+ )
486
+ ]
@@ -0,0 +1,215 @@
1
+ """Stripe webhook event processing."""
2
+
3
+ import json
4
+ import logging
5
+ from typing import Dict, Any
6
+
7
+ try:
8
+ import stripe
9
+ except ImportError:
10
+ stripe = None
11
+
12
+ from .credit_manager import CreditManager
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class WebhookProcessor:
18
+ """Process Stripe webhook events."""
19
+
20
+ def __init__(self, webhook_secret: str, credit_manager: CreditManager):
21
+ """Initialize with webhook secret and credit manager."""
22
+ self.webhook_secret = webhook_secret
23
+ self.credit_manager = credit_manager
24
+
25
+ def verify_and_parse(self, payload: str, signature: str) -> Dict[str, Any]:
26
+ """Verify webhook signature and parse event."""
27
+ if not stripe:
28
+ raise ImportError("stripe package not installed")
29
+
30
+ try:
31
+ event = stripe.Webhook.construct_event(
32
+ payload, signature, self.webhook_secret
33
+ )
34
+ return event
35
+ except ValueError as e:
36
+ logger.error(f"Invalid webhook payload: {e}")
37
+ raise
38
+ except stripe.error.SignatureVerificationError as e:
39
+ logger.error(f"Invalid webhook signature: {e}")
40
+ raise
41
+
42
+ def process_event(self, event: Dict[str, Any]) -> Dict[str, Any]:
43
+ """
44
+ Process a verified webhook event.
45
+ Returns response data.
46
+ """
47
+ event_type = event.get("type")
48
+ event_data = event.get("data", {}).get("object", {})
49
+
50
+ logger.info(f"Processing webhook event: {event_type}")
51
+
52
+ if event_type == "payment_intent.succeeded":
53
+ return self._handle_payment_intent_succeeded(event_data)
54
+
55
+ elif event_type == "checkout.session.completed":
56
+ return self._handle_checkout_completed(event_data)
57
+
58
+ elif event_type == "customer.subscription.created":
59
+ return self._handle_subscription_created(event_data)
60
+
61
+ elif event_type == "customer.subscription.updated":
62
+ return self._handle_subscription_updated(event_data)
63
+
64
+ elif event_type == "customer.subscription.deleted":
65
+ return self._handle_subscription_deleted(event_data)
66
+
67
+ elif event_type == "invoice.payment_succeeded":
68
+ return self._handle_invoice_paid(event_data)
69
+
70
+ elif event_type == "invoice.payment_failed":
71
+ return self._handle_invoice_failed(event_data)
72
+
73
+ elif event_type == "charge.dispute.created":
74
+ return self._handle_dispute_created(event_data)
75
+
76
+ else:
77
+ logger.info(f"Unhandled event type: {event_type}")
78
+ return {"message": f"Event {event_type} received but not processed"}
79
+
80
+ def _handle_checkout_completed(self, session: Dict[str, Any]) -> Dict[str, Any]:
81
+ """Handle successful checkout session for credit purchase."""
82
+ metadata = session.get("metadata", {})
83
+ user_id = metadata.get("user_id")
84
+
85
+ if not user_id:
86
+ logger.error("No user_id in checkout session metadata")
87
+ return {"error": "Missing user_id"}
88
+
89
+ # Get line items to determine credits purchased
90
+ if session.get("mode") == "payment":
91
+ # One-time payment for credits
92
+ # In production, fetch line items from Stripe to get price metadata
93
+ # For now, extract from session metadata if available
94
+ credits = int(metadata.get("credits", 0))
95
+
96
+ if credits > 0:
97
+ new_balance = self.credit_manager.add_credits(user_id, credits)
98
+ logger.info(f"Added {credits} credits to user {user_id}, new balance: {new_balance}")
99
+ return {"credits_added": credits, "new_balance": new_balance}
100
+
101
+ return {"message": "Checkout processed"}
102
+
103
+ def _handle_subscription_created(self, subscription: Dict[str, Any]) -> Dict[str, Any]:
104
+ """Handle new subscription creation."""
105
+ metadata = subscription.get("metadata", {})
106
+ user_id = metadata.get("user_id")
107
+ customer_id = subscription.get("customer")
108
+ subscription_id = subscription.get("id")
109
+ status = subscription.get("status")
110
+
111
+ if user_id:
112
+ self.credit_manager.set_subscription_state(
113
+ user_id=user_id,
114
+ status=status,
115
+ stripe_customer_id=customer_id,
116
+ stripe_subscription_id=subscription_id
117
+ )
118
+ logger.info(f"Created subscription {subscription_id} for user {user_id}")
119
+
120
+ return {"subscription_id": subscription_id, "status": status}
121
+
122
+ def _handle_subscription_updated(self, subscription: Dict[str, Any]) -> Dict[str, Any]:
123
+ """Handle subscription updates (pause/resume/etc)."""
124
+ metadata = subscription.get("metadata", {})
125
+ user_id = metadata.get("user_id")
126
+ subscription_id = subscription.get("id")
127
+ status = subscription.get("status")
128
+
129
+ if user_id:
130
+ self.credit_manager.set_subscription_state(
131
+ user_id=user_id,
132
+ status=status,
133
+ stripe_subscription_id=subscription_id
134
+ )
135
+ logger.info(f"Updated subscription {subscription_id} status to {status}")
136
+
137
+ return {"subscription_id": subscription_id, "status": status}
138
+
139
+ def _handle_subscription_deleted(self, subscription: Dict[str, Any]) -> Dict[str, Any]:
140
+ """Handle subscription cancellation."""
141
+ metadata = subscription.get("metadata", {})
142
+ user_id = metadata.get("user_id")
143
+ subscription_id = subscription.get("id")
144
+
145
+ if user_id:
146
+ self.credit_manager.set_subscription_state(
147
+ user_id=user_id,
148
+ status="cancelled",
149
+ stripe_subscription_id=subscription_id
150
+ )
151
+ logger.info(f"Cancelled subscription {subscription_id} for user {user_id}")
152
+
153
+ return {"subscription_id": subscription_id, "status": "cancelled"}
154
+
155
+ def _handle_invoice_paid(self, invoice: Dict[str, Any]) -> Dict[str, Any]:
156
+ """Handle successful subscription payment."""
157
+ # For monthly subscriptions, could grant monthly credit allotment here
158
+ # For now, just log the payment
159
+ customer_id = invoice.get("customer")
160
+ amount = invoice.get("amount_paid", 0) / 100.0
161
+ logger.info(f"Invoice paid: ${amount} from customer {customer_id}")
162
+ return {"amount_paid": amount}
163
+
164
+ def _handle_invoice_failed(self, invoice: Dict[str, Any]) -> Dict[str, Any]:
165
+ """Handle failed subscription payment."""
166
+ customer_id = invoice.get("customer")
167
+ logger.warning(f"Invoice payment failed for customer {customer_id}")
168
+ # Could pause subscription or send notification here
169
+ return {"status": "payment_failed"}
170
+
171
+ def _handle_payment_intent_succeeded(self, payment_intent: Dict[str, Any]) -> Dict[str, Any]:
172
+ """Handle successful payment intent (credit purchase)."""
173
+ metadata = payment_intent.get("metadata", {})
174
+ user_id = metadata.get("user_id")
175
+
176
+ if not user_id:
177
+ logger.error("No user_id in payment_intent metadata")
178
+ return {"error": "Missing user_id"}
179
+
180
+ # Check if this is a verification charge ($1)
181
+ if metadata.get("type") == "verification":
182
+ # This was the $1 verification, credits already added in payment_setup handler
183
+ logger.info(f"Verification charge completed for user {user_id}")
184
+ return {"type": "verification", "status": "completed"}
185
+
186
+ # Get credits from metadata (set during payment creation)
187
+ credits = int(metadata.get("credits", 0))
188
+
189
+ if credits > 0:
190
+ new_balance = self.credit_manager.add_credits(user_id, credits)
191
+ logger.info(f"Added {credits} credits to user {user_id}, new balance: {new_balance}")
192
+ return {"credits_added": credits, "new_balance": new_balance}
193
+
194
+ return {"message": "Payment processed"}
195
+
196
+ def _handle_dispute_created(self, dispute: Dict[str, Any]) -> Dict[str, Any]:
197
+ """Handle charge dispute (mark account as disputed)."""
198
+ # Get the charge and its metadata
199
+ charge_id = dispute.get("charge")
200
+
201
+ if not charge_id:
202
+ logger.error("No charge_id in dispute")
203
+ return {"error": "Missing charge_id"}
204
+
205
+ # In production, would fetch the charge from Stripe to get metadata
206
+ # For now, log the dispute for manual handling
207
+ amount = dispute.get("amount", 0) / 100.0
208
+ reason = dispute.get("reason", "unknown")
209
+
210
+ logger.warning(f"Dispute created for charge {charge_id}: ${amount}, reason: {reason}")
211
+
212
+ # TODO: Mark user account as disputed in CreditsTable
213
+ # This would prevent new purchases until resolved
214
+
215
+ return {"dispute_id": dispute.get("id"), "status": "created", "amount": amount}