Преглед изворни кода

payment.py: Fix Stripe checkout error by using price_data instead of price

This commit fixes a critical Stripe checkout error where product IDs were
incorrectly being passed to the 'price' field in line_items. Stripe expects
price IDs (starting with 'price_') in this field, not product IDs (starting
with 'prod_').

The fix uses Stripe's 'price_data' approach which allows creating inline
prices by specifying:
- currency
- product ID
- unit amount

This approach avoids the need for creating and storing separate price IDs
while still allowing Stripe checkout to process payments correctly.

Error fixed: "resource_missing - line_items[0][price]"
brid пре 1 година
родитељ
комит
d2128cbc97
1 измењених фајлова са 26 додато и 9 уклоњено
  1. 26 9
      app/payment.py

+ 26 - 9
app/payment.py

@@ -15,27 +15,44 @@ from app.schema import CartSession, NowPaymentsInvoice, ShippingCostEntry, Shipp
 
 logger = logging.getLogger(__name__)
 
-
-def prepare_stripe_data(cart: CartSession) -> list[str, int]:
+def prepare_stripe_data(cart: CartSession) -> list[dict]:
     """Returns list of items ready for Stripe to be processed.
-    Each item is in the form of {price: <price_id>, quantity: <amount>}
+    Each item is in the form of {price_data: {...}} or {price: <price_id>, quantity: <amount>}
+    
+    When using product IDs, we need to use price_data to create prices inline:
+    list_items = [
+        {
+            'price_data': {
+                'currency': 'usd',
+                'product': 'prod_XYZ',
+                'unit_amount': 2000  # amount in cents
+            },
+            'quantity': 1
+        }
+    ]
+    
+    When using price IDs:
     list_items = [
         {
-            # Provide the exact Price ID (for example, pr_1234) of the product you want to sell
-            'price': ,
-            'quantity': 0
+            'price': 'price_XYZ',
+            'quantity': 1
         }
     ]
     """
     list_items = []
 
     for item in cart.items.values():
-        item = {
-            "price": item.product_id,
+        # Create inline price data using the product ID
+        item_data = {
+            "price_data": {
+                "currency": cart.meta.currency.lower(),
+                "product": item.product_id,
+                "unit_amount": int(item.price * 100 / item.quantity),  # Convert to cents
+            },
             "quantity": item.quantity,
         }
 
-        list_items.append(item)
+        list_items.append(item_data)
 
     return list_items