-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaypal.py
386 lines (318 loc) · 12.6 KB
/
paypal.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
import os
import webapp2
import jinja2
from google.appengine.ext import ndb
from google.appengine.api import users
import datetime
from google.appengine.api import memcache
import urllib, urllib2,httplib
from google.appengine.api import urlfetch
import logging
#Jinja Loader
template_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.getcwd()))
sandBoxMode = True
if sandBoxMode:
PP_URL = "https://www.sandbox.paypal.com/cgi-bin/webscr"
ACCOUNT_EMAIL= "mobiusndou@gmail.com"
else:
PP_URL = "https://www.paypal.com/cgi-bin/webscr"
ACCOUNT_EMAIL = "mobiusndou@gmail.com"
class PayPalPayments(ndb.Expando):
_transaction_status = ['completed','pending','failed']
_supported_currencies = ['$','R']
strReference = ndb.StringProperty()
strPayPalTransactionID = ndb.StringProperty()
strPayMentEmail = ndb.StringProperty()
strTransactionStatus = ndb.StringProperty()
strInvoiceID = ndb.StringProperty()
strCurrency = ndb.StringProperty()
strAmount = ndb.StringProperty()
strFee = ndb.StringProperty()
strPayerID = ndb.StringProperty()
strPayerEmail = ndb.StringProperty()
strDateTimeOFTransaction = ndb.DateTimeProperty(auto_now_add=True)
def writeReference(self,strinput):
try:
strinput = str(strinput)
if strinput != None:
self.strReference = strinput
return True
else:
return False
except:
return False
def writeTransactionID(self,strinput):
try:
strinput = str(strinput)
if strinput != None:
self.strPayPalTransactionID = strinput
return True
else:
return False
except:
return False
def writePaymentEmail(self,strinput):
try:
strinput = str(strinput)
if strinput != None:
self.strPayMentEmail = strinput
return True
else:
return False
except:
return False
def writeTransactionStatus(self,strinput):
try:
strinput = str(strinput)
strinput = strinput.lower()
if strinput in self._transaction_status:
self.strTransactionStatus = strinput
return True
else:
return False
except:
return False
def writeInvoiceID(self,strinput):
try:
strinput = str(strinput)
if strinput != None:
self.strInvoiceID = strinput
return True
else:
return False
except:
return False
def writeCurrency(self,strinput):
try:
strinput = str(strinput)
if strinput in self._supported_currencies:
self.strCurrency = strinput
return True
else:
return False
except:
return False
def writeAmount(self,strinput):
try:
strinput = str(strinput)
#TODO-Consider testing for actual values
if strinput != None:
self.strAmount = strinput
return True
else:
return False
except:
return False
def writeFee(self,strinput):
try:
strinput = str(strinput)
if strinput != None:
self.strFee = strinput
return True
else:
return False
except:
return False
def writePayerID(self,strinput):
try:
strinput = str(strinput)
if strinput != None:
self.strPayerID = strinput
return True
else:
return False
except:
return False
def writePayerEmail(self,strinput):
try:
strinput = str(strinput)
if strinput != None:
self.strPayerEmail = strinput
return True
else:
return False
except:
return False
def retrieveTransactionsByReference(self,strinput):
try:
strinput = str(strinput)
if strinput != None:
findQuery = PayPalPayments.query(PayPalPayments.strReference == strinput)
results = findQuery.fetch()
if len(results) > 0:
return results
else:
return None
else:
return None
except:
return None
def retrieveTransactionsByTransactionID(self,strinput):
try:
strinput = str(strinput)
if strinput != None:
findQuery = PayPalPayments.query(PayPalPayments.strPayPalTransactionID == strinput)
results = findQuery.fetch()
if len(results) > 0:
return results
else:
return None
else:
return None
except:
return None
def retrieveTransactionsByPaymentEmail(self,strinput):
try:
strinput = str(strinput)
if strinput != None:
findQuery = PayPalPayments.query(PayPalPayments.strPayMentEmail == strinput)
results = findQuery.fetch()
if len(results) > 0:
return results
else:
return None
else:
return None
except:
return None
def retrieveTransactionsByTransactionStatus(self,strinput):
try:
strinput = str(strinput)
strinput = strinput.lower()
if strinput in self._transaction_status:
findQuery = PayPalPayments.query(PayPalPayments.strTransactionStatus == strinput)
results = findQuery.fetch()
if len(results) > 0:
return results
else:
return None
else:
return None
except:
return None
def storePayPalPayments(self):
try:
self.put()
return True
except:
return False
class PayPalIPNHandler(webapp2.RequestHandler):
def post(self):
parameters = None
PayPalPay = PayPalPayments()
userid = self.request.get('userid')
# Check payment is completed, not Pending or Failed.
PayPalPay.writeReference(strinput=userid)
if self.request.get('payment_status') == 'Completed':
if self.request.POST:
parameters = self.request.POST.copy()
PayPalPay.writeTransactionStatus(strinput="completed")
if self.request.GET:
parameters = self.request.GET.copy()
logging.debug("IPN verification Executing")
PayPalPay.writeTransactionStatus(strinput="pending")
else:
self.response.out.write("Error Sorry the Parameter was not completed")
PayPalPay.writeTransactionStatus(strinput="failed")
#TODO- Check the IPN POST request came from real PayPal,
#TODO- Not from a Fraudster.
if parameters:
parameters['cmd'] = '_notify-validate'
params = urllib.urlencode(parameters)
status = urlfetch.fetch(
url=PP_URL,
method=urlfetch.POST,
payload=params,
).content
if not(status == "VERIFIED"):
template = template_env.get_template('templates/deposit.html')
context = {'Message': "Error IPN not Verified"}
self.response.write(template.render(context))
else:
parameters['homemadeParameterValidity']=False
# parameters = None
# You may log this data in your database,
# for later investigation.
# Check the money is really to go to your account,
# not to a fraudster's account.
if parameters['receiver_email'] == ACCOUNT_EMAIL:
transaction_id = parameters['txn_id']
PayPalPay.writePaymentEmail(strinput=ACCOUNT_EMAIL)
PayPalPay.writeTransactionID(strinput=transaction_id)
# Check if this is a new, unique txn,
# not a fraudster re-using an old, verified txn.
invoice_id = parameters['invoice']
PayPalPay.writeInvoiceID(strinput=invoice_id)
currency = parameters['mc_currency']
PayPalPay.writeCurrency(strinput=currency)
amount = parameters['mc_gross']
PayPalPay.writeAmount(strinput=amount)
fee = parameters['mc_fee']
PayPalPay.writeFee(strinput=fee)
# Check if they are the right product/item, right price,
# right currency, right amount, etc.
email = parameters['payer_email']
PayPalPay.writePayerEmail(strinput=email)
identifier = parameters['payer_id']
PayPalPay.writePayerID(strinput=identifier)
if PayPalPay.storePayPalPayments():
template = template_env.get_template('templates/deposit.html')
context = {'strTransactionStatus': "OK a Record of this Transaction has also been sent to your email",
'strTransactionID': transaction_id,
'strInvoiceID': invoice_id,
'strPayerEmail': email}
self.response.write(template.render(context))
# Email/notify/inform the user for whatever reason.
parameters['your_parm'] = "It is ok on 19 September, 2010."
logging.debug('IPN 100. All OK.')
logging.debug(parameters['txn_id'])
logging.debug(parameters['invoice'])
logging.debug(parameters['payer_email'])
# With this IPN testing, you can't see results on the browser.
# See results on the log file maintained by Google AppEngine.
else:
template = template_env.get_template('templates/deposit.html')
context = {'strTransactionStatus': "Transaction unsuccesfull"}
self.response.write(template.render(context))
else: # Payment Status is not Complete
template = template_env.get_template('templates/deposit.html')
context = {'strTransactionStatus': "Transaction unsuccessful"}
self.response.write(template.render(context))
class DepositSuccesfulHandler(webapp2.RequestHandler):
"""
if the user gets redirected here the deposit was succesful
<form method=post action="https://www.paypal.com/cgi-bin/webscr">
<input type="hidden" name="cmd" value="_notify-synch">
<input type="hidden" name="tx" value="TransactionID">
<input type="hidden" name="at" value="QieZsRoNf8Fmt3XVZx6AMKKuQs5SC2NIpmfNFrCM7Aiw5RHbk20ye7C0kiS">
<input type="submit" value="PDT">
</form>
"""
def get(self):
try:
thisTX = self.request.get('tx')
params = urllib.urlencode({'cmd': "_notify-synch", 'tx': thisTX, 'at': "QieZsRoNf8Fmt3XVZx6AMKKuQs5SC2NIpmfNFrCM7Aiw5RHbk20ye7C0kiS"})
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
conn = httplib.HTTPConnection("https://www.paypal.com/cgi-bin/webscr")
conn.request("POST", "", params, headers)
response = conn.getresponse()
thisContent = response.read()
self.response.write(thisContent)
except:
self.response.write("Error")
def post(self):
self.response.write("Transaction worked")
class DepositCancelledHandler(webapp2.RequestHandler):
def get(self):
template = template_env.get_template('templates/admin/paypal/paymentcancelled.html')
context = {}
self.response.write(template.render(context))
def post(self):
self.response.write("Deposit was cancelled")
app = webapp2.WSGIApplication([
('/depositsuccesful', DepositSuccesfulHandler),
('/depositcancelled', DepositCancelledHandler),
('/paypalIPN0485234hhisidf683475bknbjsdf9843', PayPalIPNHandler)
], debug=True)