def test_check_signature(self): signature = '41f929117dd6231a953f632cfb3be174b8e3ef08' timestamp = '1434295379' nonce = 'ueivlkyhvdng46da0qxr52qzcjabjmo7' # 测试无 Token 初始化 wechat = WechatBasic() with self.assertRaises(NeedParamError): wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce) # 测试有 Token 初始化 wechat = WechatBasic(token=self.token) self.assertTrue(wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce)) self.assertFalse(wechat.check_signature(signature=signature, timestamp=timestamp+'2', nonce=nonce))
def index(request): # 实例化 We_chat_Basic we_chat = WechatBasic(token=WECHAT_TOKEN, appid=AppID, appsecret=AppSecret) if request.method == "GET": signature = request.GET.get("signature") timestamp = request.GET.get("timestamp") nonce = request.GET.get("nonce") if not we_chat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponse("Verify failed") else: return HttpResponse(request.GET.get("echostr"), content_type="text/plain") else: signature = request.GET.get("signature") timestamp = request.GET.get("timestamp") nonce = request.GET.get("nonce") if not we_chat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponse("Verify failed") try: we_chat.parse_data(data=request.body) except ParseError: return HttpResponseBadRequest("Invalid XML Data") message = we_chat.get_message() if isinstance(message, EventMessage): if message.type == "click": if message.key == "STEP_COUNT": step_array = Record.objects.filter(user=message.source) if step_array: step = step_array[len(step_array) - 1].step response = we_chat.response_text("跑了" + str(step) + "步咯") # 里面的数字应由其他函数获取 return HttpResponse(response) else: response = we_chat.response_text("Sorry, there' no data about you in our database.") return HttpResponse(response) if message.key == "CHART": print 1 response = we_chat.response_news( [ { "title": "Today's amount of exercise", "description": "data analysis", "picurl": "http://7xn2s5.com1.z0.glb.clouddn.com/ez.png", "url": SERVER_IP + "TodayChart/" + message.source, } ] ) return HttpResponse(response) response = we_chat.response_text("Cheer up!") return HttpResponse(response)
def index(request): # 实例化 We_chat_Basic we_chat = WechatBasic( token=WECHAT_TOKEN, appid=AppID, appsecret=AppSecret ) if request.method == "GET": signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') if not we_chat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponse("Verify failed") else: return HttpResponse(request.GET.get("echostr"), content_type="text/plain") else: signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') if not we_chat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponse("Verify failed") try: we_chat.parse_data(data=request.body) except ParseError: return HttpResponseBadRequest('Invalid XML Data') message = we_chat.get_message() if isinstance(message, EventMessage): if message.type == 'click': if message.key == 'STEP_COUNT': step_array = Record.objects.filter(user=message.source) if step_array: step = step_array[len(step_array) - 1].step response = we_chat.response_text(u'跑了' + str(step) + u'步咯') # 里面的数字应由其他函数获取 return HttpResponse(response) else: response = we_chat.response_text(u'Sorry, there\' no data about you in our database.') return HttpResponse(response) if message.key == 'CHART': print 1 response = we_chat.response_news([{ 'title': u'Today\'s amount of exercise', 'description': 'data analysis', 'picurl': 'http://7xn2s5.com1.z0.glb.clouddn.com/ez.png', 'url': SERVER_IP + 'TodayChart/' + message.source}]) return HttpResponse(response) response = we_chat.response_text(u'Cheer up!') return HttpResponse(response)
def do_action(self): # 创建wechat sdk 把消息给封装起来,方便调用验证,以及消息提取和消息回复 conf = WechatConf(token='xuyung', appid='wxffc2efc83cd3cac8', appsecret='6619da74b175a079677e505cbb6fe9dc', encrypt_mode='normal') wechat = WechatBasic(conf=conf) signature = self.get_argument('signature', '') if signature: timestamp = self.get_argument('timestamp', '') nonce = self.get_argument('nonce', '') if wechat.check_signature(signature, timestamp, nonce): if self.get_argument('echostr', ''): self.result = self.get_argument('echostr', '') return else: wechat.parse_data(self.request.body) process = ProcessBody(wechat) self.result = process.get_result() else: self.result = 'error' else: wechat.parse_data(self.request.body) process = ProcessBody(wechat) self.result = process.get_result()
def wechat_home(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') wechat_instance = WechatBasic(conf=conf) if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': response = request.GET.get('echostr', 'error') else: try: wechat_instance.parse_data(request.body) message = wechat_instance.get_message() if isinstance(message, TextMessage): reply_text = 'http://123.206.8.219/query/' elif isinstance(message, VoiceMessage): reply_text = '13020031069 liutianfeng' elif isinstance(message, ImageMessage): reply_text = '13020031069 liutianfeng' elif isinstance(message, LinkMessage): reply_text = '13020031069 liutianfeng' elif isinstance(message, LocationMessage): reply_text = '13020031069 liutianfeng' elif isinstance(message, VideoMessage): reply_text = '13020031069 liutianfeng' elif isinstance(message, ShortVideoMessage): reply_text = '13020031069 liutianfeng' else: reply_text = '13020031069 liutianfeng' response = wechat_instance.response_text(content=reply_text) except ParseError: return HttpResponseBadRequest('Invalid XML Data') return HttpResponse(response, content_type="application/xml")
async def getWechat(signature: str, echostr: int, timestamp: str, nonce: str): wechat_instance = WechatBasic(conf=conf) if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return 'Verify Failed' else: return echostr
def weixin_response(token, signature, timestamp, nonce, body_text=''): debug_log('check sign ...\n') # 用户的请求内容 (Request 中的 Body) # 请更改 body_text 的内容来测试下面代码的执行情况 # 实例化 wechat wechat = WechatBasic(token=token) # 对签名进行校验 if wechat.check_signature(signature, timestamp, nonce): # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作) wechat.parse_data(body_text) # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义) message = wechat.get_message() response = None if message.type == 'text': if message.content == 'wechat': response = wechat.response_text(u'^_^') else: response = wechat.response_text(u'文字') elif message.type == 'image': response = wechat.response_text(u'图片') else: response = wechat.response_text(u'未知') # 现在直接将 response 变量内容直接作为 HTTP Response 响应微信服务器即可,此处为了演示返回内容,直接将响应进行输出 return response return HttpResponse('')
def entrance(request): def get_access_token(): url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+APP_ID+'&secret='+APP_SECRET access_token = get_rsp_data(url)['access_token'] return access_token def get_user_info(): access_token = get_access_token() url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='+access_token+'&openid='+message.source ueser_info_dic = get_rsp_data(url) user_info = "" for k, v in ueser_info_dic.items(): user_info = user_info+str(k)+":"+str(v)+"\n" return user_info def OAuth(): REDIRECT_URL = 'http://115.159.160.143/oauth' url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+APP_ID+'&redirect_uri='+REDIRECT_URL+'&response_type=code&scope=snsapi_userinfo&state=2#wechat_redirect=0' rsp = '<a href="'+url+'">点我授权</a>' return rsp wechat = WechatBasic(token=TOKEN) if wechat.check_signature(signature=request.GET['signature'], timestamp=request.GET['timestamp'], nonce=request.GET['nonce']): if request.method == 'GET': rsp = request.GET.get('echostr', 'error') else: wechat.parse_data(request.body) message = wechat.get_message() rsp = wechat.response_text(OAuth()) else: rsp = "failed" return HttpResponse(rsp)
def weixin(request): wechat = WechatBasic(token=token) if wechat.check_signature(signature=request.GET['signature'], timestamp=request.GET['timestamp'], nonce=request.GET['nonce']): if request.method == 'GET': rsp = request.GET.get('echostr', 'error') else: wechat.parse_data(request.body) message = wechat.get_message() # write_log(message.type) if message.type == u'text': response_content = 'this is text' # response_content = handle_text(message.content) if message.content == u'wechat': # response_content = 'hello wechat' rsp = wechat.response_text(u'^_^') elif re.findall(u'锐捷', message.content): rsp = wechat.response_news(ruijie_response) else: rsp = wechat.response_news(default_response) else: # rsp = wechat.response_text(u'消息类型: {}'.format(message.type)) rsp = wechat.response_news(default_response) else: rsp = wechat.response_text('check error') return HttpResponse(rsp)
def index(request): signature = request.GET['signature'] timestamp = request.GET['timestamp'] nonce = request.GET['nonce'] conf = WechatConf(token=TOKEN, appid=APP_ID, appsecret=APP_SECRET, encrypt_mode="normal") wechat = WechatBasic(conf=conf) if request.method == "GET": echostr = request.GET['echostr'] if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): print 'Accept' else: print 'Wrong' return HttpResponse(echostr) elif request.method == "POST": print request.body return HttpResponse("%r" % request.POST)
def wechatChatForFun(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') wechat_instance = WechatBasic(conf=ChatForFunConf) reply_text = "" if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': response = request.GET.get('echostr', 'error') else: try: wechat_instance.parse_data(request.body) message = wechat_instance.get_message() if isinstance(message, TextMessage): reply_text = str(message.content).encode('utf8') reply_text = ParserMsg(reply_text, message.source) elif isinstance(message, ImageMessage): reply_text = str(message.picurl).encode('utf8') reply_text = ParserMsg(reply_text, message.source) elif isinstance(message, LocationMessage): reply_text = str(message.label).encode('utf8') reply_text = ParserMsg(reply_text, message.source) else: reply_text = U"服务器:目前只支持文字消息,非常抱歉" response = wechat_instance.response_text(content=reply_text) except ParseError: return HttpResponseBadRequest("Invalid XML Data") return HttpResponse(response, content_type='application/xml')
def index(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') xml = request.body body_text = """ <xml> <ToUserName><![CDATA[touser]]></ToUserName> <FromUserName><![CDATA[fromuser]]></FromUserName> <CreateTime>1405994593</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[新闻]]></Content> <MsgId>6038700799783131222</MsgId> </xml> """ token = get_weixin_accesstoken() # 实例化 wechat wechat = WechatBasic(token=token) # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作) wechat.parse_data(body_text) # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义) message = wechat.get_message() response = None if isinstance(message, TextMessage): response = wechat.response_text(content=u'文字信息') elif isinstance(message, VoiceMessage): response = wechat.response_text(content=u'语音信息') elif isinstance(message, ImageMessage): response = wechat.response_text(content=u'图片信息') elif isinstance(message, VideoMessage): response = wechat.response_text(content=u'视频信息') elif isinstance(message, LinkMessage): response = wechat.response_text(content=u'链接信息') elif isinstance(message, LocationMessage): response = wechat.response_text(content=u'地理位置信息') elif isinstance(message, EventMessage): # 事件信息 if message.type == 'subscribe': # 关注事件(包括普通关注事件和扫描二维码造成的关注事件) if message.key and message.ticket: # 如果 key 和 ticket 均不为空,则是扫描二维码造成的关注事件 response = wechat.response_text(content=u'用户尚未关注时的二维码扫描关注事件') else: response = wechat.response_text(content=u'普通关注事件') elif message.type == 'unsubscribe': response = wechat.response_text(content=u'取消关注事件') elif message.type == 'scan': response = wechat.response_text(content=u'用户已关注时的二维码扫描事件') elif message.type == 'location': response = wechat.response_text(content=u'上报地理位置事件') elif message.type == 'click': response = wechat.response_text(content=u'自定义菜单点击事件') elif message.type == 'view': response = wechat.response_text(content=u'自定义菜单跳转链接事件') elif message.type == 'templatesendjobfinish': response = wechat.response_text(content=u'模板消息事件') # 现在直接将 response 变量内容直接作为 HTTP Response 响应微信服务器即可,此处为了演示返回内容,直接将响应进行输出 print response return render_to_response('index.html',response)
def post(self): # 实例化 wechat wechat = WechatBasic(token=token) signature = self.get_argument("signature", None) timestamp = self.get_argument("timestamp", None) nonce = self.get_argument("nonce", None) # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作) # look request method # print dir(self.request) content = self.request.body wechat.parse_data(content) # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义) message = wechat.get_message() response = None if message.type == 'text': if message.content == 'wechat': response = wechat.response_text(u''' <a href="https://open.weixin.qq.com/connect/oauth2/authorize? appid=wxafac6b4bc457eb26&redirect_uri=http://tuteng.info/login_access& response_type=code&scope=snsapi_userinfo&state=14#wechat_redirect">testtt</a> ''') else: response = wechat.response_text(u'world') elif message.type == 'image': response = wechat.response_text(u'image') else: response = wechat.response_text(u'no image')
def home(request): token = TOKEN if request.method == 'POST': signature = request.POST.get('signature', '') timestamp = request.POST.get('timestamp', '') nonce = request.POST.get('nonce') elif request.method == 'GET': signature = request.GET.get('signature', '') timestamp = request.GET.get('timestamp', '') nonce = request.GET.get('nonce') echostr = request.GET.get('echostr', '') if DEBUG: debug_log('==========') debug_log('token: '+str(token)) debug_log('signature: '+str(signature)) debug_log('timestamp: '+str(timestamp)) debug_log('nonce: '+str(nonce)) if token and timestamp and nonce and echostr: s = ''.join(sorted([token,timestamp,nonce])) debug_log('calculated sign: '+hashlib.sha1(s.encode('utf-8')).hexdigest()) debug_log('echostr: '+str(echostr)) wechat = WechatBasic(token=token) # 对签名进行校验 if wechat.check_signature(signature, timestamp, nonce): return HttpResponse(echostr) else: return HttpResponse('') if signature: return weixin_response(token, signature, timestamp, nonce, request.body) return HttpResponse('<h1>微信开发中 ...</h1>') """
def validate(): signature = request.args.get('signature') echostr = request.args.get('echostr') timestamp = request.args.get('timestamp') nonce = request.args.get('nonce') token = "test" body_text = request.get_data() # 实例化 wechat wechat = WechatBasic(token=token) # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作) wechat.parse_data(body_text) # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义) message = wechat.get_message() response = None if message.type == 'subscribe': response = wechat.response_text("谢谢关注V2EX热帖分享,输入任意内容以获取最新热帖咨询") if message.type == 'text': newsList = generate() response = wechat.response_news(newsList) # 现在直接将 response 变量内容直接作为 HTTP Response 响应微信服务器即可,此处为了演示返回内容,直接将响应进行输出 return response
def weixin_main(request): wechat = WechatBasic(token = token, appid = appid, appsecret = appsecret) signature = request.GET.get('signature', None) timestamp = request.GET.get('timestamp', None) nonce = request.GET.get('nonce', None) body_text = request.body if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): wechat.parse_data(body_text) message = wechat.get_message() response = None if isinstance(message, TextMessage): response = wechat.response_text(content=u'文字信息') elif isinstance(message, VoiceMessage): response = wechat.response_text(content=u'语音信息') elif isinstance(message, ImageMessage): response = wechat.response_text(content=u'图片信息') elif isinstance(message, VideoMessage): response = wechat.response_text(content=u'视频信息') elif isinstance(message, LinkMessage): response = wechat.response_text(content=u'链接信息') elif isinstance(message, LocationMessage): response = wechat.response_text(content=u'地理位置信息') elif isinstance(message, EventMessage): # 事件信息 if message.type == 'subscribe': # 关注事件(包括普通关注事件和扫描二维码造成的关注事件) if message.key and message.ticket: # 如果 key 和 ticket 均不为空,则是扫描二维码造成的关注事件 response = wechat.response_text(content=u'用户尚未关注时的二维码扫描关注事件') else: response = wechat.response_text(content=u'普通关注事件') elif message.type == 'unsubscribe': response = wechat.response_text(content=u'取消关注事件') elif message.type == 'scan': response = wechat.response_text(content=u'用户已关注时的二维码扫描事件') elif message.type == 'location': response = wechat.response_text(content=u'上报地理位置事件') elif message.type == 'click': if message.key == 'V1001_hospital_introduce': response = wechat.response_text(content=u'永康医院(原永康市红十字会医院),始建于1952年,是一家集急救、医疗、预防、康复保健、科研和教学为一体的以专科为特色的市直属二级乙等综合性医院,是社保、医保、农保及各商业保险公司定点医院,是残疾人等级鉴定体检定点医院。医院先后荣获爱婴医院、中国红十字会优秀冠名医院、省扶残助残爱心城市建设先进单位、省级卫生先进单位等荣誉。是永康市外来民工孕产妇分娩定点医院,市白内障复明工程免费手术定点医院。医院核定床位200张,职工280余人。开设急诊科、内科、外科、妇产科、眼科、口腔科等20多个专科科室,其中以眼科、口腔科、妇产科为主,眼科是永康市重点学科。配备有进口CT机、佳能DR、口腔全景机、阿洛卡彩超、电子胃镜、腹腔镜、阴道镜、锐扶刀、眼科A/B超、玻璃体超声乳化切割一体机、眼底造影机、OCT、全自动综合验光仪等仪器设备。在市卫计局和联想集团的领导下,医院立足“办一所医院、树一方品牌”的宗旨,以大五官、妇产科为先导,大内科、大外科齐头并进,加强发展老年病防治和康复医疗服务,全面提升医疗技术和服务水平,力争打造一所老百姓身边的好医院。服务时间:普通门诊:上午8:00—11:30;下午13:30—17:00 (夏令时:14:00—17:30;急诊:24小时服务') elif message.key == 'V1002_hospital_trend': response = wechat.response_text(content=u'我们更名啦! 2015年5月1日起,原“永康市红十字会医院”正式更名为“永康医院”,名称变更后,医院法律主体地位不变,联系方式、地址保持不变。因医院名称变更给各单位及广大患者带来的不便,我们深感歉意,敬请谅解。特此通告!') elif message.key == 'V1003_department_introduce': response = wechat.response_text(content=u'永康医院开设急诊科、内科、呼吸内科、心血管内科、糖尿病专科,肝病专科、外科、肛肠科、骨伤科、男性科、皮肤科、手外科、整形美容科,妇科、产科,儿科生长发育科,眼科、耳鼻喉科、口腔科,中医科、不孕不育科、康复科、肠道门诊、犬伤门诊、健康体检中心、离休干部门诊等诊疗科室。其中眼科、口腔科、妇产科是我市及周边地区规模最大、设备最好、群众最信赖、技术一流的专科治疗中心之一。') elif message.key == 'V1005_hospital_culture': response = wechat.response_text(content=u'医院文化:一切为了病人、 一切为了医院、一切为了职工、一切为了工作。') elif message.key == 'V2002_zhuyuanxuzhi': response = wechat.response_text(content=u'您好!欢迎您来我院检查治疗,我们将努力为您提供更多的照顾,更好的治疗。同时我们的工作也需要您的理解和支持!谢谢您的配合,祝您早日康复! 一、住院注意事项:1、保持病房安静整洁卫生,请不要往窗口、阳台外倒水,不要随地吐痰,垃圾及果皮请丢在纸篓内。请不要在走廊 上成群逗留、高声喧哗。 2、为了您和他人的健康和安全,请不要在病区内吸烟、饮酒及使用明火和其他电器。 3、床头上方有呼叫器,在您需要帮助时,可用呼叫器呼叫护士。4、病人的饮食由医师依病情而定。 5、住院期间请您注意安全: (1)请保持卫生间、阳台地面干燥,以免滑倒。请您不要把床摇得太高,以免发生意外。 (2)如您年事已高或身体虚弱或行动不便,务必请家属陪伴不要独自下床活动、入厕等。 (3)病员不得随意外出或在院外住宿,如擅自外出,一切后果自负。 (4)贵重物品如手机、珠宝、现金等请您妥善保管,不要随意放在床头柜、枕头等处,以免遗失,如有遗失责任自负。 (5)请在护士的指导下使用热水袋、电热毯等取暖物,不要擅自使用。 6、请勿接受医院之外药品及治疗品的推销。不可自行邀请外院医师诊治,如需要诊治,您可与主管医师商量。 7、请及时缴费,以免影响您的治疗。 8、在使用空调时,请关闭门窗。请您爱护公物,如有损坏,照价赔偿。 9、在离院前请到住院处结清帐目,有出院带药者请与护士联系。') elif message.key == 'V3001_connectus': response = wechat.response_text(content=u'医院地址:永康市胜利街前花园2号\n交通路线:旁边有大润发商场,华联商厦、佳香基、丽中宾馆、中国银行、建设银行、农业银行和民主小学。公交车路线:丽州中路永康医院站牌(K3、K13、H01),九铃东路铃川路口站牌(K2、K16),南苑路南苑一弄站牌(K6、K8、K17)等路线均能到达。\n\n医院总机:0579-87143966\n\n传真号码:0579-87143100 \n\n急救电话:0579-87143999 87143120 \n\n专家预约电话:15372989120') else: response = wechat.response_text(content=u'自定义菜单点击事件') elif message.type == 'view': response = wechat.response_text(content=u'自定义菜单跳转链接事件') elif message.type == 'templatesendjobfinish': response = wechat.response_text(content=u'模板消息事件') return HttpResponse(response)
def auth(self): args = ['signature', 'timestamp', 'nonce'] kwargs = {k: self.get_argument(k, '') for k in args} wechat = WechatBasic(token=options.token) if not wechat.check_signature(**kwargs): self.set_status(403) self.write('auth failed') self.finish()
def wechat(request): signature = request.GET.get('signature') # 获取请求信息 timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') wechat_instance = WechatBasic(conf=conf) # 实例化微信基类对象 if not wechat_instance.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 检查验证请求的签名 return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': return HttpResponse(request.GET.get('echostr', None)) # 返回请求中的回复信息
def smart_entry(request): signature = request.REQUEST.get('signature', None) timestamp = request.REQUEST.get('timestamp', None) nonce = request.REQUEST.get('nonce', None) # if it's account authenticate request echostr = request.REQUEST.get('echostr', None) if echostr: return HttpResponse(echostr) wechat = WechatBasic(token=settings.WECHAT_TOKEN, appid=settings.WECHAT_ACCOUNT) # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作) body_text = request.body wechat.parse_data(body_text) # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义) message = wechat.get_message() response = None if isinstance(message, TextMessage): response = wechat.response_text(content=u'文字信息') elif isinstance(message, VoiceMessage): response = wechat.response_text(content=u'语音信息') elif isinstance(message, ImageMessage): response = wechat.response_text(content=u'图片信息') elif isinstance(message, VideoMessage): response = wechat.response_text(content=u'视频信息') elif isinstance(message, LinkMessage): response = wechat.response_text(content=u'链接信息') elif isinstance(message, LocationMessage): response = wechat.response_text(content=u'地理位置信息') elif isinstance(message, EventMessage): # 事件信息 if message.type == 'subscribe': # 关注事件(包括普通关注事件和扫描二维码造成的关注事件) if message.key and message.ticket: # 如果 key 和 ticket 均不为空,则是扫描二维码造成的关注事件 response = wechat.response_text(content=u'用户尚未关注时的二维码扫描关注事件') else: response = wechat.response_text(content=u'普通关注事件') elif message.type == 'unsubscribe': response = wechat.response_text(content=u'取消关注事件') elif message.type == 'scan': response = wechat.response_text(content=u'用户已关注时的二维码扫描事件') elif message.type == 'location': response = wechat.response_text(content=u'上报地理位置事件') elif message.type == 'click': response = wechat.response_text(content=u'自定义菜单点击事件') elif message.type == 'view': response = wechat.response_text(content=u'自定义菜单跳转链接事件') elif message.type == 'templatesendjobfinish': response = wechat.response_text(content=u'模板消息事件') return HttpResponse(response) return HttpResponse("Not implemented yet")
def validate(): wechat = WechatBasic(token=settings['wechat_app']['token'], appid=settings['wechat_app']['appID'], appsecret=settings['wechat_app']['appsecret']) signature = request.args.get('signature') timestamp = request.args.get('timestamp') nonce = request.args.get('nonce') # log the checking event logger.info("checking signature: (%s, %s, %s)", signature, timestamp, nonce) if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return request.args.get('echostr') return ""
def Index(request): signature = request.REQUEST.get("signature", "") timestamp = request.REQUEST.get("timestamp", "") nonce = request.REQUEST.get("nonce", "") echostr = request.REQUEST.get("echostr", "") KLBWechatBasic = WechatBasic(token=WECHAT_TOKEN, appid=WECHAT_APPID, appsecret=WECHAT_APPSECRET) IsOK = KLBWechatBasic.check_signature(signature, timestamp, nonce) if IsOK: return HttpResponse(echostr) else: return HttpResponse("")
def index(): token = settings.TOKEN signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') # 实例化 wechat wechat = WechatBasic(token=token) if not wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return 'fail' # 对签名进行校验 echostr = request.args.get('echostr') if echostr: return echostr wechat.parse_data(request.data) message = wechat.get_message() if message.type == 'text': response = wechat.group_transfer_message() elif message.type == 'image': response = wechat.response_text(u'图片') elif isinstance(message, EventMessage): if message.type == 'subscribe': if message.key and message.ticket: scene = message.key.startswith( 'qrscene_') and message.key[8:] or 'default' else: scene = 'default' SubscribeEvent.create_event(message.source, scene, message.time) response = wechat.response_text(content=settings.GREETINGS) elif message.type == 'unsubscribe': UnsubscribeEvent.create_event(message.source, message.time) # TODO response = '' elif message.type == 'scan': # TODO response = '' elif message.type == 'location': response = wechat.response_text(content=u'上报地理位置事件') elif message.type == 'click': content = settings.CLICK_MENU_TEXT_MAPPER.get(message.key, u'未知') response = wechat.response_text(content=content) elif message.type == 'view': response = wechat.response_text(content=u'自定义菜单跳转链接事件') elif message.type == 'templatesendjobfinish': response = wechat.response_text(content=u'模板消息事件') else: response = wechat.response_text(u'未知') return response
def index(): token = settings.TOKEN signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') # 实例化 wechat wechat = WechatBasic(token=token) if not wechat.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return 'fail' # 对签名进行校验 echostr = request.args.get('echostr') if echostr: return echostr wechat.parse_data(request.data) message = wechat.get_message() if message.type == 'text': response = wechat.group_transfer_message() elif message.type == 'image': response = wechat.response_text(u'图片') elif isinstance(message, EventMessage): if message.type == 'subscribe': if message.key and message.ticket: scene = message.key.startswith( 'qrscene_') and message.key[8:] or 'default' else: scene = 'default' SubscribeEvent.create_event(message.source, scene, message.time) response = wechat.response_text(content=settings.GREETINGS) elif message.type == 'unsubscribe': UnsubscribeEvent.create_event(message.source, message.time) # TODO response = '' elif message.type == 'scan': # TODO response = '' elif message.type == 'location': response = wechat.response_text(content=u'上报地理位置事件') elif message.type == 'click': content = settings.CLICK_MENU_TEXT_MAPPER.get(message.key, u'未知') response = wechat.response_text(content=content) elif message.type == 'view': response = wechat.response_text(content=u'自定义菜单跳转链接事件') elif message.type == 'templatesendjobfinish': response = wechat.response_text(content=u'模板消息事件') else: response = wechat.response_text(u'未知') return response
def get(self): w_signature = self.get_argument('signature') w_timestamp = self.get_argument('timestamp') w_nonce = self.get_argument('nonce') w_echostr = self.get_argument('echostr') wechat = WechatBasic(conf=self.conf) if wechat.check_signature(w_signature, w_timestamp, w_nonce): print "成功了" self.write(json.dumps(int(w_echostr))) else: print "失败了"
def handleRequest(request): signature = request.GET.get("signature", '') timestamp = request.GET.get("timestamp", '') nonce = request.GET.get("nonce", '') wechat = WechatBasic(token=TOKEN) if request.method == 'GET': echoStr = request.GET.get("echostr", '') if wechat.check_signature(signature, timestamp, nonce): response = HttpResponse(echoStr, content_type="text/plain") else: response = HttpResponse('', content_type="text/plain") return response elif request.method == 'POST': if wechat.check_signature(signature, timestamp, nonce): response = HttpResponse(responseMsg(request, wechat), content_type="application/xml") else: response = HttpResponse('', content_type="application/xml") return response else: return HttpResponse('', content_type="application/xml")
def WeChat(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') wechat_instance = WechatBasic(conf=conf) if not wechat_instance.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': response = request.GET.get('echostr', 'error') else: try: wechat_instance.parse_data(request.body) message = wechat_instance.get_message() if isinstance(message, TextMessage): print(message.source, message.time, message.content) # 显示最近 24 小时内的秘密 if message.content.lower() in topic: reply_text = show_topic(10) response = wechat_instance.response_text(reply_text, escape=True) # 显示关于信息 elif message.content.lower() in about: reply_text = show_about() response = wechat_instance.response_news(reply_text) # 显示帮助信息 elif message.content.lower() in help or len(message.content) <= content_min_length: reply_text = show_help() response = wechat_instance.response_news(reply_text) # 过滤自定义表情 elif cmp(message.content, gif_msg)== 0: response = wechat_instance.response_text(u'ʕ •ᴥ•ʔ 自定义表情是不会被记录的哎,写点文字吧~') # 记录用户的消息 else: save_message(message.source, message.content, timezone.now()) response = wechat_instance.response_text(u'嘘~~~ 树洞知道了~\n输入「树洞」可以看到大家最新的小秘密 ヾ(o◕∀◕)ノヾ', escape=True) elif isinstance(message, VoiceMessage): response = wechat_instance.response_text(u'("▔□▔)/ 暂时还听不懂你在说什么唉,写点文字吧~') elif isinstance(message, ImageMessage): response = wechat_instance.response_text(u'("▔□▔)/ 暂时还不能识别图片唉,写点文字吧~') elif isinstance(message, LinkMessage): response = wechat_instance.response_text(u'("▔□▔)/ 链接我是不会记录的唉,写点文字吧~') elif isinstance(message, LocationMessage): response = wechat_instance.response_text(u'("▔□▔)/ 位置信息我是不会记录的唉,写点文字吧~') elif isinstance(message, VideoMessage): response = wechat_instance.response_text(u'("▔□▔)/ 视频我是不会记录的唉,写点文字吧~') elif isinstance(message, ShortVideoMessage): response = wechat_instance.response_text(u'("▔□▔)/ 小视频我是不会记录的唉,写点文字吧~') else: response = wechat_instance.response_text(u'恭喜你成为了 G2EX 前 60 亿个粉丝!随便写点什么试试吧~') except ParseError: return HttpResponseBadRequest('Invalid XML Data') return HttpResponse(response, content_type="application/xml")
def test_check_signature(self): signature = '41f929117dd6231a953f632cfb3be174b8e3ef08' timestamp = '1434295379' nonce = 'ueivlkyhvdng46da0qxr52qzcjabjmo7' # 测试无 Token 初始化 wechat = WechatBasic() with self.assertRaises(NeedParamError): wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce) # 测试有 Token 初始化 wechat = WechatBasic(token=self.token) self.assertTrue( wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce)) self.assertFalse( wechat.check_signature(signature=signature, timestamp=timestamp + '2', nonce=nonce))
def wechat_home(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') wechat_instance = WechatBasic(conf=MyConf) reply_text = "" if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') else: reply_text = "Test" response = wechat_instance.response_text(content=reply_text) return HttpResponse(response, content_type='application/xml')
def jfjl_valiation(): args = request.args token = 'jiefangjieli' echostr = args['echostr'] signature = args['signature'] timestamp = args['timestamp'] nonce = args['nonce'] wechat = WechatBasic(token=token) # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return echostr else: return "This is jfjl valiation!"
def wechat_home(request): # get signature, timestamp and nonce signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') # create a newInstance wechat_instance = WechatBasic(conf=conf) # check_signature function tells whether the request is sent by wechat # not checked if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') else: # checked # GET method represents that Wechat sent verification information if request.method == 'GET': response = request.GET.get('echostr', 'error') # POST method stands for Wechat sent user's messages else: try: wechat_instance.parse_data( request.body) # parse data from instance message = wechat_instance.get_message() # get message # classify the type of message if isinstance(message, TextMessage): # text message reply_text = 'text' elif isinstance(message, VoiceMessage): # voice message reply_text = 'voice' elif isinstance(message, ImageMessage): # image message reply_text = 'image' elif isinstance(message, LinkMessage): # link message reply_text = 'link' elif isinstance(message, LocationMessage): # location message reply_text = 'location' elif isinstance(message, VideoMessage): # video message reply_text = 'video' elif isinstance(message, ShortVideoMessage): # shortvideo message reply_text = 'shortvideo' else: reply_text = 'other' # other message response = wechat_instance.response_text(content=reply_text) except ParseError: # ERROR when parsing return HttpResponseBadRequest('Invalid XML Data') # reply with our defined message return HttpResponse(response, content_type="application/xml") # END
def wechat_auth(): wechat = WechatBasic(token=TOKEN) if request.method == 'GET': token = TOKEN # your token query = request.args # GET 方法附上的参数 signature = query.get('signature', '') timestamp = query.get('timestamp', '') nonce = query.get('nonce', '') echostr = query.get('echostr', '') if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return make_response(echostr) else: return 'Signature Mismatch' else: body_text=request.data wechat.parse_data(body_text) # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义) message = wechat.get_message() response = None # 在这里解析 message.content 也就是用户发来的文字 if message.type == 'text': if message.content.lower() in ('h', 'help'): response = wechat.response_text(u'z 看知乎日报\nv 看 V2EX 十大\nh 为帮助\n输入其他文字与机器人对话 : )') elif message.content == 'wechat': response = wechat.response_text(u'^_^') elif message.content[0:3] == 'test': response = wechat.response_text(u'I\'m testing ' + message.content[4:]) elif (u'陆' or u'杰') in message.content: response = wechat.response_text(u'爸爸是个天才') elif (u'***' or u'内内') in message.content: response = wechat.response_text(u'内内,为什么你名字那么难写') elif message.content.upper() in ('V', 'V2EX'): response = wechat.response_news(get_v2ex_news()) elif message.content.upper() in ('Z', 'ZHIHU'): response = wechat.response_news(get_zhihudaily()) else: response = wechat.response_text(get_turing(message.content)) elif message.type == 'image': response = wechat.response_text(u'您发来了一个图片') elif message.type == 'location': response = wechat.response_text(u'您的位置我已收到') elif message.type == 'subscribe': response = wechat.response_text(u'oh...你居然关注了,其实我自己也不知道关注这个号有啥用.\nz 看知乎日报\nv 看 V2EX 十大\nh 为帮助\n输入其他文字与机器人对话 : )') elif message.type == 'unsubscribe': response = wechat.response_text(u'呜呜呜,爱我别走.....') else: response = wechat.response_text(u'未知类型。您发的是什么?') return response
def wechat(request): signature = request.GET.get('signature', '') timestamp = request.GET.get('timestamp', '') nonce = request.GET.get('nonce', '') wechat_instance = WechatBasic(conf=conf) # 验证微信公众平台的消息 if wechat_instance.check_signature(signature!=signature, timestamp!=timestamp, nonce!=nonce): return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': response = request.GET.get('echostr', 'error') else: try: wechat_instance.parse_data(request.body) message = wechat_instance.get_message() except ParseError: return HttpResponseBadRequest('Invalid XML Data') response = wechat_instance.response_text( content=( '感谢您的关注!\n回复【help】查看支持的功能' '\n【<a href="http://www.rwnexus.site">我的博客</a>】' )) if isinstance(message, TextMessage): # 当前会话内容 content = message.content.strip() if content == 'help': reply_text = ( '目前支持的功能:\n1. 输入【博客】来查看我的博客\n' '2. 回复【天气】来获取近几日天气情况\n' '3. 回复【快递】来查询快递情况\n' '还有更多功能正在开发中哦 ^_^\n' '【<a href="http://www.rwnexus.site">我的博客</a>】' ) elif content == u'博客': reply_text = '我的博客地址是http://www.rwnexus.site' elif content == u'天气': reply_text = '天气功能还在开发中噢,亲可以先查看【<a href="http://www.rwnexus.site">我的博客</a>】' elif content == u'快递': reply_text = '快递功能还在开发中噢,亲可以先查看【<a href="http://www.rwnexus.site">我的博客</a>】' else: reply_text = '功能还在开发中哦,亲可以提出您宝贵的意见' response = wechat_instance.response_text(content=reply_text) return HttpResponse(response, content_type="application/xml")
def handshake(params): conf = WechatConf( token='modefliptwentysixteen', appid='wx007c42b9e3f7413d', appsecret='015cc6487b24128615e2ed395f04de52', encrypt_mode='safe', encoding_aes_key='UNippv5nGwtw0zgeSROQ82qzDhFcFfCdpGTkZ9nEbBn') wechat = WechatBasic(conf=conf) signature = params.get('signature') timestamp = params.get('timestamp') nonce = params.get('nonce') print 'echostr:', params.get('echostr') if wechat.check_signature(signature, timestamp, nonce): return params.get('echostr') return None
def index(request): """微信公众号的主控制器""" access_token, access_token_expires_at = get_new_access_token() wechat_obj = WechatBasic( token='projie', appid='wxe6dd92b5d69334ad', appsecret='6f377e6996fed8734832531b9503e9f3', access_token=access_token, access_token_expires_at=int(access_token_expires_at)) if request.method == 'GET': # 执行token验证 if wechat_obj.check_signature(signature=request.GET.get('signature'), timestamp=request.GET.get('timestamp'), nonce=request.GET.get('nonce')): return HttpResponse(request.GET.get('echostr'), content_type="text/plain") else: return HttpResponseBadRequest('Verify Error') else: # 各种回复消息 try: wechat_obj.parse_data(request.body) except ParseError: return HttpResponseBadRequest('XML PARSE ERROR') # 获取消息的主体内容 message = wechat_obj.get_message() # 默认的回复内容 response = wechat_obj.response_text(content="你好,欢迎关注我的微信公众号!") if isinstance(message, TextMessage): # 文本消息 Txt = TextResponse(wechat_obj, message) response = Txt.main() elif isinstance(message, ImageMessage): # 图片消息 response = wechat_obj.response_text(content='这是什么图') elif isinstance(message, VoiceMessage): # 语音消息 response = wechat_obj.response_text(content=message.recognition) elif isinstance(message, VideoMessage) or isinstance( message, ShortVideoMessage): # 视频消息 response = wechat_obj.response_text(content='天天就知道看片') elif isinstance(message, LocationMessage): # 位置信息 response = wechat_obj.response_text(content='你在这里呀') elif isinstance(message, LinkMessage): # 链接消息 response = wechat_obj.response_text(content='这是**网站?') elif isinstance(message, EventMessage): # 事件 event = EventResponse(wechat_obj, message) response = event.main() # 执行回复 return HttpResponse(response, content_type="application/xml")
def send_template_massage(): try: token = Config.WECHAT_TOKEN args = request.args echostr = args['echostr'] signature = args['signature'] timestamp = args['timestamp'] nonce = args['nonce'] # 实例化 wechat wechat = WechatBasic(token=token) # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): user_id = 'o5lpBuCdBW7HABytpcAbMy3QbBPs' template_id = 'grsshOaPw-0pCrkdZwjOS4Mr4AaQQVteEG-2R_RK6BY' data = { "first": { "value": "恭喜你购买成功!", "color": "#173177" }, "keynote1":{ "value": "巧克力", "color": "#173177" }, "keynote2": { "value": "39.8元", "color": "#173177" }, "keynote3": { "value": "2014年9月16日", "color": "#173177" }, "remark":{ "value": "欢迎再次购买!", "color": "#173177" } } WechatBasic.send_template_message(user_id, template_id, data) print 'wechat token' return 'Hello' except TemplateNotFound: abort(404)
def wechat_home(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') wechat_instance = WechatBasic(conf=conf) if not wechat_instance.check_signature(signature, timestamp, nonce): return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': res = request.GET.get('echostr', 'error') return HttpResponse(res, content_type='application/xml') else: try: wechat_instance.parse_data(request.body) message = wechat_instance.get_message() res = dawn_train(message, wechat_instance) except ParseError: return HttpResponseBadRequest('Invalid XML Data') return HttpResponse(res, content_type='application/xml')
def auth(self, request, code, signature, timestamp, nonce, echostr=None): logger.debug('WeChat connected: code=%s, signature=%s, timestamp=%s, nonce=%s, echostr=%s', code, signature, timestamp, nonce, echostr) request.uid = 1 account_obj = request.registry['wechat.account'] account = account_obj.get_account_config(request.cr, request.uid, code, context=request.context) if not account.token: return '' we_chat = WechatBasic(token=account.token) if we_chat.check_signature(signature, timestamp, nonce): if echostr: return Response(echostr) else: logger.info('WeChat check_signature success: code=%s, signature=%s, timestamp=%s, nonce=%s, echostr=%s', code, signature, timestamp, nonce, echostr) return Response(self._make_response(request, we_chat, account)) else: logger.warn('WeChat check_signature Failed: code=%s, signature=%s, timestamp=%s, nonce=%s, echostr=%s', code, signature, timestamp, nonce, echostr) return Response('')
def index(request): """ 所有的消息都会先进入这个函数进行处理,函数包含两个功能, 微信接入验证是GET方法, 微信正常的收发消息是用POST方法。 """ return_str = '' signature = request.GET.get("signature", None) timestamp = request.GET.get("timestamp", None) nonce = request.GET.get("nonce", None) echostr = request.GET.get("echostr", None) if request.method == "GET": tmp_list = [WEIXIN_TOKEN, timestamp, nonce] tmp_list.sort() tmp_str = "%s%s%s" % tuple(tmp_list) tmp_str = hashlib.sha1(tmp_str).hexdigest() if tmp_str == signature: return_str = echostr else: return_str = "weixin index" else: body_text = smart_str(request.body) wechat = WechatBasic(token=WEIXIN_TOKEN) # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作) wechat.parse_data(body_text) # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义) message = wechat.get_message() # 现在直接将 response 变量内容直接作为 HTTP Response 响应微信服务器即可,此处为了演示返回内容,直接将响应进行输出 return_str = weixin_main(wechat, message) return HttpResponse(return_str)
def wechat_home(request): global url_base signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') wechat_instance = WechatBasic(conf=config) if not wechat_instance.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': response = request.GET.get('echostr', 'error') else: try: wechat_instance.parse_data(request.body) message = wechat_instance.get_message() if isinstance(message, TextMessage): reply_text = '''★想要知道你缴纳了多多少笔违法,点击<a href="%s/jilu/">这里</a>立刻查看缴款历史记录''' % url_base elif isinstance(message, VoiceMessage): reply_text = 'voice' elif isinstance(message, ImageMessage): reply_text = 'image' elif isinstance(message, LinkMessage): reply_text = 'link' elif isinstance(message, LocationMessage): reply_text = 'location' elif isinstance(message, VideoMessage): reply_text = 'video' elif isinstance(message, ShortVideoMessage): reply_text = 'shortvideo' else: reply_text = '''感谢关注武汉交警! ★立刻加入V用户,不仅可以在线处理交通违法、还能享受学习减免3分、首违警告等福利哦! 很简单,点击下方菜单——警民互动——实名认证即可哒~ ★回复【记录】查看本人在武汉交警微信上的缴款历史记录,看快去看看哦!''' response = wechat_instance.response_text(content=reply_text) except ParseError: return HttpResponseBadRequest('Invalid XML Data') return HttpResponse(response, content_type="application/xml")
def weixin_test(request): # 下面这些变量均假设已由 Request 中提取完毕 token = 'WECHAT_TOKEN' # 你的微信 Token signature = 'f24649c76c3f3d81b23c033da95a7a30cb7629cc' # Request 中 GET 参数 signature timestamp = '1406799650' # Request 中 GET 参数 timestamp nonce = '1505845280' # Request 中 GET 参数 nonce body_text = """ <xml> <ToUserName><![CDATA[touser]]></ToUserName> <FromUserName><![CDATA[fromuser]]></FromUserName> <CreateTime>1405994593</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[锐捷]]></Content> <MsgId>6038700799783131222</MsgId> </xml> """ wechat = WechatBasic(token=token) # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作) wechat.parse_data(body_text) # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义) message = wechat.get_message() response = None if message.type == 'text': if message.content == 'wechat': response = wechat.response_text(u'^_^') else: response = wechat.response_text(u'文字') elif message.type == 'image': response = wechat.response_text(u'图片') else: response = wechat.response_text(u'未知') # 现在直接将 response 变量内容直接作为 HTTP Response 响应微信服务器即可,此处为了演示返回内容,直接将响应进行输出 print response return HttpResponse(response)
def WeChat(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') # 实例化 WechatBasic 类 wechat_instance = WechatBasic(conf=conf) # 验证微信公众平台的消息 if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': response = request.GET.get('echostr', 'error') else: try: wechat_instance.parse_data(request.body) message = wechat_instance.get_message() # 判断消息类型 if isinstance(message, TextMessage): reply_text = 'text' elif isinstance(message, VoiceMessage): reply_text = 'voice' elif isinstance(message, ImageMessage): reply_text = 'image' elif isinstance(message, LinkMessage): reply_text = 'link' elif isinstance(message, LocationMessage): reply_text = 'location' elif isinstance(message, VideoMessage): reply_text = 'video' elif isinstance(message, ShortVideoMessage): reply_text = 'shortvideo' else: reply_text = 'other' response = wechat_instance.response_text(content=reply_text) except ParseError: return HttpResponseBadRequest('Invalid XML Data') return HttpResponse(response, content_type="application/xml")
def WeChat(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') # 实例化 WechatBasic 类 wechat_instance = WechatBasic(conf=conf) # 验证微信公众平台的消息 if not wechat_instance.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': response = request.GET.get('echostr', 'error') else: try: wechat_instance.parse_data(request.body) message = wechat_instance.get_message() # 判断消息类型 if isinstance(message, TextMessage): reply_text = 'text' elif isinstance(message, VoiceMessage): reply_text = 'voice' elif isinstance(message, ImageMessage): reply_text = 'image' elif isinstance(message, LinkMessage): reply_text = 'link' elif isinstance(message, LocationMessage): reply_text = 'location' elif isinstance(message, VideoMessage): reply_text = 'video' elif isinstance(message, ShortVideoMessage): reply_text = 'shortvideo' else: reply_text = 'other' response = wechat_instance.response_text(content=reply_text) except ParseError: return HttpResponseBadRequest('Invalid XML Data') return HttpResponse(response, content_type="application/xml")
def wechat_home1(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') BASE_ROOT = os.path.abspath(os.path.join(os.path.split(__file__)[0], '..')) path = BASE_ROOT + "/web/wx_w.txt" r = open(path, "w") r.write("soe") r.close() wechat = WechatBasic(conf=conf) #wechat = WechatBasic(appid='wx4ed8e5a367d2451f', appsecret='d41a46925b7791a7fd7d2dc95823591b') if not wechat.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': response = request.GET.get('echostr', 'error') else: try: # BASE_ROOT = os.path.abspath(os.path.join(os.path.split(__file__)[0], '..')) # path = BASE_ROOT+"/web/wx_w.txt" # r=open(path,"w") # r.write("soe") # r.close() # source = wechat.message.source # BASE_ROOT = os.path.abspath(os.path.join(os.path.split(__file__)[0], '..')) # path = BASE_ROOT+"/web/wx_w.txt" # r=open(path,"w") # r.write("source") # r.close() wechat.parse_data(request.body) response = wechat.response_text(content="reason") except Exception, e: reason = e response = wechat.response_text(content=reason) return HttpResponse(response, content_type="application/xml")
# 请更改 body_text 的内容来测试下面代码的执行情况 body_text = """ <xml> <ToUserName><![CDATA[touser]]></ToUserName> <FromUserName><![CDATA[fromuser]]></FromUserName> <CreateTime>1405994593</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[wechat]]></Content> <MsgId>6038700799783131222</MsgId> </xml> """ # 实例化 wechat wechat = WechatBasic(token=token) # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作) wechat.parse_data(body_text) # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义) message = wechat.get_message() response = None if message.type == 'text': if message.content == 'wechat': response = wechat.response_text(u'^_^') else: response = wechat.response_text(u'文字') elif message.type == 'image': response = wechat.response_text(u'图片') else: response = wechat.response_text(u'未知')
def auto_reply(signature, timestamp, nonce, body_text): # 实例化 wechat wechat = WechatBasic(token=TOKEN) # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作) wechat.parse_data(body_text) # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义) message = wechat.get_message() response = None if isinstance(message, TextMessage): keyword = message.content try: P = Post(keyword, wechat) P.run() except Exception as ex: response = wechat.response_text(content=u'无查询结果,请尝试其它关键词。输入h,查看帮助。') logger.exception(ex) try: response = Response.objects.get(keyword=keyword).content logger.info("auto reply response") except Exception as ex: response = wechat.response_text(content=u'无查询结果,请尝试其它关键词。输入h,查看帮助。') logger.error(ex) elif isinstance(message, VoiceMessage): save_message("VoiceMessage") response = wechat.response_text(content=u'语音信息') elif isinstance(message, ImageMessage): save_message("ImageMessage") response = wechat.response_text(content=u'图片信息') elif isinstance(message, VideoMessage): save_message("VideoMessage") response = wechat.response_text(content=u'视频信息') elif isinstance(message, LinkMessage): save_message("LinkMessage") response = wechat.response_text(content=u'链接信息') elif isinstance(message, LocationMessage): save_message("LocationMessage") response = wechat.response_text(content=u'地理位置信息') elif isinstance(message, EventMessage): # 事件信息 if message.type == 'subscribe': # 关注事件(包括普通关注事件和扫描二维码造成的关注事件) if message.key and message.ticket: # 如果 key 和 ticket 均不为空,则是扫描二维码造成的关注事件 response = wechat.response_text(content=u'用户尚未关注时的二维码扫描关注事件') else: reply_text = u"你好!感谢关注linux-world公众号。" \ u"让我们一起感受Linux的魅力,享受学习的乐趣吧!" \ u"发送“h”或者“help”,查看相关帮助信息。" \ u"点击右上角,查看历史信息,发现精彩内容。" \ u"目前微信平台在开发之中,后期会推出更加精彩的功能和内容。" # response = wechat.response_text(content=u'普通关注事件') response = wechat.response_text(content=reply_text) elif message.type == 'unsubscribe': response = wechat.response_text(content=u'取消关注事件') elif message.type == 'scan': response = wechat.response_text(content=u'用户已关注时的二维码扫描事件') elif message.type == 'location': response = wechat.response_text(content=u'上报地理位置事件') elif message.type == 'click': response = wechat.response_text(content=u'自定义菜单点击事件') elif message.type == 'view': response = wechat.response_text(content=u'自定义菜单跳转链接事件') else: response = "error, 非法的微信请求!" return response
def get_reply(request): signature = request.GET.get('signature') # 获取请求信息 timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') openid = request.GET.get("openid") wechat_instance = WechatBasic(conf=conf) # 实例化微信基类对象 if not wechat_instance.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 检查验证请求的签名 return HttpResponseBadRequest('Verify Failed') else: # if request.method == 'GET': # return HttpResponse(request.GET.get('echostr', None)) # 返回请求中的回复信息 # data = requests.post.get # if request.method == 'GET': # # data = request.GET.get('data') # openid = request.GET.get("openid") # elif request.method == 'POST': # # data = request.POST.get('data') # openid = request.POST.get("openid") # else: # openid = "not_get" # return HttpResponse("俺也不知道发生了什么!") try: wechat.parse_data(data=request.body) except ParseError: return HttpResponseBadRequest('无效的xml数据') message = wechat.get_message() data_get = message.content.strip().replace("小风", "小思") # print(data) url = "https://api.ownthink.com/bot" body = { "spoken": data_get, "appid": "f2a2c494b2a7022199e95d22572635e4", "userid": "hehe" } try: res = requests.post(url, data=json.dumps(body)) data = json.loads(res.text) if data["message"] == "success": reply = data["data"]["info"]["text"] print(reply) if not reply: reply = choice(reply_list) else: reply = "服务器异常" except: reply = choice(reply_list) createdAt = datetime.now() user_name = WechatRobotLog.objects.filter(open_id=openid) try: username = user_name[0].user_name except: username = '' db = WechatRobotLog(open_id=openid, user_text=data_get, reply_text=reply, created_at=str(createdAt), user_name=username) db.save() reply = reply.replace("小思", "小风") result = wechat.response_text(content=reply) return HttpResponse(result, content_type='application/xml')
def weixin(request): # 实例化 We_chat_Basic we_chat = WechatBasic( token=WECHAT_TOKEN, appid=AppID, appsecret=AppSecret ) if request.method == "GET": signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') if "bet" in request.GET: return get_user_bet(request) if not we_chat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponse("Verify failed") else: #create_menu() return HttpResponse(request.GET.get("echostr"), content_type="text/plain") else: signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') if not we_chat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponse("Verify failed") try: we_chat.parse_data(data=request.body) except ParseError: return HttpResponseBadRequest('Invalid XML Data') message = we_chat.get_message() if isinstance(message, TextMessage): result = process_text_message(message) response = we_chat.response_text(result) return HttpResponse(response) if isinstance(message, EventMessage): if message.type == 'click': if message.key == 'STEP_COUNT': step_user = RingUser.objects.filter(user_id=message.source)[0] if step_user: try: target = step_user.target step = get_today_step(step_user) goal_completion = int(float(step) / target * 100) response = we_chat.response_text(u'跑了' + str(step) + u'步咯,完成今日目标:' + str(goal_completion) + u'%') except Exception as e: print e # 里面的数字应由其他函数获取 return HttpResponse(response) else: response = we_chat.response_text(u'Sorry, there\' no data about you in our database.') return HttpResponse(response) elif message.key == 'RANK_LIST': response = RESPONSE_RANKLIST % (message.source, message.target) return HttpResponse(response) elif message.key == '2048': response = we_chat.response_news([{ 'title': u'Let us play 2048 together', 'description': 'a simple but interesting game', 'picurl': 'http://7xn2s5.com1.z0.glb.clouddn.com/2048.jpg', 'url': 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+AppID+'&redirect_uri=http%3a%2f%2f'+LOCAL_IP+'%2fdodojump.html'+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'}]) return HttpResponse(response) elif message.key == 'FLAPPY': response = we_chat.response_news([{ 'title': u'Let us play Flappy Bird together', 'description': 'a simple but interesting game', 'picurl': 'http://7xn2s5.com1.z0.glb.clouddn.com/flappy_bird.jpg', 'url': 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+AppID+'&redirect_uri=http%3a%2f%2f'+LOCAL_IP+'%2fflyingdog.html'+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'}]) return HttpResponse(response) elif message.key == 'CHART': print "here" response = we_chat.response_news([{ 'title': u'Today\'s amount of exercise', 'description': 'data analysis', 'picurl': 'http://7xn2s5.com1.z0.glb.clouddn.com/info.jpg', 'url': 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+AppID+'&redirect_uri=http%3a%2f%2f'+LOCAL_IP+'%2fsleepAnalysis.html'+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'}]) return HttpResponse(response) elif message.key == 'CHEER': response = we_chat.response_text(u'We are family!') return HttpResponse(response) return HttpResponse('OK')
def checker(request): if request.method == 'GET': # 公众号后台接入 signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') echostr = request.GET.get('echostr') wechat = WechatBasic(token=token) if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponse(echostr) else: return HttpResponse('INVALID') else: # 处理用户发送的信息 body_text = request.body wechat = WechatBasic(token=token) wechat.parse_data(body_text) # 获取微信消息类WechatMessage message = wechat.get_message() # 获取用户openid openid = message.source try: user = User.objects.get(openid=openid) except User.DoesNotExist: user = User(openid=openid) user.save() response = None if message.type == 'text': if user.status == 'MASTER': if check_user_enter(message.content, 'NAME_INFO'): user.status = 'NAME_INFO' user.save() response = wechat.response_text(ENTER_NAME_RESPONSE) elif check_user_enter(message.content, 'LCT_INFO'): user.status = 'LCT_INFO' user.save() response = wechat.response_text(ENTER_LCT_RESPONSE) elif check_user_enter(message.content, 'DISC_INFO'): user.status = 'DISC_INFO' user.save() response = wechat.response_text(ENTER_DISC_RESPONSE) else: response = wechat.response_text(CHOOSE_FUNC_RESPONSE) elif user.status == 'NAME_INFO' or user.status == 'DISC_INFO': if message.content == u'退出': user.status = 'MASTER' user.save() response = wechat.response_text(CHOOSE_FUNC_RESPONSE) else: try: restaurant = Restaurant.objects.get(name=message.content) restaurant_template = RestaurantTemplate(restaurant=restaurant) response = wechat.response_text(restaurant_template.response()) except Restaurant.DoesNotExist: res_list, user.res_list = name_searcher(message.content) user.save() if res_list: if user.status == 'NAME_INFO': user.status = 'NAME_CHOOSE' user.save() else: user.status == 'DISC_CHOOSE' user.save() back_info = RES_LIST_RESPONSE for k in range(0, len(res_list)): back_info = "%s\n%d: %s" % (back_info, k+1, res_list[k]) back_info += ENTER_NUM_RESPONSE response = wechat.response_text(back_info) else: response = wechat.response_text(RES_NOT_FOUND_RESPONSE) elif user.status == 'LCT_INFO': if message.content == u'退出': user.status = 'MASTER' user.save() response = wechat.response_text(CHOOSE_FUNC_RESPONSE) else: if user.lct and message.content == '0': restaurant = location_recommend(user, 0.7) restaurant_template = RestaurantTemplate(restaurant=restaurant) response = wechat.response_text(restaurant_template.response() + ENTER_ROLL_RESPONSE) else: lct_list, user.lct_list = location_searcher(message.content) user.save() if lct_list: user.lct = message.content user.save() restaurant = location_recommend(user, 0.7) restaurant_template = RestaurantTemplate(restaurant=restaurant) response = wechat.response_text(restaurant_template.response() + ENTER_ROLL_RESPONSE) else: user.lct = '' user.save() response = wechat.response_text(LCT_NOT_FOUND_RESPONSE) elif user.status == 'NAME_CHOOSE': if message.content == u'退出': user.status = 'NAME_INFO' user.save() response = wechat.response_text(ENTER_NAME_RESPONSE) else: res_list = user.res_list.split(',') try: index = int(message.content) if not (index in range(1, len(res_list))): raise ValueError restaurant = Restaurant.objects.get(id=int(res_list[index])) restaurant_template = RestaurantTemplate(restaurant=restaurant) response = wechat.response_text(restaurant_template.response()) except ValueError: response = wechat.response_text(NAME_CHOOSE_ERROR_RESPONSE) elif message.type == 'location' and user.status == 'LCT_INFO': latitude = float(message.location[0]) longitude = float(message.location[1]) user.lct_list = distance_recommend(latitude, longitude) user.save() if user.lct_list: user.lct = message.label user.save() restaurant = location_recommend(user, 0.7) restaurant_template = RestaurantTemplate(restaurant=restaurant) response = wechat.response_text(restaurant_template.response() + ENTER_ROLL_RESPONSE) else: user.lct = '' user.save() response = wechat.response_text(LCT_NOT_FOUND_RESPONSE) else: response = wechat.response_text(ENTER_NAME_RESPONSE) return HttpResponse(response)
def smart_entry(request): signature = request.REQUEST.get('signature', None) timestamp = request.REQUEST.get('timestamp', None) nonce = request.REQUEST.get('nonce', None) # if it's account authenticate request echostr = request.REQUEST.get('echostr', None) if echostr: return HttpResponse(echostr) wechat = WechatBasic(token=settings.WECHAT_TOKEN, appid=settings.WECHAT_ACCOUNT) # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作) body_text = request.body log.info("Wechat message come: {0}".format(body_text)) wechat.parse_data(body_text) # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义) message = wechat.get_message() #response = None if isinstance(message, EventMessage): if message.type == 'click' and message.key == 'V1001_PLANT_LIVE': # post latest image records = IoTRecord.objects.filter().order_by("-timestamp")[:1] if not records or not records[0].image: return HttpResponse(wechat.response_text(u"找不到你的菜呀!")) api = WechatCgiApi(app_id=settings.WECHAT_APP_ID, app_secret=settings.WECHAT_APP_SECRET) result_token = WechatConfig.objects.filter(key=WechatConfig.KEY_ACCESS_TOKEN) if not result_token or result_token[0].is_expired(): result_update, resp_json = WechatConfig.refresh_access_token() if result_update: token = resp_json[u"access_token"] else: log.error("Cannot update wechat access token: {0}".format(resp_json)) return HttpResponse(wechat.response_text(u"服务器有点小问题。。。")) else: token = result_token[0].value with open(records[0].image.path, 'rb') as live_image: api_result = api.create_temp_media(token, "image", media={"media": live_image}) log.info("Wechat upload image response: {0}".format(api_result)) if api_result and api_result["media_id"]: return HttpResponse(wechat.response_image(api_result["media_id"])) else: log.warning("Wechat upload temporary image failed: {0}".format(api_result)) return HttpResponse(wechat.response_text(u"发送图片失败: {0}".format(str(api_result)))) elif message.type == 'click' and message.key == 'V1001_HEALTH_STATS': return HttpResponse(wechat.response_text(u"功能未实现")) elif message.type == 'click' and message.key == 'V1001_GROW_VID': return HttpResponse(wechat.response_text(u"功能未实现。")) elif message.type == 'click' and message.key == 'V1001_PLAY_CUTE': return HttpResponse(wechat.response_text(u"我已经长得很好吃了,主人请摘我吧!")) # response = wechat.response_text(content=u'文字信息') response = wechat.response_news([{ "title": "我是别人的菜", "description": "你要的功能失败了,这是测试页面", "picurl": "http://wechat.lucki.cn/static/iotimages/test.jpg", "url": "http://wechat.lucki.cn/", },]) return HttpResponse(response) return HttpResponse("Not implemented yet")
def check_signature(self, **post): _logger.info('post are %s', post) wechat = WechatBasic(token="gongzi") if wechat.check_signature(signature=post.get('signature'), timestamp=post.get('timestamp'), nonce=post.get('nonce')): return post.get('echostr') return 'Error'
def wechattest(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') wechat_instance = WechatBasic(conf=conf) if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': response = request.GET.get('echostr', 'err') else: try: wechat_instance.parse_data(request.body) message = wechat_instance.get_message() wechat_user_openid = wechat_instance.message.source # res = wechat_instance.create_qrcode({ # "expire_seconds": "QR_LIMIT_SCENE", # "action_name": "QR_SCENE", # "action_info": { # "scene": { # "scene_id": 123 # } # } # }) # response = wechat_instance.show_qrcode(res['ticket']) # with open('tmpfile', 'wb') as fd: # for chunk in response.iter_content(1024): # fd.write(chunk) if isinstance(message, ImageMessage): try: link = WechatQRCode.objects.get( wechat_openid=wechat_user_openid) link.qrcode_url = message.picurl link.save() response = wechat_instance.download_media( message.media_id) # import pdb; pdb.set_trace() # filename = os.path.join(os.path.pardir,'/static/img/' + link.account.account_name + '.jpeg') with open( 'ILink/static/img/' + link.account.account_name + '.jpeg', 'wb') as fd: for chunk in response.iter_content(1024): fd.write(chunk) reply_text = '二维码上传成功' except Exception, e: reply_text = '请先绑定帐号\n\n绑定ILink帐号,请使用 - 为分隔符输入帐号密码\n上传个人微信二维码,请直接发送图片' elif isinstance(message, TextMessage): content = message.content if content.find("-") > -1: # User varification account, passwd = content.split("-") # Encode account password md5 = hashlib.md5() md5.update(passwd.encode('utf-8')) passwd = md5.hexdigest() # Account validation try: account_for_validation = Account.objects.get( _account_name=account) except Exception, e: reply_text = '绑定ILink帐号,请使用 - 为分隔符输入帐号密码\n上传个人微信二维码,请直接发送图片' # import pdb; pdb.set_trace() if account_for_validation: if account_for_validation.account_passwd == passwd: try: link = WechatQRCode.objects.get( wechat_openid=wechat_user_openid) link.account = account_for_validation reply_text = '重新绑定ILink帐号成功' except Exception, e: newlink = WechatQRCode.create( account=account_for_validation, openid=wechat_user_openid) newlink.save() reply_text = '绑定ILink帐号成功' else: reply_text = '绑定ILink帐号验证失败' else:
def wechattest(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') wechat_instance = WechatBasic(conf = conf) if not wechat_instance.check_signature(signature = signature, timestamp = timestamp, nonce = nonce) : return HttpResponseBadRequest('Verify Failed') else : if request.method == 'GET' : response = request.GET.get('echostr', 'err') else : try: wechat_instance.parse_data(request.body) message = wechat_instance.get_message() wechat_user_openid = wechat_instance.message.source # res = wechat_instance.create_qrcode({ # "expire_seconds": "QR_LIMIT_SCENE", # "action_name": "QR_SCENE", # "action_info": { # "scene": { # "scene_id": 123 # } # } # }) # response = wechat_instance.show_qrcode(res['ticket']) # with open('tmpfile', 'wb') as fd: # for chunk in response.iter_content(1024): # fd.write(chunk) if isinstance(message, ImageMessage) : try: link = WechatQRCode.objects.get(wechat_openid = wechat_user_openid) link.qrcode_url = message.picurl link.save() response = wechat_instance.download_media(message.media_id) # import pdb; pdb.set_trace() # filename = os.path.join(os.path.pardir,'/static/img/' + link.account.account_name + '.jpeg') with open('ILink/static/img/' + link.account.account_name + '.jpeg', 'wb') as fd : for chunk in response.iter_content(1024) : fd.write(chunk) reply_text = '二维码上传成功' except Exception, e: reply_text = '请先绑定帐号\n\n绑定ILink帐号,请使用 - 为分隔符输入帐号密码\n上传个人微信二维码,请直接发送图片' elif isinstance(message, TextMessage) : content = message.content if content.find("-") > -1 : # User varification account, passwd = content.split("-") # Encode account password md5 = hashlib.md5() md5.update(passwd.encode('utf-8')) passwd = md5.hexdigest() # Account validation try: account_for_validation = Account.objects.get(_account_name = account) except Exception, e: reply_text = '绑定ILink帐号,请使用 - 为分隔符输入帐号密码\n上传个人微信二维码,请直接发送图片' # import pdb; pdb.set_trace() if account_for_validation : if account_for_validation.account_passwd == passwd : try: link = WechatQRCode.objects.get(wechat_openid = wechat_user_openid) link.account = account_for_validation reply_text = '重新绑定ILink帐号成功' except Exception, e: newlink = WechatQRCode.create(account = account_for_validation, openid=wechat_user_openid) newlink.save() reply_text = '绑定ILink帐号成功' else : reply_text = '绑定ILink帐号验证失败' else :
def wechat_token(): print '------------------------------------' args = request.args print args if request.method == 'GET': if hasattr(args, 'echostr'): token = 'midstation' echostr = args['echostr'] signature = args['signature'] timestamp = args['timestamp'] nonce = args['nonce'] # 实例化 wechat wechat = WechatBasic(token=token) # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): print 'wechat check_signature' return echostr return redirect(url_for('auth.login')) # 微信消息监听 if request.method == 'POST': print args print '--------------------- wechat ----------------------' token = 'midstation' signature = args['signature'] timestamp = args['timestamp'] nonce = args['nonce'] # 实例化 wechat wechat = WechatBasic(token=token, appid='wx6b84ff9cb6f9a54e', appsecret='4e09e5b35198bdbf35b90a65d5f76af4') if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作) print request.data wechat.parse_data(request.data) # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义) print 'check signature' message = wechat.get_message() response = None if message.type == 'text': if lower(message.content) == '/a': key = auth_key() response = wechat.response_text(unicode(key)) # 存入内容,openid, 对应的验证码 save_auth_key(message.source, key, AUTH_KEY_EXPIRE) print '得到的验证码为: {0}'.format(redis_store.get(message.source)) else: response = wechat.response_text(u'如果要绑定微信,请输入/a获取验证码,验证码将会在%s秒内失效' % AUTH_KEY_EXPIRE) elif message.type == 'image': response = wechat.response_text(u'图片') else: response = wechat.response_text(u'未知') return response return 'auth token fail'
body_text = """ <xml> <ToUserName><![CDATA[touser]]></ToUserName> <FromUserName><![CDATA[fromuser]]></FromUserName> <CreateTime>1405994593</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[新闻]]></Content> <MsgId>6038700799783131222</MsgId> </xml> """ # 实例化 wechat wechat = WechatBasic(token=token) # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作) wechat.parse_data(body_text) # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义) message = wechat.get_message() response = None if message.type == 'text' and message.content == u'新闻': response = wechat.response_news([{ 'title': u'第一条新闻标题', 'description': u'第一条新闻描述,这条新闻没有预览图', 'url': u'http://www.google.com.hk/', }, { 'title': u'第二条新闻标题, 这条新闻无描述', 'picurl':
def handler(request): """ wechat backend handler :param request: :return: """ if request.method == "GET": # wechat server signature signature = request.GET.get('signature', '') timestamp = request.GET.get('timestamp', '') nonce = request.GET.get('nonce', '') echostr = request.GET.get('echostr', '') wechat = WechatBasic(token=appToken) if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponse(echostr) else: return HttpResponse('INVALID') # text from user body_text = request.body wechat = WechatBasic(token=appToken) wechat.parse_data(body_text) # get wechat message message = wechat.get_message() # check message type if message.type != 'text': return HttpResponse(wechat.response_text(u'说人话')) content = message.content # if search if content.startswith(u"搜:"): content = get_magnet_from_keyword(content[2:]) # check if magnet if content.startswith("magnet:?xt=urn:btih:"): if Work.objects.filter(magnet=content): return HttpResponse(wechat.response_text(u'已经添加过这个链接了')) work = Work(magnet=content, operate=Operator.DOWNLOAD) work.save() return HttpResponse( wechat.response_text(u'链接已添加!回复【%s】显示详情。' % keyword_check)) # user check if content == keyword_check: works = Work.objects.filter(is_removed=False).order_by('-create_time') work_list = u'任务详情:\n\n' for index, work in enumerate(works): name = work.name if work.name else u'名字解析中' speed = work.down_speed progress = work.progress operate = work.get_operate_name() work_list += "%d. %s [%s] [%s] [%s]\n" % (index + 1, name, speed, progress, operate) work_list += u'\n回复【%s】下载,【%s】暂停,【%s】删除,后跟相应数字' % ( keyword_download, keyword_pause, keyword_remove) return HttpResponse(wechat.response_text(work_list)) return HttpResponse(wechat.response_text(u'待开发'))
def index(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') xml = request.body body_text = """ <xml> <ToUserName><![CDATA[touser]]></ToUserName> <FromUserName><![CDATA[fromuser]]></FromUserName> <CreateTime>1405994593</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[新闻]]></Content> <MsgId>6038700799783131222</MsgId> </xml> """ token = get_weixin_accesstoken() # 实例化 wechat wechat = WechatBasic(token=token) # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作) wechat.parse_data(body_text) # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义) message = wechat.get_message() response = None if isinstance(message, TextMessage): response = wechat.response_text(content=u'文字信息') elif isinstance(message, VoiceMessage): response = wechat.response_text(content=u'语音信息') elif isinstance(message, ImageMessage): response = wechat.response_text(content=u'图片信息') elif isinstance(message, VideoMessage): response = wechat.response_text(content=u'视频信息') elif isinstance(message, LinkMessage): response = wechat.response_text(content=u'链接信息') elif isinstance(message, LocationMessage): response = wechat.response_text(content=u'地理位置信息') elif isinstance(message, EventMessage): # 事件信息 if message.type == 'subscribe': # 关注事件(包括普通关注事件和扫描二维码造成的关注事件) if message.key and message.ticket: # 如果 key 和 ticket 均不为空,则是扫描二维码造成的关注事件 response = wechat.response_text( content=u'用户尚未关注时的二维码扫描关注事件') else: response = wechat.response_text(content=u'普通关注事件') elif message.type == 'unsubscribe': response = wechat.response_text(content=u'取消关注事件') elif message.type == 'scan': response = wechat.response_text(content=u'用户已关注时的二维码扫描事件') elif message.type == 'location': response = wechat.response_text(content=u'上报地理位置事件') elif message.type == 'click': response = wechat.response_text(content=u'自定义菜单点击事件') elif message.type == 'view': response = wechat.response_text(content=u'自定义菜单跳转链接事件') elif message.type == 'templatesendjobfinish': response = wechat.response_text(content=u'模板消息事件') # 现在直接将 response 变量内容直接作为 HTTP Response 响应微信服务器即可,此处为了演示返回内容,直接将响应进行输出 print response return render_to_response('index.html', response)