-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathrave_payment.py
More file actions
496 lines (435 loc) · 19.3 KB
/
rave_payment.py
File metadata and controls
496 lines (435 loc) · 19.3 KB
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
import requests
import json
import copy
from rave_python.rave_base import RaveBase
from rave_python.rave_exceptions import RaveError, IncompletePaymentDetailsError, AuthMethodNotSupportedError, TransactionChargeError, TransactionVerificationError, TransactionValidationError, ServerError, RefundError, PreauthCaptureError
from rave_python.rave_misc import checkIfParametersAreComplete
response_object = {
"error": False,
"transactionComplete": False,
"flwRef": "",
"txRef": "",
"chargecode": '00',
"status": "",
"vbvcode": "",
"vbvmessage": "",
"acctmessage": "",
"currency": "",
"chargedamount": 00,
"chargemessage": "",
"meta": ""
}
# All payment subclasses are encrypted classes
class Payment(RaveBase):
""" This is the base class for all the payments """
def __init__(self, publicKey, secretKey, production, usingEnv):
# Instantiating the base class
super(
Payment,
self).__init__(
publicKey,
secretKey,
production,
usingEnv)
@classmethod
def retrieve(cls, mapping, *keys):
return (mapping[key] for key in keys)
@classmethod
def deleteUnnecessaryKeys(cls, response_dict, *keys):
for key in keys:
del response_dict[key]
return response_dict
def _preliminaryResponseChecks(self, response, TypeOfErrorToRaise, txRef=None, flwRef=None):
preliminary_error_response = copy.deepcopy(response_object)
preliminary_error_response = Payment.deleteUnnecessaryKeys(
preliminary_error_response,
"transactionComplete",
"chargecode",
"vbvmessage",
"vbvcode",
"acctmessage",
"currency"
)
# Check if we can obtain a json
try:
responseJson = response.json()
except BaseException:
raise ServerError(
{
"error": True,
"txRef": txRef,
"flwRef": flwRef,
"errMsg": response
}
)
# Check if the response contains data parameter
if responseJson.get("data", None):
if txRef:
flwRef = responseJson["data"].get("flwRef", None)
if flwRef:
txRef = responseJson["data"].get("txRef", None)
else:
raise TypeOfErrorToRaise(
{
"error": True,
"txRef": txRef,
"flwRef": flwRef,
"errMsg": responseJson.get("message","Server is down")
}
)
# Check if it is returning a 200
if not response.ok:
errMsg = responseJson["data"].get("message", None)
raise TypeOfErrorToRaise(
{
"error": True,
"txRef": txRef,
"flwRef": flwRef,
"errMsg": errMsg
}
)
return {
"json": responseJson,
"flwRef": flwRef,
"txRef": txRef
}
def _handleChargeResponse(self, response, txRef, request=None, isMpesa=False):
""" This handles transaction charge responses """
# If we cannot parse the json, it means there is a server error
res = self._preliminaryResponseChecks(
response, TransactionChargeError, txRef=txRef)
responseJson = res["json"]
if isMpesa:
return {
"error": False,
"status": responseJson["status"],
"validationRequired": True,
"txRef": txRef,
"flwRef": responseJson["data"]["flwRef"],
"narration": responseJson["data"]["narration"],
}
else:
# if all preliminary tests pass
if not (
responseJson["data"].get(
"chargeResponseCode",
None) == "00"):
if responseJson.get("message", 'None') == 'Momo initiated':
return {
"error": False,
"status": responseJson["status"],
"message": responseJson["message"],
"code": responseJson["data"]["code"],
"transaction status": responseJson["data"]["status"],
"ts": responseJson["data"]["ts"],
"link": responseJson["data"]["link"]
}
return {
"error": False,
"status": responseJson["status"],
"validationRequired": True,
"txRef": txRef,
"flwRef": responseJson["data"]["data"]["flw_reference"],
"chargeResponseMessage": responseJson["data"]["response_message"],
"redirect": responseJson["data"]["data"]["redirect"],
"type": responseJson["data"]["data"]["type"],
"provider": responseJson["data"]["data"]["provider"]
}
else:
return {
"error": True,
"validationRequired": False,
"txRef": txRef,
"flwRef": responseJson["data"]["flwRef"]}
def _handleCaptureResponse(self, response, request=None):
""" This handles transaction charge responses """
# If we cannot parse the json, it means there is a server error
res = self._preliminaryResponseChecks(
response, PreauthCaptureError, txRef='')
responseJson = res["json"]
flwRef = responseJson["data"]["flwRef"]
txRef = responseJson["data"]["txRef"]
# if all preliminary tests pass
if not (responseJson["data"].get("chargeResponseCode", None) == "00"):
return {
"error": False,
"validationRequired": True,
"txRef": txRef,
"flwRef": flwRef}
else:
return {
"error": False,
"status": responseJson["status"],
"message": responseJson["message"],
"validationRequired": False,
"txRef": txRef,
"flwRef": flwRef}
# This can be altered by implementing classes but this is the default behaviour
# Returns True and the data if successful
def _handleVerifyResponse(self, response, txRef):
""" This handles all responses from the verify call.\n
Parameters include:\n
response (dict) -- This is the response Http object returned from the verify call
"""
verify_response = copy.deepcopy(response_object)
res = self._preliminaryResponseChecks(
response, TransactionVerificationError, txRef=txRef)
responseJson = res["json"]
# retrieve necessary properties from response
verify_response["status"] = responseJson['status']
verify_response['flwRef'], verify_response["txRef"], verify_response["vbvcode"], verify_response["vbvmessage"], verify_response["acctmessage"], verify_response["currency"], verify_response["paymenttype"], verify_response["chargecode"], verify_response["amount"], verify_response[
"chargedamount"], verify_response["chargemessage"], verify_response["custname"], verify_response["custemail"], verify_response["custphone"], verify_response["meta"] = Payment.retrieve(responseJson['data'], "flwref", "txref", "vbvcode", "vbvmessage", "acctmessage", "currency", "paymenttype", "chargecode", "amount", "chargedamount", "chargemessage", "custname", "custemail", "custphone", "meta")
# Check if the chargecode is 00
if verify_response['chargecode'] == "00":
verify_response["error"] = False
verify_response["transactionComplete"] = True
return verify_response
else:
verify_response["error"] = True # changed to True on 15/10/2018
verify_response["transactionComplete"] = False
return verify_response
# # Check if the chargecode is 00
# if not (responseJson["data"].get("chargecode", None) == "00"):
# return {"error": False, "transactionComplete": False, "txRef": txRef,
# "flwRef":flwRef}
# else:
# return {"error": False, "transactionComplete": True, "txRef": txRef,
# "flwRef":flwRef}
# returns true if further action is required, false if it isn't
def _handleValidateResponse(self, response, flwRef, request=None):
""" This handles validation responses """
# If json is not parseable, it means there is a problem in server
res = self._preliminaryResponseChecks(
response, TransactionValidationError, flwRef=flwRef)
responseJson = res["json"]
if responseJson["data"].get("tx") is None:
txRef = responseJson["data"]["txRef"]
else:
txRef = responseJson["data"]["tx"]["txRef"]
# Of all preliminary checks passed
if not (
responseJson["data"].get(
"tx",
responseJson["data"]).get(
"chargeResponseCode",
None) == "00"):
errMsg = responseJson["data"].get(
"tx", responseJson["data"]).get(
"chargeResponseMessage", None)
raise TransactionValidationError(
{"error": True, "txRef": txRef, "flwRef": flwRef, "errMsg": errMsg})
else:
return {
"status": responseJson["status"],
"message": responseJson["message"],
"error": False,
"txRef": txRef,
"flwRef": flwRef}
# Charge function (hasFailed is a flag that indicates there is a timeout),
# shouldReturnRequest indicates whether to send the request back to the
# _handleResponses function
def charge(
self,
feature_name,
paymentDetails,
requiredParameters,
endpoint,
shouldReturnRequest=False,
isMpesa=False):
""" This is the base charge call. It is usually overridden by implementing classes.\n
Parameters include:\n
paymentDetails (dict) -- These are the parameters passed to the function for processing\n
requiredParameters (list) -- These are the parameters required for the specific call\n
hasFailed (boolean) -- This is a flag to determine if the attempt had previously failed due to a timeout\n
shouldReturnRequest -- This determines whether a request is passed to _handleResponses\n
"""
# Checking for required components
try:
checkIfParametersAreComplete(requiredParameters, paymentDetails)
except BaseException:
raise
# Performing shallow copy of payment details to prevent tampering with
# original
paymentDetails = copy.copy(paymentDetails)
# Adding PBFPubKey param to paymentDetails
paymentDetails.update({"PBFPubKey": self._getPublicKey()})
# Collating request headers
headers = {
'content-type': 'application/json',
}
if "token" in paymentDetails:
paymentDetails.update({"SECKEY": self._getSecretKey()})
# print(json.dumps(paymentDetails))
response = requests.post(
endpoint,
headers=headers,
data=json.dumps(paymentDetails))
else:
# Encrypting payment details (_encrypt is inherited from
# RaveEncryption)
encryptedPaymentDetails = self._encrypt(json.dumps(paymentDetails))
# Collating the payload for the request
payload = {
"PBFPubKey": paymentDetails["PBFPubKey"],
"client": encryptedPaymentDetails,
"alg": "3DES-24"
}
response = requests.post(
endpoint, headers=headers, data=json.dumps(payload))
if shouldReturnRequest:
if isMpesa:
return self._handleChargeResponse(
response, paymentDetails["txRef"], paymentDetails, True)
return self._handleChargeResponse(
response, paymentDetails["txRef"], paymentDetails)
else:
if isMpesa:
return self._handleChargeResponse(
response, paymentDetails["txRef"], paymentDetails, True)
return self._handleChargeResponse(
response, paymentDetails["txRef"])
# print (paymentDetails, endpoint, headers, json.dumps(payload))
# return response.json()
def validate(self, feature_name, flwRef, otp, endpoint=None):
""" This is the base validate call.\n
Parameters include:\n
flwRef (string) -- This is the flutterwave reference returned from a successful charge call. You can access this from action["flwRef"] returned from the charge call\n
otp (string) -- This is the otp sent to the user \n
"""
if not endpoint:
endpoint = self._baseUrl + self._endpointMap["account"]["validate"]
# Collating request headers
headers = {
'content-type': 'application/json',
}
payload = {
"PBFPubKey": self._getPublicKey(),
"transactionreference": flwRef,
"transaction_reference": flwRef,
"otp": otp
}
response = requests.post(
endpoint,
headers=headers,
data=json.dumps(payload))
# feature logging
if response.ok:
tracking_endpoint = self._trackingMap
responseTime = response.elapsed.total_seconds()
tracking_payload = {
"publicKey": self._getPublicKey(),
"language": "Python v2",
"version": "1.2.13",
"title": feature_name,
"message": responseTime}
tracking_response = requests.post(
tracking_endpoint, data=json.dumps(tracking_payload))
else:
tracking_endpoint = self._trackingMap
responseTime = response.elapsed.total_seconds()
tracking_payload = {
"publicKey": self._getPublicKey(),
"language": "Python v2",
"version": "1.2.13",
"title": feature_name + "-error",
"message": responseTime}
tracking_response = requests.post(
tracking_endpoint, data=json.dumps(tracking_payload))
return self._handleValidateResponse(response, flwRef)
# Verify charge
def verify(self, feature_name, txRef, endpoint=None):
""" This is used to check the status of a transaction.\n
Parameters include:\n
txRef (string) -- This is the transaction reference that you passed to your charge call. If you didn't define a reference, you can access the auto-generated one from payload["txRef"] or action["txRef"] from the charge call\n
"""
if not endpoint:
endpoint = self._baseUrl + self._endpointMap["verify"]
# Collating request headers
headers = {
'content-type': 'application/json',
}
# Payload for the request headers
payload = {
"txref": txRef,
"SECKEY": self._getSecretKey()
}
response = requests.post(
endpoint,
headers=headers,
data=json.dumps(payload))
# feature logging
if response.ok:
tracking_endpoint = self._trackingMap
responseTime = response.elapsed.total_seconds()
tracking_payload = {
"publicKey": self._getPublicKey(),
"language": "Python v2",
"version": "1.2.13",
"title": feature_name,
"message": responseTime}
tracking_response = requests.post(
tracking_endpoint, data=json.dumps(tracking_payload))
else:
tracking_endpoint = self._trackingMap
responseTime = response.elapsed.total_seconds()
tracking_payload = {
"publicKey": self._getPublicKey(),
"language": "Python v2",
"version": "1.2.13",
"title": feature_name + "-error",
"message": responseTime}
tracking_response = requests.post(
tracking_endpoint, data=json.dumps(tracking_payload))
return self._handleVerifyResponse(response, txRef)
# Refund call
def refund(self, feature_name, flwRef, amount, ):
""" This is used to refund a transaction from any of Rave's component objects.\n
Parameters include:\n
flwRef (string) -- This is the flutterwave reference returned from a successful call from any component. You can access this from action["flwRef"] returned from the charge call
"""
payload = {
"ref": flwRef,
"seckey": self._getSecretKey(),
"amount": amount,
}
headers = {
"Content-Type": "application/json"
}
endpoint = self._baseUrl + self._endpointMap["refund"]
response = requests.post(
endpoint,
headers=headers,
data=json.dumps(payload))
# feature logging
if response.ok:
tracking_endpoint = self._trackingMap
responseTime = response.elapsed.total_seconds()
tracking_payload = {
"publicKey": self._getPublicKey(),
"language": "Python v2",
"version": "1.2.13",
"title": feature_name,
"message": responseTime}
tracking_response = requests.post(
tracking_endpoint, data=json.dumps(tracking_payload))
else:
tracking_endpoint = self._trackingMap
responseTime = response.elapsed.total_seconds()
tracking_payload = {
"publicKey": self._getPublicKey(),
"language": "Python v2",
"version": "1.2.13",
"title": feature_name + "-error",
"message": responseTime}
tracking_response = requests.post(
tracking_endpoint, data=json.dumps(tracking_payload))
try:
responseJson = response.json()
except ValueError:
raise ServerError(response)
if responseJson.get("status", None) == "error":
raise RefundError(responseJson.get("message", None))
elif responseJson.get("status", None) == "success":
return True, responseJson.get("data", None)
# responseJson =response.json()
# return responseJson.get("data", None)