/
client.py
427 lines (348 loc) · 15.8 KB
/
client.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
# -*- coding: utf-8 -*-
"""
Copyright 2008 Online Agility (www.onlineagility.com)
Copyright 2009 John D'Agostino (http://www.mercurycomplex.com)
Copyright 02011 Ben Keating (http://bpk.deepdream.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import sys
import time
import re
import types
import logging
try:
from urllib.parse import urlsplit
from urllib.request import urlopen
from urllib.request import Request
except ImportError:
from urllib2 import Request
from urllib2 import urlopen
from urllib2 import urlparse
urlsplit = urlparse.urlsplit
from .classes import Address
from .classes import Amount
from .classes import CreditCard
from .classes import parse_parameters
from .classes import Profile
from .classes import Response
from .classes import Tracking
"""
TENDER_TYPES:
'A', # Automated clearinghouse
'C', # Credit card
'D', # Pinless debit
'K', # Telecheck
'P', # PayPal
TRANSACTION_TYPES:
'S', # Sale transaction
'C', # Credit
'A', # Authorization
'D', # Delayed Capture
'V', # Void
'F', # Voice Authorization
'I', # Inquiry
'N', # Duplicate transaction
'R', # Recurring
"""
class CurrentTimeIdGenerator(object):
def id(self):
"""Returns the current time in milliseconds as an integer."""
return int(time.time() * 1000) # Current time in milliseconds
class PayflowProClient(object):
"""Payflow Pro Client Object
For API version 4 (also known as the HTTPS API interface)
"""
URL_BASE_TEST = 'https://pilot-payflowpro.paypal.com'
URL_BASE_LIVE = 'https://payflowpro.paypal.com'
REDIRECT_TEST = 'https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token='
REDIRECT_LIVE = 'https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token='
HOSTPORT = 443
API_VERSION = '4'
CLIENT_IDENTIFIER = 'python-payflowpro'
MAX_RETRY_COUNT = 5 # How many times to retry failed logins or rate limited operations
def __init__(self, partner, vendor, username, password, timeout_secs=45,
idgenerator=CurrentTimeIdGenerator(), url_base=URL_BASE_TEST):
self.partner = partner
self.vendor = vendor
self.username = username
self.password = password
self.timeout = timeout_secs
self.url_base = url_base
self.idgenerator = idgenerator
self.log = logging.getLogger('payflow_pro')
if self.url_base == self.URL_BASE_TEST:
self.redirect = self.REDIRECT_TEST
else:
self.redirect = self.REDIRECT_LIVE
def _build_parmlist(self, parameters):
"""
Converts a dictionary of name and value pairs into a
PARMLIST string value acceptable to the Payflow Pro API.
"""
args = []
for key, value in parameters.items():
if not value is None:
# We always use the explicit-length keyname format, to reduce the chance
# of requests failing due to unusual characters in parameter values.
try:
classinfo = unicode
except NameError:
classinfo = str
if isinstance(value, classinfo):
key = '%s[%d]' % (key.upper(), len(value.encode('utf-8')))
else:
key = '%s[%d]' % (key.upper(), len(str(value)))
args.append('%s=%s' % (key, value))
args.sort()
parmlist = '&'.join(args)
return parmlist
def _parse_parmlist(self, parmlist):
"""
Parses a PARMLIST string into a dictionary of name and value
pairs. The parsing is complicated by the following:
- parameter keynames may or may not include a length
specification
- delimiter characters (=, &) may appear inside parameter
values, provided the parameter has an explicit length.
For example, the following parmlist values are possible:
A=B&C=D
A[1]=B&C[1]=D
A=B&C[1]=D
A[3]=B&B&C[1]=D (Here, the value of A is "B&B")
A[1]=B&C[3]=D=7 (Here, the value of C is "D=7")
"""
parmlist = "&" + parmlist
name_re = re.compile(r'\&([A-Z0-9_]+)(\[\d+\])?=')
results = {}
offset = 0
match = name_re.search(parmlist, offset)
while match:
name, len_suffix = match.groups()
offset = match.end()
if len_suffix:
val_len = int(len_suffix[1:-1])
else:
next_match = name_re.search(parmlist, offset)
if next_match:
val_len = next_match.start() - match.end()
else:
# At end of parmlist
val_len = len(parmlist) - match.end()
value = parmlist[match.end() : match.end() + val_len]
results[name.lower()] = value
match = name_re.search(parmlist, offset)
return results
def _do_request(self, request_id, parameters={}):
"""
"""
if request_id is None:
# Generate a new request identifier using the class' default generator
request_id = self.idgenerator.id()
req_params = dict(parameters)
req_params.update(dict(
partner = self.partner,
vendor = self.vendor,
user = self.username,
pwd = self.password,
))
parmlist = self._build_parmlist(req_params)
headers = {
'Host': urlsplit(self.url_base)[1],
'X-VPS-REQUEST-ID': str(request_id),
'X-VPS-CLIENT-TIMEOUT': str(self.timeout), # Doc says to do this
'X-VPS-Timeout': str(self.timeout), # Example says to do this
'X-VPS-INTEGRATION-PRODUCT': self.CLIENT_IDENTIFIER,
'X-VPS-INTEGRATION-VERSION': self.API_VERSION,
'X-VPS-VIT-OS-NAME': sys.platform,
'Connection': 'close',
'Content-Type': 'text/namevalue',
}
self.log.debug(u'Request Headers: %s' % headers)
try_count = 0
results = None
while (results is None and try_count < self.MAX_RETRY_COUNT):
try:
try_count += 1
request = Request(
url = self.url_base,
data = parmlist.encode('utf-8'),
headers = headers)
response = urlopen(request)
result_parmlist = response.read().decode('utf-8')
response.close()
self.log.debug(
u'Result text: %s' % result_parmlist
)
results = self._parse_parmlist(result_parmlist)
except Exception as e:
if try_count < self.MAX_RETRY_COUNT:
self.log.warn(
u'API request attempt %s of %s failed - %%s' % (
try_count, self.MAX_RETRY_COUNT), e
)
else:
self.log.exception(u'Final API request failed - %s', e)
raise e
self.log.debug(u'Parsed PARMLIST: %s' % results)
# Parse results dictionary into a set of PayflowProObjects
result_objects, unconsumed_data = parse_parameters(results)
self.log.debug(u'Result parsed objects: %s' % result_objects)
self.log.debug(u'Unconsumed Data: %s' % unconsumed_data)
return (result_objects, unconsumed_data)
##### Implementations of standard transactions #####
def sale(self, credit_card, amount, request_id=None, extras=[]):
params = dict(trxtype = "S")
for item in [credit_card, amount] + extras:
params.update(item.data)
return self._do_request(request_id, params)
def authorization(self, credit_card, amount, request_id=None, extras=[]):
params = dict(trxtype = "A")
for item in [credit_card, amount] + extras:
params.update(item.data)
return self._do_request(request_id, params)
def capture(self, auth_pnref, request_id=None, extras=[]):
params = dict(trxtype = "D", origid = auth_pnref)
for item in extras:
params.update(item.data)
return self._do_request(request_id, params)
def voice_authorization(self, voice_auth_code, credit_card, amount, request_id=None, extras=[]):
params = dict(trxtype = "F", authcode = voice_auth_code)
for item in [credit_card, amount] + extras:
params.update(item.data)
return self._do_request(request_id, params)
def credit_referenced(self, original_pnref, request_id=None, extras=[]):
params = dict(trxtype = "C", origid = original_pnref)
for item in extras:
params.update(item.data)
return self._do_request(request_id, params)
def credit_unreferenced(self, credit_card, amount, request_id=None, extras=[]):
params = dict(trxtype = "C")
for item in [credit_card, amount] + extras:
params.update(item.data)
return self._do_request(request_id, params)
def void(self, original_pnref, request_id=None, extras=[]):
params = dict(trxtype = "V", origid = original_pnref)
for item in extras:
params.update(item.data)
return self._do_request(request_id, params)
def inquiry(self, original_pnref=None, customer_ref=None, request_id=None, extras=[]):
params = dict(trxtype = "I", origid = original_pnref, custref = customer_ref)
if original_pnref is None and customer_ref is None:
raise TypeError("An inquiry requires one of the 'original_pnref' or 'customer_ref' arguments")
if not original_pnref is None and not customer_ref is None:
raise TypeError("An inquiry requires only one of the 'original_pnref' or 'customer_ref' arguments, not both")
for item in extras:
params.update(item.data)
return self._do_request(request_id, params)
def reference_transaction(self, transaction_type, original_pnref, amount, request_id=None, extras=[]):
params = dict(trxtype = transaction_type, origid = original_pnref)
for item in [amount] + extras:
params.update(item.data)
return self._do_request(request_id, params)
def reference_transaction_baid(self, transaction_type, baid, amount, request_id=None, extras=[]):
params = dict(trxtype = transaction_type, baid = baid,tender='P',
action='D')
for item in [amount] + extras:
params.update(item.data)
return self._do_request(request_id, params)
##### Implementations of paypal express checkout #####
def set_checkout(self, setpaypal, amount, extras=[]):
params = dict(trxtype = "S", action = "S")
for item in [setpaypal, amount] + extras:
params.update(item.data)
return self._do_request(None, params)
def baid_set_checkout(self, setpaypal, amount, extras=[]):
params = dict(trxtype = "A", action = "S")
for item in [setpaypal, amount] + extras:
params.update(item.data)
return self._do_request(None, params)
def get_baid(self, token):
params = dict(trxtype = "A", action = "X", tender = "P",
token = token)
return self._do_request(None, params)
def get_checkout(self, getpaypal, extras=[]):
params = dict(trxtype = "S", action = "G")
for item in [getpaypal] + extras:
params.update(item.data)
return self._do_request(None, params)
def do_checkout(self, dopaypal, amount, extras=[]):
params = dict(trxtype = "S", action = "D")
for item in [dopaypal, amount] + extras:
params.update(item.data)
return self._do_request(None, params)
##### Implementations of recurring transactions #####
def profile_add(self, profile, credit_card, amount, request_id=None, extras=[]):
params = dict(trxtype = 'R', action = 'A')
for item in [profile, credit_card, amount] + extras:
params.update(item.data)
return self._do_request(request_id, params)
def profile_baid_add(self, profile, amount, request_id=None, extras=[]):
params = dict(trxtype = 'R', action = 'A', tender = "P")
for item in [profile, amount] + extras:
params.update(item.data)
return self._do_request(request_id, params)
def profile_add_from_transaction(self, original_pnref, request_id=None, extras=[]):
params = dict(trxtype = 'R', action = 'A', origid = original_pnref)
for item in extras:
params.update(item.data)
return self._do_request(request_id, params)
def profile_modify(self, profile_id, request_id=None, extras=[]):
params = dict(trxtype = 'R', action = 'M', origprofileid = profile_id)
for item in extras:
params.update(item.data)
return self._do_request(request_id, params)
def profile_reactivate(self, profile_id, request_id=None, extras=[]):
params = dict(trxtype = 'R', action = 'R', origprofileid = profile_id)
for item in extras:
params.update(item.data)
return self._do_request(request_id, params)
def profile_cancel(self, profile_id, request_id=None, extras=[]):
params = dict(trxtype = 'R', action = 'C', origprofileid = profile_id)
for item in extras:
params.update(item.data)
return self._do_request(request_id, params)
def profile_inquiry(self, profile_id, payment_history_only=False, request_id=None, extras=[]):
params = dict(trxtype = 'R', action = 'I', origprofileid = profile_id)
if payment_history_only:
params['paymenthistory'] = 'Y'
for item in extras:
params.update(item.data)
return self._do_request(request_id, params)
def profile_pay(self, profile_id, payment_number, request_id=None, extras=[]):
params = dict(trxtype = 'R', action = 'P',
origprofileid = profile_id, paymentnum = payment_number)
for item in extras:
params.update(item.data)
return self._do_request(request_id, params)
def find_class_in_list(klass, lst):
"""
Returns the first occurrence of an instance of type `klass` in
the given list, or None if no such instance is present.
"""
filtered = list(filter(lambda x: x.__class__ == klass, lst))
if filtered:
return filtered[0]
return None
def find_classes_in_list(klasses, lst):
"""
Returns a tuple containing an entry corresponding to each of
the requested class types, where the entry is either the first
object instance of that type or None of no such instances are
available.
Example Usage:
find_classes_in_list(
[Address, Response],
[<classes.Response...>, <classes.Amount...>, <classes.Address...>])
Produces: (<classes.Address...>, <classes.Response...>)
"""
if not isinstance(klasses, list):
klasses = [klasses]
return tuple(map(lambda klass: find_class_in_list(klass, lst), klasses))