This repository has been archived by the owner on Sep 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
264 lines (218 loc) · 9 KB
/
app.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
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# -*- coding: utf-8 -*-
'''
Author: Oliver Zscheyge
Description:
Web app that generates beautiful order documents for ePages Beyond shops.
'''
import os
import logging
import random
from urllib.parse import urlencode, urlparse, unquote
from flask import Flask, render_template, request, Response, abort, escape, jsonify
from app_installations import AppInstallations, PostgresAppInstallations
from shops import Shop, PostgresShops, get_shop_id
from payment_method_definitions import create_payment_method
import payments
from signers import sign
app = Flask(__name__)
APP_INSTALLATIONS = None
SHOPS = None
CLIENT_SECRET = ''
DEFAULT_HOSTNAME = ''
LOGGER = logging.getLogger('app')
AUTO_INSTALLED_PAYMENT_METHOD_DEFINITIONS = [
'beautiful-test-payment-embedded',
'beautiful-test-payment-embedded-selection',
'beautiful-test-payment-capture-on-demand'
]
@app.route('/')
def root():
if DEFAULT_HOSTNAME != '':
return render_template('index.html', installed=True, hostname=DEFAULT_HOSTNAME)
return render_template('index.html', installed=False)
@app.route('/<hostname>')
def root_hostname(hostname):
return render_template('index.html', installed=True, hostname=hostname)
@app.route('/callback')
def callback():
args = request.args
return_url = args.get('return_url')
access_token_url = args.get('access_token_url')
api_url = args.get('api_url')
code = args.get('code')
signature = unquote(args.get('signature'))
APP_INSTALLATIONS.retrieve_token_from_auth_code(api_url, code, access_token_url, signature)
hostname = urlparse(api_url).hostname
installation = get_installation(hostname)
created_payment_methods = _auto_create_payment_methods(installation)
_get_and_store_shop_id(installation)
return render_template('callback_result.html',
return_url=return_url,
created_payment_methods=created_payment_methods)
def _auto_create_payment_methods(installation):
created_payment_methods = []
for pmd_name in AUTO_INSTALLED_PAYMENT_METHOD_DEFINITIONS:
status = create_payment_method(installation, pmd_name)
created_payment_methods.append({
'status_code': status,
'payment_method_definition_name': pmd_name
})
print('Created payment method for %s in shop %s with status %i' % (pmd_name, installation.hostname, status))
return created_payment_methods
def _get_and_store_shop_id(installation):
shop_id = get_shop_id(installation)
shop = Shop(shop_id, installation.hostname)
SHOPS.create_or_update_shop(shop)
@app.route('/merchants/<shop_id>')
def merchant_account_status(shop_id):
print('Serving always ready merchant account status')
return jsonify({
'ready' : True,
'details' : {
'primaryEmail' : '[email protected]'
}
})
@app.route('/payments', methods=['POST'])
def create_payment():
print('Creating payment with paymentNote')
return jsonify({
'paymentNote': 'Please transfer the money using the reference %s to the account %s' % (generate_id(), generate_id()),
})
@app.route('/embedded-payments', methods=['POST'])
def create_embedded_payment():
app_hostname = urlparse(request.url_root).hostname
payload = request.get_json(force=True)
shop = payload.get('shop', {}).get('name', '')
shop_id = payload.get('shopId', '')
payment_id = payload.get('paymentId', '')
signature = sign('%s:%s' % (shop_id, payment_id), CLIENT_SECRET)
params = {
'paymentId': payment_id,
'signature': signature,
'shop': shop,
'shopId': shop_id
}
embeddedApprovalUri = 'https://%s/embedded-payment-approval?%s' % (app_hostname, urlencode(params))
print('Created embedded payment for shop %s' % shop)
return jsonify({
'embeddedApprovalUri': embeddedApprovalUri
})
@app.route('/embedded-payment-approval')
def embedded_payment_approval():
args = request.args
payment_id = unquote(args.get('paymentId', ''))
signature = unquote(args.get('signature', ''))
shop = unquote(args.get('shop', ''))
shop_id = unquote(args.get('shopId', ''))
approve_uri = '/payments/%s/approve' % payment_id
cancel_uri = '/payments/%s/cancel' % payment_id
if _validate_signature(signature, shop_id, payment_id):
return render_template('embedded_payment_approval.html',
state='PENDING',
signature=signature,
shop=shop,
shop_id=shop_id,
approve_uri=approve_uri,
cancel_uri=cancel_uri)
return render_template('embedded_payment_approval.html',
state='ERROR')
def _validate_signature(signature_to_validate, shop_id, payment_id):
expected_signature = sign('%s:%s' % (shop_id, payment_id), CLIENT_SECRET)
match = signature_to_validate == expected_signature
print('Validated signatures: %s | %s | match: %s' % (signature_to_validate, expected_signature, str(match)))
return match
@app.route('/payments/<payment_id>/approve', methods=['POST'])
def approve_payment(payment_id):
''' Currently only needed for embedded payments
'''
print('Approving payment %s' % payment_id)
shop_id = request.form.get('shop_id', '')
signature = request.form.get('signature', '')
shop = SHOPS.get_shop(shop_id)
installation = get_installation(shop.hostname)
if _validate_signature(signature, shop_id, payment_id):
return_uri = payments.approve_payment(installation, payment_id)
return render_template('embedded_payment_approval.html',
state='APPROVED',
return_uri=return_uri)
return render_template('embedded_payment_approval.html',
state='ERROR')
@app.route('/payments/<payment_id>/cancel', methods=['POST'])
def cancel_payment(payment_id):
''' Currently only needed for embedded payments
'''
print('Canceling payment %s' % payment_id)
shop_id = request.form.get('shop_id', '')
signature = request.form.get('signature', '')
shop = SHOPS.get_shop(shop_id)
installation = get_installation(shop.hostname)
if _validate_signature(signature, shop_id, payment_id):
return_uri = payments.cancel_payment(installation, payment_id)
return render_template('embedded_payment_approval.html',
state='CANCELED',
return_uri=return_uri)
return render_template('embedded_payment_approval.html',
state='ERROR')
@app.route('/payments/<payment_id>/capture', methods=['POST'])
def capture_payment(payment_id):
print('Capturing payment %s' % payment_id)
return jsonify({
'paymentStatus' : 'CAPTURED',
})
def generate_id():
return ''.join(random.choice('ABCDEFGHJKLMNPQRSTUVWXYZ23456789') for _ in range(8))
@app.before_request
def limit_open_proxy_requests():
'''Security measure to prevent:
http://serverfault.com/questions/530867/baidu-in-nginx-access-log
http://security.stackexchange.com/questions/41078/url-from-another-domain-in-my-access-log
http://serverfault.com/questions/115827/why-does-apache-log-requests-to-get-http-www-google-com-with-code-200
http://stackoverflow.com/questions/22251038/how-to-limit-flask-dev-server-to-only-one-visiting-ip-address
'''
if not is_allowed_request():
print('Someone is messing with us:')
print(request.url_root)
print(request)
abort(403)
def is_allowed_request():
url = request.url_root
return '.herokuapp.com' in url or \
'.ngrok.io' in url or \
'localhost:8080' in url or \
'127.0.0' in url or \
'0.0.0.0:80' in url
def get_installation(hostname):
installation = APP_INSTALLATIONS.get_installation(hostname)
if not installation:
raise ShopNotKnown(hostname)
return installation
@app.errorhandler(404)
def page_not_found(e):
return '<h1>404 File Not Found! :(</h1>', 404
class ShopNotKnown(Exception):
def __init__(self, hostname):
super()
self.hostname = hostname
@app.errorhandler(ShopNotKnown)
def shop_not_known(e):
return render_template('index.html', installed=False, error_message='App not installed for the requested shop with hostname %s' % e.hostname)
@app.errorhandler(Exception)
def all_exception_handler(error):
LOGGER.exception(error)
return 'Error', 500
def init():
global APP_INSTALLATIONS
global SHOPS
global DEFAULT_HOSTNAME
global CLIENT_SECRET
CLIENT_ID = os.environ.get('CLIENT_ID', '')
CLIENT_SECRET = os.environ.get('CLIENT_SECRET', '')
print('Initialize PostgresAppInstallations')
APP_INSTALLATIONS = PostgresAppInstallations(os.environ.get('DATABASE_URL'), CLIENT_ID, CLIENT_SECRET)
APP_INSTALLATIONS.create_schema()
print('Initialize PostgresShops')
SHOPS = PostgresShops(os.environ.get('DATABASE_URL'))
SHOPS.create_schema()
init()
if __name__ == '__main__':
app.run()