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.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 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 api_wechat(request): # 从 request 中提取基本信息 (signature, timestamp, nonce, xml) signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') xml = request.body # 实例化 WechatBasic 并检验合法性 wechat_instance = WechatBasic(token='CCPL') # if not wechat_instance.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # return HttpResponseBadRequest('Verify Failed') # 解析本次请求的 XML 数据 try: wechat_instance.parse_data(data=xml) message = wechat_instance.get_message() # 获取解析好的微信请求信息 print message except ParseError: print xml return HttpResponseBadRequest('Invalid XML Data') ret = u'感谢关注“心理地图”!欢迎您登陆我们的网站:http://ccpl.psych.ac.cn/PsyMap/ (网站功能还在开发中,敬请期待。)' #message.type response = wechat_instance.response_text(ret) return HttpResponse(response)
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 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")
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 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 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 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 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 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 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 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 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 handle_message(body_text): wechat = WechatBasic(token=token) # 对签名进行校验 # wechatnonce, wechatsignature, wechattimestamp = wechat_get_paramaters(wechatserviceinfo) # if not (wechat.check_signature(signature=wechatsignature, timestamp=wechattimestamp, nonce=wechatnonce)): # return wechat.parse_data(body_text) message = wechat.get_message() try: message_handler = build_handler(message) resp_content = message_handler.process(message.content) except Exception, e: resp_content = constants.sys_err print e
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 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 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 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 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 wechat_resp(token='', appid='', appsecret='', encoding_aes_key='', encrypt_mode='', signature='', timestamp='', nonce='', body_text=''): conf = WechatConf(token=token, appid=appid, appsecret=appsecret, encoding_aes_key=encoding_aes_key, encrypt_mode=encrypt_mode) global wechat wechat = WechatBasic(conf=conf) print body_text wechat.parse_data(body_text) message = wechat.get_message() response = None if message.type == 'text' and message.content == u'浴室': return bathroom() elif message.type != 'text': return defalut_resp() elif message.type == 'text' and message.content == u'加入': return join() elif message.type == 'text' and message.content == u'详情': return defalut_resp() elif message.type == 'text' and message.content == u'介绍': return introduce() else: return tuling_robot(message.content, message.source)
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 handle_message(body_text): # 实例化 wechat wechat = WechatBasic(token=token) # 对签名进行校验 # serviceinfo = get_last_service_info() # if not (wechat.check_signature(signature=serviceinfo.signature, timestamp=serviceinfo.timestamp, # nonce=serviceinfo.nonce)): # return # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作) wechat.parse_data(body_text) # 获得解析结果, message 为 WechatMessage 对象 (wechat_sdk.messages中定义) message = wechat.get_message() resp = None if message.type == 'text': resp = handle_text_message(message, resp, wechat) elif message.type == 'image': resp = wechat.response_text(u'图片') else: resp = wechat.response_text(u'未知') return resp
def post(self): log.debug('enter') self.auth() wechat_basic = WechatBasic(token=options.token) wechat_basic.parse_data(self.request.body) base_msg = wechat_basic.get_message() c, t = base_msg.content, base_msg.time log.info('recieve: {}, {}'.format(c.encode('utf8'), t)) cmd = CmdRobot.cmd_help fakeid, user = None, None try: raw_msg = action(options.username, options.password, 'get_message_list') msgs = json.loads(raw_msg)['msg_item'] for msg in msgs: if c == msg['content'] and t == msg['date_time']: fakeid = msg['fakeid'] user = msg['nick_name'].encode('utf8') log.info('found. {}, {}'.format(fakeid, user)) cmd = getattr(CmdRobot, 'cmd_{}'.format(c.encode('utf8')).lower(), CmdRobot.cmd_help) break else: log.error('no match. {}'.format(msgs[0]['content'])) self.write( wechat_basic.response_text( 'system error. please wait a second and send it again\n' )) except Exception as e: log.error(e) pass self.write(wechat_basic.response_text(cmd(fakeid, user))) log.debug('exit')
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 receive(): wechat = WechatBasic(token=settings['wechat_app']['token'], appid=settings['wechat_app']['appID'], appsecret=settings['wechat_app']['appsecret']) data = request.get_data(as_text=True) for k, v in request.headers: print '%s : %s' % (k, v) print data wechat.parse_data(data) message = wechat.get_message() if message.type == 'text': content = message.content res = validator.extract(content) if not res: return wechat.response_text(HELP_MESSAGE) # has track no in the text message isadding = content.startswith(u'ZQQ') if isadding: nums = ','.join(map(lambda x: '"%s"' % x, res)) push_sock.send((u'{"track_no_list": [%s]}' % nums).encode('utf-8')) response = wechat.response_text(u'%s\n已添加.' % (u'\n'.join(res),)) else: track_no = res[0] record = db.find_one(track_no) if record['status'] == 0: return wechat.response_text(status_message(record['status'])) # has track data for this track No. latest = record['data'][-1] track = latest['location'] + ', ' + latest['context'] track_time = latest['time'] response = wechat.response_text(TRACK_INFO_TMP.format(time=record['time'], track_info=track, track_time=track_time)) return response else: return wechat.response_text(u'对不起,目前不支持非文本消息~ ^_^') return 'success'
def interface(): """初始化接入""" signature = str(request.args.get("signature")) timestamp = str(request.args.get('timestamp')) nonce = str(request.args.get('nonce')) echostr = request.args.get('echostr') if 'access_token' not in session: # 实例化 wechat access_token = None access_token_expires_at = None wechat = WechatBasic(appid=appid, appsecret=appsecret) token_dict = wechat.get_access_token() access_token = token_dict.get('access_token') if access_token: session['access_token'] = access_token session['access_token_expires_at'] = token_dict.get('access_token_expires_at') response = "" wechat = WechatBasic(token=token) # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 获取请求类型 if request.method == 'POST': # 读取用户发送消息 body_text = request.data print body_text wechat.parse_data(body_text) # 获得解析结果 message = wechat.get_message() print "target_user,", message.target print "from_user,", message.source print "message_type:", message.type openid = message.source # print request.data # 用户发送文本消息 if message.type == 'text': if message.content == 'test': response = wechat.response_text(u'^_^') else: response = wechat.response_text(u'您好!') if not g.user: # 检查用户是否存在 user = User.query.filter(User.profile.any(Profile.openid == openid)).first() if user is not None: signin_user(user) print u'新用户(%s)关注微信...' % user.name else: user = add_wechat_user_to_db(openid) session['openid'] = openid else: user = g.user message = WechatMessage(user_id=user.id, content=message.content) db.session.add(message) db.session.commit() # 用户发送图片消息 elif message.type == 'image': response = wechat.response_text(u'图片') elif message.type == 'scan': if message.key and message.ticket: # TODO 扫码回收优惠券,这里还要判断扫码的用户是否为该品牌店授权的店员 # TODO 考虑到还有绑定店员的扫码事件,key分为两种:11[brandid],12[discount_id] logging.info(message.key[0:2]) logging.info(message.key[2]) if message.key[0:2] == '11': brand_id = int(message.key[2:]) brand = Brand.query.get(brand_id) if not brand: response = wechat.response_text("要绑定的店铺不存在") data = {"bid": brand_id} url_text = current_app.config.get("SITE_DOMAIN") + "/check_saler_info" + "?" + urlencode(data) brand_text = "<a href='{0}'>{1}</a>".format(url_text, brand.name) print brand_text text = "您正在申请绑定门店%s,点击输入手机号验证身份" % brand_text response = wechat.response_text(text) elif message.key[0:2] == '12': record_id = int(message.key[2:]) ticket_record = GetTicketRecord.query.get(record_id) logging.info("tid" + str(ticket_record.id)) # 判断扫码用户是否为该店铺的店员 discount_id = ticket_record.discount_id discount = Discount.query.get(discount_id) scan_user = User.query.filter(User.profile.any(Profile.openid == openid)).first() salers = Saler.query.filter(Saler.user_id == scan_user.id) if salers.count() > 0: saler = salers.filter(Saler.brand_id == discount.brand_id).first() if not saler: brand = Brand.query.get(discount.brand_id) tip = "您不是该店铺{0}的店员".format(brand.name) response = wechat.response_text(tip) else: callback_ticket(record_id) saler.count += 1 db.session.add(saler) db.session.commit() response = "" else: tip = "您还没有绑定该店铺" response = wechat.response_text(tip) # 用户在关注微信时就将用户数据写入数据库 elif message.type == 'subscribe': if message.key and message.ticket: # TODO 扫码回收优惠券,这里还要判断扫码的用户是否为该品牌店授权的店员 # TODO 考虑到还有绑定店员的扫码事件,key分为两种:bind_[brandid],ticket_[code] value = message.key.replace("qrscene_", "") if value.split("_")[0] == 'ticket': record_id = int(message.key.split("_")[1]) callback_ticket(record_id) response = "" elif value.split("_")[0] == 'bind': brand_id = int(message.key.split("_")[1]) brand = Brand.query.get(brand_id) data = {"bid": brand_id} url_text = current_app.config.get("SITE_DOMAIN") + "/check_saler_info" + "?" + urlencode(data) brand_text = "<a href='{0}'>{1}</a>".format(url_text, brand.name) text = "您正在申请绑定门店%s,点击输入手机号验证身份" % brand_text response = wechat.response_text(text) openid = message.source if not g.user: # 检查用户是否存在 user = User.query.filter(User.profile.any(Profile.openid == openid)).first() if user is None: add_wechat_user_to_db(openid) print u'新用户(%s)关注微信' % user.name response = wechat.response_text(u'欢迎关注汝州百事优惠圈') elif message.type == 'location': # 这里有location事件 TODO latitude, longitude, precision = message.latitude, message.longitude, message.precision print '-' * 10, latitude, longitude, precision, request.remote_addr session['latitude'] = latitude session['longitude'] = longitude session['precision'] = precision g.latitude = latitude g.longitude = longitude g.precision = precision return "" else: return "" return response else: return echostr else: return "error"
<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'未知') # 现在直接将 response 变量内容直接作为 HTTP Response 响应微信服务器即可,此处为了演示返回内容,直接将响应进行输出 print(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 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): db_path = '/root/mysite/info.db' keywords=(message.content).strip() openid=message.source reply_text = '' if not os.path.isfile(db_path): conn = sqlite3.connect(db_path) cursor = conn.cursor() cursor.execute('create table user(openid varchar(30) primary key,account varchar(20),passwd varchar(20),card text,update_time varchar(20),is_valid varchar(10))') cursor.execute('create table grade(account varchar(20) ,course varchar(30),credit varchar(10),gpa varchar(10),score varchar(10))') cursor.execute('create table library(account varchar(20) ,book_name text,borrow_time varchar(20),return_time varchar(20),renew_count varchar(10),situation varchar(10))') cursor.close() conn.commit() conn.close() match = re.search(r'绑定\s+(\d+)\s+(.*)',keywords) if match: account=match.group(1) passwd=match.group(2) status=Crawler.verify(account, passwd) if status == True: t = threading.Thread(target=Crawler.invoke, args=(openid, account, passwd)) t.start() reply_text = '身份验证通过,数据库大约将在1分钟之后更新完成' else: reply_text = '身份验证未通过,错误信息:'+str(status) else: conn = sqlite3.connect(db_path) cursor = conn.cursor() cursor.execute('select * from user where openid=?', (openid,)) value = cursor.fetchall() if value and (value[0][5]=='True'): account = value[0][1] update_time=value[0][4] if keywords in ['成绩','grade','Grade']: cursor.execute('select course,credit,gpa,score from grade where account=?', (account,)) value = cursor.fetchall() for course in value: reply_text += ' '.join(course)+'\r\n' reply_text +='更新时间:'+update_time elif keywords in ['图书馆','library','Library']: cursor.execute('select book_name,return_time,renew_count,situation from library where account=?', (account,)) value = cursor.fetchall() for book in value: reply_text += ' '.join(book) + '\r\n' reply_text += '更新时间:' + update_time elif keywords in ['一卡通','card','Card']: reply_text = value[0][3]+ '\r\n' reply_text += '更新时间:' + update_time else: reply_text='无效指令' else: reply_text = '账号未绑定或账号信息已过期\r\n回复 绑定 学号 统一身份认证密码(各部分用空格隔开)完成账号绑定' cursor.close() conn.commit() conn.close() 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) # 验证微信公众平台的消息 wechat_instance.create_menu({ 'button': [{ 'type': 'click', 'name': '我的资料', 'url': 'https://user.qzone.qq.com/1148038318?_t_=0.29004385220437' }, { 'name': '菜单', 'sub_button': [{ 'type': 'view', 'name': '搜索', 'url': 'https://user.qzone.qq.com/1148038318?_t_=0.29004385220437' }, { 'type': 'view', 'name': '视频', 'url': 'http://v.qq.com/' }, { 'type': 'click', 'name': '赞一下我们', 'key': 'V1001_GOOD' }] }] }) 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: print request.body wechat_instance.parse_data(request.body) message = wechat_instance.get_message() # 判断消息类型 if isinstance(message, TextMessage): reply_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' elif isinstance(message, EventMessage): if message.type == 'subscribe': reply_text = '欢迎订阅于我一生,许我一世' else: reply_text = 'other' response = wechat_instance.response_text(content=reply_text) if isinstance(message, ImageMessage): response = wechat_instance.response_news([{ 'title': u'第一条新闻', 'description': u'新闻描述', 'picurl': u'https://github.com/yuzp1996/python/blob/master/wife.jpg?raw=true', 'url': u'https://yuzp1996.github.io/', }, { 'title': u'第二条消息', 'description': u'第二条消息描述', }]) except ParseError: print ParseError return HttpResponseBadRequest('Invalid XML Data') return HttpResponse(response, content_type="application/xml")
class Server: def __init__(self, ip='0.0.0.0', port=9000, log_level=logging.DEBUG): self.ip = ip self.port = port self.author = __author__ self.version = __version__ self.file_path = os.path.realpath(__file__) self.dir_path = os.path.dirname(self.file_path) # mark system start time self.system_initialized = datetime.now() # weixin about self.appid = 'wxb1efccbbb5bafcbb' self.appsecret = '9d64356f48062e46159b4d179dea5c44' self.token = 'shenhailuanma' self.access_token = '' self.signature = None self.echostr = None self.timestamp = None self.nonce = None self.wechat = WechatBasic(token=self.token, appid=self.appid, appsecret=self.appsecret) self.weather = weather() # database self.database = Database() # set the logger self.log_level = logging.DEBUG self.log_path = 'myWeixinServer.log' self.logger = logging.getLogger('myWeixinServer') self.logger.setLevel(self.log_level) # create a handler for write the log to file. fh = logging.FileHandler(self.log_path) fh.setLevel(self.log_level) # create a handler for print the log info on console. ch = logging.StreamHandler() ch.setLevel(self.log_level) # set the log format formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) # add the handlers to logger self.logger.addHandler(fh) self.logger.addHandler(ch) self.logger.info('init over.') ####### web test ###### @bottle.route('/') def index_get(): try: # get the post data self.logger.debug('handle a GET request: /, ') # e.g : /?signature=04d39d841082682dc7623945528d8086cc9ece97&echostr=8242236714827861439×tamp=1440564411&nonce=2061393952 # get the data self.logger.debug('handle the request data: %s' %(bottle.request.query_string)) #self.logger.debug('handle the request signature:%s' %(bottle.request.query.signature)) #self.logger.debug('handle the request echostr:%s' %(bottle.request.query.echostr)) #self.logger.debug('handle the request timestamp:%s' %(bottle.request.query.timestamp)) #self.logger.debug('handle the request nonce:%s' %(bottle.request.query.nonce)) return bottle.request.query.echostr except Exception,ex: return "%s" %(ex) return "Hello, this is myWeixinServer." @bottle.route('/', method="POST") def index_post(): try: response = '' self.logger.debug('handle a POST request: /, ') self.logger.debug('handle the request data: %s' %(bottle.request.query_string)) post_data = bottle.request.body.getvalue() self.logger.debug('handle the request post data: %s' %(post_data)) echostr = bottle.request.query.echostr signature = bottle.request.query.signature timestamp = bottle.request.query.timestamp nonce = bottle.request.query.nonce if self.wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): self.logger.debug('check_signature ok.') self.wechat.parse_data(post_data) message = self.wechat.get_message() if message.type == 'text': if message.content == 'wechat': response = self.wechat.response_text(u'^_^') elif u'天气' in message.content: city = u'北京' data = self.database.get_weather_data(city) self.logger.debug('get the weather response:{0}'.format(data)) response = self.wechat.response_text(data) else: response = self.wechat.response_text(u'文字') elif message.type == 'image': response = self.wechat.response_text(u'图片') elif message.type == 'video': self.logger.debug('message.media_id:%s' %(message.media_id)) response = self.wechat.download_media(message.media_id) self.logger.debug('message.media_id:%s over' %(message.media_id)) #response = self.wechat.response_text(u'视频') elif message.type == 'voice': response = self.wechat.response_text(u'音频') elif message.type == 'location': response = self.wechat.response_text(u'位置') else: response = self.wechat.response_text(u'未知') return response except Exception,ex: self.logger.debug('error:%s' %(ex)) return "%s" %(ex)
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)
class WeChatService(object): def __init__(self, app_id=None, app_secret=None): self.redis = redis.StrictRedis(host='localhost', port=6379, db=1) self.app_id = app_id self.app_secret = app_secret if not app_id: self.wechat_admin = WeChatAdmin.objects.all().order_by('id')[1] self.wechat = WechatBasic(appid=self.wechat_admin.app_id, appsecret=self.wechat_admin.app_secret, token=self.wechat_admin.access_token) self.app_id = self.wechat_admin.app_id self.app_secret = self.wechat_admin.app_secret else: self.wechat_admin = None self.wechat = WechatBasic(appid=app_id, appsecret=app_secret, token='123') self.get_token() def get_token(self): key = 'access_token_{0}'.format(self.app_id) token = self.redis.get(key) if not token: res = self.wechat.grant_token() token = res.get('access_token') self.redis.set(key, token, 3500) if self.wechat_admin: self.wechat_admin.access_token = token self.wechat_admin.save() return token def send_message(self, open_id, message): token = self.get_token() req_url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}'.format( token) message = message.decode('utf-8') data = { 'touser': open_id, 'msgtype': 'text', 'text': { 'content': str('测试') } } result = requests.post(req_url, data=simplejson.dumps(data)) return json.loads(result.content) def get_kefu_list(self): token = self.get_token() req_url = 'https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token={0}'.format( token) result = requests.get(req_url) return json.loads(result.content) def distribution_kefu(self, open_id, account, extra_mes): token = self.get_token() req_url = 'https://api.weixin.qq.com/customservice/kfsession/create?access_token={0}'.format( token) data = {'kf_account': account, 'openid': open_id, 'text': extra_mes} result = requests.post(req_url, data=json.dumps(data)) return result def create_qrcode(self, scene): data = { "action_name": "QR_LIMIT_STR_SCENE", "action_info": { "scene": { "scene_str": scene } } } result = self.wechat.create_qrcode(data) ticket = result.get('ticket', '') url = result.get('url', '') return ticket, url def get_user_info_by_code(self, code): req_url = '''https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code'''.format( self.wechat_admin.app_id, self.wechat_admin.app_secret, code) result = requests.get(req_url) return json.loads(result.content) def get_promotion_info(self, openID, channel=None): result = Promotion.objects.filter(open_id=openID) if result.exists(): return result[0] user_info = self.wechat.get_user_info(openID) nick = user_info.get('nickname', None) city = user_info.get('city', None) province = user_info.get('province', None) sex = '男' if str(user_info.get('sex', 0)) == '2': sex = '女' elif str(user_info.get('sex', 0)) == '0': sex = '未知' new_promotion = Promotion(open_id=openID, nick=nick, sex=sex, city=city, province=province, channel=channel) new_promotion.save() return new_promotion def message_manage(self, message_body): self.wechat.parse_data(message_body) message = self.wechat.get_message() manage_dict = { 'text': self.text_manage, 'image': self.image_manage, 'video': self.other_manage, 'shortvideo': self.other_manage, 'link': self.other_manage, 'location': self.other_manage, 'subscribe': self.event_manage, 'unsubscribe': self.event_manage, 'scan': self.event_manage, 'view': self.event_manage, 'event': self.event_manage, 'voice': self.other_manage, 'click': self.click_manage } result, is_news = manage_dict[message.type](message) if not is_news: response = self.wechat.response_text(result) else: response = result return response def image_manage(self, message): return '照片已收到', False def other_manage(self, message): pass def click_manage(self, message): pass def text_manage(self, message): if message.content == 'cm': menu = { 'button': [ { 'name': '🚘去保养', 'type': 'view', 'url': 'http://sy.chafanbao.com/page/shops/' }, { 'name': '昆仑微网', 'type': 'view', 'url': 'http://kunlunlube.cnpc.com.cn/klrhy/mindex/m_index.shtml?from=weixin' }, ] } self.wechat.create_menu(menu) return 'cm success', False return '收到', False def response_article(self, mount, token): article = { 'url': 'http://sy.chafanbao.com/page/phone/?token={0}'.format(token), 'title': '恭喜您获得一张 {0} 元电子券'.format(mount), 'description': '快来领取!', 'picurl': 'http://static.fibar.cn/{0}y.jpg'.format(mount) } news = self.wechat.response_news([article]) return news, True def event_manage(self, message): if message.type == 'subscribe': return self.handle_coupon(message) elif message.type == 'scan': return self.handle_coupon(message) def handle_coupon(self, message): key = message.key if key.startswith('qrscene_'): unique_id = key.split('qrscene_')[1] else: unique_id = key uc = UniqueCode.objects.filter(unique_id=unique_id).all() scode_type = {1: '10', 2: '30', 3: '50', 4: '60', 11: '50'} if uc.exists(): uc = uc[0] if uc.code_type == 10: return "<a href='http://sy.chafanbao.com/page/shops/'>导航</a>", False # return "<a href='https://ditu.amap.com/place/B01670M5JQ'>导航</a>", False if uc.code_type == 11: return self.response_article(scode_type.get(uc.code_type), uc.unique_id) # return "<a href='http://sy.chafanbao.com/page/phone/?token={0}'>点击领券</a>".format(unique_id) if not uc.use: return self.response_article(scode_type.get(uc.code_type), uc.unique_id) # return "<a href='http://sy.chafanbao.com/page/phone/?token={0}'>点击领券</a>".format(unique_id) return '优惠券已被领取', False
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 weixin(request): #设置配置信息 conf = WechatConf(token=WEIXIN_TOKEN, appid=APPID, appsecret=APPSECRET, encrypt_mode='normal', access_token_expires_at=7200, access_token=ACCESS_TOKEN) wechat = WechatBasic(conf=conf) #验证服务器 if wechat.check_signature(signature=request.GET.get('signature'), timestamp=request.GET.get('timestamp'), nonce=request.GET.get('nonce')): print("111") if request.method == 'GET': print("是GET请求") rsp = request.GET.get('echostr', 'error') else: print("是POST请求") wechat.create_menu(menu_data=MENU_DATA) wechat.parse_data(request.body) message = wechat.get_message() print("message" + str(message)) #自动回复图文消息 if isinstance(message, TextMessage): content = message.content open_id = message.source if content == "管理员登录": openIds = Setting.ADMIN_OPEN_ID #管理员 open_id 列表 if open_id in openIds: return HttpResponse( wechat.response_text( "http://www.tiaoliaopifawang.cn/#/search")) else: return HttpResponse( wechat.response_text("对不起,您无权获取管理员页面!")) else: return HttpResponse(wechat.response_text("请点击菜单栏操作")) #自动回复音频消息 if isinstance(message, VoiceMessage): media_id = message.media_id return HttpResponse(wechat.response_voice(media_id)) #自定义菜单事件推送 elif isinstance(message, EventMessage): if message.type == "subscribe": rsp = wechat.response_text("欢迎关注我的微信公众号~\n在这里你可以轻松地下订单") if message.type == "unsubscribe": rsp = wechat.response_text("这是取消关注事件") if message.type == "click": print("到了click事件") if message.key == "cancelOrder": print("点击的是删除今日订单事件") open_id = message.source orders = models.orders.objects.filter( open_id=open_id, create_time__startswith=date.today()) ordersLen = len(orders) if ordersLen == 0: msg = "您今天还没有订单呢~" else: models.orders.objects.filter( open_id=open_id, create_time__startswith=date.today()).delete() msg = "您成功取消今日订单" return HttpResponse(wechat.response_text(msg)) elif message.key == "getOrderByOpenId": print("点击的是查询订单事件") open_id = message.source data = [] order = [] orders = models.orders.objects.filter(open_id=open_id) orderLen = len(orders) if (orderLen == 0): msg = "没有订单" return HttpResponse( wechat.response_text("您还没有订单信息,快快点击在线下单订货吧~")) elif orderLen > 3: orders = orders[0:3] msg = "超过三个订单" else: msg = "三个订单以下" print(msg) count = 1 data.append("最近的订单信息:(最多三个)") for item in orders: print(item.client_name) print(item.content) print( item.create_time.strftime("%Y-%m-%d %H:%M:%S")) order.append("[订单" + str(count) + "]:") order.append("客户姓名:" + str(item.client_name)) order.append("电 话:" + str(item.phone)) order.append("收货地址:" + str(item.address)) order.append("订单内容:" + str(item.content)) order.append("订单时间:" + str( item.create_time.strftime("%Y-%m-%d %H:%M:%S")) ) append_str = "\n".join(order) data.append(append_str) order = [] count = count + 1 rsp = wechat.response_text("\n".join(data)) else: rsp = wechat.response_text("测试键~你的openid是:" + str(message.source)) if message.type == "view": open_id = message.source print("view事件中的openid=" + str(open_id)) rsp = wechat.response_text("自定义菜单跳转链接事件" + str(message.source)) #自动回复其他消息 else: wechat.response_text("请点击菜单栏操作") else: rsp = wechat.response_text('check error') return HttpResponse(rsp)
class Index: def __init__(self): self.response = '' self.wechat = None self.is_admin = False self.openid = '' self.message = None self.result = 0 self.user_name = '' self.user_keyword = '' self.is_super_admin = False pass def GET(self): arg = web.input(wechat_arg=[]) signature = arg.signature timestamp = arg.timestamp nonce = arg.nonce self.wechat = WechatBasic(token=token) if self.wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return arg.echostr def POST(self): data = web.data() arg = web.input(wechat_arg=[]) signature = arg.signature timestamp = arg.timestamp nonce = arg.nonce self.wechat = WechatBasic(token=token) if self.wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): self.wechat.parse_data(data) self.message = self.wechat.get_message() self.openid = self.message.source if self.message.type == 'text': self.result = DataOperation.check_flag(self.openid) #normal status and ready to receive the keyword or admin command if self.result == 0: self.get_user_info() if cmp(self.message.content, keyword['reset']) == 0: self.resetting() elif cmp(self.message.content, self.user_keyword) == 0: self.open_door_success() elif cmp(self.message.content, keyword['manage']) == 0: self.managing() elif cmp(self.message.content, keyword['super_manage']) == 0: self.super_managing() else: self.open_door_fail() #resetting status and ready to receive the new keyword elif self.result == 1: self.get_user_info() if (self.message.content, keyword['reset']) == 0: self.reset_fail() else: self.reset_success() #registering status and check user's permission elif self.result == 2: permission = self.check_permission() if permission: self.register_success() else: self.register_fail() #manage status and ready to receive the command elif self.result == 3: self.get_user_info() if self.message.content == u'1': self.choose_magic_1() elif self.message.content == u'2': self.choose_magic_2() else: self.choose_magic_fail() #if the name which is exist will be deleted elif self.result == 4: add_name = self.message.content exist = DataOperation.check_permission(add_name) if exist: DataOperation.delete_user_temp(add_name, Method.NAME) else: DataOperation.add_user(add_name, keyword['default_key']) DataOperation.change_flag(self.openid, Status.READY) self.response_and_log('magic_success') elif self.result == 5: add_name = self.message.content exist = DataOperation.check_admin(add_name, Method.NAME) if exist: DataOperation.change_admin(add_name, Direction.REDUCE) self.response_and_log('magic_success') elif exist is None: self.response_and_log('super_magic_failed') else: DataOperation.change_admin(add_name, Direction.PROMOTE) self.response_and_log('magic_success') DataOperation.change_flag(self.openid, Status.READY) #initial status elif self.result is None: if cmp(self.message.content, keyword['register']) == 0: self.registering() else: self.rejecting() else: self.response = self.wechat.response_text(reply['unknown']) return self.response def resetting(self): DataOperation.change_flag(self.openid, Status.RESETTING) self.response_and_log('resetting') def open_door_success(self): door_rpc.open_door() self.response_and_log('open_success') def get_user_info(self): self.user_keyword = DataOperation.get_keyword(self.openid) self.user_name = DataOperation.get_name(self.openid) self.is_admin = DataOperation.check_admin(self.openid, Method.OPENID) def managing(self): if not self.is_admin: self.response_and_log('permission_deny') else: DataOperation.change_flag(self.openid, Status.MANAGING) self.response_and_log('managing') def super_managing(self): is_super_admin = DataOperation.check_super_admin(self.openid) if not is_super_admin: self.response_and_log('permission_deny') else: DataOperation.change_flag(self.openid, Status.SUPER_MAGIC) self.response_and_log('super_managing') def open_door_fail(self): self.response_and_log('open_failed') def reset_success(self): DataOperation.change_keyword(self.openid, self.message.content) DataOperation.change_flag(self.openid, Status.READY) self.response_and_log('reset') def reset_fail(self): DataOperation.change_flag(self.openid, Status.READY) self.response_and_log('reset_failed') def register_success(self): self.user_name = self.message.content DataOperation.delete_user_temp(self.openid, Method.OPENID) DataOperation.register_user(self.openid, self.user_name) self.response_and_log('registered') def register_fail(self): DataOperation.delete_user_temp(self.openid, Method.OPENID) self.response_and_log('register_failed') def registering(self): DataOperation.register_user_temp(self.openid, keyword['default_name'], 2, keyword['default_key'], 0) self.response = self.wechat.response_text(reply['registering']) def rejecting(self): self.response = self.wechat.response_text(reply['rejected']) def check_permission(self): result = DataOperation.check_permission(self.message.content) if result is None: result = False return result def choose_magic_1(self): self.response_and_log('manage_magic_1') DataOperation.change_flag(self.openid, Status.MAGIC) def choose_magic_2(self): self.response_and_log('manage_magic_2') DataOperation.change_flag(self.openid, Status.MAGIC) def choose_magic_fail(self): self.response_and_log('choose_magic_failed') DataOperation.change_flag(self.openid, Status.READY) def response_and_log(self, content): self.response = self.wechat.response_text(reply[content]) door_log.add_log(self.user_name, self.message.content, log_text[content])
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): content = message.content if content == "音乐": m = reply_music("喜欢你") reply_text = ('<a href="%s">%s-%s1</a>' % (m[3], m[1], m[2])) elif content[:2] == "音乐": m = reply_music(content[2:]) reply_text = ('<a href="%s">%s-%s2</a>' % (m[3], m[1], m[2])) elif content == "新闻": # reply_text = "今日新闻" reply_text = [{ 'title': u'第一条新闻标题', 'description': u'第一条新闻描述,这条新闻没有预览图', 'url': u'http://www.google.com.hk/', }, { 'title': u'第二条新闻标题, 这条新闻无描述', 'picurl': u'http://doraemonext.oss-cn-hangzhou.aliyuncs.com/test/wechat-test.jpg', 'url': u'http://www.github.com/', }, { 'title': u'第三条新闻标题', 'description': u'第三条新闻描述', 'picurl': u'http://doraemonext.oss-cn-hangzhou.aliyuncs.com/test/wechat-test.jpg', 'url': u'http://www.v2ex.com/', }] response = wechat_instance.response_news( articles=reply_text) return HttpResponse(response, content_type="application/xml") else: reply_text = auto_reply.reply(content) elif isinstance(message, VoiceMessage): content = message.recognition if content == "音乐": m = reply_music("喜欢你") reply_text = ('<a href="%s">%s-%s1</a>' % (m[3], m[1], m[2])) elif content[:2] == "音乐": m = reply_music(content[2:]) reply_text = ('<a href="%s">%s-%s2</a>' % (m[3], m[1], m[2])) else: reply_text = auto_reply.reply(content) 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 index(): echostr = request.args.get('echostr', '') if (echostr != ''): return echostr signature = request.args.get('signature') timestamp = request.args.get('timestamp') nonce = request.args.get('nonce') body_text = request.data print 'body=======' print body_text print '========' wechat = WechatBasic(token = wechat_config['token'], appid = wechat_config['appid'], appsecret = wechat_config['appsecret']) wechat.grant_token() # 对签名进行校验 if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): # 对 XML 数据进行解析 (必要, 否则不可执行 response_text, response_image 等操作) wechat.parse_data(body_text) message = wechat.get_message() openid = message.source 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'图片') elif message.type == 'click': if message.key == 'GET_STEP': response = wechat.response_news([{ 'title': u'步数信息', 'url': u'http://%s:5000%s' % (wechat_config['localAddr'], url_for('main.step', openid = openid)) }]) elif message.key == 'GET_RATE_CURVE': response = wechat.response_news([{ 'title': u'心率曲线', 'url': u'http://%s:5000%s' % (wechat_config['localAddr'], url_for('main.rate', openid = openid)) }]) elif message.key == 'GET_RATE_NOW': response = wechat.response_news([{ 'title': u'当前心率', 'url': u'http://%s:5000%s' % (wechat_config['localAddr'], url_for('main.rate_now', openid = openid)) }]) elif message.key == 'GET_RANK': response = response_rank(message.target, message.source) print ranklist elif message.key == 'SET_INFO': response = wechat.response_news([{ 'title': u'信息维护', 'url': u'http://%s:5000%s' % (wechat_config['localAddr'], url_for('main.register', openid = openid)) }]) elif message.key == 'ADD_SPORT': response = wechat.response_news([{ 'title': u'添加运动', 'url': u'http://%s:5000%s' % (wechat_config['localAddr'], url_for('main.add_sport', openid = openid)) }]) elif message.key == 'PET_SYS': if exist_user(message.source): response = wechat.response_news([{ 'title': u'宠物系统', 'url': u'http://%s:5000%s' % (wechat_config['localAddr'], url_for('main.pet_welcome', openid = openid)) }]) else: response = wechat.response_text(u'请先维护个人信息(点击“个人”-“信息维护”)') else: response = wechat.response_text(u'抱歉,这个功能还在开发中0 0') elif message.type == 'subscribe': response = wechat.response_text(u'雷吼!') else: response = wechat.response_text(u'未知') # 现在直接将 response 变量内容直接作为 HTTP Response 响应微信服务器即可 print 'response: ========' #print response print '========' return 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 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:
class IndexHandler(BaseHandler): """ 微信消息主要处理控制器 """ WechatConfCachekey = 'taurusxee.wechat.conf.cache' def check_xsrf_cookie(self): """ 对于微信消息不做加密cookie处理 """ pass def get_error_html(self, status_code=500, **kwargs): """ 定制微信消息错误返回 """ self.set_header('Content-Type', 'application/xml;charset=utf-8') self.write(self.wechat.response_text(u'回复h查看帮助。')) self.finish() def check_signature(self): """ 微信消息验签处理 """ signature = self.get_argument('signature', '') timestamp = self.get_argument('timestamp', '') nonce = self.get_argument('nonce', '') return self.wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce) def init_wechat(self): try: wechat_conf_cache = self.cache.get(self.WechatConfCachekey) if not wechat_conf_cache: token = self.get_param_value('mps_token') appid = self.get_param_value('mps_appid') appsecret = self.get_param_value('mps_apisecret') encrypt_mode = self.get_param_value('mps_encrypt_mode', 'normal') encoding_aes_key = self.get_param_value( 'mps_encoding_aes_key', '') wechat_conf_cache = dict(token=token, appid=appid, appsecret=appsecret, encrypt_mode=encrypt_mode, encoding_aes_key=encoding_aes_key) self.cache.set(self.WechatConfCachekey, wechat_conf_cache, expire=300) _c = wechat_conf_cache wechat_conf = WechatConf( token=_c['token'], appid=_c['appid'], appsecret=_c['appsecret'], encrypt_mode=_c['encrypt_mode'], encoding_aes_key=_c['encoding_aes_key'], access_token_getfunc=functools.partial( self.mpsapi.get_access_token, _c['appid'], _c['appsecret']), access_token_setfunc=self.mpsapi.set_access_token) self.wechat = WechatBasic(conf=wechat_conf) except Exception as err: logger.exception(err) def get(self): self.init_wechat() echostr = self.get_argument('echostr', '') if self.check_signature(): self.write(echostr) logger.info('Signature check success.') else: logger.error('Signature check failed.') @defer.inlineCallbacks def post(self): """ 微信消息处理 """ self.init_wechat() if not self.check_signature(): logger.error('Signature check failed.') return try: self.set_header('Content-Type', 'application/xml;charset=utf-8') body = self.request.body self.wechat.parse_data(body) msg = self.wechat.get_message() logger.debug(u'message type %s from %s with %s' % (self.wechat.message.type, self.wechat.message.source, body.decode('utf-8'))) response = yield wxrouter.dispatch(msg, gdata=self.application, wechat=self.wechat) logger.debug(u'Replied to %s with "%s"' % (self.wechat.message.source, response)) self.write(response) except Exception as err: logger.exception(err) self.write('error')
<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': u'http://doraemonext.oss-cn-hangzhou.aliyuncs.com/test/wechat-test.jpg', 'url': u'http://www.github.com/', }, { 'title': u'第三条新闻标题', 'description': u'第三条新闻描述',
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 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 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'
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 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: 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'%') # 里面的数字应由其他函数获取 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+'%2f2048.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+'%2fbird.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 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)