-
Notifications
You must be signed in to change notification settings - Fork 27
/
web.py
205 lines (180 loc) · 7.86 KB
/
web.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
# This is just for very basic implementation reference, in production, you should validate the incoming requests and implement your backend more securely.
import datetime
import json
import os
from flask import Flask, render_template, request, jsonify
from midtransclient import Snap, CoreApi
# @TODO: Change/fill the following API Keys variable with Your own server & client keys
# You can find it in Merchant Portal -> Settings -> Access keys
SERVER_KEY = 'SB-Mid-server-GwUP_WGbJPXsDzsNEBRs8IYA'
CLIENT_KEY = 'SB-Mid-client-61XuGAwQ8Bj8LxSS'
# Note: by default it uses hardcoded sandbox demo API keys for demonstration purpose
app = Flask(__name__)
#==============#
# Using SNAP
#==============#
# Very simple Snap checkout
@app.route('/simple_checkout')
def simple_checkout():
snap = Snap(
is_production=False,
server_key=SERVER_KEY,
client_key=CLIENT_KEY
)
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
transaction_token = snap.create_transaction_token({
"transaction_details": {
"order_id": "order-id-python-"+timestamp,
"gross_amount": 200000
}, "credit_card":{
"secure" : True
}
})
return render_template('simple_checkout.html',
token = transaction_token,
client_key = snap.api_config.client_key)
#==============#
# Using Core API - Credit Card
#==============#
# [0] Setup API client and config
core = CoreApi(
is_production=False,
server_key=SERVER_KEY,
client_key=CLIENT_KEY
)
# [1] Render HTML+JS web page to get card token_id and [3] 3DS authentication
@app.route('/simple_core_api_checkout')
def simple_core_api_checkout():
return render_template('simple_core_api_checkout.html',
client_key = core.api_config.client_key)
# [2] Handle Core API credit card token_id charge
@app.route('/charge_core_api_ajax', methods=['POST'])
def charge_core_api_ajax():
request_json = request.get_json()
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
try:
charge_api_response = core.charge({
"payment_type": "credit_card",
"transaction_details": {
"gross_amount": 200000,
"order_id": "order-id-python-"+timestamp,
},
"credit_card":{
"token_id": request_json['token_id'],
"authentication": request_json['authenticate_3ds'],
}
})
except Exception as e:
charge_api_response = e.api_response_dict
return charge_api_response
# [4] Handle Core API check transaction status
@app.route('/check_transaction_status', methods=['POST'])
def check_transaction_status():
request_json = request.get_json()
transaction_status = core.transactions.status(request_json['transaction_id'])
# [5.A] Handle transaction status on your backend
# Sample transaction_status handling logic
if transaction_status == 'capture':
if fraud_status == 'challenge':
# TODO set transaction status on your databaase to 'challenge'
None
elif fraud_status == 'accept':
# TODO set transaction status on your databaase to 'success'
None
elif transaction_status == 'settlement':
# TODO set transaction status on your databaase to 'success'
# Note: Non-card transaction will become 'settlement' on payment success
# Card transaction will also become 'settlement' D+1, which you can ignore
# because most of the time 'capture' is enough to be considered as success
None
elif transaction_status == 'cancel' or transaction_status == 'deny' or transaction_status == 'expire':
# TODO set transaction status on your databaase to 'failure'
None
elif transaction_status == 'pending':
# TODO set transaction status on your databaase to 'pending' / waiting payment
None
elif transaction_status == 'refund':
# TODO set transaction status on your databaase to 'refund'
None
return jsonify(transaction_status)
#==============#
# Handling HTTP Post Notification
#==============#
# [4] Handle Core API check transaction status
@app.route('/notification_handler', methods=['POST'])
def notification_handler():
request_json = request.get_json()
transaction_status_dict = core.transactions.notification(request_json)
order_id = request_json['order_id']
transaction_status = request_json['transaction_status']
fraud_status = request_json['fraud_status']
transaction_json = json.dumps(transaction_status_dict)
summary = 'Transaction notification received. Order ID: {order_id}. Transaction status: {transaction_status}. Fraud status: {fraud_status}.<br>Raw notification object:<pre>{transaction_json}</pre>'.format(order_id=order_id,transaction_status=transaction_status,fraud_status=fraud_status,transaction_json=transaction_json)
# [5.B] Handle transaction status on your backend
# Sample transaction_status handling logic
if transaction_status == 'capture':
if fraud_status == 'challenge':
# TODO set transaction status on your databaase to 'challenge'
None
elif fraud_status == 'accept':
# TODO set transaction status on your databaase to 'success'
None
elif transaction_status == 'settlement':
# TODO set transaction status on your databaase to 'success'
# Note: Non card transaction will become 'settlement' on payment success
# Credit card will also become 'settlement' D+1, which you can ignore
# because most of the time 'capture' is enough to be considered as success
None
elif transaction_status == 'cancel' or transaction_status == 'deny' or transaction_status == 'expire':
# TODO set transaction status on your databaase to 'failure'
None
elif transaction_status == 'pending':
# TODO set transaction status on your databaase to 'pending' / waiting payment
None
elif transaction_status == 'refund':
# TODO set transaction status on your databaase to 'refund'
None
app.logger.info(summary)
return jsonify(summary)
#==============#
# Using Core API - other payment method, example: Permata VA
#==============#
@app.route('/simple_core_api_checkout_permata', methods=['GET'])
def simple_core_api_checkout_permata():
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
charge_api_response = core.charge({
"payment_type": "bank_transfer",
"transaction_details": {
"gross_amount": 200000,
"order_id": "order-id-python-"+timestamp,
}
})
return render_template('simple_core_api_checkout_permata.html',
permata_va_number = charge_api_response['permata_va_number'],
gross_amount = charge_api_response['gross_amount'],
order_id = charge_api_response['order_id'])
#==============#
# Run Flask app
#==============#
# Homepage of this web app
@app.route('/')
def index():
if not SERVER_KEY or not CLIENT_KEY:
# non-relevant function only used for demo/example purpose
return printExampleWarningMessage()
return render_template('index.html')
# credit card frontend demo
@app.route('/core_api_credit_card_frontend_sample')
def core_api_credit_card_frontend_sample():
return render_template('core_api_credit_card_frontend_sample.html',
client_key = core.api_config.client_key)
def printExampleWarningMessage():
pathfile = os.path.abspath("web.py")
message = "<code><h4>Please set your server key and client key from sandbox</h4>In file: " + pathfile
message += "<br><br># Set Your server key"
message += "<br># You can find it in Merchant Portal -> Settings -> Access keys"
message += "<br>SERVER_KEY = ''"
message += "<br>CLIENT_KEY = ''</code>"
return message
if __name__ == '__main__':
app.run(debug=True,port=5000,host='0.0.0.0')