1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| from wechatpy.utils import check_signature from wechat import settings from wechatpy.exceptions import InvalidSignatureException from django.http import HttpResponse from wechatpy import parse_message, create_reply from wechatpy.replies import BaseReply from wechatpy import WeChatClient from wechatpy.oauth import WeChatOAuth from django.shortcuts import redirect from wechat.util import reply_text
def serve(request): if request.method == 'GET': signature = request.GET.get('signature', '') timestamp = request.GET.get('timestamp', '') nonce = request.GET.get('nonce', '') echo_str = request.GET.get('echostr', '') try: check_signature(settings.Token, signature, timestamp, nonce) except InvalidSignatureException: echo_str = '错误的请求' response = HttpResponse(echo_str) else: msg = parse_message(request.body) msg_dict = msg.__dict__['_data'] print(type(msg)) print(msg.id, msg.source, msg.create_time, msg.type, msg.target, msg.time, '====') if msg.type == 'text': reply = reply_text.do_reply(msg) elif msg.type == 'event': if msg_dict['Event'] == 'subscribe': pass else: pass response = HttpResponse(reply.render(), content_type="application/xml") return response
def getWxClient(): return WeChatClient(settings.AppID, settings.AppSecret)
def getWxUserInfo(openid): wxClient = getWxClient() wxUserInfo = wxClient.user.get(openid) return wxUserInfo
def getWeChatOAuth(redirect_url): return WeChatOAuth(settings.AppID, settings.AppSecret, redirect_url)
def oauth(method): def warpper(request): if request.session.get('user_info', None) is None: code = request.GET.get('code', None) wechat_oauth = getWeChatOAuth(request.get_raw_uri()) url = wechat_oauth.authorize_url if code: try: wechat_oauth.fetch_access_token(code) user_info = wechat_oauth.get_user_info() except Exception as e: print(str(e)) else: request.session['user_info'] = user_info else: return redirect(url)
return method(request) return warpper
@oauth def get_wx_user_info(request): user_info = request.session.get('user_info') return HttpResponse(str(user_info))
|