支付mock笔记(一)

mock原理

通过hosts指向自己部署的服务,模拟返回第三方支付端参数达到支付mock效果

工具准备

python,flask,stunnel(生成本地pem后缀证书用于访问https,依赖openssl,证书放在flask同目录下)

paymock脚本编码(基于flask)

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
# !/usr/bin/env python
# -*- coding :utf-8 -*-
import threading
from flask import Flask, request, render_template, send_from_directory
import requests
import json
import hashlib
from base64 import b64encode
from Crypto.Cipher import AES
import time, datetime
import xmltodict
from urllib import urlencode, quote
app = Flask(__name__)
######## Pay ############
def sortedDictValues1(adict):
items = adict.items()
items.sort()
# return dict(items)
return [key for key, value in items]
salt = 'eh9tbxpzbcq24zgq152yhlcryimhij2k'
def getapisign(dictparam):
sortres = sortedDictValues1(dictparam)
apistr = ''
for x in sortres:
if apistr:
apistr = apistr + '&'
apistr = apistr + str(x) + '=' + dictparam[x]
apisgsrc = apistr + salt
#print apisgsrc
apisg = hashlib.md5()
apisg.update(apisgsrc.encode("utf-8"))
apisign = apisg.hexdigest()
return apisign
@app.route('/standard/auth.htm')
def alipay():
return request.form
@app.route('/gatewayM.do')
def alipay_mapi():
#print request.values
print request.method
servicename = request.args.get("service")
if "notify_verify" == servicename:
#check notify
print "+++++++++++notify check"
return 'true'
elif "create_direct_pay_by_user" == servicename:
#create pay
# create trade_no
# notify_id
notreq = {}
notreq['body'] = request.args.get('body')
notreq['buyer_email'] = "mock_alipay@jj.com" #hardcode
notreq['buyer_id'] = '2088002902500000' #hardcode
notreq['exterface'] = request.args.get('service')
notreq['is_success'] = 'T'
notreq['notify_id'] = 'RqPnCoPT3K9%2Fvwbh3InXS9kO3drvvK3F69X3aC6JaYMjIDVFAYTgC8uOdDBs7xVfI6S7'
notreq['notify_time'] = time.strftime("%Y-%m-%d %H:%M:%S")
notreq['notify_type'] = 'trade_status_sync'
notreq['out_trade_no'] = request.args.get('out_trade_no')
notreq['payment_type'] = request.args.get('payment_type')
notreq['seller_email'] = request.args.get('seller_email')
notreq['seller_id'] = '2088902537249214'
notreq["subject"] = request.args.get("subject")
notreq["total_fee"] = request.args.get("total_fee")
notreq['trade_no'] = '2016050921001004180253708841'
notreq['trade_status'] = 'TRADE_SUCCESS'
# sign
dictpayload=dict(notreq.items())
apisign = getapisign(dictpayload)
print apisign
notreq['sign'] = "skjdfksjdlkfjlskdjflkdjflkjdlkfjdlkjfl"#apisign
notreq['sign_type'] = 'MD5'
# send notify to notify url
url = request.args.get('notify_url')
print url
headers = {
'content-type': 'application/x-www-form-urlencoded',
#'User-Agent':'tangtang',
#'User-Agent':'zhe;3.3.5;HUAWEI U9508;Android4.2.2',
}
r = requests.post(url, data=notreq, headers=headers)
#r = requests.get(url, params=notreq, headers=headers)
print '-----------------------'
print r.text
return 'ddd:'+r.text
else:
#return request.get_data()
content = "Service:" + request.args.get("service") + "<br>"
content += "body: " + request.args.get("body") + "<br>"
content += "total_fee: " + request.args.get("total_fee") + "<br>"
content += "trade No: " + request.args.get("out_trade_no") + "<br>"
content += "notify: " + request.args.get("notify_url") + "<br>"
return content
@app.route('/gateway.do')
def pay_manual():
notreq = {}
notreq = request.args.to_dict()
notreq["UA"] = request.headers.get('User-Agent')
return render_template("PayMockPage.html", paytype="AliPay", autourl="/alipay/pcauto", req=notreq)
@app.route('/alipay/pcauto')
def alipay_auto():
print "alipay start"
print request.method
notreq = {}
if request.args.get('service') == "alipay.acquire.page.createandpay":
notreq["gmt_create"] = time.strftime("%Y-%m-%d %H:%M:%S")
notreq["is_total_fee_adjust"] = "N",
notreq["gmt_payment"] = time.strftime("%Y-%m-%d %H:%M:%S")
notreq["notify_action_type"] = "payByAccountAction"
else:
notreq['is_success'] = 'T'
notreq['exterface'] = request.args.get('exterface')
notreq['payment_type'] = request.args.get('payment_type')
notreq['body'] = request.args.get('body')
notreq['buyer_email'] = "mock_alipay@jp.com" #hardcode
notreq['buyer_id'] = '2088002902000000' #hardcode
notreq['notify_id'] = '000000THIS000IS000MOCK000000'
notreq['notify_time'] = time.strftime("%Y-%m-%d %H:%M:%S")
notreq['notify_type'] = 'trade_status_sync'
notreq['out_trade_no'] = request.args.get('out_trade_no')
notreq['seller_email'] = request.args.get('seller_email')
notreq['seller_id'] = '2088902537249214'
notreq["subject"] = request.args.get("subject")
notreq["total_fee"] = request.args.get("total_fee")
notreq['trade_no'] = time.strftime("%Y%m%d%H%M%S") + '04180288888888'
notreq['trade_status'] = 'TRADE_SUCCESS'
notreq['sign'] = "000000ThisIsAMockSign000000"#apisign
notreq['sign_type'] = request.args.get("sign_type")
# send notify to notify url
url = request.args.get('notify_url')
#url = "http://192.168.148.21/paygate/gateway_pay_async_push/pc_alipay/1490493"
print url
headers = {
'content-type': 'application/x-www-form-urlencoded',
'User-Agent':request.args.get("ua"),
#'User-Agent':'zhe;3.3.5;HUAWEI U9508;Android4.2.2',
}
print '-------start-----------'
r = requests.post(url, data=notreq, headers=headers)
#r = requests.get(url, params=notreq, headers=headers)
print '-----------------------'
print r.text
return r.text
#------alipay wap pay-------
@app.route('/service/rest.htm', methods=['POST','GET'])
def alipay_wap_manual():
print request.method
print request.form.to_dict()
return "2016092097ed2ed152e59a7e8474375267552558"
####Union Pay####
@app.route('/gateway/api/frontTransReq.do', methods=['POST'])
def unionpay_manual():
print request.method
notreq = {}
notreq = request.form.to_dict()
notreq["UA"] = request.headers.get('User-Agent')
return render_template("PayMockPage.html", paytype="Unino Pay", autourl="/unionpay/pcauto", req=notreq)
@app.route('/unionpay/pcauto')
def unionpay_auto():
print request.method
notreq = {}
notreq['version'] = request.args.get('version')
notreq['encoding'] = request.args.get('encoding')
notreq['signMethod'] = request.args.get('signMethod')
notreq['certId'] = request.args.get('certId')
notreq['txnType'] = request.args.get('txnType')
notreq['txnSubType'] = request.args.get('txnSubType')
notreq['bizType'] = request.args.get('bizType')
notreq["accessType"] = request.args.get("accessType")
notreq["orderId"] = request.args.get("orderId")
notreq["txnTime"] = request.args.get("txnTime")
notreq["txnAmt"] = request.args.get("txnAmt")
notreq["settleAmt"] = request.args.get("txnAmt")
notreq["currencyCode"] = request.args.get("currencyCode")
notreq["settleCurrencyCode"] = request.args.get("currencyCode")
notreq["merId"] = request.args.get("merId")
notreq["reqReserved"] = request.args.get("reqReserved")
notreq["signature"] = "ThisIsPayMockThisIsPayMockThisIsPayMockThisIsPayMockThisIsPayMockThisIsPayMockThisIsPayM/11gO/W+ubXure/7dR4Hn3x1No5kBGtnsbYvo2sb/AHIY8sRKWdH+JC6slIohL+TlPBFs7hds/Kn5hdYRadykDJIDA0cADLL3ZDG4ziuqVZK/XFV9GZkoiseQ7WYcVe8SK/JHgVSpyruYurwgnk726UgA0MQ5wl9Y79lRChEB5q2/4q3rCZLBNRS5n9gWpDgu1dgSMqQgG4V34rLwDupA1aYVWZ/4WwjANbSNGVUNEsLAkJmF5mN0Ci/+oURqg=="
notreq["respCode"] = "00"
notreq["respMsg"] = "\u6210\u529f[0000000]"
notreq["queryId"] = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3]+"8888"
#notreq["tn"] = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3]+"8888"
notreq["settleDate"] = datetime.datetime.now().strftime("%m%d")
notreq["traceNo"] = "888888"
notreq["traceTime"] = datetime.datetime.now().strftime("%m%d%H%M%S")
notreq["accNo"] = "6216***********8888"
#notreq["UA"] = request.headers.get('User-Agent')
# send notify to notify url
url = request.args.get('backUrl')
print url
headers = {
'content-type': 'application/x-www-form-urlencoded',
'User-Agent':request.args.get("UA"),
#'User-Agent':'zhe;3.3.5;HUAWEI U9508;Android4.2.2',
}
r = requests.post(url, data=notreq, headers=headers)
print '-----------------------'
print r.text
return r.text
######## WX Pay ########
@app.route('/pay/unifiedorder', methods=['POST'])
def wxpay_create_order():
print request.method
rec_xml = request.get_data()
rec_dict = xmltodict.parse(rec_xml)
paydata = {}
paydata['notify_url'] = rec_dict['xml']['notify_url']
paydata['appid'] = rec_dict['xml']['appid']
paydata['mch_id'] = rec_dict['xml']['mch_id']
paydata['body'] = rec_dict['xml']['body'].encode('utf-8')
paydata['trade_type'] = rec_dict['xml']['trade_type']
paydata['total_fee'] = rec_dict['xml']['total_fee']
paydata['out_trade_no'] = rec_dict['xml']['out_trade_no']
apistr = urlencode(paydata)
print apistr
resb_xml = "<xml>"
resb_xml += "<return_code><![CDATA[SUCCESS]]></return_code>"
resb_xml += "<return_msg><![CDATA[OK]]></return_msg>"
resb_xml += "<result_code><![CDATA[SUCCESS]]></result_code>"
resb_xml += "<appid><![CDATA[" + paydata['appid'] + "]]></appid>"
resb_xml += "<mch_id><![CDATA[" + paydata['mch_id'] + "]]></mch_id>"
resb_xml += "<prepay_id><![CDATA[wx" + datetime.datetime.now().strftime("%Y%m%d%H%M%S") + "thisismock8888888888]]></prepay_id>"
resb_xml += "<trade_type><![CDATA[" + paydata['trade_type'] + "]]></trade_type>"
resb_xml += "<code_url><![CDATA[" + "http://192.168.149.34:80/wxpay/pcauto?" + apistr + "]]></code_url>"
resb_xml += "<nonce_str><![CDATA[" + "ThisIsMockThisIsMock888888888888" + "]]></nonce_str>"
resb_xml += "<sign><![CDATA[" + "ThisIsMockThisIsMock888888888888" + "]]></sign>"
resb_xml += "</xml>"
return resb_xml
@app.route('/wxpay/pcauto')
def wxpay_auto():
print request.method
appid = request.args.get('appid')
mch_id = request.args.get('mch_id')
body = request.args.get('body')
trade_type = request.args.get('trade_type')
total_fee = request.args.get('total_fee')
out_trade_no = request.args.get('out_trade_no')
resq_xml = "<xml>"
resq_xml += "<return_code><![CDATA[SUCCESS]]></return_code>"
resq_xml += "<result_code><![CDATA[SUCCESS]]></result_code>"
resq_xml += "<appid><![CDATA[" + appid + "]]></appid>"
resq_xml += "<mch_id><![CDATA[" + mch_id + "]]></mch_id>"
resq_xml += "<attach><![CDATA[" + body + "]]></attach>"
resq_xml += "<openid><![CDATA[" + "ThisIsMockThisIsMock88888888" + "]]></openid>"
resq_xml += "<trade_type><![CDATA[" + trade_type + "]]></trade_type>"
resq_xml += "<bank_type><![CDATA[ICBC_DEBIT]]></bank_type>"
resq_xml += "<total_fee><![CDATA[" + total_fee + "]]></total_fee>"
resq_xml += "<transaction_id><![CDATA[" + datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3]+"88888888888" + "]]></transaction_id>"
resq_xml += "<out_trade_no><![CDATA[" + out_trade_no + "]]></out_trade_no>"
resq_xml += "<time_end><![CDATA[" + datetime.datetime.now().strftime("%Y%m%d%H%M%S") + "]]></time_end>"
resq_xml += "<nonce_str><![CDATA[" + "ThisIsMockThisIsMock888888888888" + "]]></nonce_str>"
resq_xml += "<sign><![CDATA[" + "ThisIsMockThisIsMock888888888888" + "]]></sign>"
resq_xml += "</xml>"
# send notify to notify url
url = request.args.get('notify_url')
print url
headers = {
'content-type': 'application/xml',
'User-Agent':request.args.get("UA"),
}
r = requests.post(url, data=resq_xml.encode('utf-8'), headers=headers)
print '-----------------------'
print r.text
html = '<script type="text/javascript">'
if "SUCCESS" in r.text or "success" in r.text:
html += 'alert("Pay Success!");'
else:
html += 'alert("Pay Failed!!!\r\n' + r.text.replace('<',"&lt;").replace('>',"&gt;").replace('"',"&quot;") + '")'
html += 'window.opener=null;window.close();</script>'
return html
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80, debug=True)

生成vpsee证书(通过stunnel)

  • openssl genrsa -out key.pem 2048
  • openssl req -new -x509 -key key.pem -out cert.pem -days 1095
  • cat key.pem cert.pem >>vpsee.pem

    https代理配置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    pid =
    cert = vpsee.pem
    debug = 7
    foreground = yes
    [https]
    accept = 443
    connect = 80
    `

部署mock前端

包含static和templates文件夹

修改alipay配置(以修改php文件为例,pc端)

  • 修改alipay源码;
    /xxxx.com/ThinkPHP/Extend/Vendor/Alipay/alipay_notify.class.php

    1
    2
    3
    4
    5
    6
    7
    8
    function verifyNotify()
    注释(//$isSign = $this->getSignVeryfy($_POST, $_POST["sign"]);)
    添加 $isSign = true;
    注释( //if (! empty($_POST["notify_id"])) {$responseTxt = $this->getResponse($_POST["notify_id"]);})
    function verifyReturn()
    注释(//$isSign = $this->getSignVeryfy($_REQUEST, $_REQUEST["sign"]);)
    添加 $isSign = true;
  • 新增支付服务ua

    1
    2
    /xxxx/Conf/config.php add 'GATEWAY_USER_AGENT'=> 'wushi',
    rm -rf /xxxx/Runtime/*
  • 修改支付回调url

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    /xxxx.com/Conf/config.php
    //支付异步回调通知URL(todo 正式环境地方)
    'PAY_ASYNCHRONOUS_CALLBACK' => 'http:/xxxx.com/paygate/gateway_pay_async_push',
    //支付同步回调通知URL(todo 正式环境地方)
    'PAY_SYNCHRONOUS_CALLBACK' => 'http://xxxx.com/paygate/gateway_pay_sync_push',
    //退款异步回调通知URL(todo 正式环境地方)
    'REFUND_ASYNCHRONOUS_CALLBACK' => 'http://xxxx.com/refundgate/gateway_refund_async_push',
    to
    //支付异步回调通知URL(todo 正式环境地方)
    'PAY_ASYNCHRONOUS_CALLBACK' => 'http://192.168.143.171:8139/paygate/gateway_pay_async_push',
    //支付同步回调通知URL(todo 正式环境地方)
    'PAY_SYNCHRONOUS_CALLBACK' => 'http://192.168.143.171:8139/paygate/gateway_pay_sync_push',
    //退款异步回调通知URL(todo 正式环境地方)
    'REFUND_ASYNCHRONOUS_CALLBACK' => 'http://192.168.143.171:8139/refundgate/gateway_refund_async_push',

rm -rf /xxxx.com/Runtime/*

  • 配置host
    192.168.149.34 mapi.alipay.com