-
Notifications
You must be signed in to change notification settings - Fork 0
/
nalogapi.py
201 lines (179 loc) · 7.25 KB
/
nalogapi.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
import requests
import json
import random
import string
from datetime import datetime, timezone
class ConfigurationError(Exception):
pass
class AuthenticationError(Exception):
pass
class NalogAPI():
apiUrl = 'https://lknpd.nalog.ru/api/v1'
username = None
password = None
autologin = False
inn = None
token = None
tokenExpireIn = None
refreshToken = None
sourceDeviceId = None
def __init__(self):
if self.username is None or self.password is None:
raise ConfigurationError("username and password are required")
if self.sourceDeviceId is None:
self.sourceDeviceId = self.createDeviceId()
if self.autologin:
self.auth(self.login, self.password)
@staticmethod
def configure(username, password, autologin = False):
NalogAPI.username = username
NalogAPI.password = password
NalogAPI.autologin = autologin
@staticmethod
def createDeviceId():
return ''.join(random.choice(string.digits) for i in range(21))
@staticmethod
def getUtcDateTime(timestr):
return datetime.strptime(timestr, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc)
@staticmethod
def getTimeString(dt):
return dt.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def auth(self, login, password):
headers = {
'accept': 'application/json, text/plain, */*',
'accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',
'content-type': 'application/json',
'referrer': 'https://lknpd.nalog.ru/',
'referrerPolicy': 'strict-origin-when-cross-origin',
}
payload = {
'username': login,
'password': password,
'deviceInfo': {
'sourceDeviceId': self.sourceDeviceId,
'sourceType': 'WEB',
'appVersion': '1.0.0',
'metaDetails': {
'userAgent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.192 Safari/537.36'
}
}
}
s = requests.Session()
retries = requests.adapters.Retry(total=3, backoff_factor=0.5, status_forcelist=[ 502, 503, 504 ])
s.mount('http://', requests.adapters.HTTPAdapter(max_retries=retries))
url = self.apiUrl + '/auth/lkfl'
try:
r = s.post(url, data=json.dumps(payload), headers=headers, timeout=5)
except requests.ConnectionError:
raise AuthenticationError("Can't connect to authentication server")
res = r.json()
if not res['refreshToken']:
raise AuthenticationError("Authentication failure")
self.inn = res['profile']['inn']
self.token = res['token']
self.tokenExpireIn = self.getUtcDateTime(res['tokenExpireIn'])
self.refreshToken = res['refreshToken']
def getToken(self):
if self.token and self.tokenExpireIn and self.tokenExpireIn > datetime.now().replace(tzinfo=timezone.utc):
return self.token
if self.refreshToken is None:
self.auth(self.username, self.password)
return self.token
headers = {
'accept': 'application/json, text/plain, */*',
'accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',
'content-type': 'application/json',
'referrer': 'https://lknpd.nalog.ru/sales',
'referrerPolicy': 'strict-origin-when-cross-origin',
}
payload = {
'deviceInfo': {
'sourceDeviceId': self.sourceDeviceId,
'sourceType': 'WEB',
'appVersion': '1.0.0',
'metaDetails': {
'userAgent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.192 Safari/537.36'
}
},
'refreshToken': self.refreshToken
}
s = requests.Session()
retries = requests.adapters.Retry(total=3, backoff_factor=0.5, status_forcelist=[ 502, 503, 504 ])
s.mount('http://', requests.adapters.HTTPAdapter(max_retries=retries))
url = self.apiUrl + '/auth/token'
try:
r = s.post(url, data=json.dumps(payload), headers=headers, timeout=5)
except requests.ConnectionError:
raise Exception("Failed to fetch token")
res = r.json()
if res['refreshToken']:
self.refreshToken = res['refreshToken']
self.token = res['token']
self.tokenExpireIn = res['tokenExpireIn']
return self.token
def call(self, endpoint, payload=None):
post = True if payload is not None else False
headers = {
'authorization': str('Bearer ' + self.getToken()),
'accept': 'application/json, text/plain, */*',
'accept-language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',
'content-type': 'application/json',
'referrer': 'https://lknpd.nalog.ru/sales/create',
'referrerPolicy': 'strict-origin-when-cross-origin',
}
s = requests.Session()
retries = requests.adapters.Retry(total=3, backoff_factor=0.5, status_forcelist=[ 502, 503, 504 ])
s.mount('http://', requests.adapters.HTTPAdapter(max_retries=retries))
url = self.apiUrl + '/' + endpoint
r = None
if post:
try:
r = s.post(url, data=json.dumps(payload), headers=headers, timeout=5)
except requests.ConnectionError:
raise Exception("Failed to call")
else:
try:
r = s.get(url, headers=headers, timeout=5)
except requests.ConnectionError:
raise Exception("Failed to call")
res = r.json()
return res
@classmethod
def addIncome(cls, date, amount, name):
self = cls()
payload = {
'paymentType': 'CASH',
'ignoreMaxTotalIncomeRestriction': False,
'client': {
'contactPhone': None,
'displayName': None,
'incomeType': 'FROM_INDIVIDUAL',
'inn': None
},
'requestTime': self.getTimeString(datetime.utcnow()),
'operationTime': self.getTimeString(date),
'services': [{
'name': name, # 'Предоставление информационных услуг #970/2495',
'amount': str(amount),
'quantity': 1
}],
'totalAmount': str(amount)
}
res = self.call('income', payload)
if not res or not 'approvedReceiptUuid' in res:
return {'error': res}
return "{}/receipt/{}/{}/print".format(self.apiUrl, self.inn, res['approvedReceiptUuid'])
@classmethod
def userInfo(cls):
self = cls()
print(self.call('user'))
@classmethod
def paymentsInfo(cls):
self = cls()
print(self.call('keys'))
def main():
NalogAPI.configure("INN", "password") #Пароль от личного кабинета налогоплательщика lkfl
NalogAPI.userInfo()
# NalogAPI.addIncome(datetime.utcnow(), 1.0, "Предоставление информационных услуг #970/2495")
if __name__ == '__main__':
main()