-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpayment_server.py
More file actions
131 lines (101 loc) · 4.22 KB
/
payment_server.py
File metadata and controls
131 lines (101 loc) · 4.22 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
import os
import re
from flask import Flask,redirect, request, session, url_for
import paypalrestsdk
# Initialized Paypal RESTful client.
SANDBOX_CLIENT_ID = "AQkquBDf1zctJOWGKWUEtKXm6qVhueUEMvXO_-MCI4DQQ4-LWvkDLIN2fGsd"
SANDBOX_CLIENT_SECRET = "EL1tVxAjhT7cJimnz5-Nsx9k2reTKSVfErNQF-CmrwJgxRtylkGTKlU4RvrX"
# Paypal SDK related config.
HOST_URL_BASE = os.environ.get("HOST_URL_BASE", "http://192.168.59.103")
PAYPAL_CLIENT_ID = os.environ.get("PAYPAL_CLIENT_ID", SANDBOX_CLIENT_ID)
PAYPAL_CLIENT_SECRET = os.environ.get("PAYPAL_CLIENT_SECRET", SANDBOX_CLIENT_SECRET)
PAYPAL_MODE = os.environ.get("PAYPAL_MODE", 'sandbox')
PAYPAL_RETURN_URL = HOST_URL_BASE + "/approve-payment?success=true"
PAYPAL_CANCEL_URL = HOST_URL_BASE + "/approve-payment?success=false"
PAYMENT_SERVER_SECRET_KEY = os.environ.get('PAYMENT_SERVER_SECRET_KEY', "doushidashabi")
PAYMENT_SERVER_PORT = os.environ.get("PAYMENT_SERVER_PORT", 5000)
ACCESS_CHECKING_URL = HOST_URL_BASE + "/check-code.html"
CREATE_PAYMENT_URL = HOST_URL_BASE + "/create-payment.html"
CREATE_FAILED_URL = CREATE_PAYMENT_URL
APPROVE_PAYMENT_FAILED_URL = HOST_URL_BASE + "/success.html"
APPROVE_PAYMENT_SUCCESS_URL = HOST_URL_BASE + "/failure.html"
# Misc Config
PAYMENT_DESC = "Recharge Fee"
ACCESS_CODE_PATTERN = r"k.{3}s.{3}"
#-----------------------------------------------------------------------------
# Initialization Function
paypal_api = paypalrestsdk.configure({
'mode': PAYPAL_MODE,
'client_id': PAYPAL_CLIENT_ID,
'client_secret': PAYPAL_CLIENT_SECRET})
# Initialized Flask App.
app = Flask(__name__)
app.secret_key = PAYMENT_SERVER_SECRET_KEY
access_code_pattern = re.compile(ACCESS_CODE_PATTERN)
#-----------------------------------------------------------------------------
# ROUTING RULES
@app.route('/create-payment', methods=['POST', 'GET'])
def create_payment():
# Access checking procedure.
if PAYPAL_MODE != 'sandbox':
try:
if not session['pass']:
return redirect(ACCESS_CHECKING_URL)
except Exception, e:
return redirect(ACCESS_CHECKING_URL)
if request.method == 'GET':
return redirect(CREATE_PAYMENT_URL)
# Start to create payment.
redirect_url = CREATE_FAILED_URL
payment_amount = request.form['payment_amount']
# Return to this page if the input is not a valid number.
try:
float(payment_amount)
except ValueError as e:
print e
return redirect ('/create-payment/')
payment = paypalrestsdk.Payment({
"intent": "sale",
"payer": {"payment_method": "paypal"},
"redirect_urls": {
"return_url": PAYPAL_RETURN_URL,
"cancel_url": PAYPAL_CANCEL_URL},
"transactions": [{
"amount": {"total": payment_amount, "currency": "USD"},
"description": PAYMENT_DESC}]})
if payment.create():
print("Payment[%s] created successfully" % (payment.id))
for link in payment.links:
if link.method == "REDIRECT":
redirect_url = link.href
break
else:
print("Error while creating payment:")
print(payment.error)
return redirect(redirect_url)
@app.route('/approve-payment', methods=['GET'])
def approve_payment():
payment_id = request.args.get('payment_id', None)
payer_id = request.args.get('payer_id', None)
if not payer_id or not payment_id:
return redirect(APPROVE_PAYMENT_FAILED_URL)
payment = paypalrestsdk.Payment.find(payment_id)
if payment.execute({"payer_id": payer_id}):
print("Payment[%s] execute successfully" % (payment.id))
return redirect(APPROVE_PAYMENT_SUCCESS_URL)
return redirect(APPROVE_PAYMENT_FAILED_URL)
@app.route("/check-access", methods=['POST'])
def check_access():
# add hash token to session
crc = request.form["crc"]
rst = re.match(access_code_pattern, crc)
if not rst:
return redirect(ACCESS_CHECKING_URL)
session["pass"] = True
return redirect("/create-payment")
#-----------------------------------------------------------------------------
# Only for debugging
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(PAYMENT_SERVER_PORT)
app.run(host='0.0.0.0', port=port, debug=True)