def set_menu(): wechat = WechatBasic(appid=APPID, appsecret=APPSECRET) wechat.create_menu({ 'button':[ { 'name':u'功能测试', 'sub_button':[ { 'type':'view', 'name':u'JS-SDK', 'url':'http://cms.olive-app.com/weixin/testjs/' } ] }, { 'name':u'菜单2', 'sub_button':[ { 'type':'view', 'name':u'个人中心', 'url':'http://xiande.olive-app.com/member/' }, { 'type':'view', 'name':u'个人资产', 'url':'http://xiande.olive-app.com/member/assets/' }, { 'type':'view', 'name':u'我要理财', 'url':'http://xiande.olive-app.com/member/join/' }, { 'type':'view', 'name':u'个人小金库', 'url':'http://xiande.olive-app.com/member/money/' } ] }, { 'name':u'菜单3', 'sub_button':[ { 'type':'click', 'name':u'热门活动', 'key':'event_hot' }, { 'type':'click', 'name':u'本月活动', 'key':'event_month' }, { 'type':'view', 'name':u'我要报名', 'url':'http://xiande.olive-app.com/event/join/' } ] } ]})
def set_menu(): wechat = WechatBasic(appid='wxf6b62f557ceff535', appsecret='639058f6e069390dd94727e073868d91') wechat.create_menu({ 'button': [{ 'name': u'金融服务', 'sub_button': [{ 'type': 'view', 'name': u'关于我们', 'url': 'http://xiande.olive-app.com/about/' }, { 'type': 'view', 'name': u'投资理念', 'url': 'http://xiande.olive-app.com/thinking/' }, { 'type': 'view', 'name': u'理财产品', 'url': 'http://xiande.olive-app.com/project/' }] }, { 'name': u'理财管家', 'sub_button': [{ 'type': 'view', 'name': u'个人中心', 'url': 'http://xiande.olive-app.com/member/' }, { 'type': 'view', 'name': u'个人资产', 'url': 'http://xiande.olive-app.com/member/assets/' }, { 'type': 'view', 'name': u'我要理财', 'url': 'http://xiande.olive-app.com/member/join/' }, { 'type': 'view', 'name': u'个人小金库', 'url': 'http://xiande.olive-app.com/member/money/' }] }, { 'name': u'超值享', 'sub_button': [{ 'type': 'click', 'name': u'热门活动', 'key': 'event_hot' }, { 'type': 'click', 'name': u'本月活动', 'key': 'event_month' }, { 'type': 'view', 'name': u'我要报名', 'url': 'http://xiande.olive-app.com/event/join/' }] }] })
def test_create_menu(self): menu_info = { 'button': [ { 'type': 'click', 'name': '今日歌曲', 'key': 'V1001_TODAY_MUSIC' }, { 'type': 'click', 'name': '歌手简介', 'key': 'V1001_TODAY_SINGER' }, { 'name': '菜单', 'sub_button': [ { 'type': 'view', 'name': '搜索', 'url': 'http://www.soso.com/' }, { 'type': 'view', 'name': '视频', 'url': 'http://v.qq.com/' }, { 'type': 'click', 'name': '赞一下我们', 'key': 'V1001_GOOD' } ] } ] } # 测试无 appid 和 appsecret 初始化 wechat = WechatBasic() with self.assertRaises(NeedParamError): wechat.create_menu(menu_info) # 测试有 appid 和 appsecret 初始化 wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret) with HTTMock(wechat_api_mock): resp = wechat.create_menu(menu_info) self.assertEqual(resp['errcode'], 0) self.assertEqual(resp['errmsg'], 'ok')
def test_create_menu(self): menu_info = { 'button': [{ 'type': 'click', 'name': '今日歌曲', 'key': 'V1001_TODAY_MUSIC' }, { 'type': 'click', 'name': '歌手简介', 'key': 'V1001_TODAY_SINGER' }, { 'name': '菜单', 'sub_button': [{ 'type': 'view', 'name': '搜索', 'url': 'http://www.soso.com/' }, { 'type': 'view', 'name': '视频', 'url': 'http://v.qq.com/' }, { 'type': 'click', 'name': '赞一下我们', 'key': 'V1001_GOOD' }] }] } # 测试无 appid 和 appsecret 初始化 wechat = WechatBasic() with self.assertRaises(NeedParamError): wechat.create_menu(menu_info) # 测试有 appid 和 appsecret 初始化 wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret) with HTTMock(wechat_api_mock): resp = wechat.create_menu(menu_info) self.assertEqual(resp['errcode'], 0) self.assertEqual(resp['errmsg'], 'ok')
def menu(request): if request.method == 'GET': return render(request, "menu_form.html", {}) else: data = DATA conf = WechatConf(tok=TOKEN, appid=APP_ID, appsecret=APP_SECRET, encrypt_mode="normal") wechat = WechatBasic(conf=conf) ret = wechat.create_menu(DATA) return HttpResponse("%r" % ret)
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")
def create_menu(cls, data): wechat = WechatBasic(appid=settings.APP_ID, appsecret=settings.SECRET) resp = wechat.create_menu(data) return resp.get('errmsg', '')
def wechat_home(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') wechat = WechatBasic(conf=conf) #wechat = WechatBasic(appid='wx4ed8e5a367d2451f', appsecret='d41a46925b7791a7fd7d2dc95823591b') if not wechat.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': # menu_data={ # 'button':[ # { # 'type': 'click', # 'name': '认识优邻1', # 'key': 'V1001_TODAY_MUSIC' # }, # { # 'type': 'click', # 'name': '歌手简介2', # 'key': 'V1001_TODAY_SINGER' # }, # { # 'name': '菜单2', # 'sub_button': [ # { # 'type': 'view', # 'name': '搜索2', # 'url': 'http://123.57.9.62/yl/web/user_login' # }, # { # 'type': 'view', # 'name': '视频4', # 'url': 'http://v.qq.com/' # }, # { # 'type': 'click', # 'name': '赞一下我们7777', # 'key': 'V1001_GOOD' # } # ] # } # ] # } # wechat.create_menu(menu_data) response = request.GET.get('echostr', 'error') else: try: wechat.parse_data(request.body) source = wechat.message.source url_down = 'http://www.youlinzj.cn/yl/wx/cv?auth_id=' + str( source) url_sign = 'http://www.youlinzj.cn/yl/wx/sign?auth_id=' + str( source) menu_data = { 'button': [ { 'name': '认识优邻', 'sub_button': [ { 'type': 'view', 'name': '软件下载', 'url': url_down, # 'url': "https://123.57.9.62/yl/wx/sign/", # 'url': "http://storage.pgyer.com/6/b/8/f/a/6b8fa2402b05d4baf7806e61970c739b.apk", }, { 'type': 'click', 'name': '了解我们', 'key': 'V1002_US' }, ] }, { 'name': '最新动态', 'sub_button': [ { 'type': 'view', 'name': '签到有礼', 'url': url_sign, # 'url': 'https://123.57.9.62/yl/wx/sign/', }, { 'type': 'click', 'name': '历史消息', 'key': 'V2002_HISTORY' }, ] }, { 'name': '联系我们', 'sub_button': [ { 'type': 'click', 'name': '常见问题', 'key': 'V3001_QUESTION' # 'url': 'http://www.soso.com/', }, { 'type': 'click', 'name': '联系客服', 'key': 'V3002_SERVICE' # 'url': 'http://mp.weixin.qq.com/s?__biz=MzI1NDIyNDQyMQ==&mid=100000009&idx=1&sn=c42e576ab9f13aa362b6f33342cecb78#rd' }, { 'type': 'click', 'name': '合作模式', 'key': 'V3003_WORK' # 'url': 'http://mp.weixin.qq.com/s?__biz=MzI1NDIyNDQyMQ==&mid=100000030&idx=1&sn=cd8695012624324a9dfe85253843fae1#rd' }, ] }, ] } wechat.create_menu(menu_data) message = wechat.get_message() response = POST(request, wechat) except Exception, e: reason = e response = wechat.response_text(content=reason) return HttpResponse(response, content_type="application/xml")
def create_menu(cls, data): wechat = WechatBasic(appid=settings.APP_ID, appsecret=settings.SECRET) resp = wechat.create_menu(data) return resp.get('errmsg', '')
wechat_instance.create_menu({ "button": [{ "name": "来上网吧", "sub_button": [ { "type": "click", "name": "绑定VIP", "key": "BindVIP", }, { "type": "view", "name": "预定机器", "url": "http://guandashi.xicp.net/netbar_reservePC", }, { "type": "click", "name": "优惠活动", "key": "Promotio", }, ] }, { "type": "view", "name": "吃与喝", "url": "http://guandashi.xicp.net/eleme", }, { "name": "服务中心", "sub_button": [ { "type": "click", "name": "呼叫网管", "key": "CallMaster", }, { "type": "click", "name": "消费查询", "key": "ConsumeQuery", }, { "type": "click", "name": "结账下机", "key": "CheckOut", }, ] }] })
wechat_instance.create_menu({ 'button': [ { 'type': 'view', 'name': '首页', 'url': index }, { 'name': '充电', 'sub_button': [{ 'type': 'view', 'name': '附近', 'url': redirect_uri_nearby }, { 'type': 'view', 'name': '实时状态', 'url': redirect_uri_state }, { 'type': 'view', 'name': '实时控制', 'url': redirect_uri_control }] }, { 'name': '我的', 'sub_button': [{ 'type': 'view', 'name': '绑定', 'url': redirect_uri_bind }, { 'type': 'view', 'name': '消费记录', 'url': redirect_uri_history }] }, ] })
def create_menu(cls, data): wechat = WechatBasic(appid=settings.app_id, appsecret=settings.secret) resp = wechat.create_menu(data) return resp.get('errmsg', '')
}, { 'type': 'view', 'name': '优惠菜品', 'url': 'http://www.bangwz.cn/onsale' }, { 'type': 'click', 'name': '店铺地址', 'key': 'V04_address' } ] } ] } wechat_instance.create_menu(menu_list) def getxingzuo(word): if word in ['白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座']: ltime = time.localtime() date_name = time.strftime("%Y年%m月%d日", ltime) try: xingyun_object = XingyunModel.objects.get(xingzuoming__contains=word, riqi=date_name) touxiangurl = xingyun_object.turl zhengtiyunshixing1 = xingyun_object.zhengtiyunshixing aiqingyunshixing1 = xingyun_object.aiqingyunshixing shiyeyunshixing1 = xingyun_object.shiyeyunshixing caifuyunshixing1 = xingyun_object.caifuyunshixing jiankangzhishu1 = xingyun_object.jiankangzhishu shangtanzhishu1 = xingyun_object.shangtanzhishu xingyunyanse1 = xingyun_object.xingyunyanse xingyunshuzi1 = xingyun_object.xingyunshuzi
"type": "view", "name": "关于我们", "url" : "http://www.yipaiyaokong.com" }, { "type": "view", "name": "反馈建议", "url" : "http://www.yipaiyaokong.com" }, { "type": "click", "name": "使用指南", "key": "instruction" }, { "type": "click", "name": "投资加盟", "key": "investment" }, ] } ] } res = wechat.create_menu(menu) if res['errmsg'] == 'ok': print '创建菜单成功!' else: print '创建菜单失败!' print res
class MenusHandler(BaseHandler): def __init__(self, *argc, **argkw): super(MenusHandler, self).__init__(*argc, **argkw) self.MpsMenuCacheKey = 'taurusxee.cache.mps.menus' try: 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 = WechatConf( token=token, appid=appid, appsecret=appsecret, encrypt_mode=encrypt_mode, encoding_aes_key=encoding_aes_key, access_token_getfunc=functools.partial( self.mpsapi.get_access_token, appid, appsecret), access_token_setfunc=self.mpsapi.set_access_token) self.wechat = WechatBasic(conf=wechat_conf) except Exception as err: logger.exception(err) def get_menu_data(self, mps_apiurl): try: _fetch_result = lambda: self.wechat.get_menu().get('menu') menus_obj = self.cache.aget(self.MpsMenuCacheKey, _fetch_result, expire=86400) if isinstance(menus_obj, (str, unicode)): menus_obj = json.loads(menus_obj) logger.debug(menus_obj) return menus_obj except Exception as err: logger.exception(err) mstr = menutpl_str.replace('{mps_apiurl}', mps_apiurl) return json.loads(utils.safestr(mstr)) @authenticated def get(self, template_variables={}): """ 查询菜单,从数据库解析json字符串发送到页面初始化 """ mps_apiurl = self.get_param_value('mps_apiurl', '') menus_obj = self.get_menu_data(mps_apiurl) menu_buttons_array = menus_obj['button'] menudata = {} _midx = 1 for mbs in menu_buttons_array: midx = 'menu%s' % _midx menudata['%s_name' % midx] = mbs['name'] menudata['%s_type' % midx] = mbs.get('type', '') menudata['%s_key' % midx] = mbs.get('key', '') menudata['%s_url' % midx] = mbs.get('url', '') sub_buttons = mbs.get('sub_button', []) _idx = 1 for sbmenu in sub_buttons: menudata['%s_sub%s_type' % (midx, _idx)] = sbmenu['type'] menudata['%s_sub%s_name' % (midx, _idx)] = sbmenu['name'] menudata['%s_sub%s_key' % (midx, _idx)] = sbmenu.get( 'key', '') menudata['%s_sub%s_url' % (midx, _idx)] = sbmenu.get( 'url', '') _idx += 1 _midx += 1 menu_str = json.dumps(menudata, ensure_ascii=False).replace('"', '\\"') self.render('mps_menus.html', menudata=menu_str) @authenticated def post(self, *args, **kwargs): """ 更新菜单,保存菜单数据为json字符串 """ menudata = self.get_argument('menudata') menu_json = json.loads(menudata) try: menu_object = {'button': []} for menu in ['menu1', 'menu2', 'menu3']: menu_buttons = {'name': menu_json['%s_name' % menu]} menu_type = menu_json.get('%s_type' % menu) menu_url = menu_json.get('%s_url' % menu) menu_key = menu_json.get('%s_key' % menu) if all([menu_type, menu_url]) or all([menu_type, menu_key ]): menu_buttons['type'] = menu_type if 'click' in menu_type: menu_buttons['key'] = menu_key else: menu_buttons['url'] = menu_url menu_object['button'].append(menu_buttons) continue menu_buttons['sub_button'] = [] for ms in range(1, 6): menu_button = {} _menu_type = menu_json['%s_sub%s_type' % (menu, ms)] _menu_name = menu_json['%s_sub%s_name' % (menu, ms)] _menu_key = menu_json['%s_sub%s_key' % (menu, ms)] _menu_url = menu_json['%s_sub%s_url' % (menu, ms)] if len(_menu_name) > 1: menu_button['type'] = _menu_type menu_button['name'] = _menu_name if 'click' in _menu_type: menu_button['key'] = _menu_key else: menu_button['url'] = _menu_url menu_buttons['sub_button'].append(menu_button) menu_object['button'].append(menu_buttons) menu_result = json.dumps(menu_object, ensure_ascii=False, sort_keys=True, indent=4, separators=(',', ': ')) logger.info(menu_result) self.cache.set(self.MpsMenuCacheKey, menu_result) _resp = self.wechat.create_menu(menu_object) if int(_resp.get('errcode')) > 0: logger.error(u'同步菜单失败,' + _resp.get('errmsg')) logger.error(menu_result) return self.render_json(code=0, msg=u'同步微信菜单失败了[%s],请检查错误再试试' % _resp.get('errmsg')) except: logger.exception(u'更新菜单失败') return self.render_json(code=0, msg=u'更新菜单失败') self.render_json(code=0, msg=u'更新菜单成功')
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)
def create_menu(): from wechat_sdk import WechatBasic from config import wechat_config wechat = WechatBasic(token = wechat_config['token'], appid = wechat_config['appid'], appsecret = wechat_config['appsecret']) print wechat.create_menu({ 'button': [ { 'name': '个人', 'sub_button': [ { 'type': 'click', 'name': '设备绑定', 'key' : 'SET_DEVICE' }, { 'type': 'click', 'name': '信息维护', 'key' : 'SET_INFO' }, { 'type': 'click', 'name': '排行榜', 'key' : 'GET_RANK' }, { 'type': 'click', 'name': '宠物系统', 'key' : 'PET_SYS' } ] }, { 'name': '运动', 'sub_button': [ { 'type': 'click', 'name': '查看步数', 'key' : 'GET_STEP' }, { 'type': 'click', 'name': '查看运动', 'key' : 'GET_SPORT' }, { 'type': 'click', 'name': '添加运动', 'key' : 'ADD_SPORT' }, { 'type': 'click', 'name': '查看目标', 'key' : 'GET_GOAL' }, { 'type': 'click', 'name': '设定目标', 'key' : 'SET_GOAL' } ] }, { 'name': '健康', 'sub_button': [ { 'type': 'click', 'name': '查看睡眠', 'key' : 'GET_SLEEP' }, { 'type': 'click', 'name': '心率曲线', 'key' : 'GET_RATE_CURVE' }, { 'type': 'click', 'name': '当前心率', 'key' : 'GET_RATE_NOW' }, { 'type': 'click', 'name': '查看卡路里', 'key' : 'GET_CALORIE' } ] } ]})
'url': 'http://www.soso.com/' }, { 'type': 'view', 'name': '视频', 'url': 'http://v.qq.com/' }, { 'type': 'click', 'name': '赞一下我们', 'key': 'V1001_GOOD' }] }] } py_wechat = WechatBasic(conf=conf) try: py_wechat.create_menu(menu_info) except OfficialAPIError, ex: print ex #homepage just for fun @app.route('/') def home(): return render_template('index.html') #公众号消息服务器网址接入验证 #需要在公众帐号管理台手动提交, 验证后方可接收微信服务器的消息推送 @app.route('/weixin', methods=['GET']) def weixin_access_verify(): echostr = request.args.get('echostr')
def createmenu(): ''' 创建微信菜单 Returns: ''' conf = Wconf.conf wechat = WechatBasic(conf=conf) # menu = { # 'button':[ # { # 'name':'教程', # 'sub_button':[ # { # 'type':'click', # 'name':'基础教程', # 'key':'V1001_BASIC_COURSE' # }, # { # 'type': 'click', # 'name': '专题教程', # 'key': 'V1001_SPECIAL_COURSE' # } # ] # }, # { # 'name':'约拍', # 'sub_button':[ # { # 'type':'view', # 'name':'摄影师单', # 'url':'http://www.soso.com/' # }, # { # 'type': 'view', # 'name': '模特单', # 'url': 'http://www.soso.com/' # }, # { # 'type': 'view', # 'name': '我要发单', # 'url': 'http://www.soso.com/' # }, # { # 'type': 'view', # 'name': '约拍伴侣', # 'url': 'http://www.soso.com/' # }, # { # 'type': 'view', # 'name': '我的约拍', # 'url': 'http://www.soso.com/' # }, # ] # }, # { # 'name':'活动', # 'sub_button':[ # { # 'type':'view', # 'name':'往期活动', # 'url': 'http://www.soso.com/' # }, # { # 'type': 'view', # 'name': '活动预告及报名', # 'url': 'http://www.soso.com/' # }, # { # 'type': 'view', # 'name': '发起活动', # 'url': 'http://www.soso.com/' # }, # ] # }, # ] # } menu = { 'button': [ { 'name': '活动', 'sub_button': [{ 'type': 'click', 'name': '历史活动', 'key': 'V1001_BASIC_COURSE' }, { 'type': 'click', 'name': '活动预告', 'key': 'V1001_SPECIAL_COURSE' }] }, ] } try: wechat.create_menu(menu) except OfficialAPIError, e: print e
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
wechat_instance.create_menu({ 'button': [ { 'type': 'view', 'name': '首页', 'url': index }, { 'name': '充电', 'sub_button': [ { 'type': 'view', 'name': '附近', 'url': redirect_uri_nearby } , { 'type': 'view', 'name': '实时状态', 'url': redirect_uri_state }, { 'type': 'view', 'name': '实时控制', 'url': redirect_uri_control } ] }, { 'name': '我的', 'sub_button': [ { 'type': 'view', 'name': '绑定', 'url': redirect_uri_bind }, { 'type': 'view', 'name': '消费记录', 'url': redirect_uri_history } ] }, ] })
def wechat_home(request): global confPath cp = ConfigParser.SafeConfigParser() #读取配置文件 cp.read('/home/pi/watchdog/Face/Face_Project/data/face.conf') time_switch = int(cp.get('settings', 'time')) temp_switch = int(cp.get('settings', 'temp')) ONF = int(cp.get('settings', 'onf')) Face = int(cp.get('settings', 'face')) sheel = int(cp.get('settings', 'sheel')) signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') global wechat_instance 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() #自定义菜单 menu = { 'button': [{ 'name': 'PI', 'sub_button': [{ 'type': 'click', 'name': '时间', 'key': 'PI_TIME' }, { 'type': 'click', 'name': '温度', 'key': 'PI_TEMP' }, { 'type': 'click', 'name': '关闭警报', 'key': 'RED' }, { 'type': 'click', 'name': '帮助', 'key': 'PI_HELP' }, { 'type': 'view', 'name': 'Github', 'url': 'http://github.com' }] }, { 'name': 'Face', 'sub_button': [{ 'type': 'click', 'name': '导入人脸', 'key': 'Face_import' }, { 'type': 'click', 'name': '添加信息', 'key': 'Face_data' }, { 'type': 'click', 'name': '显示细节', 'key': 'Face_small' }, { 'type': 'click', 'name': '拍照', 'key': 'Face_camera' }] }, { 'name': 'settings', 'sub_button': [{ 'type': 'click', 'name': '开关', 'key': 'OFF' }, { 'type': 'click', 'name': '严格模式', 'key': 'SSS' }, { 'type': 'click', 'name': '普通模式', 'key': 'S' }, { 'type': 'click', 'name': '查看日志', 'key': 'LOG' }, { 'type': 'click', 'name': '开启sheel', 'key': 'Sheel' }] }] } wechat_instance.create_menu(menu) if isinstance(message, TextMessage): countent = message.content.strip() if countent == '全灭': new_botton.restart() reply_text = 'OK' elif countent == 'ip' or countent == 'IP': reply_text = IP elif countent == 'test': img = open( '/home/pi/watchdog/Face/Face_Project/data/unknow/q.jpg' ) data = wechat_instance.upload_media( 'image', img, 'jpg') img.close() img_id = data['media_id'] elif 'name:' in countent: name = countent.split(':') name = name[1] data = open( '/home/pi/watchdog/Face/Face_Project/data/face_data.log', 'w') data.write(name) data.close() reply_text = '信息导入成功' else: if sheel == 1: if countent == 'vim' or 'rm' in countent: reply_text == '警告!,禁止执行!' else: (status, output) = commands.getstatusoutput( '{cmd}'.format(cmd=countent)) reply_text = output else: reply_text = countent elif isinstance(message, VoiceMessage): reply_text = 'voice' elif isinstance(message, ImageMessage): picurl = message.picurl media_id = message.media_id if Face == 0: f = open( '/home/pi/watchdog/Face/Face_Project/data/face_data.log' ) result = f.readlines() f.close() if result == []: reply_text = '还没有导入人脸信息' else: response = wechat_instance.download_media(media_id) ra = random.randint(2, 99) if ra % 100 < 10: img_path = '/home/pi/watchdog/Face/Face_Project/data/image/' + '10000000000' + str( ra) + '.' + str(result[0]) + '.' + 'jpg' elif ra % 100 > 10: img_path = '/home/pi/watchdog/Face/Face_Project/data/image/' + '1000000000' + str( ra) + '.' + str(result[0]) + '.' + 'jpg' with open(img_path, 'wb') as fd: for chunk in response.iter_content(1024): fd.write(chunk) os.remove( '/home/pi/watchdog/Face/Face_Project/data/face_data.log' ) os.mknod( '/home/pi/watchdog/Face/Face_Project/data/face_data.log' ) importFace.main() reply_text = '导入成功' elif Face == 1: response = wechat_instance.download_media(media_id) img_path = '/home/pi/watchdog/Face/Face_Project/data/details/img.jpg' with open(img_path, 'wb') as fd: for chunk in response.iter_content(1024): fd.write(chunk) pi_face_landmark(img_path) img = open(img_path) data = wechat_instance.upload_media( 'image', img, 'jpg') img.close() media_id = data['media_id'] user_id = 'opL4ZwSzQPdCcefPKYo_LR0ImjhI' wechat_instance.send_image_message(user_id, media_id) 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 == 'click': if message.key == 'PI_TIME': localtime = time.asctime( time.localtime(time.time())) reply_text = '时间:' + str(localtime) cp.set('settings', 'time', '1') cp.set('settings', 'temp', '0') fh = open(confPath, 'w') cp.write(fh) fh.close() elif message.key == 'RED': SAKS.ledrow.set_row([ None, None, None, None, None, None, False, False ]) cp.set('settings', 'red', '0') fh = open(confPath, 'w') cp.write(fh) fh.close() elif message.key == 'PI_TEMP': cpu_temp = new_botton.get_cpu_temp() gpu_temp = new_botton.get_gpu_temp() t = SAKS.ds18b20.temperature if str(t) == '-128.0': reply_text = 'cpu温度:' + str(cpu_temp) + '\n' + \ 'gpu温度:' + str(gpu_temp) + '\n' + \ '室温:' + '获取失败,请稍后再试' else: reply_text = 'cpu温度:' + str(cpu_temp) + '\n' + \ 'gpu温度:' + str(gpu_temp) + '\n' + \ '室温:' + str(t) cp.set('settings', 'temp', '1') cp.set('settings', 'time', '0') fh = open(confPath, 'w') cp.write(fh) fh.close() elif message.key == 'Face_camera': result = ScreenFetch() if result == True: screen_img = open( '/home/pi/watchdog/Face/Face_Project/data/screenfetch/screenfetch.jpg' ) data = wechat_instance.upload_media( 'image', screen_img, 'jpg') screen_img.close() img_id = data['media_id'] else: reply_text = '拍照失败' elif message.key == 'Face_import': cp.set('settings', 'face', '0') fh = open(confPath, 'w') cp.write(fh) fh.close() reply_text = '已设置导入人脸模式' elif message.key == 'Face_data': reply_text = '请输入名称:(格式如name:test)' elif message.key == 'Face_small': reply_text = '已设置显示人脸细节' cp.set('settings', 'face', '1') fh = open(confPath, 'w') cp.write(fh) fh.close() elif message.key == 'S': reply_text = '普通模式已开启' cp.set('settings', 'mode', 'normal') fh = open(confPath, 'w') cp.write(fh) fh.close() elif message.key == 'SSS': reply_text = '严格模式已开启' cp.set('settings', 'mode', 'strict') fh = open(confPath, 'w') cp.write(fh) fh.close() elif message.key == 'OFF': if ONF == 1: reply_text = '正在关闭' cp.set('settings', 'ONF', '0') fh = open(confPath, 'w') cp.write(fh) fh.close() elif ONF == 0: reply_text = '正在开启' cp.set('settings', 'ONF', '1') fh = open(confPath, 'w') cp.write(fh) fh.close() elif message.key == 'LOG': log = open( '/home/pi/watchdog/Face/Face_Project/data/log/out.log' ) txt = log.readlines() log.close() reply_text = txt elif message.key == 'Sheel': if sheel == 1: reply_text = '已关闭sheel' cp.set('settings', 'sheel', '0') s = open(confPath, 'w') cp.write(s) s.close() if sheel == 0: reply_text = '已开启sheel' cp.set('settings', 'sheel', '1') s = open(confPath, 'w') cp.write(s) s.close() else: reply_text = 'other' try: response = wechat_instance.response_text( content=reply_text) except UnboundLocalError: pass try: response = wechat_instance.response_image(img_id) except UnboundLocalError: pass except ParseError: return HttpResponseBadRequest('Invalid XML Data') return HttpResponse(response, content_type="application/xml")