Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -92,6 +92,31 @@ except Exception as e:
|
|
| 92 |
|
| 93 |
#--- END Firebase Initialization ---
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
#--- NEW: Geolocation Helpers ---
|
| 96 |
def _calculate_geohash(lat, lon):
|
| 97 |
"""Calculates the geohash for a given latitude and longitude."""
|
|
@@ -2272,5 +2297,137 @@ def get_ai_chat_history():
|
|
| 2272 |
return jsonify(dict(sorted_history)), 200
|
| 2273 |
except Exception as e: return handle_route_errors(e, uid_context=uid)
|
| 2274 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2275 |
if __name__ == '__main__':
|
| 2276 |
app.run(debug=True, host="0.0.0.0", port=int(os.getenv("PORT", 7860)))
|
|
|
|
| 92 |
|
| 93 |
#--- END Firebase Initialization ---
|
| 94 |
|
| 95 |
+
|
| 96 |
+
# Paynow #
|
| 97 |
+
# --- Paynow Initialization ---
|
| 98 |
+
from paynow import Paynow
|
| 99 |
+
|
| 100 |
+
PAYNOW_INTEGRATION_ID = os.getenv("PAYNOW_INTEGRATION_ID")
|
| 101 |
+
PAYNOW_INTEGRATION_KEY = os.getenv("PAYNOW_INTEGRATION_KEY")
|
| 102 |
+
# IMPORTANT: This should be the publicly accessible URL of your deployed application
|
| 103 |
+
APP_BASE_URL = os.getenv("APP_BASE_URL", "https://tunasongaagri.co.zw")
|
| 104 |
+
|
| 105 |
+
paynow_client = None
|
| 106 |
+
if PAYNOW_INTEGRATION_ID and PAYNOW_INTEGRATION_KEY:
|
| 107 |
+
try:
|
| 108 |
+
paynow_client = Paynow(
|
| 109 |
+
PAYNOW_INTEGRATION_ID,
|
| 110 |
+
PAYNOW_INTEGRATION_KEY,
|
| 111 |
+
return_url=f"{APP_BASE_URL}/my-deals", # A page for the user to land on after payment
|
| 112 |
+
result_url=f"{APP_BASE_URL}/api/payment/webhook/paynow" # The webhook URL for server-to-server updates
|
| 113 |
+
)
|
| 114 |
+
logger.info("Paynow client initialized successfully.")
|
| 115 |
+
except Exception as e:
|
| 116 |
+
logger.error(f"Failed to initialize Paynow client: {e}")
|
| 117 |
+
else:
|
| 118 |
+
logger.warning("Paynow environment variables not set. Payment features will be disabled.")
|
| 119 |
+
|
| 120 |
#--- NEW: Geolocation Helpers ---
|
| 121 |
def _calculate_geohash(lat, lon):
|
| 122 |
"""Calculates the geohash for a given latitude and longitude."""
|
|
|
|
| 2297 |
return jsonify(dict(sorted_history)), 200
|
| 2298 |
except Exception as e: return handle_route_errors(e, uid_context=uid)
|
| 2299 |
|
| 2300 |
+
|
| 2301 |
+
@app.route('/api/deals/<deal_id>/payment/initiate', methods=['POST'])
|
| 2302 |
+
def initiate_payment(deal_id):
|
| 2303 |
+
auth_header = request.headers.get('Authorization')
|
| 2304 |
+
buyer_uid = None
|
| 2305 |
+
try:
|
| 2306 |
+
if not paynow_client:
|
| 2307 |
+
return jsonify({'error': 'Payment service is not configured.'}), 503
|
| 2308 |
+
|
| 2309 |
+
buyer_uid = verify_token(auth_header)
|
| 2310 |
+
|
| 2311 |
+
deal_ref = db.reference(f'deals/{deal_id}', app=db_app)
|
| 2312 |
+
deal_data = deal_ref.get()
|
| 2313 |
+
|
| 2314 |
+
# --- SURGICAL VALIDATION ---
|
| 2315 |
+
if not deal_data:
|
| 2316 |
+
return jsonify({'error': 'Deal not found.'}), 404
|
| 2317 |
+
if deal_data.get('buyer_id') != buyer_uid:
|
| 2318 |
+
return jsonify({'error': 'You are not authorized to pay for this deal.'}), 403
|
| 2319 |
+
if deal_data.get('status') != 'active':
|
| 2320 |
+
return jsonify({'error': 'This deal is not active and cannot be paid for.'}), 400
|
| 2321 |
+
if deal_data.get('payment', {}).get('status') == 'paid':
|
| 2322 |
+
return jsonify({'error': 'This deal has already been paid for.'}), 400
|
| 2323 |
+
|
| 2324 |
+
# --- BACKEND CALCULATION ---
|
| 2325 |
+
price = float(deal_data['proposed_price'])
|
| 2326 |
+
quantity = int(deal_data['proposed_quantity'])
|
| 2327 |
+
total_amount = round(price * quantity, 2)
|
| 2328 |
+
|
| 2329 |
+
# Create a new payment object
|
| 2330 |
+
payment = paynow_client.create_payment(
|
| 2331 |
+
f"TNSG-{deal_id}", # A unique reference for this transaction
|
| 2332 |
+
deal_data.get('buyer_email', 'buyer@example.com') # Get buyer email if stored, otherwise a placeholder
|
| 2333 |
+
)
|
| 2334 |
+
payment.add(f"Deal {deal_id} for {deal_data.get('crop_type', 'produce')}", total_amount)
|
| 2335 |
+
|
| 2336 |
+
# Send the payment to Paynow
|
| 2337 |
+
response = paynow_client.send(payment)
|
| 2338 |
+
|
| 2339 |
+
if not response.success:
|
| 2340 |
+
logger.error(f"Paynow initiation failed for deal {deal_id}: {response.error}")
|
| 2341 |
+
return jsonify({'error': 'Failed to initiate payment with the provider.', 'details': response.error}), 500
|
| 2342 |
+
|
| 2343 |
+
# --- UPDATE FIREBASE BEFORE REDIRECT ---
|
| 2344 |
+
payment_update_payload = {
|
| 2345 |
+
"status": "pending",
|
| 2346 |
+
"paynow_reference": response.paynow_reference,
|
| 2347 |
+
"poll_url": response.poll_url,
|
| 2348 |
+
"amount": total_amount,
|
| 2349 |
+
"currency": "USD", # Or make this dynamic if needed
|
| 2350 |
+
"initiated_at": datetime.now(timezone.utc).isoformat()
|
| 2351 |
+
}
|
| 2352 |
+
deal_ref.child('payment').set(payment_update_payload)
|
| 2353 |
+
|
| 2354 |
+
# Return the redirect URL to the frontend
|
| 2355 |
+
return jsonify({
|
| 2356 |
+
'success': True,
|
| 2357 |
+
'message': 'Payment initiated. Redirecting...',
|
| 2358 |
+
'redirect_url': response.redirect_url
|
| 2359 |
+
}), 200
|
| 2360 |
+
|
| 2361 |
+
except Exception as e:
|
| 2362 |
+
return handle_route_errors(e, uid_context=buyer_uid)
|
| 2363 |
+
|
| 2364 |
+
@app.route('/api/payment/webhook/paynow', methods=['POST'])
|
| 2365 |
+
def paynow_webhook():
|
| 2366 |
+
try:
|
| 2367 |
+
# The Paynow SDK does not have a built-in webhook handler, so we do it manually.
|
| 2368 |
+
# This is a simplified representation. Refer to Paynow docs for the exact fields and hash method.
|
| 2369 |
+
paynow_data = request.form.to_dict() # Paynow sends form data
|
| 2370 |
+
logger.info(f"Received Paynow webhook: {paynow_data}")
|
| 2371 |
+
|
| 2372 |
+
paynow_reference = paynow_data.get('paynowreference')
|
| 2373 |
+
merchant_reference = paynow_data.get('reference') # This is our "TNSG-deal_id"
|
| 2374 |
+
status = paynow_data.get('status', '').lower()
|
| 2375 |
+
received_hash = paynow_data.get('hash')
|
| 2376 |
+
|
| 2377 |
+
# --- CRITICAL: HASH VERIFICATION ---
|
| 2378 |
+
# You MUST generate a hash from the received data using your Integration Key
|
| 2379 |
+
# and compare it to the received_hash. If they don't match, discard the request.
|
| 2380 |
+
# Example (pseudo-code, check Paynow docs for exact implementation):
|
| 2381 |
+
# calculated_hash = generate_hash(paynow_data, PAYNOW_INTEGRATION_KEY)
|
| 2382 |
+
# if calculated_hash != received_hash:
|
| 2383 |
+
# logger.warning("Invalid hash on Paynow webhook. Discarding.")
|
| 2384 |
+
# return jsonify({'error': 'Invalid hash'}), 403
|
| 2385 |
+
|
| 2386 |
+
if not merchant_reference or not merchant_reference.startswith('TNSG-'):
|
| 2387 |
+
return jsonify({'error': 'Invalid reference format'}), 400
|
| 2388 |
+
|
| 2389 |
+
deal_id = merchant_reference.split('TNSG-')[1]
|
| 2390 |
+
deal_ref = db.reference(f'deals/{deal_id}', app=db_app)
|
| 2391 |
+
deal_data = deal_ref.get()
|
| 2392 |
+
|
| 2393 |
+
if not deal_data:
|
| 2394 |
+
logger.error(f"Webhook for non-existent deal {deal_id} received.")
|
| 2395 |
+
return jsonify({'error': 'Deal not found'}), 404
|
| 2396 |
+
|
| 2397 |
+
# Prevent processing old webhooks if deal is already paid
|
| 2398 |
+
if deal_data.get('payment', {}).get('status') == 'paid':
|
| 2399 |
+
logger.info(f"Webhook for already paid deal {deal_id} received. Ignoring.")
|
| 2400 |
+
return jsonify({'status': 'ok'}), 200
|
| 2401 |
+
|
| 2402 |
+
payment_update_payload = {
|
| 2403 |
+
"status": status,
|
| 2404 |
+
"completed_at": datetime.now(timezone.utc).isoformat()
|
| 2405 |
+
}
|
| 2406 |
+
deal_ref.child('payment').update(payment_update_payload)
|
| 2407 |
+
|
| 2408 |
+
# --- NOTIFY USERS BASED ON STATUS ---
|
| 2409 |
+
if status == 'paid':
|
| 2410 |
+
farmer_id = deal_data.get('farmer_id')
|
| 2411 |
+
buyer_id = deal_data.get('buyer_id')
|
| 2412 |
+
|
| 2413 |
+
# Find admins to notify
|
| 2414 |
+
admins_ref = db.reference('users', app=db_app).order_by_child('is_admin').equal_to(True).get()
|
| 2415 |
+
|
| 2416 |
+
success_message = f"Payment for deal {deal_id} has been successfully received."
|
| 2417 |
+
|
| 2418 |
+
_send_system_notification(buyer_id, f"Your payment for deal {deal_id} was successful.", "payment_success", f"/deals/{deal_id}")
|
| 2419 |
+
_send_system_notification(farmer_id, success_message, "payment_received", f"/deals/{deal_id}")
|
| 2420 |
+
if admins_ref:
|
| 2421 |
+
for admin_id, _ in admins_ref.items():
|
| 2422 |
+
_send_system_notification(admin_id, success_message, "admin_payment_notification", f"/admin/deals/{deal_id}")
|
| 2423 |
+
|
| 2424 |
+
# Acknowledge receipt to Paynow
|
| 2425 |
+
return jsonify({'status': 'ok'}), 200
|
| 2426 |
+
|
| 2427 |
+
except Exception as e:
|
| 2428 |
+
logger.error(f"Error in Paynow webhook: {e}\n{traceback.format_exc()}")
|
| 2429 |
+
return jsonify({'error': 'Internal server error'}), 500
|
| 2430 |
+
|
| 2431 |
+
|
| 2432 |
if __name__ == '__main__':
|
| 2433 |
app.run(debug=True, host="0.0.0.0", port=int(os.getenv("PORT", 7860)))
|