NarratifAI deploy commited on
Commit
667e116
Β·
1 Parent(s): 51dd51c

Deploy asr_system 4cbca09

Browse files
Files changed (1) hide show
  1. app.py +54 -4
app.py CHANGED
@@ -1692,6 +1692,10 @@ async def paystack_init(request: Request):
1692
  if isinstance(naira, bool) or not isinstance(naira, int) or not CUSTOM_MIN_NGN <= naira <= CUSTOM_MAX_NGN:
1693
  raise HTTPException(status_code=400, detail="Choose a valid credit pack or whole-naira amount")
1694
  credits = credits_for_naira(naira)
 
 
 
 
1695
  reference = "narratifai-" + uuid.uuid4().hex
1696
  order = await asyncio.to_thread(_supabase_request, "POST", "/rest/v1/payment_orders", {
1697
  "reference": reference, "firebase_uid": uid, "email": email,
@@ -1699,10 +1703,12 @@ async def paystack_init(request: Request):
1699
  })
1700
  if not order:
1701
  raise HTTPException(status_code=503, detail="Could not create payment order")
1702
- callback = body.get("callback_url") or "narratifai://paystack-callback"
1703
- if callback not in ("narratifai://paystack-callback", "https://narratifai.com/pricing?paid=1",
1704
- "https://www.narratifai.com/pricing?paid=1"):
1705
- raise HTTPException(status_code=400, detail="Invalid payment callback")
 
 
1706
  try:
1707
  response = await asyncio.to_thread(_requests.post,
1708
  "https://api.paystack.co/transaction/initialize",
@@ -1715,9 +1721,53 @@ async def paystack_init(request: Request):
1715
  raise ValueError("Payment initialization failed")
1716
  except Exception:
1717
  raise HTTPException(status_code=502, detail="Could not start payment. Please try again.")
 
 
 
1718
  return {"authorization_url": data["authorization_url"], "reference": reference, "credits": credits}
1719
 
1720
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1721
  # ── Apple in-app purchase (iOS) ───────────────────────────────────────────────
1722
  # Credit packs are consumable IAPs with product ids
1723
  # com.consulaw.narratifai.credits.<pack id>. The app sends the StoreKit 2
 
1692
  if isinstance(naira, bool) or not isinstance(naira, int) or not CUSTOM_MIN_NGN <= naira <= CUSTOM_MAX_NGN:
1693
  raise HTTPException(status_code=400, detail="Choose a valid credit pack or whole-naira amount")
1694
  credits = credits_for_naira(naira)
1695
+ callback = body.get("callback_url") or "narratifai://paystack-callback"
1696
+ if callback not in ("narratifai://paystack-callback", "https://narratifai.com/pricing?paid=1",
1697
+ "https://www.narratifai.com/pricing?paid=1"):
1698
+ raise HTTPException(status_code=400, detail="Invalid payment callback")
1699
  reference = "narratifai-" + uuid.uuid4().hex
1700
  order = await asyncio.to_thread(_supabase_request, "POST", "/rest/v1/payment_orders", {
1701
  "reference": reference, "firebase_uid": uid, "email": email,
 
1703
  })
1704
  if not order:
1705
  raise HTTPException(status_code=503, detail="Could not create payment order")
1706
+ # One checkout per tap: the same request arriving twice (some browsers and
1707
+ # data-saving proxies resend it) shares the first checkout instead of
1708
+ # opening a second Paystack payment.
1709
+ shared = await _same_checkout(uid, naira * 100, reference, order)
1710
+ if shared:
1711
+ return shared
1712
  try:
1713
  response = await asyncio.to_thread(_requests.post,
1714
  "https://api.paystack.co/transaction/initialize",
 
1721
  raise ValueError("Payment initialization failed")
1722
  except Exception:
1723
  raise HTTPException(status_code=502, detail="Could not start payment. Please try again.")
1724
+ # Kept so a duplicate of this request can be sent to the same checkout.
1725
+ await asyncio.to_thread(_supabase_request, "PATCH", "/rest/v1/payment_orders",
1726
+ {"authorization_url": data["authorization_url"]}, {"reference": f"eq.{reference}"})
1727
  return {"authorization_url": data["authorization_url"], "reference": reference, "credits": credits}
1728
 
1729
 
1730
+ CHECKOUT_DEDUPE_SECONDS = 15
1731
+
1732
+
1733
+ def _created_at(row) -> str:
1734
+ row = row[0] if isinstance(row, list) and row else row
1735
+ return str((row or {}).get("created_at") or "") if isinstance(row, dict) else ""
1736
+
1737
+
1738
+ async def _same_checkout(uid: str, amount_kobo: int, reference: str, order) -> Optional[dict]:
1739
+ """If an identical checkout (same account, same amount) started just before
1740
+ this one, drop this order and return that checkout instead. The first of
1741
+ two simultaneous requests always proceeds, so exactly one payment opens."""
1742
+ from datetime import datetime, timedelta, timezone
1743
+ mine = _created_at(order)
1744
+ if not mine:
1745
+ return None
1746
+ since = (datetime.now(timezone.utc) - timedelta(seconds=CHECKOUT_DEDUPE_SECONDS)).isoformat()
1747
+ rows = await asyncio.to_thread(_supabase_request, "GET", "/rest/v1/payment_orders", None, {
1748
+ "firebase_uid": f"eq.{uid}", "amount": f"eq.{amount_kobo}", "fulfilled_at": "is.null",
1749
+ "created_at": f"gte.{since}", "select": "reference,created_at,credits",
1750
+ "order": "created_at.asc,reference.asc", "limit": "5",
1751
+ }) or []
1752
+ earlier = [r for r in rows if isinstance(r, dict) and r.get("reference") != reference
1753
+ and (str(r.get("created_at")), str(r.get("reference"))) < (mine, reference)]
1754
+ if not earlier:
1755
+ return None
1756
+ first = earlier[0]
1757
+ await asyncio.to_thread(_supabase_request, "DELETE", "/rest/v1/payment_orders", None,
1758
+ {"reference": f"eq.{reference}", "fulfilled_at": "is.null"})
1759
+ # The first request is usually still talking to Paystack: wait for its page.
1760
+ for _ in range(20):
1761
+ got = await asyncio.to_thread(_supabase_request, "GET", "/rest/v1/payment_orders", None, {
1762
+ "reference": f"eq.{first['reference']}", "select": "authorization_url", "limit": "1"})
1763
+ url = got[0].get("authorization_url") if isinstance(got, list) and got else None
1764
+ if url:
1765
+ logger.info(f"Duplicate checkout {reference} for {uid} joined {first['reference']}")
1766
+ return {"authorization_url": url, "reference": first["reference"], "credits": first.get("credits")}
1767
+ await asyncio.sleep(0.5)
1768
+ raise HTTPException(status_code=409, detail="Your payment is already opening. Please wait a moment.")
1769
+
1770
+
1771
  # ── Apple in-app purchase (iOS) ───────────────────────────────────────────────
1772
  # Credit packs are consumable IAPs with product ids
1773
  # com.consulaw.narratifai.credits.<pack id>. The app sends the StoreKit 2