-
Notifications
You must be signed in to change notification settings - Fork 0
/
iyzico_objects.py
552 lines (435 loc) · 16.5 KB
/
iyzico_objects.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
# coding=utf-8
__author__ = 'Ugur Atar <[email protected]>'
import requests
import settings
import uuid
class IyzicoCardException(ValueError):
def __init__(self, *args, **kwargs):
super(IyzicoCardException, self).__init__(*args, **kwargs)
class IyzicoValueException(ValueError):
def __init__(self, *args, **kwargs):
super(IyzicoValueException, self).__init__(*args, **kwargs)
class IyzicoHTTPException(IOError):
def __init__(self, *args, **kwargs):
response = kwargs.pop('response', None)
self.response = response
self.request = kwargs.pop('request', None)
if (response is not None and not self.request and
hasattr(response, 'request')):
self.request = self.response.request
super(IyzicoHTTPException, self).__init__(*args, **kwargs)
class IyzicoCard:
def __init__(self, card_number, card_expiry_month,
card_expiry_year, card_verification,
card_holder_name):
self.card_number = card_number
self.card_expiry_month = card_expiry_month
self.card_expiry_year = card_expiry_year
self.card_verification = card_verification
self.card_holder_name = card_holder_name
self.card_brand = None
self._bin_response = None
self._connector = None
self._valid = False
self.validate()
@property
def connector(self):
return self._connector
@property
def is_valid(self):
return self._valid
@property
def card_number(self):
return self.card_number
@property
def card_expiry_month(self):
return self.expiry_month
@property
def card_expiry_year(self):
return self.card_expiry_year
@property
def card_verification(self):
return self.card_verification
@property
def card_brand(self):
return self.card_brand
@property
def card_holder_name(self):
return self.card_holder_name
def validate(self):
if self._bin_response is None:
self._bin_check()
if self._bin_response.success:
self._valid = True
self._connector = self._find_connector()
self.card_brand = self._bin_response.issuer
else:
self._valid = False
self.card_brand = self._card_brand()
elif self._bin_response.bin != self.card_number[:6]:
self._bin_check()
if self._bin_response.success:
self._connector = self._find_connector()
self.card_brand = self._bin_response.issuer
self._valid = True
else:
self._valid = False
self.card_brand = self._card_brand()
elif self._bin_response.success:
self._valid = True
self.card_brand = self._bin_response.issuer
self._connector = self._find_connector()
def _bin_check(self):
payload = {'api_id': settings.api_id,
'secret': settings.api_secret,
'bin': self.card_number[:6]}
try:
raw_response = requests.post(settings.bin_check_url,
payload)
bin_response = IyzicoBinResponse(raw_response)
self._bin_response = bin_response
return bin_response
except requests.RequestException as re:
self.card_brand = self._card_brand()
raise IyzicoHTTPException(re.args, response=re.response)
except ValueError as value_error:
self.card_brand = self._card_brand()
raise IyzicoValueException(value_error)
def _card_brand(self):
number = str(self.card_number)
card_brand = "Invalid"
if len(number) == 15:
if number[:2] == "34" or number[:2] == "37":
card_brand = "AMEX"
if len(number) == 13:
if number[:1] == "4":
card_brand = "VISA"
if len(number) == 16:
if number[:4] == "6011":
card_brand = "DISCOVER"
if 51 <= int(number[:2]) <= 55:
card_brand = "MASTER"
if number[:1] == "4":
card_brand = "VISA"
return card_brand
def _find_connector(self):
if self._bin_response.card_brand == "Bonus":
return "Denizbank"
elif self._bin_response.card_brand == "Maximum":
return "Isbank"
elif self._bin_response.card_brand == "World":
return "Vakifbank"
if self._bin_response.bank_code == "12":
return "Halkbank"
elif self._bin_response.bank_code == "111":
return "Finansbank"
elif self._bin_response.bank_code == "208":
return "Bankasya"
return "Bankasya"
class IyzicoCustomer:
def __init__(self, customer_first_name=None,
customer_last_name=None,
customer_contact_email=None,):
if customer_first_name is None \
or customer_last_name is None\
or customer_first_name is None\
or len(customer_first_name.strip()) == 0\
or len(customer_last_name.strip()) == 0 \
or len(customer_contact_email.strip()) == 0:
return None
else:
self.customer_first_name = customer_first_name
self.customer_last_name = customer_last_name
self.customer_contact_email = customer_contact_email
@property
def customer_first_name(self):
return self.customer_first_name
@property
def customer_last_name(self):
return self.customer_last_name
@property
def customer_contact_email(self):
return self.customer_contact_email
class IyzicoCardToken:
def __init__(self, card_token,):
self.card_token = card_token
@property
def card_token(self):
return self.card_token
class IyzicoSettings:
def __init__(self, api_id=None, secret=None,
mode=None):
if api_id is not None and secret is not None and mode is not None:
self.api_id = api_id
self.secret = secret
self.mode = mode
else:
self.api_id = settings.api_id
self.secret = settings.api_secret
self.mode = settings.mode
@property
def api_id(self):
return self.api_id
@property
def secret(self):
return self.secret
@property
def mode(self):
return self.mode
class IyzicoPayloadBuilder:
payload = {}
def __init__(self, settings):
if not isinstance(settings, IyzicoSettings):
raise TypeError(str(self.__class__)
+ ": settings is not instance of "
+ str(IyzicoSettings))
self.settings = settings
self.reset()
def reset(self):
self.payload = {}
self._append_object(self.settings)
self.payload['response_mode'] = 'SYNC'
def debit_with_token(self, card_token, amount, descriptor,
currency, customer):
if not isinstance(card_token, IyzicoCardToken):
raise TypeError(str(self.__class__)
+ ": card_token is not instance of "
+ str(IyzicoCardToken))
self.reset()
self.payload['external_id'] = uuid.uuid1().hex
self._append_object(card_token)
self.payload["type"] = "DB"
self.payload["amount"] = self.format_amount(amount)
self.payload["currency"] = currency
self.payload["descriptor"] = descriptor
if customer is not None and isinstance(customer,
IyzicoCustomer):
self._append_object(customer)
return self.payload
def debit(self, card, amount, descriptor, currency,
customer=None, card_register=False,
installment=None):
if not isinstance(card, IyzicoCard):
raise TypeError(str(self.__class__)
+ ": card is not instance of "
+ str(IyzicoCard))
self.reset()
self._append_object(card)
self.payload['external_id'] = uuid.uuid1().hex
self.payload["type"] = "DB"
self.payload["amount"] = self.format_amount(amount)
self.payload["currency"] = currency
self.payload["descriptor"] = descriptor
if installment is not None and isinstance(installment, int) \
and installment > 1:
self.payload["connector_type"] = card.connector
self.payload["installment_count"] = str(int(installment))
if card_register:
self.payload["card_register"] = str(int(card_register))
if customer is not None and isinstance(customer,
IyzicoCustomer):
self._append_object(customer)
return self.payload
def register_card(self, card):
if not isinstance(card, IyzicoCard):
raise TypeError(str(self.__class__)
+ ": card is not instance of "
+ str(IyzicoCard))
self.reset()
self._append_object(card)
return self.payload
def delete_card(self, card_token):
if not isinstance(card_token, IyzicoCardToken):
raise TypeError(str(self.__class__)
+ ": card token is not instance of "
+ str(IyzicoCardToken))
self.reset()
self._append_object(card_token)
return self.payload
def pre_authorization(self, card, amount, descriptor, currency,
customer=None, ):
if not isinstance(card, IyzicoCard):
raise TypeError(str(self.__class__)
+ ": card is not instance of "
+ str(IyzicoCard))
self.reset()
self._append_object(card)
self.payload['external_id'] = uuid.uuid1().hex
self.payload["type"] = "PA"
self.payload["amount"] = self.format_amount(amount)
self.payload["currency"] = currency
self.payload["descriptor"] = descriptor
if customer is not None and isinstance(customer,
IyzicoCustomer):
self._append_object(customer)
return self.payload
def capture(self, transaction_id, amount, descriptor, currency,
customer=None, ):
self.reset()
self.payload['transaction_id'] = transaction_id
self.payload['external_id'] = uuid.uuid1().hex
self.payload["type"] = "CP"
self.payload["amount"] = self.format_amount(amount)
self.payload["currency"] = currency
self.payload["descriptor"] = descriptor
if customer is not None and isinstance(customer,
IyzicoCustomer):
self._append_object(customer)
return self.payload
def refund(self, transaction_id, amount, descriptor, currency,
customer=None,):
self.reset()
self.payload['transaction_id'] = transaction_id
self.payload['external_id'] = uuid.uuid1().hex
self.payload["type"] = "RF"
self.payload["amount"] = self.format_amount(amount)
self.payload["currency"] = currency
self.payload["descriptor"] = descriptor
if customer is not None and isinstance(customer,
IyzicoCustomer):
self._append_object(customer)
return self.payload
def reversal(self, transaction_id, amount, descriptor, currency,
customer=None,):
self.refund(transaction_id, amount, descriptor, currency,
customer)
self.payload["type"] = "RV"
return self.payload
def installment_matrix(self, amount, bin_number):
self.reset()
self.payload["bin_number"] = bin_number
self.payload["amount"] = self.format_amount(amount)
del self.payload["response_mode"]
return self.payload
def _append_object(self, obj):
for attr, value in obj.__dict__.iteritems():
if not attr.startswith('_'):
self.payload[attr] = value
@staticmethod
def format_amount(amount):
return str(int(100 * float("{:.2f}".format(amount))))
class IyzicoRequest():
@staticmethod
def execute(url, payload):
try:
raw_response = requests.post(url, payload)
response = IyzicoResponse(raw_response)
return response
except requests.RequestException as re:
raise IyzicoHTTPException(re.args, response=re.response)
except ValueError as value_error:
raise IyzicoValueException(value_error)
class IyzicoResponse():
def __init__(self, server_response):
self._raw_response = server_response
self._json_response = server_response.json()
self.response = self._json_response["response"]
self.error_message = None
self.error_code = None
self.transaction = None
self.transaction_id = None
self.transaction_state = None
self.reference_id = None
self.request_id = None
self.account = None
self.card_token = None
if self.response["state"] == "success":
self.success = True
try:
self.mode = self._json_response["mode"]
except KeyError:
self.mode = None
try:
self.transaction = self._json_response["transaction"]
self.transaction_id = \
self._json_response["transaction"]["transaction_id"]
self.transaction_state = \
self._json_response["transaction"]["state"]
self.reference_id = \
self._json_response["transaction"]["reference_id"]
except KeyError:
self.transaction = None
self.transaction_id = None
self.transaction_state = None
self.reference_id = None
try:
self.request_id = self.response["request_id"]
except KeyError:
self.request_id = None
try:
self.account = self._json_response["account"]
except KeyError:
self.account = None
try:
self.customer = self._json_response["customer"]
except KeyError:
self.customer = None
try:
self.card_token = self._json_response["card_token"]
except KeyError:
self.card_token = None
else:
self.success = False
try:
self.error_message = self.response["error_message"]
except KeyError:
self.error_message = None
try:
self.error_code = self.response["error_code"]
except KeyError:
self.error_code = None
@property
def response(self):
return self.response
@property
def mode(self):
return self.mode
@property
def card_token(self):
return self.card_token
@property
def transaction(self):
return self.transaction
@property
def customer(self):
return self.customer
@property
def account(self):
return self.account
@property
def success(self):
return self.success
class IyzicoBinResponse():
def __init__(self, server_response):
self._raw_response = server_response
self._json_response = server_response.json()
self.details = self._json_response["details"]
self.success = False
if self._json_response["status"] == "SUCCESS":
self.success = True
self.card_type = self.details["CARD_TYPE"]
self.bin = self.details["BIN"]
self.card_brand = self.details["BRAND"]
self.bank_code = self.details["BANK_CODE"]
self.issuer = self.details["ISSUER"]
@property
def success(self):
return self.success
@property
def card_type(self):
return self.card_type
@property
def bin(self):
return self.bin
@property
def card_brand(self):
return self.card_brand
@property
def bank_code(self):
return self.bank_code
@property
def issuer(self):
return self.issuer
@property
def details(self):
return self.details