使用PYTHON 模拟微信服务端
琼中中立科技 | 2018-01-26 23:57:40 | 阅读:41346
#-*-coding:utf-8-*-#/usr/bin/envpython__version__='0.1'__author__='http://weibo.com/wtmmac''''微信Server模拟'''importsys,urllib,httplib,time,hashlib,random#配置interface_url='www.xxx.net'interface_path='/interface/weixin.php'Token='weixin'messages={#用户关注消息'subscribe':'''<xml><ToUserName><![CDATA[测试服务帐号]]></ToUserName><FromUserName><![CDATA[小黑]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[subscribe]]></Event><EventKey><![CDATA[EVENTKEY]]></EventKey></xml>''',#用户发送文本信息'text':'''<xml><ToUserName><![CDATA[测试服务帐号]]></ToUserName><FromUserName><![CDATA[小黑]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[周杰伦]]></Content><MsgId>1234567890123456</MsgId></xml>'''}defmake_post(action):'''模拟用户行为产生的消息提交给接口程序'''conn=httplib.HTTPConnection(interface_url)headers={"Content-type":"text/xml","Content-Length":"%d"%len(messages[action])}#生成签名相关变量timestamp=int(time.time())nonce=random.randint(1,100000)signature=makeSignature(Token,timestamp,nonce)params=urllib.urlencode({'signature':signature,'timestamp':timestamp,'nonce':nonce})conn.request("POST",interface_path+"?"+params,"",headers)conn.send(messages[action])response=conn.getresponse()printresponse.status,response.reasonprintresponse.read()conn.close()defmakeSignature(Token,timestamp,nonce):'''生成签名'''try:Token=int(Token)exceptException,e:passsorted_arr=map(str,sorted([Token,timestamp,nonce]))sha1obj=hashlib.sha1()sha1obj.update(''.join(sorted_arr))hash=sha1obj.hexdigest()returnhashdeflistAction():print("======Supportedactions:======")foriinmessages.keys():print(i)print("==============================")if__name__=='__main__':iflen(sys.argv)<2:print(u"Pleaseinputyouraction")listAction()else:if(messages.has_key(sys.argv[1])):make_post(sys.argv[1])else:print("Nothisaction")listAction()