-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathexamples.py
279 lines (247 loc) · 9.83 KB
/
examples.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
# -*- coding: utf-8 -*-
import json
import logging
import os
from random import sample
from string import ascii_letters, digits
import time
import uuid
from flask import Flask, jsonify, request
from wechatpayv3 import WeChatPay, WeChatPayType
# 微信支付商户号(直连模式)或服务商商户号(服务商模式,即sp_mchid)
MCHID = '1234567890'
# 商户证书私钥
with open('path_to_key/apiclient_key.pem') as f:
PRIVATE_KEY = f.read()
# 商户证书序列号
CERT_SERIAL_NO = '444F4864EA9B34415...'
# API v3密钥, https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay3_2.shtml
APIV3_KEY = 'MIIEvwIBADANBgkqhkiG9w0BAQE...'
# APPID,应用ID或服务商模式下的sp_appid
APPID = 'wxd678efh567hg6787'
# 回调地址,也可以在调用接口的时候覆盖
NOTIFY_URL = 'https://www.xxxx.com/notify'
# 微信支付平台证书缓存目录,减少证书下载调用次数,首次使用确保此目录为空目录。
# 初始调试时可不设置,调试通过后再设置,示例值:'./cert'。
# 新申请的微信支付商户号如果使用平台公钥模式,可以不用设置此参数。
CERT_DIR = None
# 日志记录器,记录web请求和回调细节
logging.basicConfig(filename=os.path.join(os.getcwd(), 'demo.log'), level=logging.DEBUG, filemode='a', format='%(asctime)s - %(process)s - %(levelname)s: %(message)s')
LOGGER = logging.getLogger("demo")
# 接入模式:False=直连商户模式,True=服务商模式
PARTNER_MODE = False
# 代理设置,None或者{"https": "http://10.10.1.10:1080"},详细格式参见https://requests.readthedocs.io/en/latest/user/advanced/#proxies
PROXY = None
# 请求超时时间配置
TIMEOUT = (10, 30) # 建立连接最大超时时间是10s,读取响应的最大超时时间是30s
# 微信支付平台公钥
# 注:2024年09月后新申请的微信支付账号使用公钥模式初始化,需配置此参数。
with open('path_to_wechat_pay_public_key/pub_key.pem') as f:
PUBLIC_KEY = f.read()
# 微信支付平台公钥ID
# 注:2024年09月后新申请的微信支付账号使用公钥模式初始化,需配置此参数。
PUBLIC_KEY_ID = 'PUB_KEY_ID_444F4864EA9B34415...'
# 初始化
wxpay = WeChatPay(
wechatpay_type=WeChatPayType.NATIVE,
mchid=MCHID,
private_key=PRIVATE_KEY,
cert_serial_no=CERT_SERIAL_NO,
apiv3_key=APIV3_KEY,
appid=APPID,
notify_url=NOTIFY_URL,
cert_dir=CERT_DIR,
logger=LOGGER,
partner_mode=PARTNER_MODE,
proxy=PROXY,
timeout=TIMEOUT)
# 微信支付平台公钥模式初始化,2024年09月之后申请的账号参考使用此模式。
# 平台证书模式向公钥模式切换期间也请使用此方式初始化。
wxpay = WeChatPay(
wechatpay_type=WeChatPayType.NATIVE,
mchid=MCHID,
private_key=PRIVATE_KEY,
cert_serial_no=CERT_SERIAL_NO,
apiv3_key=APIV3_KEY,
appid=APPID,
notify_url=NOTIFY_URL,
logger=LOGGER,
partner_mode=PARTNER_MODE,
proxy=PROXY,
timeout=TIMEOUT,
public_key=PUBLIC_KEY,
public_key_id=PUBLIC_KEY_ID)
app = Flask(__name__)
@app.route('/pay')
def pay():
# 以native下单为例,下单成功后即可获取到'code_url',将'code_url'转换为二维码,并用微信扫码即可进行支付测试。
out_trade_no = ''.join(sample(ascii_letters + digits, 8))
description = 'demo-description'
amount = 1
code, message = wxpay.pay(
description=description,
out_trade_no=out_trade_no,
amount={'total': amount},
pay_type=WeChatPayType.NATIVE
)
return jsonify({'code': code, 'message': message})
@app.route('/pay_jsapi')
def pay_jsapi():
# 以jsapi下单为例,下单成功后,将prepay_id和其他必须的参数组合传递给JSSDK的wx.chooseWXPay接口唤起支付
out_trade_no = ''.join(sample(ascii_letters + digits, 8))
description = 'demo-description'
amount = 1
payer = {'openid': 'demo-openid'}
code, message = wxpay.pay(
description=description,
out_trade_no=out_trade_no,
amount={'total': amount},
pay_type=WeChatPayType.JSAPI,
payer=payer
)
result = json.loads(message)
if code in range(200, 300):
prepay_id = result.get('prepay_id')
timestamp = str(int(time.time()))
noncestr = str(uuid.uuid4()).replace('-', '')
package = 'prepay_id=' + prepay_id
sign = wxpay.sign([APPID, timestamp, noncestr, package])
signtype = 'RSA'
return jsonify({'code': 0, 'result': {
'appId': APPID,
'timeStamp': timestamp,
'nonceStr': noncestr,
'package': 'prepay_id=%s' % prepay_id,
'signType': signtype,
'paySign': sign
}})
else:
return jsonify({'code': -1, 'result': {'reason': result.get('code')}})
@app.route('/pay_h5')
def pay_h5():
# 以h5下单为例,下单成功后,将获取的的h5_url传递给前端跳转唤起支付。
out_trade_no = ''.join(sample(ascii_letters + digits, 8))
description = 'demo-description'
amount = 1
scene_info = {'payer_client_ip': '1.2.3.4', 'h5_info': {'type': 'Wap'}}
code, message = wxpay.pay(
description=description,
out_trade_no=out_trade_no,
amount={'total': amount},
pay_type=WeChatPayType.H5,
scene_info=scene_info
)
return jsonify({'code': code, 'message': message})
@app.route('/pay_miniprog')
def pay_miniprog():
# 以小程序下单为例,下单成功后,将prepay_id和其他必须的参数组合传递给小程序的wx.requestPayment接口唤起支付
out_trade_no = ''.join(sample(ascii_letters + digits, 8))
description = 'demo-description'
amount = 1
payer = {'openid': 'demo-openid'}
code, message = wxpay.pay(
description=description,
out_trade_no=out_trade_no,
amount={'total': amount},
pay_type=WeChatPayType.MINIPROG,
payer=payer
)
result = json.loads(message)
if code in range(200, 300):
prepay_id = result.get('prepay_id')
timestamp = str(int(time.time()))
noncestr = str(uuid.uuid4()).replace('-', '')
package = 'prepay_id=' + prepay_id
sign = wxpay.sign(data=[APPID, timestamp, noncestr, package])
signtype = 'RSA'
return jsonify({'code': 0, 'result': {
'appId': APPID,
'timeStamp': timestamp,
'nonceStr': noncestr,
'package': 'prepay_id=%s' % prepay_id,
'signType': signtype,
'paySign': sign
}})
else:
return jsonify({'code': -1, 'result': {'reason': result.get('code')}})
@app.route('/pay_app')
def pay_app():
# 以app下单为例,下单成功后,将prepay_id和其他必须的参数组合传递给IOS或ANDROID SDK接口唤起支付
out_trade_no = ''.join(sample(ascii_letters + digits, 8))
description = 'demo-description'
amount = 1
code, message = wxpay.pay(
description=description,
out_trade_no=out_trade_no,
amount={'total': amount},
pay_type=WeChatPayType.APP
)
result = json.loads(message)
if code in range(200, 300):
prepay_id = result.get('prepay_id')
timestamp = str(int(time.time()))
noncestr = str(uuid.uuid4()).replace('-', '')
package = 'Sign=WXPay'
sign = wxpay.sign(data=[APPID, timestamp, noncestr, prepay_id])
return jsonify({'code': 0, 'result': {
'appid': APPID,
'partnerid': MCHID,
'prepayid': prepay_id,
'package': package,
'nonceStr': noncestr,
'timestamp': timestamp,
'sign': sign
}})
else:
return jsonify({'code': -1, 'result': {'reason': result.get('code')}})
@app.route('/pay_codepay')
def pay_codepay():
# 以付款码支付为例,终端条码枪扫描用户付款码将解码后的auth_code放入payer传递给微信支付服务器扣款。
out_trade_no = ''.join(sample(ascii_letters + digits, 8))
description = 'demo-description'
amount = 1
payer = {'auth_code': '130061098828009406'}
scene_info={'store_info' : {'id' : '0001'}}
code, message = wxpay.pay(
description=description,
out_trade_no=out_trade_no,
amount={'total': amount},
payer=payer,
scene_info=scene_info,
pay_type=WeChatPayType.CODEPAY
)
result = json.loads(message)
if code in range(200, 300):
trade_state = result.get('trade_state')
trade_state_desc = result.get('trade_state_desc')
if trade_state == 'SUCCESS':
# 扣款成功,提示终端做后续处理
return jsonify({'code': 0, 'result': {'reason': trade_state_desc}})
else:
# 扣款失败,提示终端做后续处理
return jsonify({'code': -1, 'result': {'reason': trade_state_desc}})
else:
return jsonify({'code': -1, 'result': {'reason': result.get('code')}})
@app.route('/notify', methods=['POST'])
def notify():
result = wxpay.callback(request.headers, request.data)
if result and result.get('event_type') == 'TRANSACTION.SUCCESS':
resp = result.get('resource')
appid = resp.get('appid')
mchid = resp.get('mchid')
out_trade_no = resp.get('out_trade_no')
transaction_id = resp.get('transaction_id')
trade_type = resp.get('trade_type')
trade_state = resp.get('trade_state')
trade_state_desc = resp.get('trade_state_desc')
bank_type = resp.get('bank_type')
attach = resp.get('attach')
success_time = resp.get('success_time')
payer = resp.get('payer')
amount = resp.get('amount').get('total')
# TODO: 根据返回参数进行必要的业务处理,处理完后返回200或204
return jsonify({'code': 'SUCCESS', 'message': '成功'})
else:
return jsonify({'code': 'FAILED', 'message': '失败'}), 500
if __name__ == '__main__':
app.run()