In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is to share with you the content of an example analysis of WeChat Pay's development process. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Note that I use the Wechat open platform for payment, which is related to mobile app, but has nothing to do with public accounts.
The main operation flow of WeChat Pay
1. The user browses the app, selects the item and places the order.
two。 The server processes the order logic and begins to formally initiate the payment process
3. First, the background server initiates a request to the weixin server to get a token.
4. The backend server gets the token, encrypts it with other parameters, and initiates a request to the weixin server again to obtain a prepaid prepayid
5. The background server returns the prepayid to the app client
6.app calls the Wechat control on the phone to complete the payment process.
7.app initiates a callback request to the backend server to notify the server that the transaction is completed.
After the 8.weixin server has processed all the processes, it initiates a post request to the backend server to formally inform the backend server that the transaction has been completed.
Some notes on the above process:
1. The token obtained each time is time-limited, with a default of 7200s, and a maximum of 200s per day, so it is best to cache it in redis and retrieve it again when it expires.
The callback initiated by 2.app is unreliable by default, and the backend should, as far as possible (not necessary), initiate an order query to the Wechat server to query the result of this transaction.
The notify initiated by the 3.weixin server to the background is the last barrier to ensure that the transaction is completed. The background server must return "success" after confirmation, otherwise the weixin server will try to resend the request.
Get token
This is a simple step, just send a get request. Just configure the correct parameters.
'' get token''' def _ getAccessTokenFromWeixin (self) from Wechat server: response = requests.get (self.tokenUrl% (self.appId, self.appSecret)) if response.status_code = 200: text = response.text tokenInfo = json.loads (text) try: token = tokenInfo ['access_token'] expires_in = tokenInfo [' expires_in'] self._writeWeixinTokenLog (token Self.order_no) return token except KeyError: return None # token failed to get return None # http request failed
Get prepayid
In WeChat Pay's development process, the most tedious thing is to get prepayid.
In this step, we need to assemble a parameter like this:
{"appid": "wxd930ea5d5a258f4f", "traceid": "test_1399514976", "noncestr": "e7d161ac8d8a76529d39d9f5b4249ccb", "timestamp": 1399514976, "package": "bank_type=WX&body=%E6%94%AF%E4%BB%98%E6%B5%8B%E8%AF%95&fee_type=1&input_charset=UTF-8¬ify_url=http%3A%2F%2Fweixin.qq.com&out_trade_ no=7240b65810859cbf2a8d9f76a638c0a3&partner=1900000109&spbill_create_ip=196.168.1.1& total_fee=1&sign=7F77B507B755B3262884291517E380F8", "sign_method": "sha1" "app_signature": "7f77b507b755b3262884291517e380f8"}
Assemble package
The first step here is to assemble the package:
"package": "bank_type=WX&body=%E6%94%AF%E4%BB%98%E6%B5%8B%E8%AF%95&fee_type=1&input_charset=UTF-8¬ify_url=http%3A%2F%2Fweixin.qq.com&out_trade_ no=7240b65810859cbf2a8d9f76a638c0a3&partner=1900000109&spbill_create_ip=196.168.1.1& total_fee=1&sign=7F77B507B755B3262884291517E380F8"
The parameters required to assemble the package are shown in the above code, so we need to prepare a params and then prepare the signature. The signature process is as follows:
1. Sort the params according to the dictionary order of key, and then splice them into strings. Note that these key do not include sign.
two。 Concatenate key=paternerKey after the above string, then md5 the entire string, and then convert it to uppercase, and we get the signature
Then we transcode all the value of params by urlencode, and then concatenate the sign=signValue to get the package string.
The MD5 created here is as follows:
Def createMD5Signature (self, signParams):''sort first' sortedParams = sorted (signParams.iteritems (), key=lambda dappld [0])''splicing' 'stringSignTemp = "&" .join (["% slots% s"% (item [0]]) Item [1]) for item in sortedParams if item [0]! = 'sign' and''! = item [1]) # plus stringSignTemp + ='& key=%s'% (self.partnerKey) # sign with MD5 Then convert to uppercase stringSign = hashlib.md5 (stringSignTemp). Hexdigest (). Upper () # Upper return stringSign
The code to assemble the package:
Def getPackage (self, packageParams):''first get the sign of params, then urlencode the params, and finally assemble it. Plus sign''' sign= self.createMD5Signature (packageParams) packageParams = sorted (packageParams.iteritems (), key=lambda djand [0]) stringParams = "&" .join (["% slots% s"% (item [0], urllib.quote (str (item[ 1]) for item in packageParams]) stringParams + ='& sign=%s'% (sign) return stringParams
Continue to assemble parameters
After we get the package, we continue to assemble the parameters:
The parameters required here are:
Appid=wxd930ea5d5a258f4fappkey=L8LrMqqeGRxST5reouB0K66CaY A WpqhA Vsq7ggKkxHCOastWksvuX1uvmvQcl xaHoYd3ElNBrNO2DHnnzgfVG9Qs473M3DTOZug5er46FhuGofumV8H2FVR9qkjSlC5Knoncestr=e7d161ac8d8a76529d39d9f5b4249ccbpackage=bank_type=WX&body=%E6%94%AF%E4%BB%98%E6%B5%8B%E8%AF%95 & fee_type=1&input_charset=UTF-8¬ify_url=http%3A%2F%2Fweixin.qq.com&out_trade_no = 7240b65810859cbf2a8d9f76a638c0a3&partner=1900000109&spbill_create_ip=196.168.1.1&tot al_fee=1&sign=7F77B507B755B3262884291517E380F8timestamp=1399514976
Traceid=test_1399514976
Notice that there is a hole here:
The above parameters participate in the signature, but appKey is not included in the last parameter. Remember to delete it after signing.
1. All parameters are sorted in dictionary order and then spliced.
two。 Sha1 signature is performed and concatenated to the end of the above string
3. Note that appKey is deleted here, and then sign is added.
The code to obtain the sha1 signature is as follows:
Def createSHA1Signature (self, params):''sort first, and then concatenate' sortedParams = sorted (params.iteritems (), key=lambda dvisd [0]) stringSignTemp = "&" .join ([% slots% s "% (item [0], item [1]) for item in sortedParams]) stringSign = hashlib.sha1 (stringSignTemp). Hexdigest () return stringSign
Then we get the following parameters:
{"appid": "wxd930ea5d5a258f4f", "noncestr": "e7d161ac8d8a76529d39d9f5b4249ccb", "package": "Sign=WXpay"; "partnerid": "1900000109"prepayid": "1101000000140429eb40476f8896f4c9", "sign": "7ffecb600d7157c5aa49810d2d8f28bc2811827b", "timestamp": "1399514976"}
Get prepayid
The code is as follows:
'' get prepaid prepayid''' def gerPrepayId (self, token, requestParams):''jsonize parameters, including package Then initiate the post request''data= json.dumps (requestParams) response = requests.post (self.gateUrl% (token), data=data) if response.status_code = 200: text = response.text text = json.loads (text) errcode = text [' errcode'] if errcode = 0: return text ['prepayid'] return None
The prepayid format we get should look like this:
{"prepayid": "1101000000140429eb40476f8896f4c9", "errcode": 0, "errmsg": "Success"}
Sign again
Here, use the above sha1 signature method to sign again, and get the following parameters:
{"appid": "wxd930ea5d5a258f4f", "noncestr": "e7d161ac8d8a76529d39d9f5b4249ccb", "package": "Sign=WXpay"; "partnerid": "1900000109"prepayid": "1101000000140429eb40476f8896f4c9", "sign": "7ffecb600d7157c5aa49810d2d8f28bc2811827b", "timestamp": "1399514976"}
The backend server returns the result to app, and app can initiate payment at this time.
The above process code is:
Receive a request from app Return prepayid'''class WeixinRequirePrePaidHandler (BasicTemplateHandler):''this method is called in OrdersAddHandler' @ staticmethod def getPrePaidResult (order_no, total_pay, product_name, client_ip):''encapsulates the commonly used signature algorithm' 'weixinRequestHandler = WeixinRequestHandler (order_no)' collect order related information''addtion = str (random.randint (10,100)) # produces a two-digit number Spliced after the order number out_trade_no = str (order_no) + addtion order_price = float (total_pay) # floating point numbers must be allowed The following components are converted into int # order_price = 0.01# Test remote_addr = client_ip # IP address of the client print remote_addr current_time = int (time.time ()) order_create_time = str (current_time) order_deadline = str (current_time + 20,60)''some of the parameters here are used for the following' 'noncestr = hashlib.md5 (str) (random.random ()) .hexdigest () timestamp = str (int (time.time ()) pack = 'Sign=WXPay' get token''' access_token = weixinRequestHandler.getAccessToken () logging.info ("get token:% s"% access_token) if access_token:' 'set package parameter' 'packageParams = {} packageParams [' bank_type'] = 'WX' # payment type packageParams ['body'] = product_name # Commodity name packageParams [' fee_type'] ='1' # RMB fen packageParams ['input_charset'] =' GBK' # GBK packageParams ['notify_url'] = config [' notify_url'] # post Asynchronous message Notification packageParams ['out_trade_no'] = str (out_trade_no) # order number PackageParams ['partner'] = config [' partnerId'] # merchant number packageParams ['total_fee'] = str (int (order_price*100)) # order amount The unit is packageParams ['spbill_create_ip'] = remote_addr # IP packageParams [' time_start'] = order_create_time # order generation time packageParams ['time_expire'] = order_deadline # order expiration time' get package''' package = weixinRequestHandler.getPackage (packageParams) 'set payment parameters' signParams = {} signParams ['appid] '] = config [' appId'] signParams ['appkey'] = config [' paySignKey'] # delete signParams ['noncestr'] = noncestr signParams [' package'] = package signParams ['timestamp'] = timestamp signParams [' traceid'] = 'mytraceid_001' generate payment signature' 'app_signature = weixinRequestHandler.createSHA1Signature (signParams)' add extra parameters for non-participation signature'' 'signParams [' sign_method'] = 'sha1' signParams [' app_signature'] = app_signature' remove appKey''' del signParams ['appkey']''to get prepayid''' prepayid = weixinRequestHandler.gerPrepayId (access_token) SignParams) if prepayid:''prepare the signature again using the obtained prepayid' 'pack =' sign=WXPay' prepayParams = {} prepayParams ['appid'] = config [' appId'] prepayParams ['appkey'] = config [' paySignKey'] prepayParams ['noncestr'] = noncestr prepayParams [' package'] = pack prepayParams ['partnerid'] = config [' partnerId'] PrepayParams ['prepayid'] = prepayid prepayParams [' timestamp'] = timestamp' generate signature''sign = weixinRequestHandler.createSHA1Signature (prepayParams)' prepare output parameter''returnParams = {} returnParams [' status'] = 0 returnParams ['retmsg'] =' success' returnParams ['appid'] = config [' appId'] returnParams ['noncestr'] = noncestr returnParams [' package'] = pack returnParams ['prepayid'] = prepayid returnParams [' timestamp'] = timestamp returnParams ['sign'] = sign returnParams [' partnerId'] = config ['partnerId'] returnParams [' addtion'] = addtion else:''prepayid acquisition failed' 'returnParams = {} returnParams [' status'] =-1 returnParams ['retmsg'] =' prepayid acquisition failed 'else:' 'token acquisition failed' 'returnParams = {} returnParams [' status'] =-1 returnParams ['retmsg'] =' token acquisition failed 'generate json format text And then return to APP''' return returnParams.
Background asynchronous notification
The notify asynchronous notification sent by Wechat server is the final sign of successful payment. For security reasons, we must extend the signature:
The extension code is as follows:
Def isTenpaySign (self, params): helper = WeixinRequestHandler () sign = helper.createMD5Signature (params) return params ['sign'] = = sign
The overall process is as follows:
'' asynchronous notification sent by Wechat server to backend''class WeixinAppNotifyHandler (BasicTemplateHandler): def initialize (self): self.weixinResponseHandler = WeixinResponseHandler () def post (self):' 'parsing parameters' params = self.parseQueryString () 'verify whether it is a message sent back by weixin server' 'verifyWeixinSign = self.weixinResponseHandler.isTenpaySign (params)' processing order''if VerifyWeixinSign:''order Logic' 'order_no = str (params [' out_trade_no']) order_no = order_ no [0:-2] print'% paied successfully'% order_no self.saveWeixinReceipt (params) updateOrdersPaidByWeixin (order_no) # Update order usage status consumeCouponByOrderNo (order_no) # coupons have been used by self.write ("success" ") else: self.write (" fail ") def parseQueryString (self):''get all the parameters in url' uri = self.request.uri 'parse the query string in URI' 'parseResult = urlparse.urlparse (uri) query = parseResult.query' parse query string''params = urlparse.parse_qs (query) for item in params: Params [item] = params [item] [0] .strip () return params
Finally, the payment is not considered successful after the user has made the payment on the phone. The transaction will not be considered successful until the weixin server receives the success returned by the notify notification. At this time, our mobile phone can receive a message from the official Wechat.
Thank you for reading! This is the end of the article on "sample Analysis of WeChat Pay's Development process". I hope the above content can be of some help to you, so that you can learn more knowledge. If you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.