python achieve micro-channel payment applet

Transfer: https://www.cnblogs.com/zzqit/p/9952302.html#_label3

Before writing function, back and review it, make a note of

Want to achieve this function, the micro channel side applet is:

wx.requestPayment(
            {
              'timeStamp': res.data.data["timeStamp"],
              'nonceStr': res.data.data["nonceStr"],
              'package': res.data.data["package"],
              'signType': 'MD5',
              'paySign': res.data.data["paySign"],
              'success': function (res) {
                if (res.errMsg == "requestPayment:ok") {
                  wx.showToast({
                    title: '支付成功',
                    icon: 'success',
                    duration: 1000
                  })
                }
              },
              'fail': function (res) {
              },
              'complete': function (res) {
              }
            })

Before calling wx.requestPayment way to do that, we need to prepare the data in res.data.data provided, that is, backstage pass over the data

Background generate these data requires only a small user program provides openid on it

Background generated code data:

wechat_pay DEF (): 
    goods_price . = request.args GET ( " . price " ) 
    openid . = g.current_user GET ( " openid " ) 
    AppID = " " # applet appid, applets - development - development settings where to find 
    mch_id = " "# micro-channel pay merchant number, micro-channel pay | merchant platform - account Center - business information where to find 
    api_key = " "#API keys, micro-channel pay | merchant platform - account Center -API safety in looking 
    notify_url = " "# payment success callback path 
    OrderID = datetime.datetime.now (). the strftime ( ' % m% D the Y% H% m% S% ') # Of time for the order number
    info = WX_PayToolUtil(appid, mch_id, api_key, notify_url)
    data = info.getPayUrl(orderid, openid, goods_price)
    return json_response(0, data=data)
WX_PayToolUtil method:
# Coding = UTF- 8 
Import Requests 
Import hashlib 
Import xmltodict 
Import Time 
Import Random 
Import String 
from Random Import Random 


class WX_PayToolUtil ():
  "" " micro-channel payment instruments " "" 
 DEF __init __ (Self, APP_ID, MCH_ID, API_KEY, notify_url): 
  self._APP_ID = APP_ID # applet ID 
  self._MCH_ID = MCH_ID # # business number 
  self._API_KEY = API_KEY # merchant keys 
  self._UFDODER_URL = " https://api.mch.weixin.qq.com/pay/unifiedorder " # Interface link 
  self._NOTIFY_URL= Notify_url # asynchronous notification 


 DEF generate_sign (Self, param): 
   '' ' to generate a signature ' '' 
   stringA = '' 
   KS = the sorted (param.keys ()) # key parameter values are sorted
    for K in KS: 
    stringA + = (K + ' = ' + param [K] + ' & ' ) 
   # splice merchant KEY 
   stringSignTemp = stringA + " Key = " + self._API_KEY 
   # MD5 encryption, may also be used in other ways 
   hash_md5 = hashlib.md5 (stringSignTemp.encode ( ' utf8 '))
   Sign= Hash_md5.hexdigest () Upper ().
    Return Sign 


 DEF random_str (Self): 
  "" "
   generate a random string 
  : param randomlength: string length 
  : return :
   " ""
   STRs = '' 
  chars = ' AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789 ' 
  length = len (chars) - . 1 
  Random = the Random ()
   for I in Range ( 0 , 30 ): 
   STRs + = chars [the random.randint ( 0 , length)]
   return STRs

 
 DEF getPayUrl (Self, OrderID, OpenID, goodsPrice, ** kwargs):
   "" " sends a request to the micro-channel payment terminal, acquires URL " "" 
  Key = self._API_KEY 
  nonce_str = self.random_str () # generates a random string, less than 32
   the params = {
    ' AppID ' : self._APP_ID, # applet ID
    ' mch_id ' : self._MCH_ID, merchant number #
    ' nonce_str ' : nonce_str, random string #
    " body " : ' Learning Card ' , payment # Description
    'out_trade_no': Orderid, # generated order number
   ' Total_fee ' : str (goodsPrice), # bid amount
    ' spbill_create_ip ' : " " , # terminal IP, your server IP
    ' notify_url ' : self._NOTIFY_URL,
    ' trade_type ' : " JSAPI " , # payment type
    " openid " : openid , user ID # 
   } 
  # generates signature 
  the params [ ' Sign ' ] = self.generate_sign ( the params ) 
  param = { ' the root ' :params}
  xml = xmltodict.unparse(param)
  response = requests.post(self._UFDODER_URL, data=xml.encode('utf-8'), headers={'Content-Type': 'text/xml'})
  # xml 2 dict
  msg = response.text
  xmlmsg = xmltodict.parse(msg)
  # 4. 获取prepay_id
  if xmlmsg['xml']['return_code'] == 'SUCCESS':
    prepay_id = xmlmsg['xml']['prepay_id']
    # 时间戳
    timeStamp = str(int(time.time()))
    # 5. 五个参数
    data = {
     "appId": self._APP_ID,
     "nonceStr": nonce_str,
     "package": "prepay_id=" + prepay_id,
     "signType": 'MD5',
     "timeStamp" : TimeStamp, 
    } 
    # . 6 . PaySign signature 
    paySign = self.generate_sign (Data) 
    Data [ " paySign " ] = paySign added signatures # 
    # 7 after the parameters passed to the front end of a signature.
     Return Data

The data generated in response to the applet can then call the beginning of wx.requestPayment

Do not forget to call before the associated micro-channel micro-channel business to a small number, applets micro letter public platform to pay the associated merchant number

Micro-channel development documentation, field specific meaning to go inside to find: https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1

 

 

 

 

Guess you like

Origin www.cnblogs.com/Strangers/p/12606969.html