vb编写各种趣味小程序_记录第一次编写微信小程序后台

论坛 期权论坛 脚本     
已经匿名di用户   2022-4-26 16:02   1308   0

临近七夕,公司运营想做一个小程序来给我们app引流。后台老大交给我写,写完之后,感觉还是挺简单,跟大家分享下过程。

其他数据的接口没有什么好说的。主要说下微信分享和微信支付的过程

微信分享:

微信文档:

https://developers.weixin.qq.com/miniprogram/dev/api/share/wx.getShareInfo.html

我们设计的是H5页面分享活动,种子群用户活动参与数最大,前端获得shareTicket

aab9a9e70309860dc17727c3ebb9220e.png

c063b27e4beb845994eda262b1829870.png

异步回调返回iv和encryptedData给我 我来解析获得OPENGID(openGId 为当前群的唯一标识),以此来判断种子用户

    class WXBizDataCrypt:       def __init__(self, appId, sessionKey):          self.appId = appId          self.sessionKey = sessionKey      def decrypt(self, encryptedData, iv):          # base64 decode          sessionKey = base64.b64decode(self.sessionKey)          encryptedData = base64.b64decode(encryptedData)          iv = base64.b64decode(iv)          cipher = AES.new(sessionKey, AES.MODE_CBC, iv)          decrypted = json.loads(self._unpad(cipher.decrypt(encryptedData)))          if decrypted['watermark']['appid'] != self.appId:              raise Exception('Invalid Buffer')          return decrypted      def _unpad(self, s):          return s[:-ord(s[len(s)-1:])]                       UID = redis_conn.get(Token).decode()  encryptedData = data['encryptedData']        iv = data['iv']  appId = 'wxa0e1ee170a2760d0'        sessionKey = data['key']  pc = WXBizDataCrypt(appId, sessionKey)        de = pc.decrypt(encryptedData, iv)  openGId = de['openGId']  if openGId == "t.......8":      print('1111')      sql = "UPDATE  useropenids set isseed = 1 where UID = {}".format(UID)      cur.execute(sql)      conn.commit()      response['seed'] = 99  else:      sql = "UPDATE  useropenids set isseed = 1 where UID = {}".format(UID)      cur.execute(sql)      conn.commit()      response['seed'] = 9  response['rep'] = pc.decrypt(encryptedData, iv)

微信支付:

bbdb7bf80390d712656f3dba7192d4b1.png

  1. 登录授权获取openid

  2. 调用统一下单接口,返回五个值给前端

    7287e1c91990fccc6de66b1c83ab93ef.png

登陆:
GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

a37807eaec614ec15bad7644552cac4d.png

返回得到openid统一下单接口: URL地址:https://api.mch.weixin.qq.com/pay/unifiedorder需要参数太多,具体参考微信文档:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1&index=1
import hashlibimport randomimport time# from Cryptodome.Cipher import AESfrom Crypto.Cipher import AESfrom lxml import htmletree = html.etreedef to_dict(content):    raw = {}    root = etree.fromstring(content)    for child in root:        raw[child.tag] = child.text    return rawdef random_str(randomlength=8):  """  生成随机字符串  :param randomlength: 字符串长度  :return:  """  str = ''  chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'  length = len(chars) - 1  for i in range(randomlength):    str+=chars[random.randint(0, length)]  return strclass WXBizDataCrypt:    def __init__(self, appId, sessionKey):        self.appId = appId        self.sessionKey = sessionKey    def decrypt(self, encryptedData, iv):        # base64 decode        sessionKey = base64.b64decode(self.sessionKey)        encryptedData = base64.b64decode(encryptedData)        iv = base64.b64decode(iv)        cipher = AES.new(sessionKey, AES.MODE_CBC, iv)        decrypted = json.loads(self._unpad(cipher.decrypt(encryptedData)))        if decrypted['watermark']['appid'] != self.appId:            raise Exception('Invalid Buffer')        return decrypted    def _unpad(self, s):        return s[:-ord(s[len(s)-1:])]def order_num(phone):  """  生成扫码付款订单号  :param phone: 手机号  :return:  """  local_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))  result = phone + 'T' + local_time + random_str(5)  return resultdef get_sign(data_dict, key):  """  签名函数  :param data_dict: 需要签名的参数,格式为字典  :param key: 密钥 ,即上面的API_KEY  :return: 字符串  """  params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False) # 参数字典倒排序为列表  params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list) + '&key=' + key  # 组织参数字符串并在末尾添加商户交易密钥  md5 = hashlib.md5() # 使用MD5加密模式  md5.update(params_str.encode('utf-8')) # 将参数字符串传入  sign = md5.hexdigest().upper() # 完成加密并转为大写  return signdef to_xml(raw):    s = ""    for k, v in raw.items():        s += "0}>{    return "{0}".format(s)                
data = {"appid": "wxa0e1ee170a2760d0", "mch_id": "1601187451", "nonce_str": strr, "openid": openid, "body": "test",                "out_trade_no": trade_no, "total_fee": total, "spbill_create_ip": "192.168.1.11",                "notify_url": "http://www.example.com/pay/weixin/notify", "trade_type": "JSAPI"}sign = get_sign(data, mul_key)data['sign'] = signdata = to_xml(data)res = requests.post(req, data=data)rep = (to_dict(res.content))print(rep)paysign = "appId={}&nonceStr={}&package={}&signType=MD5&timeStamp={}&key={}".format(rep['appid'],nnstr,payid,timestamp,mul_key)
调用之后将 paySign, timeStamp, nonceStr, signType返给前端即可。 PS:保存订单号和其他支付之后的逻辑在前端成功的回调里,后端出接口调用即可
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP