File size: 3,740 Bytes
0bf932b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""Paystack recovery shared by authenticated verification and the CPU scheduler.

All grants go through the same locked, idempotent database transaction as the
signed webhook. Neither client metadata nor checkout redirects grant credits.
"""
import os
from datetime import datetime, timedelta, timezone
from urllib.parse import quote
import requests


def verified_charge(reference, secret, get=requests.get):
    response = get('https://api.paystack.co/transaction/verify/' + quote(reference, safe=''),
                   headers={'Authorization': 'Bearer ' + secret}, timeout=15)
    response.raise_for_status()
    envelope = response.json()
    data = envelope.get('data') if isinstance(envelope, dict) else None
    if envelope.get('status') is not True or not isinstance(data, dict) or data.get('reference') != reference:
        raise ValueError('Invalid payment verification response')
    return data


def charge_payload(data):
    if not isinstance(data, dict):
        raise ValueError('Invalid charge')
    customer = data.get('customer')
    amount = data.get('amount')
    if (not isinstance(data.get('reference'), str) or not data['reference']
            or type(amount) is not int or amount <= 0
            or not isinstance(data.get('currency'), str)
            or not isinstance(customer, dict) or not isinstance(customer.get('email'), str)):
        raise ValueError('Invalid charge fields')
    return {'p_reference': data['reference'], 'p_amount': amount,
            'p_currency': data['currency'], 'p_email': customer['email']}


def fulfillment_succeeded(result):
    return (isinstance(result, dict) and not result.get('error')
            and (result.get('already_credited') is True or type(result.get('balance')) is int))


def reconcile_due_orders(limit=20):
    """Retry persisted due orders; failures stay due with bounded backoff."""
    base = os.environ['SUPABASE_URL'].rstrip('/')
    key = os.environ['SUPABASE_SERVICE_ROLE_KEY']
    secret = os.environ['PAYSTACK_SECRET_KEY']
    headers = {'apikey': key, 'Authorization': 'Bearer ' + key}
    now = datetime.now(timezone.utc)
    response = requests.get(base + '/rest/v1/payment_orders', headers=headers, params={
        'select': 'reference,reconcile_attempts', 'fulfilled_at': 'is.null',
        'next_reconcile_at': 'lte.' + now.isoformat(), 'order': 'next_reconcile_at.asc,reference.asc',
        'limit': str(limit)}, timeout=15)
    response.raise_for_status()
    counts = {'checked': 0, 'credited': 0, 'pending': 0, 'errors': 0}
    for order in response.json():
        counts['checked'] += 1
        try:
            data = verified_charge(order['reference'], secret)
            if data.get('domain') == 'live' and data.get('status') == 'success':
                result = requests.post(base + '/rest/v1/rpc/fulfill_payment_order', headers=headers,
                                       json=charge_payload(data), timeout=15)
                result.raise_for_status()
                if not fulfillment_succeeded(result.json()):
                    raise ValueError('Payment fulfillment rejected')
                counts['credited'] += 1
                continue
            counts['pending'] += 1
        except Exception:
            counts['errors'] += 1
        attempts = order['reconcile_attempts'] + 1
        delay = min(1440, 5 * 2 ** min(attempts - 1, 9))
        retry = requests.patch(base + '/rest/v1/payment_orders', headers=headers,
            params={'reference': 'eq.' + order['reference'], 'fulfilled_at': 'is.null'},
            json={'reconcile_attempts': attempts,
                  'next_reconcile_at': (now + timedelta(minutes=delay)).isoformat()}, timeout=15)
        retry.raise_for_status()
    return counts