由于公众平台提供的库是针对python2.7的。所以python3.7还是费了点功夫的。
1. 安装 pycrypto
实际安装的是 pip3 install pycryptodemo
2. 对 WXBizMsgCrypt.py 文件针对python3的修改:
参考博文:https://blog.csdn.net/weixin_41762173/article/details/89221022
代码示例:
def responseMsg(self): encrypt_type = self.request.GET.get('encrypt_type',None) if encrypt_type is not None and encrypt_type == 'aes': #解密 timestamp = self.request.GET['timestamp'] nonce = self.request.GET['nonce'] msg_signature = self.request.GET['msg_signature'] pc = WXBizMsgCrypt(TOKEN,EncodingAESKey,APPID) ret,descryptMsg = pc.DecryptMsg(self.request.body,msg_signature,timestamp,nonce) if ret != 0: print(ret) return '' postStr = descryptMsg else: postStr = self.request.body postObj = self._parseMsg(postStr) msg_type = postObj['MsgType'] result ='' if msg_type == 'text': keyword = postObj['Content'] textTpl = ''' <xml> <ToUserName><![CDATA[{0}]]></ToUserName> <FromUserName><![CDATA[{1}]]></FromUserName> <CreateTime>{2}</CreateTime> <MsgType><![CDATA[{3}]]></MsgType> <Content><![CDATA[{4}]]></Content> </xml> ''' if keyword == '?' or keyword == '?': result = textTpl.format(postObj['FromUserName'], postObj['ToUserName'], int(time.time()), 'text', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) ) elif msg_type == 'event': pass if encrypt_type is not None and encrypt_type == 'aes': #解密 ret,encryotMsg = pc.EncryptMsg(result,nonce,str(int(time.time()))) result = encryotMsg return result