-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwebhook_python.py
More file actions
212 lines (172 loc) · 6.77 KB
/
webhook_python.py
File metadata and controls
212 lines (172 loc) · 6.77 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
"""
Mutasibank Webhook Handler - Python/Flask
Secure webhook receiver with HMAC-SHA256 signature verification
"""
from flask import Flask, request, jsonify
import hmac
import hashlib
import time
import json
import os
from datetime import datetime
app = Flask(__name__)
# Configuration
WEBHOOK_SECRET = os.getenv('WEBHOOK_SECRET', 'your_webhook_secret_here')
API_TOKEN = os.getenv('API_TOKEN', 'your_api_token_here')
TIMESTAMP_TOLERANCE = 300 # 5 minutes
@app.route('/webhook/mutasibank', methods=['POST'])
def mutasibank_webhook():
"""
Webhook endpoint with signature verification
"""
try:
# Step 1: Extract headers
signature = request.headers.get('X-Mutasibank-Signature', '')
timestamp = int(request.headers.get('X-Mutasibank-Timestamp', 0))
webhook_id = request.headers.get('X-Mutasibank-Webhook-Id', '')
# Step 2: Validate headers
if not signature or not timestamp:
app.logger.error('Missing signature headers')
return jsonify({
'error': 'Missing signature headers'
}), 401
# Step 3: Check timestamp (prevent replay attacks)
current_time = int(time.time())
time_diff = abs(current_time - timestamp)
if time_diff > TIMESTAMP_TOLERANCE:
app.logger.error(f'Timestamp expired. Diff: {time_diff}s')
return jsonify({
'error': 'Request expired',
'timestamp_received': timestamp,
'current_time': current_time,
'difference_seconds': time_diff
}), 401
# Step 4: Get raw payload
payload = request.get_data()
if not payload:
app.logger.error('Empty payload')
return jsonify({'error': 'Empty payload'}), 400
# Step 5: Verify signature (HMAC-SHA256)
expected_signature = hmac.new(
WEBHOOK_SECRET.encode(),
payload,
hashlib.sha256
).hexdigest()
# Use constant-time comparison
if not hmac.compare_digest(signature, expected_signature):
app.logger.error('Invalid signature', extra={'webhook_id': webhook_id})
return jsonify({
'error': 'Invalid signature',
'message': 'Webhook signature verification failed'
}), 401
app.logger.info(f'✅ Signature verified: {webhook_id}')
# Step 6: Parse and validate data
data = request.get_json()
# Verify API token (double authentication)
if data.get('api_key') != API_TOKEN:
app.logger.error('Invalid API token')
return jsonify({'error': 'Invalid API token'}), 401
# Step 7: Process webhook data
account_id = data['account_id']
account_number = data['account_number']
module = data['module'] # bca, bri, mandiri, bni
balance = data['balance']
transactions = data['data_mutasi']
app.logger.info(f'Processing webhook for account: {account_number}', extra={
'account_id': account_id,
'module': module,
'transaction_count': len(transactions),
'balance': balance
})
# Process each transaction
for transaction in transactions:
transaction_id = transaction['id']
transaction_date = transaction['transaction_date']
description = transaction['description']
tx_type = transaction['type'] # CR (credit) or DB (debit)
amount = transaction['amount']
tx_balance = transaction['balance']
app.logger.info(f'Processing transaction: {transaction_id}', extra={
'date': transaction_date,
'type': tx_type,
'amount': amount
})
# ================================================================
# YOUR BUSINESS LOGIC HERE
# ================================================================
# Example 1: Auto-confirm order
if tx_type == 'CR':
order_id = extract_order_id(description)
if order_id:
confirm_order(order_id, amount, transaction_id)
# Example 2: Save to database
# save_transaction(transaction)
# Step 8: Return success response
app.logger.info(f'✅ Webhook processed successfully: {webhook_id}', extra={
'transactions_processed': len(transactions)
})
return jsonify({
'success': True,
'webhook_id': webhook_id,
'transactions_processed': len(transactions),
'timestamp': datetime.now().isoformat()
}), 200
except Exception as e:
app.logger.error(f'Webhook processing error: {str(e)}')
return jsonify({
'error': 'Internal server error',
'message': str(e)
}), 500
# ============================================================================
# HELPER FUNCTIONS
# ============================================================================
def extract_order_id(description):
"""Extract order ID from transaction description"""
import re
patterns = [
r'ORDER[:\-\s]*(\d+)',
r'TRF\s+(\d+)',
r'INV[:\-\s]*(\d+)'
]
for pattern in patterns:
match = re.search(pattern, description, re.IGNORECASE)
if match:
return match.group(1)
return None
def confirm_order(order_id, amount, transaction_id):
"""Confirm order (example)"""
# Your database logic here
app.logger.info(f'Order confirmed: {order_id}', extra={
'amount': amount,
'transaction_id': transaction_id
})
# Example:
# db.orders.update_one(
# {'_id': order_id},
# {
# '$set': {
# 'status': 'paid',
# 'payment_amount': amount,
# 'transaction_id': transaction_id,
# 'paid_at': datetime.now()
# }
# }
# )
def save_transaction(transaction):
"""Save transaction to database (example)"""
# Example using SQLAlchemy or MongoDB
# db.transactions.insert_one({
# 'transaction_id': transaction['id'],
# 'date': datetime.fromisoformat(transaction['transaction_date']),
# 'description': transaction['description'],
# 'type': transaction['type'],
# 'amount': transaction['amount'],
# 'balance': transaction['balance'],
# 'processed_at': datetime.now()
# })
app.logger.info(f'Transaction saved: {transaction["id"]}')
if __name__ == '__main__':
PORT = int(os.getenv('PORT', 3000))
print(f'🚀 Webhook server running on port {PORT}')
print(f'📝 Endpoint: POST http://localhost:{PORT}/webhook/mutasibank')
app.run(host='0.0.0.0', port=PORT, debug=False)