def wrapper(*args, **kwargs): global cur_token if not cur_token or cur_token["access_token_expires_at"] - 60 < int(time.time()): wechat = WechatBasic(appid=wechat_appid, appsecret=wechat_appsecret) wechat.grant_token(True) cur_token = wechat.get_access_token() return wechat_function(*args, **kwargs)
def init_wechat_sdk(): """初始化微信 SDK""" access_token = redis.get("wechat:access_token") jsapi_ticket = redis.get("wechat:jsapi_ticket") token_expires_at = redis.get("wechat:access_token_expires_at") ticket_expires_at = redis.get("wechat:jsapi_ticket_expires_at") if access_token and jsapi_ticket and token_expires_at and ticket_expires_at: wechat = WechatBasic(appid=app.config['APP_ID'], appsecret=app.config['APP_SECRET'], token=app.config['TOKEN'], access_token=access_token, access_token_expires_at=int(token_expires_at), jsapi_ticket=jsapi_ticket, jsapi_ticket_expires_at=int(ticket_expires_at)) else: wechat = WechatBasic(appid=app.config['APP_ID'], appsecret=app.config['APP_SECRET'], token=app.config['TOKEN']) access_token = wechat.get_access_token() redis.set("wechat:access_token", access_token['access_token'], 7000) redis.set("wechat:access_token_expires_at", access_token['access_token_expires_at'], 7000) jsapi_ticket = wechat.get_jsapi_ticket() redis.set("wechat:jsapi_ticket", jsapi_ticket['jsapi_ticket'], 7000) redis.set("wechat:jsapi_ticket_expires_at", jsapi_ticket['jsapi_ticket_expires_at'], 7000) return wechat
def home(request): token = TOKEN if request.method == 'POST': signature = request.POST.get('signature', '') timestamp = request.POST.get('timestamp', '') nonce = request.POST.get('nonce') elif request.method == 'GET': signature = request.GET.get('signature', '') timestamp = request.GET.get('timestamp', '') nonce = request.GET.get('nonce') echostr = request.GET.get('echostr', '') if DEBUG: debug_log('==========') debug_log('token: '+str(token)) debug_log('signature: '+str(signature)) debug_log('timestamp: '+str(timestamp)) debug_log('nonce: '+str(nonce)) if token and timestamp and nonce and echostr: s = ''.join(sorted([token,timestamp,nonce])) debug_log('calculated sign: '+hashlib.sha1(s.encode('utf-8')).hexdigest()) debug_log('echostr: '+str(echostr)) wechat = WechatBasic(token=token) # 对签名进行校验 if wechat.check_signature(signature, timestamp, nonce): return HttpResponse(echostr) else: return HttpResponse('') if signature: return weixin_response(token, signature, timestamp, nonce, request.body) return HttpResponse('<h1>微信开发中 ...</h1>') """
def bind_saler(): """绑定收银台""" bid = int(request.args.get("bid", 0)) do = request.args.get("do", 0) brand = Brand.query.get(bid) salers = brand.brand_salers.count() users = brand.brandaccounts shop_id = 0 # 获取二维码 wechat = WechatBasic( appid=current_app.config.get("WECHAT_APPID"), appsecret=current_app.config.get("WECHAT_APPSECRET") ) temp_data = { "expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": int(str("11") + str(brand.id))}}, } # data = {"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": int(str("11") + str(brand.id))}}} get_ticket_data = wechat.create_qrcode(temp_data) ticket = get_ticket_data.get("ticket") if do == "download_qrcode": logging.info("download_qrcode") response = wechat.show_qrcode(ticket) response = make_response(response.content) response.headers["Content-Type"] = "image/jpg" attachment_name = "attachment; filename=汝州百事优惠圈绑定收银台专用二维码.jpg" response.headers["Content-Disposition"] = attachment_name return response return render_template("shop/bind_saler.html", brand=brand, ticket=ticket, users=users)
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 check_saler_info(): """确认收银员信息""" brand_id = int(request.args.get("bid", 0)) openid = session.get("openid") do = request.args.get("do") form = SalerInfoForm() if not openid: code = request.args.get("code") if not code: print "not code" # print "/check_saler_info" return redirect(WeixinHelper.oauth3(request.url)) else: wechat_login_fun(code) if do == 'check': # 绑定店员 mobile = request.args.get("mobile") exist_saler = Saler.query.filter(Saler.user_id == g.user.id, Saler.brand_id == brand_id).first() if not exist_saler: g.user.mobile = mobile saler = Saler(user_id=g.user.id, brand_id=brand_id) db.session.add(saler) db.session.commit() wechat = WechatBasic(appid=appid, appsecret=appsecret) wechat.send_text_message(openid, "您已成功绑定门店") return json.dumps({"message": "提交成功", "type": "success"}) else: return json.dumps({"message": "您已绑定门店,不用再次绑定", "type": "error"}) return render_template('mobile/check_saler_info.html', brand_id=brand_id, form=form)
def test_parse_data_voice_recognition(self): message = """<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1357290913</CreateTime> <MsgType><![CDATA[voice]]></MsgType> <MediaId><![CDATA[media_id]]></MediaId> <Format><![CDATA[Format]]></Format> <Recognition><![CDATA[腾讯微信团队]]></Recognition> <MsgId>1234567890123456</MsgId> </xml>""" wechat = WechatBasic() wechat.parse_data(data=message) message = wechat.message self.assertIsInstance(message, VoiceMessage) self.assertEqual(message.id, 1234567890123456) self.assertEqual(message.target, 'toUser') self.assertEqual(message.source, 'fromUser') self.assertEqual(message.time, 1357290913) self.assertEqual(message.type, 'voice') self.assertEqual(message.media_id, 'media_id') self.assertEqual(message.format, 'Format') self.assertEqual(message.recognition, '腾讯微信团队')
def sendMessage(): global conversationStatusList body = request.get_json() platform = body['platform'] conversationID = body['conversation_id'] contentType = body['content_type'] content = body['content'] appID = body['app_id'] secret = body['secret'] userID = body['user_id'] temp = conversationID.split(',') if temp[0] == userID: accountID = temp[1] else: accountID = temp[0] if conversationID not in conversationStatusList[platform]: return '', 503 elif conversationStatusList[platform][conversationID] == 'agent': if contentType.lower() == 'text': if platform == 'WeChat': tempConf = WechatConf(appid=appID, appsecret=secret, encrypt_mode='normal') tempWechat = WechatBasic(conf=tempConf) tempWechat.send_text_message(user_id=userID, content=content) print '[' + platform + ']Message sent to user: '******'agent', conversationID, '', accountID, userID, content, str(datetime.now().isoformat()[:-7]) + 'Z')) t.start() return '', 200 else: return '', 503 else: return '', 503
def test_parse_data_link_message(self): message = """<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1351776360</CreateTime> <MsgType><![CDATA[link]]></MsgType> <Title><![CDATA[公众平台官网链接]]></Title> <Description><![CDATA[公众平台官网链接]]></Description> <Url><![CDATA[url]]></Url> <MsgId>1234567890123456</MsgId> </xml>""" wechat = WechatBasic() wechat.parse_data(data=message) message = wechat.message self.assertIsInstance(message, LinkMessage) self.assertEqual(message.id, 1234567890123456) self.assertEqual(message.target, 'toUser') self.assertEqual(message.source, 'fromUser') self.assertEqual(message.time, 1351776360) self.assertEqual(message.type, 'link') self.assertEqual(message.title, '公众平台官网链接') self.assertEqual(message.description, '公众平台官网链接') self.assertEqual(message.url, 'url')
def test_parse_data_location_message(self): message = """<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1351776360</CreateTime> <MsgType><![CDATA[location]]></MsgType> <Location_X>23.134521</Location_X> <Location_Y>113.358803</Location_Y> <Scale>20</Scale> <Label><![CDATA[位置信息]]></Label> <MsgId>1234567890123456</MsgId> </xml>""" wechat = WechatBasic() wechat.parse_data(data=message) message = wechat.message self.assertIsInstance(message, LocationMessage) self.assertEqual(message.id, 1234567890123456) self.assertEqual(message.target, 'toUser') self.assertEqual(message.source, 'fromUser') self.assertEqual(message.time, 1351776360) self.assertEqual(message.type, 'location') self.assertEqual(message.location, (23.134521, 113.358803)) self.assertEqual(message.scale, 20) self.assertEqual(message.label, '位置信息')
def test_get_group(self): # 测试无 appid 和 appsecret 初始化 wechat = WechatBasic() with self.assertRaises(NeedParamError): wechat.get_groups() # 测试有 appid 和 appsecret 初始化 wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret) with HTTMock(wechat_api_mock): resp = wechat.get_groups() self.assertEqual(resp['groups'][0]['id'], 0) self.assertEqual(resp['groups'][0]['name'], '未分组') self.assertEqual(resp['groups'][0]['count'], 72596) self.assertEqual(resp['groups'][1]['id'], 1) self.assertEqual(resp['groups'][1]['name'], '黑名单') self.assertEqual(resp['groups'][1]['count'], 36) self.assertEqual(resp['groups'][2]['id'], 2) self.assertEqual(resp['groups'][2]['name'], '星标组') self.assertEqual(resp['groups'][2]['count'], 8) self.assertEqual(resp['groups'][3]['id'], 104) self.assertEqual(resp['groups'][3]['name'], '华东媒') self.assertEqual(resp['groups'][3]['count'], 4) self.assertEqual(resp['groups'][4]['id'], 106) self.assertEqual(resp['groups'][4]['name'], '★不测试组★') self.assertEqual(resp['groups'][4]['count'], 1)
def test_send_article_message(self): article_info = [ { 'title': '第一条新闻标题', 'description': '第一条新闻描述,这条新闻没有预览图', 'url': 'http://www.google.com.hk/', }, { 'title': '第二条新闻标题, 这条新闻无描述', 'picurl': 'http://doraemonext.oss-cn-hangzhou.aliyuncs.com/test/wechat-test.jpg', 'url': 'http://www.github.com/', }, { 'title': '第三条新闻标题', 'description': '第三条新闻描述', 'picurl': 'http://doraemonext.oss-cn-hangzhou.aliyuncs.com/test/wechat-test.jpg', 'url': 'http://www.v2ex.com/', } ] # 测试无 appid 和 appsecret 初始化 wechat = WechatBasic() with self.assertRaises(NeedParamError): wechat.send_article_message('12341234234', article_info) # 测试有 appid 和 appsecret 初始化 wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret) with HTTMock(wechat_api_mock): resp = wechat.send_article_message('safasf', article_info) self.assertEqual(resp['errcode'], 0) self.assertEqual(resp['errmsg'], 'ok')
def create_qrcode(cls, name): from app import Qrcode token, expired_at = _wechat.get_access_token() wechat = WechatBasic( appid=settings.app_id, appsecret=settings.secret, access_token=token, access_token_expires_at=expired_at) payload = { "action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": name}}} resp = wechat.create_qrcode(payload) ticket = resp.get('ticket', '') url = resp.get('url', '') data = cls.show_qrcode(ticket) if not data: raise output = cStringIO.StringIO() output.write(data) # upload p = qiniu.PutPolicy(settings.bucket) path = '/qrcode/%s' % name path, hash_key = p.upload(output, path) output.close() Qrcode.create_code(name, ticket, url, path, hash_key) p = qiniu.PublicGetPolicy(settings.bucket, path) return p.get_url()
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 init_wechat_sdk(): """ 初始化微信sdk :return: WechatBasic """ access_token = db.get("wechat:access_token") jsapi_ticket = db.get("wechat:jsapi_ticket") token_expires_at = db.get("wechat:access_token_expires_at") ticket_expires_at = db.get("wechat:jsapi_ticket_expires_at") if all((access_token, jsapi_ticket, token_expires_at, ticket_expires_at)): wechat = WechatBasic(appid=app.config['APP_ID'], appsecret=app.config['APP_SECRET'], token=app.config['TOKEN'], access_token=access_token, access_token_expires_at=int(token_expires_at), jsapi_ticket=jsapi_ticket, jsapi_ticket_expires_at=int(ticket_expires_at)) else: wechat = WechatBasic(appid=app.config['APP_ID'], appsecret=app.config['APP_SECRET'], token=app.config['TOKEN']) access_token = wechat.get_access_token() db.set("wechat:access_token", access_token['access_token'], 7000) db.set("wechat:access_token_expires_at", access_token['access_token_expires_at'], 7000) jsapi_ticket = wechat.get_jsapi_ticket() db.set("wechat:jsapi_ticket", jsapi_ticket['jsapi_ticket'], 7000) db.set("wechat:jsapi_ticket_expires_at", jsapi_ticket['jsapi_ticket_expires_at'], 7000) return wechat
def test_group_transfer_message(self): wechat = WechatBasic() wechat.parse_data(data=self.test_message) resp_xml = wechat.group_transfer_message() resp = xmltodict.parse(resp_xml) self.assertEqual(resp['xml']['ToUserName'], 'fromUser') self.assertEqual(resp['xml']['FromUserName'], 'toUser') self.assertEqual(resp['xml']['MsgType'], 'transfer_customer_service')
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 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 test_response_voice(self): wechat = WechatBasic() wechat.parse_data(data=self.test_message) resp_xml = wechat.response_voice(media_id='xurkvi9gl') resp = xmltodict.parse(resp_xml) self.assertEqual(resp['xml']['ToUserName'], 'fromUser') self.assertEqual(resp['xml']['FromUserName'], 'toUser') self.assertEqual(resp['xml']['MsgType'], 'voice') self.assertEqual(resp['xml']['Voice']['MediaId'], 'xurkvi9gl')
def checkout(): verify = False is_expire = False usedit = False discount_id = request.args.get("discount_id", 0, type=int) record_id = request.args.get("record_id", 0, type=int) # 领取id do = request.args.get("do") discount = Discount.query.get_or_404(discount_id) shops = discount.shops record = GetTicketRecord.query.get_or_404(record_id) if record.status == "usedit": usedit = True if discount: expire_date = discount.create_at + timedelta(days=discount.usable) print discount.create_at, discount.usable expire_date = expire_date.date() if datetime.datetime.now().date() > expire_date: is_expire = True # 获取二维码ticket if do == "get_qrcode": if record.status == "verify": verify = True if not record.ticket: # 获取永久二维码 scene_id前缀12表示是优惠券类型的二维码 wechat = WechatBasic( appid=current_app.config.get("WECHAT_APPID"), appsecret=current_app.config.get("WECHAT_APPSECRET") ) data = { "action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": int(str("12") + str(record.id))}}, } get_ticket_data = wechat.create_qrcode(data) ticket = get_ticket_data.get("ticket") session["ticket"] = ticket # 写入数据库 record.ticket = ticket db.session.add(record) db.session.commit() else: ticket = record.ticket return json.dumps({"message": {"verify": verify, "ticket": ticket, "expire": 0}}) elif do == "download_qrcode": return "" return render_template( "shop/checkout.html", shops=shops, expire_date=expire_date, is_expire=is_expire, record_id=record_id, record=record, usedit=usedit, discount=discount, )
def validate(): wechat = WechatBasic(token=settings['wechat_app']['token'], appid=settings['wechat_app']['appID'], appsecret=settings['wechat_app']['appsecret']) signature = request.args.get('signature') timestamp = request.args.get('timestamp') nonce = request.args.get('nonce') # log the checking event logger.info("checking signature: (%s, %s, %s)", signature, timestamp, nonce) if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): return request.args.get('echostr') return ""
def test_get_group_by_id(self): # 测试无 appid 和 appsecret 初始化 wechat = WechatBasic() with self.assertRaises(NeedParamError): wechat.get_group_by_id('13441123412341') # 测试有 appid 和 appsecret 初始化 wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret) with HTTMock(wechat_api_mock): resp = wechat.get_group_by_id('12554647777') self.assertEqual(resp['groupid'], 102)
class WeixinMananger: def __init__(self, appid="wxc2b14fc7557dc863", appsecret="67c0097d1bf2f7804f9eb2375f3d2039", redisIp="127.0.0.1", redisPort=6379): self.redis = redis.StrictRedis(host=redisIp) self.appid = appid; self.appsecret = appsecret; self.wechat = WechatBasic(appid=appid, appsecret=appsecret); def __getRedisWXAccessToken(self): return self.redis.get("wx_access_token") def __getRedisWXJsApiToken(self): return self.redis.get("wx_jsapi_token") def getAccessToken(self): token = self.__getRedisWXAccessToken() if token is None: token = self.wechat.grant_token() if token != None: timeout = token["expires_in"] self.redis.setex("wx_access_token", timeout, token["access_token"]) return token["access_token"] else: return None; else: return token def getJsApiToken(self): ticket = self.__getRedisWXJsApiToken() if ticket is None: print self.getAccessToken() ticket = self.wechat.grant_jsapi_ticket() if (ticket != None): timeout = ticket["expires_in"]; self.redis.setex("wx_jsapi_token", timeout, ticket["ticket"]) return ticket["ticket"] else: return None else: return ticket def getJsJDK(self, srcUrl): timestamp = int(time.time()) noncestr = str(time.time()) url = srcUrl jsApiToken = self.getJsApiToken(); data = {}; data["timestamp"] = timestamp data["nonceStr"] = noncestr data["appId"] = self.appid data["signature"] = self.wechat.generate_jsapi_signature(timestamp, noncestr, url, jsApiToken) data["jsApiList"] = ["openLocation", "getLocation", "scanQRCode", "showMenuItems"] data["debug"] = True return data
def test_send_video_message(self): # 测试无 appid 和 appsecret 初始化 wechat = WechatBasic() with self.assertRaises(NeedParamError): wechat.send_video_message('asfasdfadsf', '123412342134') # 测试有 appid 和 appsecret 初始化 wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret) with HTTMock(wechat_api_mock): resp = wechat.send_video_message('safasf', '123412343423241') self.assertEqual(resp['errcode'], 0) self.assertEqual(resp['errmsg'], 'ok')
def test_send_music_message(self): # 测试无 appid 和 appsecret 初始化 wechat = WechatBasic() with self.assertRaises(NeedParamError): wechat.send_music_message('231412341234', 'http://www.baidu.com', 'http://www.google.com', '12341234') # 测试有 appid 和 appsecret 初始化 wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret) with HTTMock(wechat_api_mock): resp = wechat.send_music_message('231412341234', 'http://www.baidu.com', 'http://www.google.com', '12341234') self.assertEqual(resp['errcode'], 0) self.assertEqual(resp['errmsg'], 'ok')
def test_create_group(self): # 测试无 appid 和 appsecret 初始化 wechat = WechatBasic() with self.assertRaises(NeedParamError): wechat.create_group('测试组') # 测试有 appid 和 appsecret 初始化 wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret) with HTTMock(wechat_api_mock): resp = wechat.create_group('测试组') self.assertEqual(resp['group']['id'], 107) self.assertEqual(resp['group']['name'], 'test')
def test_update_group(self): # 测试无 appid 和 appsecret 初始化 wechat = WechatBasic() with self.assertRaises(NeedParamError): wechat.update_group(23, 'asfff') # 测试有 appid 和 appsecret 初始化 wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret) with HTTMock(wechat_api_mock): resp = wechat.update_group(11, '113444') self.assertEqual(resp['errcode'], 0) self.assertEqual(resp['errmsg'], 'ok')
def test_move_user(self): # 测试无 appid 和 appsecret 初始化 wechat = WechatBasic() with self.assertRaises(NeedParamError): wechat.move_user("123412", 1241234) # 测试有 appid 和 appsecret 初始化 wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret) with HTTMock(wechat_api_mock): resp = wechat.update_group("21341", 12341234) self.assertEqual(resp['errcode'], 0) self.assertEqual(resp['errmsg'], 'ok')
def test_delete_menu(self): # 测试无 appid 和 appsecret 初始化 wechat = WechatBasic() with self.assertRaises(NeedParamError): wechat.delete_menu() # 测试有 appid 和 appsecret 初始化 wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret) with HTTMock(wechat_api_mock): resp = wechat.delete_menu() self.assertEqual(resp['errcode'], 0) self.assertEqual(resp['errmsg'], 'ok')
def test_send_text_message(self): # 测试无 appid 和 appsecret 初始化 wechat = WechatBasic() with self.assertRaises(NeedParamError): wechat.send_text_message('asdfasdfdf', 'asdadsfd') # 测试有 appid 和 appsecret 初始化 wechat = WechatBasic(appid=self.appid, appsecret=self.appsecret) with HTTMock(wechat_api_mock): resp = wechat.send_text_message('13412412341234242', '测试') self.assertEqual(resp['errcode'], 0) self.assertEqual(resp['errmsg'], 'ok')
# -*- coding: utf-8 -*- from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, HttpResponseBadRequest import hashlib import json from django.utils.encoding import smart_str from wechat_sdk import WechatBasic from wechat_sdk.exceptions import ParseError from wechat_sdk.messages import TextMessage, VoiceMessage, ImageMessage, VideoMessage, EventMessage # Create your views here. wechat_instance = WechatBasic( token='test', appid='wx68504760f1652652', appsecret='af867702558c8c7f62d71ab4e9294c4e', ) # wechat_instance.create_menu(menu_data={ # 'button': [ # { # 'type': 'click', # 'name': '今日歌曲', # 'key': 'MUSIC', # }, # { # 'type': 'click', # 'name': '简介', # 'key': 'INTRODUTION', # }, # ] # })
# -*- coding: utf-8 -*- from wechat_sdk import WechatBasic WECHAT_TOKEN = 'token' AppID = 'wxce660ee67e094937' AppSecret = '10108b4f9ec7bb9b76f4699087f620e6' BaseUrl = "http://sems.tunnel.qydev.com/wechat" redirect_uri = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxce660ee67e094937&redirect_uri=URL&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect" index = BaseUrl + "/index" redirect_uri_state = redirect_uri.replace("URL", BaseUrl + "/state") redirect_uri_control = redirect_uri.replace("URL", BaseUrl + "/control") redirect_uri_bind = redirect_uri.replace("URL", BaseUrl + "/bind") redirect_uri_history = redirect_uri.replace("URL", BaseUrl + "/history") redirect_uri_nearby = redirect_uri.replace("URL", BaseUrl + "/nearby") wechat_instance = WechatBasic(token=WECHAT_TOKEN, appid=AppID, appsecret=AppSecret) # 创建自定义菜单 wechat_instance.create_menu({ 'button': [ { 'type': 'view', 'name': '首页', 'url': index }, { 'name': '充电', 'sub_button': [{ 'type': 'view',
import json import hashlib from wechat_sdk import WechatConf from wechat_sdk import WechatBasic import handle import logging TOKEN = "gyn" APPID = "ws22b0c85f1a73954f" SECRET = "11efa7ed3b14e9d1fa2905608ef8f015" SECRET_MODE = False wechat_conf = WechatConf(token=TOKEN, appid=APPID, appsecret=SECRET, encrypt_mode=SECRET_MODE) wechat_base = WechatBasic(conf=wechat_conf) @csrf_exempt def response(request): if request.method == "GET": signature = request.GET.get('signature', None) timestamp = request.GET.get('timestamp', None) echostr = request.GET.get('echostr', None) nonce = request.GET.get('nonce', None) if wechat_base.check_signature(signature, timestamp, nonce): return HttpResponse(echostr) else: return HttpResponse("error") else: xml_str = smart_str(request.body)
class Wpichandler(BaseHandler): conf = '' wechat = '' def __init__(self): self.conf = Wconf.conf self.wechat = WechatBasic(conf=self.conf) def getfromwechat(self, media_ids, names): ''' Args: media_ids: 图片的media_id数组 names: 图片的名字数组 Returns: null ''' #media_ids = json.loads(media_ids) #names = json.loads(names) for media_id, name in zip(media_ids, names): response = self.wechat.download_media(media_id=media_id) with open('./{address}'.format(address=name), 'wb') as fd: for chunk in response.iter_content(1024): fd.write(chunk) def upload(self, names): ''' Args: names:图片的media数组 Returns:所有图片上传成功时,返回True,否则为False ''' auth = AuthKeyHandler() #names = json.loads(names) bucket_name = 'shacus' q = Auth(auth.access_key, auth.secret_key) for name in names: token = q.upload_token(bucket_name, name, 345600) localfile = './{address}'.format(address=name) ret, info = put_file(token, name, localfile) if info.status_code != 200: return False return True def pichandler(self, media_ids, names): ''' Args: media_ids: 图片的media_id数组 names: 图片的名字数组 Returns:所有图片上传成功时,返回True,否则为False ''' self.getfromwechat(media_ids=media_ids, names=names) if self.upload(names=names): #names = json.loads(names) for name in names: filename = '{mulu}/{address}'.format(address=name, mulu=sys.path[0]) if os.path.exists(filename): os.remove(filename) return True
class MessageManager(object): def __init__(self, conf, signature='', timestamp='', nonce=''): self.wechat = WechatBasic(conf=conf) # check wechat connect. if self.wechat.check_signature(signature, timestamp, nonce): print 'Accept' else: print 'Wrong' def receive(self, body_text): try: self.wechat.parse_data(body_text) except ParseError: print 'Invalid Body Text' id = self.wechat.message.id # 对应于 XML 中的 MsgId target = self.wechat.message.target # 对应于 XML 中的 ToUserName source = self.wechat.message.source # 对应于 XML 中的 FromUserName time = self.wechat.message.time # 对应于 XML 中的 CreateTime type = self.wechat.message.type # 对应于 XML 中的 MsgType raw = self.wechat.message.raw # 原始 XML 文本,方便进行其他分析 if isinstance(self.wechat.message, TextMessage): content = self.wechat.message.content # 对应于 XML 中的 Content if isinstance(self.wechat.message, ImageMessage): picurl = self.wechat.message.picurl # 对应于 XML 中的 PicUrl media_id = self.wechat.message.media_id # 对应于 XML 中的 MediaId if isinstance(self.wechat.message, VoiceMessage): media_id = self.wechat.message.media_id # 对应于 XML 中的 MediaId format = self.wechat.message.format # 对应于 XML 中的 Format recognition = self.wechat.message.recognition # 对应于 XML 中的 Recognition if isinstance(self.wechat.message, VideoMessage) or isinstance(self.wechat.message, ShortVideoMessage): media_id = self.wechat.message.media_id # 对应于 XML 中的 MediaId thumb_media_id = self.wechat.message.thumb_media_id # 对应于 XML 中的 ThumbMediaId if isinstance(self.wechat.message, LocationMessage): location = self.wechat.message.location # Tuple(X, Y),对应于 XML 中的 (Location_X, Location_Y) scale = self.wechat.message.scale # 对应于 XML 中的 Scale label = self.wechat.message.label # 对应于 XML 中的 Label if isinstance(self.wechat.message, LinkMessage): title = self.wechat.message.title # 对应于 XML 中的 Title description = self.wechat.message.description # 对应于 XML 中的 Description url = self.wechat.message.url # 对应于 XML 中的 Url if isinstance(self.wechat.message, EventMessage): if self.wechat.message.type == 'subscribe': # 关注事件(包括普通关注事件和扫描二维码造成的关注事件) key = self.wechat.message.key # 对应于 XML 中的 EventKey (普通关注事件时此值为 None) ticket = self.wechat.message.ticket # 对应于 XML 中的 Ticket (普通关注事件时此值为 None) elif self.wechat.message.type == 'unsubscribe': # 取消关注事件(无可用私有信息) pass elif self.wechat.message.type == 'scan': # 用户已关注时的二维码扫描事件 key = self.wechat.message.key # 对应于 XML 中的 EventKey ticket = self.wechat.message.ticket # 对应于 XML 中的 Ticket elif self.wechat.message.type == 'location': # 上报地理位置事件 latitude = self.wechat.message.latitude # 对应于 XML 中的 Latitude longitude = self.wechat.message.longitude # 对应于 XML 中的 Longitude precision = self.wechat.message.precision # 对应于 XML 中的 Precision elif self.wechat.message.type == 'click': # 自定义菜单点击事件 key = self.wechat.message.key # 对应于 XML 中的 EventKey elif self.wechat.message.type == 'view': # 自定义菜单跳转链接事件 key = self.wechat.message.key # 对应于 XML 中的 EventKey elif self.wechat.message.type == 'templatesendjobfinish': # 模板消息事件 status = self.wechat.message.status # 对应于 XML 中的 Status elif self.wechat.message.type in ['scancode_push', 'scancode_waitmsg', 'pic_sysphoto', 'pic_photo_or_album', 'pic_weixin', 'location_select']: # 其他事件 key = self.wechat.message.key # 对应于 XML 中的 EventKey def reply(self, type='text'): if type == 'text': # xml = self.wechat.response_text(content='文本回复') xml = self.wechat.response_text(content='文本回复', escape=True) if type == 'image': xml = self.wechat.response_image(media_id='media_id') if type == 'voice': xml = self.wechat.response_voice(media_id='media_id') if type == 'video': xml = self.wechat.response_video(media_id='media_id', title='video_title', description='video_description') if type == 'music': xml = self.wechat.response_music( music_url='your_music_url', title='music_title', description='music_description', hq_music_url='your_hq_music_url', thumb_media_id='your_thumb_media_id', ) if type == 'news': xml = self.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'第三条新闻描述', 'picurl': u'http://doraemonext.oss-cn-hangzhou.aliyuncs.com/test/wechat-test.jpg', 'url': u'http://www.v2ex.com/', } ])
from wechat_sdk import WechatBasic from wechat_sdk.messages import (TextMessage, VoiceMessage, ImageMessage, VideoMessage, LinkMessage, LocationMessage, EventMessage, ShortVideoMessage) # -*- coding: utf-8 -*- ''' wechatConf = WechatConf( token = 'todaycoder', appid = 'wxf2da4d91bf3b64f4', appsecret = '6a2ccbaaea6e48563c886796749a7a3e', encrypt_mode = 'normal' #normal/compatible/safe ) ''' logging.basicConfig(level=logging.DEBUG) wechat_conf = config.get_wechat_config() wechat = WechatBasic(wechat_conf) tuling_key, tuling_url = config.get_tuling_config() auto_reply = tuling.TulingAutoReply(tuling_key, tuling_url) class WX(tornado.web.RequestHandler): def get(self): signature = self.get_argument('signature', 'default') timestamp = self.get_argument('timestamp', 'default') nonce = self.get_argument('nonce', 'default') echostr = self.get_argument('echostr', 'default') if wechat_install.check_signature(signature, timestamp, nonce): self.write(echostr) else: self.write('Not Open')
def callback(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') echostr = request.GET.get('echostr') conf = HangoutConfig.get_wechat_config() wechat_base = WechatBasic(conf=conf) print('初始化:', settings.WECHAT_APPID, request.GET, signature, timestamp, nonce, echostr) print('body:', conf.appid, request.body.decode()) if not wechat_base.check_signature(request.GET.get('signature'), request.GET.get('timestamp'), request.GET.get('nonce')): print('验证不通过!') raise Http404() if not request.body.decode(): return HttpResponse(echostr) try: wechat_base.parse_data(request.body) except ParseError: print('Invalid Body Text') raise Http404() print('wechat_base.message:', wechat_base.message, wechat_base.message.type) source = wechat_base.message.source wechat_auth = _get_wechat_auth(wechat_base, openid=source) if wechat_base.message.type in ['scan', 'subscribe']: key = wechat_base.message.key print('关注事件', key, source) if not key: text = wechat_base.response_text('关注成功!') print('return by empty key', text) return HttpResponse(text) prefix = 'qrscene_' key = key.replace(prefix, '') # 已关注用户扫二维码 print('auth', wechat_auth, wechat_auth.user) try: schedule_share, created = _accept_schedule(ss_id=int(key), user=wechat_auth.user) except (ValueError, ScheduleShare.DoesNotExist) as e: logging.exception(e) return HttpResponse( wechat_base.response_text('该邀请不存在!ID: %s' % key)) schedule = schedule_share.schedule url = settings.GUPPIES_URL_PREFIX + resolve_url('hangout.detail', pk=schedule.id) if schedule.user_id == wechat_auth.user_id: text = '该事件是您创建的, 您无需扫码加入! 您可点击下方链接查看详情: \r\n%s' % url return HttpResponse(wechat_base.response_text(text)) if not created: text = '您已接受该邀请, 无需重复加入! 您可点击下方链接查看详情: \r\n%s' % url return HttpResponse(wechat_base.response_text(text)) text = '恭喜你预约成功, 我将于%s提醒您!' % (hangout_logic.natural_time( schedule.started_date)) hangout_logic.template_notify(wechat_base, wechat_auth, schedule, title=text) # notify owner who join the schedule try: text = '%s接受了您的邀请' % wechat_auth.user.userinfo.nickname owner_wechat_auth = WechatAuth.objects.get( user=schedule_share.user) hangout_logic.template_notify(wechat_base, owner_wechat_auth, schedule, title=text) except Exception as e: logging.exception(e) return HttpResponse("")
from django.shortcuts import render, render_to_response from django.utils.encoding import smart_str from wechat_sdk import WechatBasic from wechat_sdk.messages import (TextMessage, VoiceMessage, ImageMessage, VideoMessage, LinkMessage, LocationMessage, EventMessage) from .models import Text, News, SendDynamicRecord, User, PhonePaste, PhonePasteRecoder, PhonePasteTransfer, PhonePasteRechargeRecord, StaffSignRecord from .forms import ContactForm, RegistForm from datetime import date from .tools import send_dynamic_sms, check_regist, get_or_create_user_phone_paste, get_week_day from django.core.exceptions import ObjectDoesNotExist import datetime token = 'XLHW' wechat = WechatBasic(token=token) def hello(request): return HttpResponse('hello') def handleRequest(request): 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': if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce):
cash_event.event_amount = Decimal(10000) cash_event.save() return redirect('member.money') isSuccess = True return redirect('member.money') except Exception, e: messages.warning(request, e) c['f'] = f c['is_ok'] = isSuccess c['openid'] = openid wechat = WechatBasic(token=WEIXIN_TOKEN, appid=APPID, appsecret=APPSECRET) ticket = getJsApiTicket(wechat) sign = Sign(ticket, "http://" + request.get_host() + request.get_full_path()) c['sign'] = sign.sign() c['appid'] = APPID c['openid'] = openid return render_to_response("event/cash_join.html", c, context_instance=RequestContext(request)) @csrf_protect def join(request): c = {}
def wechat_binder(): g.wechat = WechatBasic(wechat_conf)
# -*- coding:utf8 -*- from wechat_sdk import WechatBasic, WechatConf conf = WechatConf( token='helloworld', appid='wx5effce4e20e97a20', appsecret='2fdd281fd8a8fa78ec94859c3bdf7501', encrypt_mode='normal', # 可选项:normal/compatible/safe,分别对应于 明文/兼容/安全 模式 encoding_aes_key='' # 如果传入此值则必须保证同时传入 token, appid ) wechat = WechatBasic(conf=conf) MENU_DATA = { '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',
signature = 'f24649c76c3f3d81b23c033da95a7a30cb7629cc' timestamp = '1406799650' nonce = '1505845280' body_text = """ <xml> <ToUserName><![CDATA[touser]]></ToUserName> <FromUserName><![CDATA[fromuser]]></FromUserName> <CreateTime>1405994593</CreateTime> <MsgType><![CDATA[image]]></MsgType> <Content><![CDATA[hehe]]></Content> <MsgId>6038700799783131222</MsgId> </xml> """ wechat = WechatBasic(token=token) if wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): wechat.parse_data(body_text) 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'wenzi')
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'更新菜单成功')
import os from flask import Blueprint from wechat_sdk import WechatConf, WechatBasic conf = WechatConf(token=os.getenv('WECHAT_TOKEN'), appid=os.getenv('WECHAT_APPID'), appsecret=os.getenv('WECHAT_APPSECRET'), encrypt_mode="normal") sdk = WechatBasic(conf=conf) wechat = Blueprint('wechat', __name__) from . import reply
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http.response import HttpResponse, HttpResponseBadRequest import json from wechat_sdk import WechatBasic from wechat_sdk.exceptions import ParseError from wechat_sdk.messages import TextMessage # 实例化 WechatBasic wechat_instance = WechatBasic(token="recruit", appid='wxffda7df5ae5ab2f9', appsecret='915878d1c58f69dff9139e3556789201') # Create your views here. def index(request): if request.method == 'GET': # 检验合法性 # 从 request 中提取基本信息 (signature, timestamp, nonce, xml) signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') return HttpResponse(request.GET.get('echostr', ''), content_type="text/plain")
import hashlib import os import numpy # wechat open_id to user_id has been linked. # if the user has linked before, we can use the following two statements to find whatever things in user. ''' openid_check = wechatUser.objects.filter(openid=openid,userLink=True) if openid_check: user = openid_check[0].mainUser else: return Failure.''' # to fetch whatever things in User type 'user' # and what you only need to change is openid. :-) Luka. wechat_instance = WechatBasic(token=Secret.SECRET_TOKEN, appid=Secret.APP_ID, appsecret=Secret.APP_SECRET) home_url = Secret.HOME_URL @csrf_exempt def wechat(request): if request.method == 'GET': # verifycation signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HTTPResponseBadRequest('Verify Failed') return HttpResponse(request.GET.get('echostr', ''), content_type="text/plain")
# coding=utf-8 from wechat_sdk import WechatBasic import time wechat_appid = "wxf7b5bd13112fe9fc" wechat_appsecret = "2d150d1243c72816c3d67645c39154b4" wechat_token = "o1q3XK7oem2dCAp8H2EiTiFB9DsoSJxefDmj6xjcMxIJ_lqkhRtt3c9Y_wZEfp1C4aDD6Yy3LF4gIZTPdpJOV1u5FocWUCGzepLn2N3H4RUMEMgAEAZRZ-EVPwCyNWgSOQZ17Na970QP4dC4unJGwYQIlz9TfpwFXSaABASKF" wechat = WechatBasic(token=wechat_token, appid=wechat_appid, appsecret=wechat_appsecret) # 最简单的单例实现,需要改进。 def get_wechat_client(): return wechat
class WeChatService(object): def __init__(self, app_id=None, app_secret=None): self.redis = redis.StrictRedis(host='localhost', port=6379, db=2) self.app_id = app_id self.app_secret = app_secret if not app_id: self.wechat_admin = Area.objects.all().order_by('id')[0] self.wechat = WechatBasic(appid=self.wechat_admin.wx_app_id, appsecret=self.wechat_admin.wx_secret, token='123') 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) return token def get_js_ticket(self): key = 'js_ticket_{0}'.format(self.app_id) ticket = self.redis.get(key) if not ticket or ticket == 'None': res = self.wechat.get_jsapi_ticket() ticket = res.get('jsapi_ticket') self.redis.set(key, ticket, 3500) return ticket def get_random_str(self): return string.join( random.sample('ZYXWVUTSRQPONMLKJIHGFEDCBA1234567890zyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba', 32)).replace(" ", "") def get_js_signature(self, url): timestamp = int(time.time()) nostr = self.get_random_str() ticket = self.get_js_ticket() signature = self.wechat.generate_jsapi_signature(timestamp, nostr, url, ticket) return {'timestamp': timestamp, 'ticket': ticket, 'noncestr': nostr, 'url': url, 'signature': signature} 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) if __name__ == '__main__': ws = WeChatService('wx53a0bb66744d6ff8', '72714e74ea52de8a0917111bb7b4b324') print ws.get_js_signature('http://www.rapospectre.com')
import hashlib from wechat_sdk import WechatBasic from django.shortcuts import render from django.http.response import * from models import * WEIXIN_TOKEN = 'write-a-value' WECHAT_TOKEN = 'zqxt' AppID = '' AppSecret = '' # 实例化 WechatBasic wechat_instance = WechatBasic(token=settings.TOKEN, appid=settings.SNS_ID, appsecret=settings.SNS_SECRET) import sys reload(sys) sys.setdefaultencoding('utf-8') def wxindex(request): if request.method == 'GET': # 检验合法性 # 从 request 中提取基本信息 (signature, timestamp, nonce, xml) signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce')
from daibang.settings import WECHAT_TOKEN, WEIXIN_APPID, WEIXIN_APPSECRET import hashlib, urllib2 #auto-menu need library import urllib import urllib2 from urllib import urlencode import json import sys reload(sys) sys.setdefaultencoding('UTF-8') wechat_instance = WechatBasic(token=WECHAT_TOKEN, appid=WEIXIN_APPID, appsecret=WEIXIN_APPSECRET) def create_menu(): url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % ( WEIXIN_APPID, WEIXIN_APPSECRET) result = urllib2.urlopen(url).read() print result access_token = json.loads(result).get('access_token') print access_token posturl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + access_token menu = '''{
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 __init__(self): self.conf = Wconf.conf self.wechat = WechatBasic(conf=self.conf)
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')
# author: HuYong # coding=utf-8 from wechat_sdk import WechatBasic # 微信推送 WECHAT_TOKEN = 'token' AppID = 'wxce660ee67e094937' AppSecret = '10108b4f9ec7bb9b76f4699087f620e6' wechat_instance = WechatBasic( token=WECHAT_TOKEN, appid=AppID, appsecret=AppSecret ) # 充电完成推送 def WeChatPush_alreadyFinish(user, charge): print "**************" responsedata = "你好," + user.username.encode("utf-8") + "\n你的车已经充电完毕,请尽快取车" data = {"data": {"value": responsedata, "color": "#173177"}} print data try: json = wechat_instance.send_template_message(str(user.openid), "saRJ7C92DuovutwG57V7wcvxeVoZwp04VvUWSZHOnas", data) except Exception,e: print e print json # 充电完毕本次充电信息推送
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)
from goods.models import GoodsList from MkOnline.settings import MEDIA_URL import requests import json # 初始化 wei_config = WxConfig.objects.get(id=1) conf = WechatConf( token=wei_config.token, appid=wei_config.appid, appsecret=wei_config.appsecret, encrypt_mode=wei_config. encrypt_mode, # 可选项:normal/compatible/safe,分别对应于 明文/兼容/安全 模式 encoding_aes_key=wei_config. encoding_aes_key # 如果传入此值则必须保证同时传入 token, appid ) wechat_instance = WechatBasic(conf=conf) # 域名地址 domain_name = "http://101.132.38.60/" # 接受微信请求函数 @csrf_exempt def wx_view(request): if request.method == 'GET': signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') return HttpResponse(request.GET.get('echostr', ''))
def api(self): return WechatBasic(conf=self.conf)
from django.http.response import HttpResponse, HttpResponseBadRequest from django.views.decorators.csrf import csrf_exempt from wechat_sdk import WechatBasic from wechat_sdk.exceptions import ParseError from wechat_sdk.messages import (TextMessage, VoiceMessage, ImageMessage, VideoMessage, LinkMessage, LocationMessage, EventMessage) import logging from wechatservice import * logger = logging.getLogger('django') wechat_instance = WechatBasic(token='johnsmovie', appid='wx8df05882fae81331', appsecret='7af8c6cbeb2b24e3ea5bcc92134a8476') @csrf_exempt def videoinfo(request): if request.method == 'GET': content = {} signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') if not request.GET.get('nsukey'): content['errmsg'] = '请通过公众号访问' return render_to_response('wechat/503.html', content) #response = wechat_instance.response_text(content=apply_text) if not request.GET.get('id') or request.GET.get('id') == '': content['errmsg'] = '搜索的视频错误'
from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from wechatpy import WeChatClient from yiyuanduobao_shop.models import * from weixin import handler as HD from weixin.backends.dj import Helper, sns_userinfo from weixin import WeixinHelper, JsApi_pub, WxPayConf_pub, UnifiedOrder_pub, Redpack_pub, Notify_pub, catch from wechat_sdk import WechatConf from wechat_sdk import WechatBasic import json # Create your views here. conf_instance = WechatConf(token=WxPayConf_pub.TOKEN, appid=WxPayConf_pub.APPID, appsecret=WxPayConf_pub.APPSECRET, encrypt_mode='normal') wechat_instance = WechatBasic(conf_instance) @csrf_exempt def do(request): # access token 记录在session中 if 'access_token' not in request.session: request.session['access_token'] = fetch_access_token() """公众平台对接""" signature = request.REQUEST.get("signature", "") timestamp = request.REQUEST.get("timestamp", "") nonce = request.REQUEST.get("nonce", "") if not any([signature, timestamp, nonce]) or not WeixinHelper.checkSignature( signature, timestamp, nonce): return HttpResponse("check failed")
#!/usr/bin/env python #-*- coding:utf-8 -*- ''' Created on 0:48 2017/11/7 @author: acer ''' from wechat_sdk import WechatBasic wechat_instance = WechatBasic(token='yuxuefendou', appid='wxf4f421a98811617a', appsecret='5e5f459dc1b1998d58dc7f40188adaa6')