import hmac
import hashlib
import time
def verify_webhook(request, webhook_secret):
timestamp = request.headers.get('X-AcountPay-Timestamp')
signature = request.headers.get('X-AcountPay-Signature')
payload = request.get_data(as_text=True)
# Check timestamp
if int(time.time()) - int(timestamp) > 300:
raise ValueError('Timestamp too old')
# Verify signature
expected = hmac.new(
webhook_secret.encode(),
f"{timestamp}.{payload}".encode(),
hashlib.sha256
).hexdigest()
if not hmac.compare_digest(signature, expected):
raise ValueError('Invalid signature')
return True
@app.route('/webhooks/acountpay', methods=['POST'])
def handle_webhook():
try:
verify_webhook(request, os.environ['WEBHOOK_SECRET'])
if request.json['event'] == 'payment.completed':
mark_order_paid(request.json['data']['referenceNumber'])
return '', 200
except ValueError:
return '', 401