App workarounds.
[wolnelektury.git] / src / club / payu / pos.py
1 import requests
2
3
4 class POS:
5     ACCESS_TOKEN_URL = '/pl/standard/user/oauth/authorize'
6     API_BASE = '/api/v2_1/'
7
8     def __init__(self, pos_id, client_secret, secondary_key, sandbox=False, currency_code='PLN'):
9         self.pos_id = pos_id
10         self.client_secret = client_secret
11         self.secondary_key = secondary_key
12         self.sandbox = sandbox
13         self.currency_code = currency_code
14
15     def get_api_host(self):
16         if self.sandbox:
17             return 'https://secure.snd.payu.com'
18         else:
19             return 'https://secure.payu.com'
20
21     def get_access_token(self):
22         response = requests.post(
23             self.get_api_host() + self.ACCESS_TOKEN_URL,
24             data={
25                 'grant_type': 'client_credentials',
26                 'client_id': self.pos_id,
27                 'client_secret': self.client_secret
28             },
29         )
30         assert response.status_code == 200
31         data = response.json()
32         assert data['token_type'] == 'bearer'
33         assert data['grant_type'] == 'client_credentials'
34         return data['access_token']
35
36     def request(self, method, url, data):
37         access_token = self.get_access_token()
38
39         full_url = self.get_api_host() + self.API_BASE + url
40         response = requests.request(
41             method, full_url, json=data, headers={
42                 'Authorization': 'Bearer ' + access_token,
43             },
44             allow_redirects=False
45         )
46         return response.json()
47