Notes for developing WeChat payment using Python: python payment

Source: Internet
Author: User

Notes for developing and paying using Python: python payment

Preface

Payment is an innovative mobile payment product jointly launched by tenpay. Nowadays, with the opening of payment, there are more and more related demands. Many developers are faced with a lot of questions when developing payment and applying for payment.

To achieve smooth development, you must first have a clear understanding of the business process. Here, the public account payment is used as an example. Therefore, the business flow chart in the Payment Official Document is also used:

Next, we will focus on several key points in the development process, including:

1. Generate merchant orders and call unified order API

2. server interaction data format

3, The Public number to pay the page through the JS-API to start to pay

4. Notify the merchant of the payment result asynchronously (callback)

1. Generate merchant orders and call unified order API

This corresponds to steps 4th and 5th in the business process. The Merchant's background first generates an order for the user, and then calls the [Unified order] interface to submit an order to the payment system. The key point here is the signature generation.

The procedure is as follows:

1. Splice all valid parameters in the form of "k = v". Valid parameters refer to non-null parameters. That is to say, if the parameter is null, they are not involved in the signature;

2. Connect all "k = v" pairs with "&" to obtain a string like "k1 = v1 & k2 = v2 & k3 = v3;

3. splice the payment API key at the end, for example, "k1 = v1 & k2 = v2 & k3 = v3 & key = secret ";

4. Complete the MD5 operation to obtain the signature.

The signature method is named HMAC (Hash-based Message Authentication Code, based on the Hash Message Code ). Based on this idea, the following signature methods can be implemented:

Def gen_sign (params, key): "Signature generation function: param params: parameter, dict object: param key: API key: return: sign string "param_list = [] for k in sorted (params. keys (): v = params. get (k) if not v: # The parameter value is null and does not participate in the signature continue param_list.append ('{0} = {1 }'. format (k, v) # splice key param_list.append ('key = {} 'at the end {}'. format (key) # Use & to connect each k-v pair, and then perform the MD5 operation on the string to return md5 ('&'. join (param_list ). encode ('utf8 ')). hexdigest ()

There is a random string in the parameters involved in the signature, and there are many methods in Python, of course, you can also useuuid Library to generate:

Def gen_nonce_str (): "generate random string, valid character a-zA-Z0-9: return: random string" "return ''. join (str (uuid. uuid4 ()). split ('-'))

 

Ii. server interaction data format

The server interacts with the merchant server in XML format, which involves converting the native Data Type of the language to facilitate processing. Interactive Data parameters are in the form of key-value, so it is more convenient to use the dictionary in Python. To parse XML, there are also libraries for third-party libraries, suchBeautifulSoup.

The specific implementation is as follows:

Def trans_xml_to_dict (xml): "converts the XML format data returned by the payment interaction to the Python Dict object: param xml: Raw XML format data: return: dict object "" soup = BeautifulSoup (xml, features = 'xml') xml = soup. find ('xml') if not xml: return {}# convert xml data to Dict data = dict ([(item. name, item. text) for item in xml. find_all ()]) return data def trans_dict_to_xml (data): "converts a dict object to the XML format data required for payment Interaction: param data: dict object: return: xml format data """ Xml = [] for k in sorted (data. keys (): v = data. get (k) if k = 'detail' and not v. startswith ('<! [CDATA ['): v =' <! [CDATA [{}]> '. format (v) xml. append ('<{key} >{value} </{key}> '. format (key = k, value = v) return '<xml >{}</xml> '. format (''. join (xml ))

Note:detail Parameters, that is, product details, whose values are in JSON format. Before converting to XML data, pay attention to usingCDATA Tags to protect them.

For example:

<detail><![CDATA[{"goods_detail": [{"wxpay_goods_id": "10010001", "price": 1, "goods_num": 1, "goods_name": "\\u82f9\\u679c", "goods_id": "10010001"}, {"wxpay_goods_id": "10010002", "price": 1, "goods_num": 1, "goods_name": "\\u9999\\u8549", "goods_id": "10010002"}]}]]></detail>

3, The Public number to pay the page through the JS-API to start to pay

This point corresponds to Step 1 in the business process. The reason for mentioning this is that the official document has dug a hole for developers (at least as of when I wrote this article ), weixinJSBridge is used in the sample code about JS in "calling the payment API on the Web page". This is a long time ago Deprecated "stuff" and is even unavailable now. The correct method is to useJS-SDKFor more information, see the public account wiki.

Call config before using the JS-SDKIt also contains a signature, but note that this signature is not related to the previous signature. ItsFirst, you need to use the public account APPID and APPKEY in exchange for access_token, and then use the access_token to call the JS-SDK in exchange for the ticket interface to get ticket, finally, use the ticket and the URI of the current user page to generate a signature using the sha1 operation.

After that, you can callwx.chooseWXPay And there is a pitfall: timestamp. The parameters in wx. chooseWXPay require that timestamp be in full lowercase.The "s" in the timestamp must be in uppercase when the signature is made. It's really silly. 

4. Notify the merchant of the payment result asynchronously (callback)

The last part is about asynchronous callback, which corresponds to Step 1 in the business process. After the payment is completed, the server will notify the merchant server of the payment result through callback. The callback address and[Unified order]Defined innotify_url .When a callback is received, you must first verify the validity of the signature to ensure "reliable source". Then, you can locate the unique order by using the openid and out_trade_no contained in the callback.

Summary

There are also many payment methods, which are also different in the business process. However, as long as you can play with one of them, other things can be quickly implemented. In addition, the implementation of the payment function involves the security of the business process. Therefore, you must clarify the business process and arrange the key nodes. The above is all of the content in this article, hoping to help you with the Python development and payment.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.