def verifyCallbackMode(query_string): d = parse_qs(query_string) wx = WXBizMsgCrypt(sToken, sEncodingAESKey, sAppId) ret, sReplyEchoStr = wx.VerifyURL(d["msg_signature"][0], d["timestamp"][0], d["nonce"][0], d["echostr"][0]) return sReplyEchoStr
def verifyCallbackMode(environ): d = parse_qs(environ['QUERY_STRING']) wx = WXBizMsgCrypt(sToken, sEncodingAESKey, sAppId) ret, sReplyEchoStr = wx.VerifyURL(d["msg_signature"][0], d["timestamp"][0], d["nonce"][0], d["echostr"][0]) return sReplyEchoStr
def post(self): """Handle the POST request. POST handler is used to format replies. """ print 'server.py: Info: WxHandler: POST request from {}'.format( self.request.remote_ip) token = config.token encoding_key = config.encodingkey app_id = config.appid decrypt_obj = WXBizMsgCrypt(token, encoding_key, app_id) try: # Catch parameters from request object. stamp = self.get_query_arguments("timestamp")[0] nonce = self.get_query_arguments("nonce")[0] msg_sign = self.get_query_arguments("msg_signature")[0] # Decrypt the message. dec_status, wx_data = decrypt_obj.DecryptMsg( self.request.body, msg_sign, stamp, nonce) if dec_status: print 'server.py: Error: decrypt fail' self.write('server: Error: Decrypt fail') else: print 'server.py: Info: wx_data:', wx_data rec_data = receive.parse_xml(wx_data) from parse import parse, chnword if isinstance(rec_data, receive.Msg) and rec_data.MsgType == 'text': to_user = rec_data.FromUserName from_user = rec_data.ToUserName word = rec_data.Content # The parse object parse_obj = parse.ParseMsg(to_user, word) parse_obj.form_reply() parse_obj.log_reply() content = parse_obj.get_reply() else: print 'server.py: Error: wrong format' to_user = rec_data.FromUserName from_user = rec_data.ToUserName content = chnword.imageNotSupported.decode('hex') # Encrypt the message for reply. encrypt_obj = WXBizMsgCrypt(token, encoding_key, app_id) enc_status, reply_data =\ encrypt_obj.EncryptMsg(reply2.TextMsg(to_user, from_user, content), nonce, stamp) if enc_status: self.write('server: Error: Encrypt fail:' + str(enc_status)) else: self.write(reply_data) except IndexError: self.write('server: error: some query parameter missing')
def post(self): print 'server.py: Info: WxHandler: POST request from {}'.format( self.request.remote_ip) token = config.token encodingKey = config.encodingkey appid = config.appid encodingkey = config.encodingkey decryptObj = WXBizMsgCrypt(token, encodingKey, appid) try: stamp = self.get_query_arguments("timestamp")[0] nonce = self.get_query_arguments("nonce")[0] msgSign = self.get_query_arguments("msg_signature")[0] # decrypt data, using module provided by wechat platform. decStatus, wxData = decryptObj.DecryptMsg(self.request.body, msgSign, stamp, nonce) if decStatus: print 'server.py: Error: decrypt fail' self.write('server: Error: Decrypt fail') else: print 'server.py: Info: wxData:', wxData recData = receive.parse_xml(wxData) from parse import parse if isinstance(recData, receive.Msg) and recData.MsgType == 'text': toUser = recData.FromUserName fromUser = recData.ToUserName word = recData.Content #parse the msg parseObj = parse.parseMsg(toUser, word) content = parseObj.replyWord() else: print 'server.py: Error: wrong format' toUser = recData.FromUserName fromUser = recData.ToUserName content = 'The format is wrong.' encryptObj = WXBizMsgCrypt(token, encodingkey, appid) encStatus, replyData = encryptObj.EncryptMsg( reply2.TextMsg(toUser, fromUser, content), nonce, stamp) if encStatus: self.write('server: Error: Encrypt fail:' + str(encStatus)) else: self.write(replyData) except IndexError: self.write('server: error: some query parameter missing')
def application(environ, start_response): # response content start_response('200 OK', [('Content-Type', 'text/html')]) if environ["REQUEST_METHOD"] == "GET": if "echostr" in environ['QUERY_STRING']: pass elif environ["PATH_INFO"] == "/send": d = parse_qs(environ['QUERY_STRING']) text = d.get('text', ["the default message"])[0] sendMsg.sendMsg(content=text, touser="******") return "/send function entered" else: return "dafault page" wx = WXBizMsgCrypt(sToken, sEncodingAESKey, sAppId) d = parse_qs(environ['QUERY_STRING']) # set up weixin callback mode if "echostr" in environ['QUERY_STRING']: return verifyCallbackMode(environ) request_body = getRequestBody(environ) ret, xml_content = wx.DecryptMsg(request_body, d["msg_signature"][0], d["timestamp"][0], d["nonce"][0]) xml_tree = ET.fromstring(xml_content) touser_name = xml_tree.find("ToUserName").text fromuser_name = xml_tree.find("FromUserName").text create_time = xml_tree.find("CreateTime").text msg_type = xml_tree.find("MsgType").text agent_ID = xml_tree.find("AgentID").text # content_text = xml_tree.find("Content").text # event = xml_tree.find("Event").text # event_key = xml_tree.find("EventKey").text if agent_ID == "0": if msg_type == "event": event_key = xml_tree.find("EventKey").text if event_key == "V1001_GITHUB": # ret, message = wx.EncryptMsg(text_T.format(getCommit("https://github.com/zhanglintc?period=daily")), d["nonce"][0]) aycs = AsyncSend(fromuser_name) aycs.start() # return null string return "" else: content_text = xml_tree.find("Content").text ret, message = wx.EncryptMsg(text_T.format(tuling(content_text)), d["nonce"][0]) return message if agent_ID == "3": log.d("agent_ID 3 entered") if msg_type == "text": content_text = xml_tree.find("Content").text pinyinList = lazy_pinyin(str(content_text)) pinyin = "" for item in pinyinList: pinyin += item log.d("pinyin: " + str(pinyin)) try: weather = getWeather(pinyin) except Exception as e: log.d(e) weather = "getWeather() exception occured" log.d("weather: " + str(weather)) ret, message = wx.EncryptMsg(text_T.format(weather), d["nonce"][0]) return message ret, message = wx.EncryptMsg(text_T.format("尚不支持..."), d["nonce"][0]) return message if agent_ID == "5": if msg_type == "event": event_key = xml_tree.find("EventKey").text if event_key == "V1001_CURRENT": commit, author, dttime, lginfo = getGitInfo() ret_info = "Remote Version Info\nModified at:\n{2}\nAuthor: {1}\nHash: {0}\nLog: {3}".format( commit, author, dttime, lginfo) ret, message = wx.EncryptMsg(text_T.format(ret_info), d["nonce"][0]) return message if event_key == "V1001_PULL_LATEST": if fromuser_name != "zhanglintc": ret, message = wx.EncryptMsg( text_T.format("You are not allowed to do this"), d["nonce"][0]) return message ups = updateSend(fromuser_name) ups.start() ret, message = wx.EncryptMsg( text_T.format("Updating Mmrz, please wait..."), d["nonce"][0]) return message if event_key == "V1002_RESTART": if fromuser_name != "zhanglintc": ret, message = wx.EncryptMsg( text_T.format("You are not allowed to do this"), d["nonce"][0]) return message restart_Mmrz() ret, message = wx.EncryptMsg( text_T.format("Server has restart at:\n" + time.ctime()), d["nonce"][0]) return message if event_key == "V1002_COPY_DB": os.system( "cp /home/yanbin/wx-guike_server/DBDATA/zncx.db /home/lane/ftp" ) ret, message = wx.EncryptMsg( text_T.format( 'zncx.db has copied to "ftp://zhanglintc.work"'), d["nonce"][0]) return message if msg_type == "text": content_text = xml_tree.find("Content").text ret, message = wx.EncryptMsg(text_T.format(tuling(content_text)), d["nonce"][0]) return message # ret, message = wx.EncryptMsg(text_T.format("尚不支持..."), d["nonce"][0]) # return message return "" # return a null string return ""
def application(environ, start_response): # response content start_response('200 OK', [('Content-Type', 'text/html')]) wx = WXBizMsgCrypt(sToken, sEncodingAESKey, sAppId) d = parse_qs(environ['QUERY_STRING']) # always restart Mmrz at start # restart_server() # set up weixin callback mode if "echostr" in environ['QUERY_STRING']: return verifyCallbackMode(environ) request_body = getRequestBody(environ) ret, xml_content = wx.DecryptMsg(request_body, d["msg_signature"][0], d["timestamp"][0], d["nonce"][0]) xml_tree = ET.fromstring(xml_content) touser_name = xml_tree.find("ToUserName").text fromuser_name = xml_tree.find("FromUserName").text create_time = xml_tree.find("CreateTime").text msg_type = xml_tree.find("MsgType").text agent_ID = xml_tree.find("AgentID").text # content_text = xml_tree.find("Content").text # event = xml_tree.find("Event").text # event_key = xml_tree.find("EventKey").text if agent_ID == "1": if msg_type == "event": event_key = xml_tree.find("EventKey").text # 轨刻:获取数据 if event_key == "V1001_PULL_LATEST_DB": return "" # 轨刻:更新服务 elif event_key == "V1002_PULL_LATEST_VERSION": ups = updateSend(fromuser_name, "wx-guike_server") ups.start() ret, message = wx.EncryptMsg( text_T.format("Updating wx-guike_server, please wait..."), d["nonce"][0]) return message # 轨刻:重启服务 elif event_key == "V1003_RESTART": restart_server("guikeServer_restart") ret, message = wx.EncryptMsg( text_T.format("restart guikeServer:7820, OK"), d["nonce"][0]) return message # 重庆微地铁:获取数据 elif event_key == "V2001_PULL_LATEST_DB": return "" # 重庆微地铁:更新服务 elif event_key == "V2002_PULL_LATEST_VERSION": ups = updateSend(fromuser_name, "wx-cqwdt") ups.start() ret, message = wx.EncryptMsg( text_T.format("Updating wx-cqwdt, please wait..."), d["nonce"][0]) return message # 重庆微地铁:重启服务 elif event_key == "V2003_RESTART": restart_server("cqwdt_restart") ret, message = wx.EncryptMsg( text_T.format("restart cqwdt:7818, OK"), d["nonce"][0]) return message else: content_text = xml_tree.find("Content").text ret, message = wx.EncryptMsg(text_T.format(tuling(content_text)), d["nonce"][0]) return message # return a null string return ""
print 'hashCode, signature:' + hashCode, sign if hashCode == sign: return echo else: return 'verify failed' except Exception, Argment: return Argment # process the query and return replies elif request.method == 'POST': try: token = config.token encodingkey = config.encodingkey appid = config.appid decryptObj = WXBizMsgCrypt(token, encodingkey, appid) stamp = request.args.get('timestamp') nonce = request.args.get('nonce') msgSign = request.args.get('msg_signature') decStatus, wxData = decryptObj.DecryptMsg(request.data, msgSign, stamp, nonce) if decStatus: return 'Decrypt fail:' + str(decStatus) print 'wxData:', wxData recData = receive.parse_xml(wxData) if isinstance(recData, receive.Msg) and recData.MsgType == 'text': toUser = recData.FromUserName fromUser = recData.ToUserName word = recData.Content content = dialogue(toUser, word) encryptObj = WXBizMsgCrypt(token, encodingkey, appid)
def index(): if request.method == 'GET': query_string = request.environ.get('QUERY_STRING') if query_string: return verifyCallbackMode(query_string) else: return 'the dafault page' else: # request.method == 'POST' wx = WXBizMsgCrypt(sToken, sEncodingAESKey, sAppId) d = parse_qs(request.environ.get('QUERY_STRING')) request_body = request.input_stream.read(request.content_length) ret, xml_content = wx.DecryptMsg(request_body, d["msg_signature"][0], d["timestamp"][0], d["nonce"][0]) xml_tree = ET.fromstring(xml_content) touser_name = xml_tree.find("ToUserName").text fromuser_name = xml_tree.find("FromUserName").text create_time = xml_tree.find("CreateTime").text msg_type = xml_tree.find("MsgType").text agent_ID = xml_tree.find("AgentID").text # content_text = xml_tree.find("Content").text # event = xml_tree.find("Event").text # event_key = xml_tree.find("EventKey").text if agent_ID == "0": if msg_type == "event": event_key = xml_tree.find("EventKey").text if event_key == "V1001_GITHUB": # ret, message = wx.EncryptMsg(text_T.format(getCommit("https://github.com/zhanglintc?period=daily")), d["nonce"][0]) aycs = AsyncSend(fromuser_name) aycs.start() # return null string return "" else: content_text = xml_tree.find("Content").text ret, message = wx.EncryptMsg( text_T.format(tuling(content_text)), d["nonce"][0]) return message if agent_ID == "3": log.d("agent_ID 3 entered") if msg_type == "text": content_text = xml_tree.find("Content").text pinyinList = lazy_pinyin(str(content_text)) pinyin = "" for item in pinyinList: pinyin += item log.d("pinyin: " + str(pinyin)) try: weather = getWeather(pinyin) except Exception as e: log.d(e) weather = "getWeather() exception occured" log.d("weather: " + str(weather)) ret, message = wx.EncryptMsg(text_T.format(weather), d["nonce"][0]) return message ret, message = wx.EncryptMsg(text_T.format("尚不支持..."), d["nonce"][0]) return message if agent_ID == "5": if msg_type == "event": event_key = xml_tree.find("EventKey").text if event_key == "V1001_CURRENT": commit, author, dttime, lginfo = getGitInfo() ret_info = "Remote Version Info\nModified at:\n{2}\nAuthor: {1}\nHash: {0}\nLog: {3}".format( commit, author, dttime, lginfo) ret, message = wx.EncryptMsg(text_T.format(ret_info), d["nonce"][0]) return message if event_key == "V1001_PULL_LATEST": if fromuser_name != "zhanglintc": ret, message = wx.EncryptMsg( text_T.format("You are not allowed to do this"), d["nonce"][0]) return message ups = updateSend(fromuser_name) ups.start() ret, message = wx.EncryptMsg( text_T.format("Updating Mmrz, please wait..."), d["nonce"][0]) return message if event_key == "V1002_RESTART": if fromuser_name != "zhanglintc": ret, message = wx.EncryptMsg( text_T.format("You are not allowed to do this"), d["nonce"][0]) return message restart_Mmrz() ret, message = wx.EncryptMsg( text_T.format("Server has restart at:\n" + time.ctime()), d["nonce"][0]) return message if event_key == "V1002_COPY_DB": os.system( "cp /home/yanbin/wx-guike_server/DBDATA/zncx.db /home/lane/ftp" ) ret, message = wx.EncryptMsg( text_T.format( 'zncx.db has copied to "ftp://zhanglintc.work"'), d["nonce"][0]) return message if msg_type == "text": content_text = xml_tree.find("Content").text ret, message = wx.EncryptMsg( text_T.format(tuling(content_text)), d["nonce"][0]) return message # ret, message = wx.EncryptMsg(text_T.format("尚不支持..."), d["nonce"][0]) # return message return "" # return a null string return ""