Backend Development 5 min read

Integrating WeChat Pay with a Flask Backend and Mini Program

This guide explains how to set up a Flask backend on Windows or CentOS, generate the required signatures for WeChat's unified order API, obtain a prepay_id, and call the mini‑program wx.requestPayment interface with the correct parameters for successful payment processing.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Integrating WeChat Pay with a Flask Backend and Mini Program

Development Environment

Local: Windows 10, Python 2.7.13 (64‑bit), Flask 0.12.2.

Online: CentOS 6.5, Python 2.7.13 (64‑bit), Flask 0.12.2.

1. Write the backend program

Review the unified order API. Two important points: a) the user identifier (openid) is required when trade_type=JSAPI; b) the request must be signed.

Generate the signature.

Set the parameters to be signed (include openid, otherwise the signature will be incorrect).

Example data dictionary:

data = {<br>    'appid': appid,<br>    'mch_id': mch_id,<br>    'nonce_str': get_nonce_str(),<br>    'body': '测试',  # product description<br>    'out_trade_no': str(int(time.time())),  # merchant order number<br>    'total_fee': '1',<br>    'spbill_create_ip': spbill_create_ip,<br>    'notify_url': notify_url,<br>    'attach': '{"msg": "自定义数据"}',<br>    'trade_type': trade_type,<br>    'openid': '1111111111111111111111'<br>}

Sort the parameters, concatenate the merchant key, and compute the MD5 hash:

stringA = '&'.join(["{0}={1}".format(k, pay_data.get(k)) for k in sorted(pay_data)])<br>stringSignTemp = '{0}&key={1}'.format(stringA, self.merchant_key)<br>sign = hashlib.md5(stringSignTemp).hexdigest()

Add the generated MD5 as the sign field, convert the dictionary to XML, and POST it to the WeChat API to obtain prepay_id :

data['sign'] = md5<br>req = urllib2.Request(url, data, headers={'Content-Type': 'application/xml'})<br>result = urllib2.urlopen(req, timeout=timeout).read()

Generate the parameters required by wx.requestPayment in the mini‑program, noting that the package field must be prepay_id=YOUR_PREPAY_ID :

paySign_data = {<br>    'appId': appId,<br>    'timeStamp': timeStamp,<br>    'nonceStr': nonceStr,<br>    'package': 'prepay_id={0}'.format(prepay_id),<br>    'signType': 'MD5'<br>}

Follow the same signing steps (including the merchant key) to create paySign . Return all these fields to the mini‑program.

2. Write the mini‑program

Create a quick project.

Call the backend endpoint to get the payment parameters and invoke wx.requestPayment directly.

wx.request({<br>    url: 'http://127.0.0.1:5000/wxpay/pay',<br>    header: {'content-type': 'application/json'},<br>    success: function (res) {<br>        wx.requestPayment({<br>            timeStamp: res.data.timeStamp,<br>            nonceStr: res.data.nonceStr,<br>            package: res.data.package,<br>            signType: res.data.signType,<br>            paySign: res.data.paySign,<br>            success: function (res) { console.log(res) },<br>            fail: function (res) { console.log(res) }<br>        })<br>    }<br>})

WeChat will send a POST notification (XML) to the server after payment. The server should verify the data and respond with XML indicating success:

'return_code': 'SUCCESS',<br>'return_msg': 'OK'

Disclaimer: This article is compiled from online sources; copyright belongs to the original author. If any rights are infringed, please contact us for removal or authorization.

BackendFlaskmini-programWeChat PayPayment Integration
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.