76 lines
2.4 KiB
Python
76 lines
2.4 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
import logging
|
|
from logging.handlers import RotatingFileHandler
|
|
from flask import Flask, request, jsonify
|
|
from flask_cors import CORS
|
|
from flask import Response
|
|
|
|
try:
|
|
from dotenv import load_dotenv
|
|
load_dotenv()
|
|
except Exception:
|
|
pass
|
|
|
|
from helpers.netopia import verify_ipn, get_status
|
|
|
|
app = Flask(__name__)
|
|
CORS(app, resources={r"/api/*": {"origins": "*"}})
|
|
|
|
# ---------- Logging ----------
|
|
app.logger.setLevel(logging.INFO)
|
|
_log_dir = os.getenv("LOG_DIR", "logs")
|
|
os.makedirs(_log_dir, exist_ok=True)
|
|
_handler = RotatingFileHandler(os.path.join(_log_dir, "netopia_api.log"), maxBytes=1_000_000, backupCount=3)
|
|
_handler.setLevel(logging.INFO)
|
|
_handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))
|
|
app.logger.addHandler(_handler)
|
|
|
|
|
|
@app.get("/healthz")
|
|
def healthz():
|
|
return {"ok": True}, 200
|
|
|
|
from flask import Response # Add this import at the top
|
|
|
|
@app.post("/api/payments/ipn")
|
|
def ipn():
|
|
try:
|
|
# 1. Verify the request with the SDK
|
|
data = verify_ipn(request)
|
|
app.logger.info("IPN OK: %s", data)
|
|
|
|
# 2. Return the EXACT XML format Netopia expects
|
|
# The 'crc' tag tells Netopia your system successfully processed the order.
|
|
xml_response = '<?xml version="1.0" encoding="utf-8" ?><crc>ok</crc>'
|
|
|
|
return Response(xml_response, mimetype='application/xml'), 200
|
|
|
|
except Exception as e:
|
|
app.logger.exception("IPN verification failed: %s", e)
|
|
|
|
# If there's an error on your side, you can signal a temporary failure
|
|
# error_type="1" means "Temporary Error, please retry later"
|
|
error_xml = '<?xml version="1.0" encoding="utf-8" ?><crc error_type="1">Internal Error</crc>'
|
|
return Response(error_xml, mimetype='application/xml'), 400
|
|
|
|
|
|
@app.get("/api/payments/status")
|
|
def status():
|
|
ntp_id = request.args.get("ntpID")
|
|
order_id = request.args.get("orderID")
|
|
try:
|
|
resp = get_status(ntp_id=ntp_id, order_id=order_id)
|
|
return jsonify({"ok": True, "data": resp}), 200
|
|
except Exception as e:
|
|
app.logger.exception("Status query failed: %s", e)
|
|
return jsonify({"ok": False, "error": str(e)}), 400
|
|
|
|
|
|
if __name__ == "__main__":
|
|
host = os.getenv("API_HOST", "0.0.0.0")
|
|
port = int(os.getenv("API_PORT", "9000"))
|
|
app.logger.info("Starting NETOPIA Flask sidecar on %s:%s", host, port)
|
|
app.run(host=host, port=port)
|