-
Notifications
You must be signed in to change notification settings - Fork 1
/
webhook_server.py
59 lines (44 loc) · 1.71 KB
/
webhook_server.py
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
from flask import Flask, jsonify, request
import os
import base64
import hashlib
import hmac
from pprint import pprint
from private_app import PrivateApp
from dotenv import load_dotenv
load_dotenv()
consumer_key = os.getenv('CONSUMER_KEY')
if not consumer_key:
raise EnvironmentError('Environment variable CONSUMER_KEY not found. How to run: \
$ CONSUMER_KEY=<your consumer key> python test.py')
with open(os.path.abspath('privatekey.pem')) as f:
private_key = f.read()
client = PrivateApp(private_key, consumer_key)
print('Instance created:', client)
webhook_key = os.getenv('WEBHOOK_KEY')
app = Flask('MyApp')
@app.route('/', methods=['GET', 'POST'])
def index():
return jsonify(Hello='World', Host=request.host), 200
@app.route('/webhook', methods=['POST'])
def webhook():
provided_signature = request.headers.get('X-Xero-Signature')
hashed = hmac.new(bytes(webhook_key, 'utf8'), request.data, hashlib.sha256)
generated_signature = base64.b64encode(hashed.digest()).decode('utf-8')
if provided_signature != generated_signature:
return '', 401
req_data = request.json
if len(req_data['events']): # assume this is intent to receive request
process_events(req_data['events'])
return '', 200
def process_events(events):
for event in events:
if event['eventCategory'] == 'INVOICE':
invoice = client.invoices(id=event['resourceId'])
if invoice['Status'] == 'PAID':
print('NEW PAID INVOICE:')
pprint(invoice, '\n\n')
else:
pprint(f'Received a non-paid invoice {event["eventType"]}: {invoice["InvoiceID"]}')
if __name__ == '__main__':
app.run(host='0.0.0.0', port='4567', debug=True)