Repository navigation
Expand file tree
/
Copy pathprofile.py
More file actions
414 lines (352 loc) · 16 KB
/
Copy pathprofile.py
File metadata and controls
414 lines (352 loc) · 16 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
import os
import sys
import random
from django.db import models
from django.forms.models import model_to_dict
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
import json
from .conf import settings
from .cim import add_profile, get_profile, update_payment_profile, \
create_payment_profile, delete_profile, delete_payment_profile
from .managers import CustomerProfileManager
from .exceptions import BillingError
@csrf_exempt
def webhook(request):
webhook_secret = 'YOUR_WEBHOOK_SECRET_HERE'
if request.POST.get('secret') != webhook_secret:
return HttpResponse("Invalid webhook secret", 'text/plain', 403)
if request.POST.get('event') == 'incoming_message':
content = request.POST.get('content')
from_number = request.POST.get('from_number')
phone_id = request.POST.get('phone_id')
# do something with the message, e.g. send an autoreply
return HttpResponse(json.dumps({
'messages': [
{'content': "Thanks for your message!"}
]
}), 'application/json')
class Malipo(object):
"""docstring for Malipo"""
def __init__(self, arg):
super(Malipo, self).__init__()
self.arg = arg
def Malipo(self):
lipakwasaa = 'payhourly'
cardless = 'go cardless'
RESPONSE_CHOICES = (
('1', 'Approved'),
('2', 'Declined'),
('3', 'Error'),
('4', 'Held for Review'),
)
AVS_RESPONSE_CODE_CHOICES = (
('A', 'Address (Street) matches, ZIP does not'),
('B', 'Address information not provided for AVS check'),
('E', 'AVS error'),
('G', 'Non-U.S. Card Issuing Bank'),
('N', 'No Match on Address (Street) or ZIP'),
('P', 'AVS not applicable for this transaction'),
('R', 'Retry - System unavailable or timed out'),
('S', 'Service not supported by issuer'),
('U', 'Address information is unavailable'),
('W', 'Nine digit ZIP matches, Address (Street) does not'),
('X', 'Address (Street) and nine digit ZIP match'),
('Y', 'Address (Street) and five digit ZIP match'),
('Z', 'Five digit ZIP matches, Address (Street) does not'),
)
METHOD_CHOICES = (
('CC', 'Credit Card'),
('ECHECK', 'eCheck'),
)
TYPE_CHOICES = (
('auth_capture', 'Authorize and Capture'),
('auth_only', 'Authorize only'),
('credit', 'Credit'),
('prior_auth_capture', 'Prior capture'),
('void', 'Void'),
)
CVV2_RESPONSE_CODE_CHOICES = (
('M', 'Match'),
('N', 'No Match'),
('P', 'Not Processed'),
('S', 'Should have been present'),
('U', 'Issuer unable to process request'),
)
CAVV_RESPONSE_CODE_CHOICES = (
('', 'CAVV not validated'),
('0', 'CAVV not validated because erroneous data was submitted'),
('1', 'CAVV failed validation'),
('2', 'CAVV passed validation'),
('3', 'CAVV validation could not be performed; issuer attempt incomplete'),
('4', 'CAVV validation could not be performed; issuer system error'),
('5', 'Reserved for future use'),
('6', 'Reserved for future use'),
('7', 'CAVV attempt - failed validation - '
'issuer available (U.S.-issued card/non-U.S acquirer)'),
('8', 'CAVV attempt - passed validation - '
'issuer available (U.S.-issued card/non-U.S. acquirer)'),
('9', 'CAVV attempt - failed validation - '
'issuer unavailable (U.S.-issued card/non-U.S. acquirer)'),
('A', 'CAVV attempt - passed validation - '
'issuer unavailable (U.S.-issued card/non-U.S. acquirer)'),
('B', 'CAVV passed validation, information only, no liability shift'),
)
CIM_RESPONSE_CODE_CHOICES = (
('I00001', 'Successful'),
('I00003', 'The record has already been deleted.'),
('E00001', 'An error occurred during processing. Please try again.'),
('E00002', 'The content-type specified is not supported.'),
('E00003', 'An error occurred while parsing the XML request.'),
('E00004', 'The name of the requested API method is invalid.'),
('E00005', 'The merchantAuthentication.transactionKey '
'is invalid or not present.'),
('E00006', 'The merchantAuthentication.name is invalid or not present.'),
('E00007', 'User authentication failed '
'due to invalid authentication values.'),
('E00008', 'User authentication failed. The payment gateway account or '
'user is inactive.'),
('E00009', 'The payment gateway account is in Test Mode. '
'The request cannot be processed.'),
('E00010', 'User authentication failed. '
'You do not have the appropriate permissions.'),
('E00011', 'Access denied. You do not have the appropriate permissions.'),
('E00013', 'The field is invalid.'),
('E00014', 'A required field is not present.'),
('E00015', 'The field length is invalid.'),
('E00016', 'The field type is invalid.'),
('E00019', 'The customer taxId or driversLicense information '
'is required.'),
('E00027', 'The transaction was unsuccessful.'),
('E00029', 'Payment information is required.'),
('E00039', 'A duplicate record already exists.'),
('E00040', 'The record cannot be found.'),
('E00041', 'One or more fields must contain a value.'),
('E00042', 'The maximum number of payment profiles '
'for the customer profile has been reached.'),
('E00043', 'The maximum number of shipping addresses '
'for the customer profile has been reached.'),
('E00044', 'Customer Information Manager is not enabled.'),
('E00045', 'The root node does not reference a valid XML namespace.'),
('E00051', 'The original transaction was not issued '
'for this payment profile.'),
)
class ResponseManager(models.Manager):
def create_from_dict(self, params):
kwargs = dict(map(lambda x: (str(x[0][2:]), x[1]), params.items()))
return self.create(**kwargs)
def create_from_list(self, items):
kwargs = dict(zip(map(lambda x: x.name,
Response._meta.fields)[1:], items))
return self.create(**kwargs)
class Response(models.Model):
"""Transaction Response (See Section 4 of AIM Developer Guide)"""
response_code = models.CharField(max_length=2, choices=RESPONSE_CHOICES)
response_subcode = models.CharField(max_length=10)
response_reason_code = models.CharField(max_length=15)
response_reason_text = models.TextField()
auth_code = models.CharField(max_length=10)
avs_code = models.CharField(max_length=10,
choices=AVS_RESPONSE_CODE_CHOICES)
trans_id = models.CharField(max_length=255, db_index=True)
invoice_num = models.CharField(max_length=20, blank=True)
description = models.CharField(max_length=255)
amount = models.CharField(max_length=16)
method = models.CharField(max_length=10, choices=METHOD_CHOICES)
type = models.CharField(max_length=20,
choices=TYPE_CHOICES,
db_index=True)
cust_id = models.CharField(max_length=20)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
company = models.CharField(max_length=50)
address = models.CharField(max_length=60)
city = models.CharField(max_length=40)
state = models.CharField(max_length=40)
zip = models.CharField(max_length=20)
country = models.CharField(max_length=60)
phone = models.CharField(max_length=25)
fax = models.CharField(max_length=25)
email = models.CharField(max_length=255)
ship_to_first_name = models.CharField(max_length=50, blank=True)
ship_to_last_name = models.CharField(max_length=50, blank=True)
ship_to_company = models.CharField(max_length=50, blank=True)
ship_to_address = models.CharField(max_length=60, blank=True)
ship_to_city = models.CharField(max_length=40, blank=True)
ship_to_state = models.CharField(max_length=40, blank=True)
ship_to_zip = models.CharField(max_length=20, blank=True)
ship_to_country = models.CharField(max_length=60, blank=True)
tax = models.CharField(max_length=16, blank=True)
duty = models.CharField(max_length=16, blank=True)
freight = models.CharField(max_length=16, blank=True)
tax_exempt = models.CharField(max_length=16, blank=True)
po_num = models.CharField(max_length=25, blank=True)
MD5_Hash = models.CharField(max_length=255)
cvv2_resp_code = models.CharField(max_length=2,
choices=CVV2_RESPONSE_CODE_CHOICES,
blank=True)
cavv_response = models.CharField(max_length=2,
choices=CAVV_RESPONSE_CODE_CHOICES,
blank=True)
test_request = models.CharField(max_length=10, default="FALSE", blank=True)
card_type = models.CharField(max_length=10, default="", blank=True)
account_number = models.CharField(max_length=10, default="", blank=True)
created = models.DateTimeField(auto_now_add=True, null=True)
objects = ResponseManager()
@property
def is_approved(self):
return self.response_code == '1'
def __unicode__(self):
return u"response_code: %s, trans_id: %s, amount: %s, type: %s" % \
(self.response_code, self.trans_id, self.amount, self.type)
class CIMResponse(models.Model):
"""Response for CIM API call (See Section 3 in CIM XML Guide)"""
result = models.CharField(max_length=8)
result_code = models.CharField(max_length=8,
choices=CIM_RESPONSE_CODE_CHOICES)
result_text = models.TextField()
transaction_response = models.ForeignKey(Response, blank=True, null=True)
created = models.DateTimeField(auto_now_add=True, null=True)
@property
def success(self):
return self.result == 'Ok'
def raise_if_error(self):
if not self.success:
raise BillingError(self.result_text)
class CustomerProfile(models.Model):
"""Authorize.NET customer profile"""
customer = models.OneToOneField(settings.CUSTOMER_MODEL,
related_name='customer_profile')
profile_id = models.CharField(max_length=50)
def save(self, *args, **kwargs):
"""If creating new instance, create profile on Authorize.NET also"""
data = kwargs.pop('data', {})
sync = kwargs.pop('sync', True)
if not self.id and sync:
self.push_to_server(data)
super(CustomerProfile, self).save(*args, **kwargs)
def delete(self):
"""Delete the customer profile remotely and locally"""
response = delete_profile(self.profile_id)
response.raise_if_error()
super(CustomerProfile, self).delete()
def push_to_server(self, data):
"""Create customer profile for given ``customer`` on Authorize.NET"""
output = add_profile(self.customer.pk, data, data)
output['response'].raise_if_error()
self.profile_id = output['profile_id']
self.payment_profile_ids = output['payment_profile_ids']
def sync(self):
"""Overwrite local customer profile data with remote data"""
output = get_profile(self.profile_id)
output['response'].raise_if_error()
for payment_profile in output['payment_profiles']:
instance, created = CustomerPaymentProfile.objects.get_or_create(
customer_profile=self,
payment_profile_id=payment_profile['payment_profile_id']
)
instance.sync(payment_profile)
objects = CustomerProfileManager()
def __unicode__(self):
return self.profile_id
class CustomerPaymentProfile(models.Model):
"""Authorize.NET customer payment profile"""
customer = models.ForeignKey(settings.CUSTOMER_MODEL,
related_name='payment_profiles')
customer_profile = models.ForeignKey('CustomerProfile',
related_name='payment_profiles')
payment_profile_id = models.CharField(max_length=50)
first_name = models.CharField(max_length=50, blank=True)
last_name = models.CharField(max_length=50, blank=True)
company = models.CharField(max_length=50, blank=True)
phone_number = models.CharField(max_length=25, blank=True)
fax_number = models.CharField(max_length=25, blank=True)
address = models.CharField(max_length=60, blank=True)
city = models.CharField(max_length=40, blank=True)
state = models.CharField(max_length=40, blank=True)
zip = models.CharField(max_length=20, blank=True, verbose_name="ZIP")
country = models.CharField(max_length=60, blank=True)
card_number = models.CharField(max_length=16, blank=True)
expiration_date = models.DateField(blank=True, null=True)
card_code = None
def __init__(self, *args, **kwargs):
self.card_code = kwargs.pop('card_code', None)
return super(CustomerPaymentProfile, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
"""Sync payment profile on Authorize.NET if sync kwarg is not False"""
if kwargs.pop('sync', True):
self.push_to_server()
self.card_code = None
self.card_number = "XXXX%s" % self.card_number[-4:]
super(CustomerPaymentProfile, self).save(*args, **kwargs)
def push_to_server(self):
"""
Use appropriate CIM API call to save payment profile to Authorize.NET
1. If customer has no profile yet, create one with this payment profile
2. If payment profile is not on Authorize.NET yet, create it there
3. If payment profile exists on Authorize.NET update it there
"""
if not self.customer_profile_id:
try:
self.customer_profile = CustomerProfile.objects.get(
customer=self.customer)
except CustomerProfile.DoesNotExist:
pass
if self.payment_profile_id:
response = update_payment_profile(
self.customer_profile.profile_id,
self.payment_profile_id,
self.raw_data,
self.raw_data,
)
response.raise_if_error()
elif self.customer_profile_id:
output = create_payment_profile(
self.customer_profile.profile_id,
self.raw_data,
self.raw_data,
)
response = output['response']
response.raise_if_error()
self.payment_profile_id = output['payment_profile_id']
else:
output = add_profile(
self.customer.id,
self.raw_data,
self.raw_data,
)
response = output['response']
response.raise_if_error()
self.customer_profile = CustomerProfile.objects.create(
customer=self.customer,
profile_id=output['profile_id'],
sync=False,
)
self.payment_profile_id = output['payment_profile_ids'][0]
@property
def raw_data(self):
"""Return data suitable for use in payment and billing forms"""
data = model_to_dict(self)
data['card_code'] = getattr(self, 'card_code')
return data
def sync(self, data):
"""Overwrite local customer payment profile data with remote data"""
for k, v in data.get('billing', {}).items():
setattr(self, k, v)
self.card_number = data.get('credit_card', {}).get('card_number',
self.card_number)
self.save(sync=False)
def delete(self):
"""Delete the customer payment profile remotely and locally"""
response = delete_payment_profile(self.customer_profile.profile_id,
self.payment_profile_id)
response.raise_if_error()
return super(CustomerPaymentProfile, self).delete()
def update(self, **data):
"""Update the customer payment profile remotely and locally"""
for key, value in data.items():
setattr(self, key, value)
self.save()
return self
def __unicode__(self):
return self.payment_profile_id