vpn-btcpay-provisioner/app/__init__.py
2024-12-30 06:03:07 +00:00

102 lines
3.4 KiB
Python

from flask import Flask, request, jsonify, render_template
import logging
from .handlers.webhook_handler import handle_payment_webhook
from .handlers.payment_handler import BTCPayHandler
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
app = Flask(__name__)
btcpay_handler = BTCPayHandler()
# Existing webhook route
@app.route('/webhook/vpn', methods=['POST'])
def handle_payment():
return handle_payment_webhook(request)
# Frontend routes
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/calculate-price', methods=['POST'])
def calculate_price():
hours = request.json.get('hours', 0)
# Basic price calculation - adjust formula as needed
base_price = hours * 100 # 100 sats per hour
# Apply volume discounts
if hours >= 720: # 1 month
base_price = base_price * 0.85 # 15% discount
elif hours >= 168: # 1 week
base_price = base_price * 0.90 # 10% discount
elif hours >= 24: # 1 day
base_price = base_price * 0.95 # 5% discount
return jsonify({
'price': int(base_price),
'duration': hours
})
@app.route('/create-invoice', methods=['POST'])
def create_invoice():
try:
logger.info("Received invoice creation request")
data = request.json
logger.debug(f"Request data: {data}")
# Validate input data
duration_hours = data.get('duration')
email = data.get('email')
if not email:
logger.error("Email address missing from request")
return jsonify({'error': 'Email is required'}), 400
if not duration_hours:
logger.error("Duration missing from request")
return jsonify({'error': 'Duration is required'}), 400
try:
duration_hours = int(duration_hours)
except ValueError:
logger.error(f"Invalid duration value: {duration_hours}")
return jsonify({'error': 'Invalid duration value'}), 400
# Calculate price using same logic as calculate-price endpoint
base_price = duration_hours * 100 # 100 sats per hour
if duration_hours >= 720: # 1 month
base_price = base_price * 0.85 # 15% discount
elif duration_hours >= 168: # 1 week
base_price = base_price * 0.90 # 10% discount
elif duration_hours >= 24: # 1 day
base_price = base_price * 0.95 # 5% discount
amount_sats = int(base_price)
logger.info(f"Calculated price: {amount_sats} sats for {duration_hours} hours")
# Create BTCPay invoice
invoice_data = btcpay_handler.create_invoice(amount_sats, duration_hours, email)
if not invoice_data:
logger.error("Failed to create invoice - no data returned from BTCPayHandler")
return jsonify({'error': 'Failed to create invoice'}), 500
logger.info(f"Successfully created invoice with ID: {invoice_data.get('invoice_id')}")
return jsonify(invoice_data)
except Exception as e:
logger.error(f"Error in create_invoice endpoint: {str(e)}")
return jsonify({'error': str(e)}), 500
@app.route('/payment/success')
def payment_success():
return render_template('payment_success.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)