Fundraising in PDF.
[wolnelektury.git] / src / club / payu / pos.py
1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 import requests
5
6
7 class POS:
8     ACCESS_TOKEN_URL = '/pl/standard/user/oauth/authorize'
9     API_BASE = '/api/v2_1/'
10
11     def __init__(self, pos_id, client_secret, secondary_key, sandbox=False, currency_code='PLN'):
12         self.pos_id = pos_id
13         self.client_secret = client_secret
14         self.secondary_key = secondary_key
15         self.sandbox = sandbox
16         self.currency_code = currency_code
17
18     def get_api_host(self):
19         if self.sandbox:
20             return 'https://secure.snd.payu.com'
21         else:
22             return 'https://secure.payu.com'
23
24     def get_access_token(self):
25         response = requests.post(
26             self.get_api_host() + self.ACCESS_TOKEN_URL,
27             data={
28                 'grant_type': 'client_credentials',
29                 'client_id': self.pos_id,
30                 'client_secret': self.client_secret
31             },
32         )
33         assert response.status_code == 200
34         data = response.json()
35         assert data['token_type'] == 'bearer'
36         assert data['grant_type'] == 'client_credentials'
37         return data['access_token']
38
39     def request(self, method, url, data):
40         access_token = self.get_access_token()
41
42         full_url = self.get_api_host() + self.API_BASE + url
43         response = requests.request(
44             method, full_url, json=data, headers={
45                 'Authorization': 'Bearer ' + access_token,
46             },
47             allow_redirects=False
48         )
49         return response.json()
50