-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathRocketGate.py
More file actions
1188 lines (1037 loc) · 44.8 KB
/
RocketGate.py
File metadata and controls
1188 lines (1037 loc) · 44.8 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
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
""""
Copyright notice:
(c) Copyright 2024 RocketGate
All rights reserved.
The copyright notice must not be removed without specific, prior
written permission from RocketGate.
This software is protected as an unpublished work under the U.S. copyright
laws. The above copyright notice is not intended to effect a publication of
this work.
This software is the confidential and proprietary information of RocketGate.
Neither the binaries nor the source code may be redistributed without prior
written permission from RocketGate.
The software is provided "as-is" and without warranty of any kind, express, implied
or otherwise, including without limitation, any warranty of merchantability or fitness
for a particular purpose. In no event shall RocketGate be liable for any direct,
special, incidental, indirect, consequential or other damages of any kind, or any damages
whatsoever arising out of or in connection with the use or performance of this software,
including, without limitation, damages resulting from loss of use, data or profits, and
whether or not advised of the possibility of damage, regardless of the theory of liability.
"""
import xml.sax
import http.client
import random
import socket
import ssl
from urllib.parse import urlsplit
class GatewayRequest:
VERSION_INDICATOR = "version"
VERSION_NUMBER = "PY3.8"
######################################################################
#
# Define constant hash values.
#
######################################################################
ACCOUNT_HOLDER = "accountHolder"
ACCOUNT_NO = "accountNo"
AFFILIATE = "affiliate"
ALLOW_CARD_DEBIT_CREDIT = "ALLOW_CARD_DEBIT_CREDIT"
AMOUNT = "amount"
AVS_CHECK = "avsCheck"
BILLING_ADDRESS = "billingAddress"
BILLING_CITY = "billingCity"
BILLING_COUNTRY = "billingCountry"
BILLING_STATE = "billingState"
BILLING_TYPE = "billingType"
BILLING_ZIPCODE = "billingZipCode"
BROWSER_ACCEPT_HEADER = "browserAcceptHeader"
BROWSER_COLOR_DEPTH = "BrowserColorDepth"
BROWSER_JAVA_ENABLED = "BrowserJavaEnabled"
BROWSER_LANGUAGE = "BrowserLanguage"
BROWSER_SCREEN_HEIGHT = "BrowserScreenHeight"
BROWSER_SCREEN_WIDTH = "BrowserScreenWidth"
BROWSER_TIME_ZONE = "BrowserTimeZone"
BROWSER_USER_AGENT = "browserUserAgent"
CAPTURE_DAYS = "captureDays"
CARDNO = "cardNo"
CARD_HASH = "cardHash"
CLONE_CUSTOMER_RECORD = "cloneCustomerRecord"
CLONE_TO_CUSTOMER_ID = "cloneToCustomerID"
COF_FRAMEWORK = "cofFramework"
CURRENCY = "currency"
CUSTOMER_FIRSTNAME = "customerFirstName"
CUSTOMER_LASTNAME = "customerLastName"
CUSTOMER_PASSWORD = "customerPassword"
CUSTOMER_PHONE_NO = "customerPhoneNo"
CVV2 = "cvv2"
CVV2_CHECK = "cvv2Check"
EMAIL = "email"
EMBEDDED_FIELDS_TOKEN = "embeddedFieldsToken"
EXPIRE_MONTH = "expireMonth"
EXPIRE_YEAR = "expireYear"
FAILED_GUID = "failedGUID"
FAILED_REASON_CODE = "failedReasonCode"
FAILED_RESPONSE_CODE = "failedResponseCode"
FAILED_SERVER = "failedServer"
FAILURE_URL = "FAILUREURL"
GATEWAY_CONNECT_TIMEOUT = "gatewayConnectTimeout"
GATEWAY_PORTNO = "gatewayPortNo"
GATEWAY_PROTOCOL = "gatewayProtocol"
GATEWAY_READ_TIMEOUT = "gatewayReadTimeout"
GATEWAY_SERVER = "gatewayServer"
GATEWAY_SERVLET = "gatewayServlet"
GATEWAY_URL = "gatewayURL"
GENERATE_POSTBACK = "generatePostback"
GOOGLE_PAY_TOKEN = "GOOGLEPAYTOKEN"
IOVATION_BLACK_BOX = "iovationBlackBox"
IOVATION_RULE = "iovationRule"
IPADDRESS = "ipAddress"
LANGUAGE = "LANGUAGE"
MERCHANT_ACCOUNT = "merchantAccount"
MERCHANT_CASCADED_AUTH = "MERCHANTCASCADEDAUTH"
MERCHANT_CUSTOMER_ID = "merchantCustomerID"
MERCHANT_DESCRIPTOR = "merchantDescriptor"
MERCHANT_DESCRIPTOR_CITY = "merchantDescriptorCity"
MERCHANT_DESCRIPTOR_TRIAL = "merchantDescriptorTrial"
MERCHANT_ID = "merchantID"
MERCHANT_INVOICE_ID = "merchantInvoiceID"
MERCHANT_PASSWORD = "merchantPassword"
MERCHANT_PRODUCT_ID = "merchantProductID"
MERCHANT_SITE_ID = "merchantSiteID"
OMIT_RECEIPT = "omitReceipt"
ONCLICK_LOGO_URL = "onClickLogoURL"
PARES = "PARES"
PARTIAL_AUTH_FLAG = "partialAuthFlag"
PAYINFO_TRANSACT_ID = "payInfoTransactID"
PAYMENT_LINK_TOKEN = "PAYMENTLINKTOKEN"
PREFERRED_MERCHANT_ACCOUNT = "preferredMerchantAccount"
PROCESSOR_3DS = "PROCESSOR3DS"
REBILL_AMOUNT = "rebillAmount"
REBILL_COUNT = "rebillCount"
REBILL_END_DATE = "rebillEndDate"
REBILL_FREQUENCY = "rebillFrequency"
REBILL_REACTIVATE = "REBILLREACTIVATE"
REBILL_RESCHEDULE = "REBILLRESCHEDULE"
REBILL_RESUME = "rebillResume"
REBILL_START = "rebillStart"
REBILL_SUSPEND = "rebillSuspend"
REFERENCE_GUID = "referenceGUID"
REFERENCE_SCHEME_SETTLEMENT_DATE = "schemeSettleDate"
REFERENCE_SCHEME_TRANSACTION_ID = "schemeTranId"
REFERRAL_NO = "referralNo"
REFERRED_CUSTOMER_ID = "referredCustomerID"
REFERRER_URL = "referrerURL"
REFERRING_MERCHANT_ID = "referringMerchantID"
ROUTING_NO = "routingNo"
SAVINGS_ACCOUNT = "savingsAccount"
SCRUB = "scrub"
SCRUB_ACTIVITY = "scrubActivity"
SCRUB_NEGDB = "scrubNegDB"
SCRUB_PROFILE = "scrubProfile"
SHOW_PAYMENT_FORM = "SHOW_PAYMENT_FORM"
SS_NUMBER = "ssNumber"
STYLE_SHEET = "style"
STYLE_SHEET2 = "style2"
STYLE_SHEET3 = "style3"
SUB_MERCHANT_ID = "subMerchantID"
SUCCESS_URL = "SUCCESSURL"
THREATMETRIX_SESSION_ID = "threatMetrixSessionID"
TRANSACTION_TYPE = "transactionType"
TRANSACT_ID = REFERENCE_GUID
TRANSLATIONS = "translations"
UDF01 = "udf01"
UDF02 = "udf02"
USERNAME = "username"
USE_3D_SECURE = "use3DSecure"
USE_PRIMARY_SCHEMEID = "usePrimarySchemeID"
XSELL_CUSTOMER_ID = "xsellCustomerID"
XSELL_MERCHANT_ACCOUNT = "xsellMerchantAccount"
XSELL_MERCHANT_ID = "xsellMerchantID"
XSELL_REFERENCE_XACT = "xsellReferenceXact"
_3DSECURE_ACS_TRANSACTION_ID = "_3DSECURE_ACS_TRANSACTION_ID"
_3DSECURE_ACS_WINDOW_SIZE = "_3DSECURE_ACS_WINDOW_SIZE"
"""
An override field that a merchant can pass in to set the challenge window size to display to the end cardholder.
The ACS will reply with content that is formatted appropriately to this window size to allow for the best user
experience.
The sizes are width x height in pixels of the window displayed in the cardholder browser window.
The possible values are:
- 01 (250x400)
- 02 (390x400)
- 03 (500x600)
- 04 (600x400)
- 05 (Full page)
"""
_3DSECURE_CHALLENGE_MANDATED_INDICATOR = "_3DSECURE_CHALLENGE_MANDATED_INDICATOR"
_3DSECURE_DF_REFERENCE_ID = "_3DSECURE_DF_REFERENCE_ID"
_3DSECURE_DS_TRANSACTION_ID = "_3DSECURE_DS_TRANSACTION_ID"
_3DSECURE_LOOKUP_CHALLENGE_INDICATOR = "_3DSECURE_LOOKUP_CHALLENGE_INDICATOR"
"""
Whether or not to request a challenge step-up flow from the ACS
- 01 - No preference
- 02 - No challenge requested
- 03 - Challenge requested (3DS Requestor Preference)
- 04 - Challenge requested (Mandate)
"""
_3DSECURE_REDIRECT_URL = "_3DSECURE_REDIRECT_URL"
_3DSECURE_THREE_DS_SERVER_TRANSACTION_ID = "_3DSECURE_THREE_DS_SERVER_TRANSACTION_ID"
_3D_CAVV_ALGORITHM = "THREEDCAVVALGORITHM"
_3D_CAVV_UCAF = "ThreeDCavvUcaf"
_3D_CHECK = "ThreeDCheck"
_3D_ECI = "ThreeDECI"
_3D_PARESSTATUS = "THREEDPARESSTATUS"
_3D_VERSION = "THREEDVERSION"
_3D_VERSTATUS = "THREEDVERSTATUS"
_3D_XID = "ThreeDXID"
def __init__(self):
"""Constructor for class."""
self.parameterList = {}
self.Set(GatewayRequest.VERSION_INDICATOR, GatewayRequest.VERSION_NUMBER)
def Set(self, key, value):
"""Sets a value in the parameter list."""
self.Clear(key) # Have key value? Delete it
if value is not None:
self.parameterList[key] = str(value) # Save the value
def Clear(self, key):
"""Clears a value in the parameter list."""
if key in self.parameterList: # Have key value?
del self.parameterList[key] # Delete it
def Get(self, key):
"""Gets a value from the parameter list."""
if key in self.parameterList: # Have key value?
return self.parameterList[key] # Return the value
return None # Don't have a value
def ToXML(self):
"""Creates an XML document from the hash list."""
#
# Build the document header.
#
xmlDocument = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
xmlDocument += "<gatewayRequest>"
#
# Loop over each key-value pairs and create
# and open tag for the key.
#
for key, value in self.parameterList.items():
xmlDocument += "<"
xmlDocument += key
xmlDocument += ">"
#
# Clean up the value and add it to the tag.
#
myValue = str(value) # In case it's not a string
myValue = myValue.replace("&", "&")
myValue = myValue.replace("<", "<")
myValue = myValue.replace(">", ">")
xmlDocument += myValue
#
#
# Add the closing tag for this element.
#
xmlDocument += "</"
xmlDocument += key
xmlDocument += ">"
#
# Close and return the document.
#
xmlDocument += "</gatewayRequest>"
return xmlDocument # Final document
class GatewayResponse(xml.sax.handler.ContentHandler):
VERSION_INDICATOR = "version"
######################################################################
#
# Define constant hash values.
#
######################################################################
ACS_URL = "acsURL"
AUTH_NO = "authNo"
AVS_RESPONSE = "avsResponse"
BALANCE_AMOUNT = "balanceAmount"
BALANCE_CURRENCY = "balanceCurrency"
BANK_RESPONSE_CODE = "bankResponseCode"
BILLING_ADDRESS = "billingAddress"
BILLING_CITY = "billingCity"
BILLING_COUNTRY = "billingCountry"
BILLING_STATE = "billingState"
BILLING_ZIPCODE = "billingZipCode"
CARD_BIN = "cardBin"
CARD_COUNTRY = "cardCountry"
CARD_DEBIT_CREDIT = "cardDebitCredit"
CARD_DESCRIPTION = "cardDescription"
CARD_EXPIRATION = "cardExpiration"
CARD_HASH = "cardHash"
CARD_ISSUER_NAME = "cardIssuerName"
CARD_ISSUER_PHONE = "cardIssuerPhone"
CARD_ISSUER_URL = "cardIssuerURL"
CARD_LAST_FOUR = "cardLastFour"
CARD_REGION = "cardRegion"
CARD_TYPE = "cardType"
CAVV_RESPONSE = "cavvResponse"
CUSTOMER_FIRSTNAME = "customerFirstName"
CUSTOMER_LASTNAME = "customerLastName"
CVV2_CODE = "cvv2Code"
ECI = "ECI"
EMAIL = "email"
EXCEPTION = "exception"
IOVATION_DEVICE = "IOVATIONDEVICE"
IOVATION_RESULTS = "IOVATIONRESULTS"
IOVATION_RULE_COUNT = "IOVATIONRULECOUNT"
IOVATION_RULE_REASON_ = "IOVATIONRULEREASON_"
IOVATION_RULE_SCORE_ = "IOVATIONRULESCORE_"
IOVATION_RULE_TYPE_ = "IOVATIONRULETYPE_"
IOVATION_SCORE = "IOVATIONSCORE"
IOVATION_TRACKING_NO = "IOVATIONTRACKINGNO"
IS_BANK_HARD_DECLINE = "isBankHardDecline"
JOIN_AMOUNT = "joinAmount"
JOIN_DATE = "joinDate"
LAST_BILLING_AMOUNT = "lastBillingAmount"
LAST_BILLING_DATE = "lastBillingDate"
LAST_REASON_CODE = "lastReasonCode"
MERCHANT_ACCOUNT = "merchantAccount"
MERCHANT_ADVICE_CODE = "merchantAdviceCode"
MERCHANT_CUSTOMER_ID = "merchantCustomerID"
MERCHANT_INVOICE_ID = "merchantInvoiceID"
MERCHANT_PRODUCT_ID = "merchantProductID"
MERCHANT_SITE_ID = "merchantSiteID"
PAREQ = "PAREQ"
PARES = "PARES"
PAYMENT_LINK_URL = "PAYMENT_LINK_URL"
PAY_HASH = CARD_HASH
PAY_LAST_FOUR = CARD_LAST_FOUR
PAY_TYPE = "payType"
PROCESSOR_3DS = "PROCESSOR3DS"
REASON_CODE = "reasonCode"
REBILL_AMOUNT = "rebillAmount"
REBILL_CURRENCY = "rebillCurrency"
REBILL_DATE = "rebillDate"
REBILL_END_DATE = "rebillEndDate"
REBILL_FREQUENCY = "rebillFrequency"
REBILL_STATUS = "rebillStatus"
RESPONSE_CODE = "responseCode"
RETRIEVAL_ID = "retrievalNo"
ROCKETPAY_INDICATOR = "rocketPayIndicator"
SCHEME_SETTLEMENT_DATE = "schemeSettlementDate"
SCHEME_TRANSACTION_ID = "schemeTransactionID"
SCRUB_RESULTS = "scrubResults"
SETTLED_AMOUNT = "approvedAmount"
SETTLED_CURRENCY = "approvedCurrency"
TRANSACTION_TIME = "transactionTime"
TRANSACT_ID = "guidNo"
_3DSECURE_ACS_TRANSACTION_ID = "_3DSECURE_ACS_TRANSACTION_ID"
_3DSECURE_CAVV_ALGORITHM = "_3DSECURE_CAVV_ALGORITHM"
_3DSECURE_CAVV_UCAF = "_3DSECURE_CAVV_UCAF"
_3DSECURE_CHALLENGE_MANDATED_INDICATOR = "_3DSECURE_CHALLENGE_MANDATED_INDICATOR"
_3DSECURE_DEVICE_COLLECTION_JWT = "_3DSECURE_DEVICE_COLLECTION_JWT"
_3DSECURE_DEVICE_COLLECTION_URL = "_3DSECURE_DEVICE_COLLECTION_URL"
_3DSECURE_DS_TRANSACTION_ID = "_3DSECURE_DS_TRANSACTION_ID"
_3DSECURE_LOOKUP_CHALLENGE_INDICATOR = "_3DSECURE_LOOKUP_CHALLENGE_INDICATOR"
_3DSECURE_LOOKUP_REFERENCE_GUID = "_3D_LOOKUP_REFERENCE_GUID"
_3DSECURE_LOOKUP_SIGNATURE = "_3DSECURE_LOOKUP_SIGNATURE"
_3DSECURE_PARESSTATUS = "_3DSECURE_PARESSTATUS"
_3DSECURE_STEP_UP_JWT = "_3DSECURE_STEP_UP_JWT"
_3DSECURE_STEP_UP_URL = "_3DSECURE_STEP_UP_URL"
_3DSECURE_THREE_DS_SERVER_TRANSACTION_ID = "_3DSECURE_THREE_DS_SERVER_TRANSACTION_ID"
_3DSECURE_VERSION = "_3DSECURE_VERSION"
_3DSECURE_VERSTATUS = "_3DSECURE_VERSTATUS"
_3DSECURE_XID = "_3DSECURE_XID"
def __init__(self):
"""Constructor for class."""
self.parameterList = {} # Fresh list
self.haveOpenTag = 0 # Haven't seen <gatewayResponse>
self.valueBuffer = "" # No value yet
def Set(self, key, value):
"""Sets a value in the parameter list."""
if key in self.parameterList: # Have key value?
del self.parameterList[key] # Delete it
if value is not None:
self.parameterList[key] = str(value) # Save the value
def Reset(self):
"""Clears all elements in a response."""
del self.parameterList # Kill old list
self.parameterList = {} # Start with fresh list
def Get(self, key):
"""Gets a value from the parameter list."""
if key in self.parameterList: # Have key value?
return self.parameterList[key] # Return the value
return None # Don't have a value
def SetFromXML(self, xmlDocument):
"""Sets values in a response object using an XML document."""
#
# Initialize the parsing.
#
self.haveOpenTag = 0 # Haven't tried to open
self.valueBuffer = "" # No value yet
#
# Parse the input string.
#
try:
xml.sax.parseString(xmlDocument, self)
#
# If there was a parsing error, set the error codes and quit.
#
except xml.sax.SAXException as ex:
self.Set(GatewayResponse.EXCEPTION, ex.getMessage() + ": " + xmlDocument)
self.Set(GatewayResponse.RESPONSE_CODE, GatewayCodes.RESPONSE_REQUEST_ERROR)
self.Set(GatewayResponse.REASON_CODE, GatewayCodes.REASON_XML_ERROR)
#
# If there was some other type of exception, set the error codes and quit.
#
except:
self.Set(GatewayResponse.EXCEPTION, "Unhandled exception: " + xmlDocument)
self.Set(GatewayResponse.RESPONSE_CODE, GatewayCodes.RESPONSE_SYSTEM_ERROR)
self.Set(GatewayResponse.REASON_CODE, GatewayCodes.REASON_BUGCHECK)
def startElement(self, name, attrs):
"""Handler for start of XML element."""
if name == "gatewayResponse": # Opening of document?
self.haveOpenTag = 1 # Have seen open tag
self.valueBuffer = "" # Start with clean value
def characters(self, data):
"""Handler for element string"""
if self.haveOpenTag: # Seen open yet?
self.valueBuffer += data
def endElement(self, name):
"""Handler for end of XML element."""
if name != "gatewayResponse": # Opening of document?
self.Set(name, self.valueBuffer)
class GatewayService:
######################################################################
#
# Define constants
#
######################################################################
ROCKETGATE_SERVLET = "/gateway/servlet/ServiceDispatcherAccess"
ROCKETGATE_CONNECT_TIMEOUT = 10
ROCKETGATE_READ_TIMEOUT = 90
ROCKETGATE_PORTNO = 443
ROCKETGATE_USER_AGENT = "RG Client - Python " + str(GatewayRequest.VERSION_NUMBER)
LIVE_HOST = "gateway.rocketgate.com"
LIVE_HOST_16 = "gateway-16.rocketgate.com"
LIVE_HOST_17 = "gateway-17.rocketgate.com"
TEST_HOST = "dev-gateway.rocketgate.com"
def __init__(self):
"""Constructor for class."""
self.testMode = 0 # Default to live
self.rocketGateHost = GatewayService.LIVE_HOST
self.rocketGateServlet = GatewayService.ROCKETGATE_SERVLET
self.rocketGatePortNo = GatewayService.ROCKETGATE_PORTNO
self.rocketGateConnectTimeout = GatewayService.ROCKETGATE_CONNECT_TIMEOUT
self.rocketGateReadTimeout = GatewayService.ROCKETGATE_READ_TIMEOUT
def SetTestMode(self, yesNo):
"""Selects test/development mode."""
if yesNo: # Setting test mode?
self.testMode = 1 # Set to test mode
del self.rocketGateHost # Delete old host list
self.rocketGateHost = GatewayService.TEST_HOST
else:
self.testMode = 0 # Set to live mode
del self.rocketGateHost # Delete old host list
self.rocketGateHost = GatewayService.LIVE_HOST
def SetHost(self, hostName):
"""Sets the host used by the service"""
del self.rocketGateHost # Delete old host list
self.rocketGateHost = hostName # Use this host
def SetPortNo(self, portNo):
"""Sets the port number used by the service."""
try:
value = int(portNo) # Get numeric value
if value > 0: # Have a valid value?
self.rocketGatePortNo = value
except:
pass
def SetServlet(self, servlet):
"""Sets servlet used by the service."""
self.rocketGateServlet = servlet # End point
def SetConnectTimeout(self, timeout):
"""Sets connection timeout"""
try:
value = int(timeout) # Get numeric value
if value > 0: # Have a valid value?
self.rocketGateConnectTimeout = value
except:
pass
def SetReadTimeout(self, timeout):
"""Sets read timeout"""
try:
value = int(timeout) # Get numeric value
if value > 0: # Have a valid value?
self.rocketGateReadTimeout = value
except:
pass
def SendTransaction(self, serverName, request, response):
"""Sends a transaction to a named host."""
#
# Gather overrides for transaction.
#
connection = None
urlServlet = request.Get(GatewayRequest.GATEWAY_SERVLET)
urlPortNo = request.Get(GatewayRequest.GATEWAY_PORTNO)
#
# Determine the final servlet name.
#
if urlServlet is None: # None specified?
urlServlet = self.rocketGateServlet
#
# Determine the final port number.
#
if urlPortNo is None:
urlPortNo = self.rocketGatePortNo
else:
try:
int(urlPortNo) # Make sure this is numeric
except:
urlPortNo = self.rocketGatePortNo
#
# Get the connection timeout.
#
connectTimeout = request.Get("gatewayConnectTimeout")
if connectTimeout is None:
connectTimeout = self.rocketGateConnectTimeout
else:
try:
int(connectTimeout) # Make sure this is numeric
except:
connectTimeout = self.rocketGateConnectTimeout
#
# Get the read timeout.
#
readTimeout = request.Get("gatewayReadTimeout")
if readTimeout is None:
readTimeout = self.rocketGateReadTimeout
else:
try:
int(readTimeout) # Make sure this is numeric
except:
readTimeout = self.rocketGateReadTimeout
#
# Prepare the values that will go into the post operation.
#
response.Reset() # Clear any response data
requestXML = request.ToXML() # Get message string
headers = {"Content-Type": "text/xml", "User-Agent": GatewayService.ROCKETGATE_USER_AGENT}
#
# Create the HTTP handler and post our request.
#
try:
connection = http.client.HTTPSConnection(serverName, urlPortNo, timeout=connectTimeout)
connection.request("POST", urlServlet, requestXML, headers)
connection.sock.settimeout(readTimeout)
#
# Read the response.
#
results = connection.getresponse()
body = results.read() # Get the response data
if isinstance(body, bytes):
body = body.decode("utf-8")
#
# If the response was not '200 OK', we must quit
#
if results.status != 200:
response.Set(GatewayResponse.EXCEPTION, str(results.status) + ": " + body)
response.Set(GatewayResponse.RESPONSE_CODE, GatewayCodes.RESPONSE_SYSTEM_ERROR)
response.Set(GatewayResponse.REASON_CODE, GatewayCodes.REASON_RESPONSE_READ_ERROR)
return GatewayCodes.RESPONSE_SYSTEM_ERROR # System error
#
# If there was a timeout, return an error.
#
except socket.timeout as ex:
response.Set(GatewayResponse.EXCEPTION, str(ex))
response.Set(GatewayResponse.RESPONSE_CODE, GatewayCodes.RESPONSE_SYSTEM_ERROR)
response.Set(GatewayResponse.REASON_CODE, GatewayCodes.REASON_UNABLE_TO_CONNECT)
return GatewayCodes.RESPONSE_SYSTEM_ERROR # System error
#
# If the read timed out, return an error.
#
except ssl.SSLError as ex:
response.Set(GatewayResponse.EXCEPTION, str(ex))
response.Set(GatewayResponse.RESPONSE_CODE, GatewayCodes.RESPONSE_SYSTEM_ERROR)
response.Set(GatewayResponse.REASON_CODE, GatewayCodes.REASON_RESPONSE_READ_TIMEOUT)
return GatewayCodes.RESPONSE_SYSTEM_ERROR # System error
#
# If there was some other type of socket problem, return an error.
#
except socket.error as ex:
response.Set(GatewayResponse.EXCEPTION, str(ex))
response.Set(GatewayResponse.RESPONSE_CODE, GatewayCodes.RESPONSE_SYSTEM_ERROR)
exString = str(ex)
if 'Connection refused' in exString:
response.Set(GatewayResponse.REASON_CODE, GatewayCodes.REASON_UNABLE_TO_CONNECT)
else:
response.Set(GatewayResponse.REASON_CODE, GatewayCodes.REASON_RESPONSE_READ_ERROR)
return GatewayCodes.RESPONSE_SYSTEM_ERROR # System error
#
# Catch general exceptions.
#
except Exception as ex:
response.Set(GatewayResponse.EXCEPTION, str(ex))
response.Set(GatewayResponse.RESPONSE_CODE, GatewayCodes.RESPONSE_SYSTEM_ERROR)
response.Set(GatewayResponse.REASON_CODE, GatewayCodes.REASON_RESPONSE_READ_ERROR)
return GatewayCodes.RESPONSE_SYSTEM_ERROR # System error
#
# Other exceptions must be caught too.
#
except:
response.Set(GatewayResponse.EXCEPTION, "Unhandled POST exception")
response.Set(GatewayResponse.RESPONSE_CODE, GatewayCodes.RESPONSE_SYSTEM_ERROR)
response.Set(GatewayResponse.REASON_CODE, GatewayCodes.REASON_RESPONSE_READ_ERROR)
return GatewayCodes.RESPONSE_SYSTEM_ERROR # System error
#
# Clean up the connection when we are all done.
#
finally:
if connection is not None:
connection.close() # Done with connection
#
# Parse the response XML and return the response code.
#
response.SetFromXML(body) # Set from response body
response_code = response.Get(GatewayResponse.RESPONSE_CODE)
reason_code = response.Get(GatewayResponse.REASON_CODE)
if response_code is None or reason_code is None:
response.Set(GatewayResponse.RESPONSE_CODE, GatewayCodes.RESPONSE_REQUEST_ERROR)
response.Set(GatewayResponse.REASON_CODE, GatewayCodes.REASON_XML_ERROR)
return response.Get(GatewayResponse.RESPONSE_CODE) # Give back results
def PerformTransaction(self, request, response):
"""Performs the transaction described in a gateway request."""
#
# If EMBEDDED_FIELDS_TOKEN is provided, send the request to the corresponding endpoint
#
fullUrl = request.Get(GatewayRequest.GATEWAY_URL)
if fullUrl is None:
if request.Get(GatewayRequest.PAYMENT_LINK_TOKEN) is not None:
fullUrl = request.Get(GatewayRequest.PAYMENT_LINK_TOKEN)
elif request.Get(GatewayRequest.EMBEDDED_FIELDS_TOKEN) is not None:
fullUrl = request.Get(GatewayRequest.EMBEDDED_FIELDS_TOKEN)
if fullUrl is not None:
try:
parsedUrl = urlsplit(fullUrl)
request.Set(GatewayRequest.GATEWAY_SERVER, parsedUrl.hostname)
request.Set(GatewayRequest.GATEWAY_SERVLET,
parsedUrl.path + ("?" + parsedUrl.query if parsedUrl.query is not None else ""))
if parsedUrl.port is not None:
request.Set(GatewayRequest.GATEWAY_PORTNO, parsedUrl.port)
except Exception as ex:
response.Set(GatewayResponse.EXCEPTION, str(ex))
response.Set(GatewayResponse.RESPONSE_CODE, GatewayCodes.RESPONSE_REQUEST_ERROR)
response.Set(GatewayResponse.REASON_CODE, GatewayCodes.REASON_INVALID_URL)
return 0 # Validation error: Invalid URL
#
# If the request specifies a server name, use it. Otherwise, use the default.
#
server_name = request.Get(GatewayRequest.GATEWAY_SERVER)
if server_name is not None: # Override?
server_list = [server_name] # Use this name
else:
try:
if self.rocketGateHost != GatewayService.LIVE_HOST:
server_list = [self.rocketGateHost]
else:
server_list = socket.gethostbyname_ex(self.rocketGateHost)[2]
except socket.gaierror:
server_list = [GatewayService.LIVE_HOST_16, GatewayService.LIVE_HOST_17]
server_list = [
GatewayService.LIVE_HOST_16 if server == "69.20.127.91"
else GatewayService.LIVE_HOST_17 if server == "72.32.126.131"
else server
for server in server_list
]
#
# Clear any error tracking that may be leftover.
#
request.Clear(GatewayRequest.FAILED_SERVER)
request.Clear(GatewayRequest.FAILED_RESPONSE_CODE)
request.Clear(GatewayRequest.FAILED_REASON_CODE)
request.Clear(GatewayRequest.FAILED_GUID)
#
# Randomly pick an endpoint.
#
if len(server_list) > 1: # Have multiples?
index = random.randint(0, len(server_list) - 1)
if index > 0: # Want to change?
swapper = server_list[0] # Save the first one
server_list[0] = server_list[index]
server_list[index] = swapper # And swap
#
# Loop over the hosts and try to send the transaction to each host in the list until it succeeds or fails
# due to an unrecoverable error.
#
index = 0 # Start at first position
while index < len(server_list): # Loop over list
results = self.SendTransaction(server_list[index], request, response)
#
# If the transaction was successful, we are done
#
if results == GatewayCodes.RESPONSE_SUCCESS: # Success?
return 1 # (TRUE) All done
#
# If the transaction is not recoverable, quit.
#
if results != GatewayCodes.RESPONSE_SYSTEM_ERROR: # Unrecoverable?
return 0 # (FALSE) Must quit
#
# Save any errors in the response so they can be transmitted along with the next request.
#
request.Set(GatewayRequest.FAILED_SERVER, server_list[index])
request.Set(GatewayRequest.FAILED_RESPONSE_CODE, response.Get(GatewayResponse.RESPONSE_CODE))
request.Set(GatewayRequest.FAILED_REASON_CODE, response.Get(GatewayResponse.REASON_CODE))
request.Set(GatewayRequest.FAILED_GUID, response.Get(GatewayResponse.TRANSACT_ID))
index += 1 # Next index
#
# If we ran out of places to send this, just quit.
#
return 0 # Must quit
def PerformTargetedTransaction(self, request, response):
"""Sends a transaction to a server based upon the GUID."""
#
# Clear any error tracking that may be leftover.
#
request.Clear(GatewayRequest.FAILED_SERVER)
request.Clear(GatewayRequest.FAILED_RESPONSE_CODE)
request.Clear(GatewayRequest.FAILED_REASON_CODE)
request.Clear(GatewayRequest.FAILED_GUID)
#
# This transaction must go to the host that processed a previous referenced transaction. Get the GUID of the
# reference transaction.
#
referenceGUID = request.Get(GatewayRequest.REFERENCE_GUID)
if referenceGUID is None: # Don't have reference?
response.Set(GatewayResponse.RESPONSE_CODE, GatewayCodes.RESPONSE_REQUEST_ERROR)
response.Set(GatewayResponse.REASON_CODE, GatewayCodes.REASON_INVALID_REFGUID)
return 0 # And quit
#
# Strip off the bits that indicate which server should be used.
#
if len(referenceGUID) > 15: # Live servers?
siteString = referenceGUID[0:2] # Get first two digits
else:
siteString = referenceGUID[0:1] # Get first digit
#
# Try to turn the site string into a number.
#
try:
siteNo = int(siteString, 16) # Get site number
except: # Parsing error?
response.Set(GatewayResponse.RESPONSE_CODE, GatewayCodes.RESPONSE_REQUEST_ERROR)
response.Set(GatewayResponse.REASON_CODE, GatewayCodes.REASON_INVALID_REFGUID)
return 0 # And quit
#
# Build the hostname to which the transaction should be directed.
#
server_name = request.Get("gatewayServer")
if server_name is None: # Don't have one?
server_name = self.rocketGateHost # Start with default
separator = server_name.find(".") # Find first .
if separator > 0: # Did we find it?
server_name = "{0}-{1}{2}".format(
server_name[0:separator],
str(siteNo),
server_name[separator:]
) # Full server name
#
# Send the transaction to the specified host.
#
results = self.SendTransaction(server_name, request, response)
if results == GatewayCodes.RESPONSE_SUCCESS: # Did server return 0?
return 1 # This succeeded
return 0 # This failed
def PerformConfirmation(self, request, response):
"""Performs the confirmation pass that tells the server we have received the transaction reply."""
#
# Verify that we have a transaction ID for the confirmation message.
#
confirmGUID = response.Get(GatewayResponse.TRANSACT_ID)
if confirmGUID is None: # Don't have reference?
response.Set(GatewayResponse.EXCEPTION, "BUG-CHECK - Missing confirmation GUID")
response.Set(GatewayResponse.RESPONSE_CODE, GatewayCodes.RESPONSE_SYSTEM_ERROR)
response.Set(GatewayResponse.REASON_CODE, GatewayCodes.REASON_BUGCHECK)
return 0 # And quit
#
# Add the GUID to the request and send it back to the original server for confirmation.
#
confirmResponse = GatewayResponse() # Need a new response object
request.Set(GatewayRequest.TRANSACTION_TYPE, "CC_CONFIRM")
request.Set(GatewayRequest.REFERENCE_GUID, confirmGUID)
results = self.PerformTargetedTransaction(request, confirmResponse)
if results: # Success?
return 1 # Yes - We are done
#
# If the confirmation failed, copy the reason and response code
# into the original response object to override the success.
#
response.Set(GatewayResponse.RESPONSE_CODE, confirmResponse.Get(GatewayResponse.RESPONSE_CODE))
response.Set(GatewayResponse.REASON_CODE, confirmResponse.Get(GatewayResponse.REASON_CODE))
return 0 # And quit
def PerformAuthOnly(self, request, response):
"""Performs an auth-only transaction."""
request.Set(GatewayRequest.TRANSACTION_TYPE, "CC_AUTH")
results = self.PerformTransaction(request, response)
if results: # Success?
results = self.PerformConfirmation(request, response)
return results # Return results
def PerformTicket(self, request, response):
"""Performs a Ticket operation for a previous auth-only transaction."""
request.Set(GatewayRequest.TRANSACTION_TYPE, "CC_TICKET")
return self.PerformTargetedTransaction(request, response) # Return results
def PerformPurchase(self, request, response):
"""Performs a complete purchase transaction."""
request.Set(GatewayRequest.TRANSACTION_TYPE, "CC_PURCHASE")
results = self.PerformTransaction(request, response)
if results: # Success?
results = self.PerformConfirmation(request, response)
return results # Return results
def PerformCredit(self, request, response):
"""Performs a Credit operation for a previous transaction."""
request.Set(GatewayRequest.TRANSACTION_TYPE, "CC_CREDIT")
#
# If this is a reference GUID, send the transaction to the appropriate server. Otherwise use the normal
# transaction distribution.
#
referenceGUID = request.Get(GatewayRequest.REFERENCE_GUID)
if referenceGUID is not None: # Have reference?
results = self.PerformTargetedTransaction(request, response)
else:
results = self.PerformTransaction(request, response)
return results # Return results
def PerformVoid(self, request, response):
"""Performs a Void operation for a previous transaction."""
request.Set(GatewayRequest.TRANSACTION_TYPE, "CC_VOID")
return self.PerformTargetedTransaction(request, response) # Return results
def PerformCardScrub(self, request, response):
"""Performs scrubbing on a card/customer"""
request.Set(GatewayRequest.TRANSACTION_TYPE, "CARDSCRUB")
return self.PerformTransaction(request, response) # Return results
def PerformRebillCancel(self, request, response):
"""Schedules cancellation of rebilling."""
request.Set(GatewayRequest.TRANSACTION_TYPE, "REBILL_CANCEL")
return self.PerformTransaction(request, response) # Return results
def PerformRebillUpdate(self, request, response):
"""Updates terms of a rebilling."""
request.Set(GatewayRequest.TRANSACTION_TYPE, "REBILL_UPDATE")
#
# If there is no prorated charge, just perform the update.
#
amount = request.Get(GatewayRequest.AMOUNT)
if amount is None: # No charge?
return self.PerformTransaction(request, response) # Return results
#
# If the amount will not result in a chage, just perform the update.
#
try: # Check the amount
value = float(amount) # Make sure this is valid
if value <= 0.0: # Not chargeable?
return self.PerformTransaction(request, response) # Return results
except: # Not a valid amount
pass
#
# If there is a charge, perform the update and confirm the charge.
#
results = self.PerformTransaction(request, response)
if results: # Success?
results = self.PerformConfirmation(request, response)
return results # Return results
def PerformCardUpload(self, request, response):
"""Uploads card data to the servers."""
request.Set(GatewayRequest.TRANSACTION_TYPE, "CARDUPLOAD")
return self.PerformTransaction(request, response) # Return results
def PerformLookup(self, request, response):
"""Performs Lookup request"""
request.Set(GatewayRequest.TRANSACTION_TYPE, "LOOKUP")
referenceGUID = request.Get(GatewayRequest.REFERENCE_GUID)
if referenceGUID is not None: # Have reference?
results = self.PerformTargetedTransaction(request, response)
else:
results = self.PerformTransaction(request, response)
return results
def GenerateXsell(self, request, response):
"""Adds an entry to the XsellQueue."""
# Apply the transaction type to the request
request.Set(GatewayRequest.TRANSACTION_TYPE, "GENERATEXSELL")
request.Set(GatewayRequest.REFERENCE_GUID, request.Get(GatewayRequest.XSELL_REFERENCE_XACT))
if request.Get(GatewayRequest.REFERENCE_GUID) is not None:
return self.PerformTargetedTransaction(request, response)
else:
return self.PerformTransaction(request, response)
def BuildPaymentLink(self, request, response) -> bool:
"""Creates an embeddable RocketGate hosted payment link"""
if request.Get(GatewayRequest.EMBEDDED_FIELDS_TOKEN) is not None:
embedded_fields_token = request.Get(GatewayRequest.EMBEDDED_FIELDS_TOKEN)
gateway_url = embedded_fields_token.replace("EmbeddedFieldsProxy", "BuildPaymentLinkSubmit")
request.Set(GatewayRequest.GATEWAY_URL, gateway_url)
else: