Customized development of WeChat public address

1, configure public number - Development - Web Services - webpage authorization - modify Authorized access to basic user information Authorized domain name (Note: public number automatic recovery development, need to open server configuration, separate access to user information is not required. jssdk is a white list authorization management. )

2. Menu access: when accessing http:// XXX / - user/info, the user is authorized. After authorization, the user will jump to http://XXX/home?code=xxx (configuration). At this time, call http:// XXX / - user/info again to get the user information and put it into the session (for later interface access)

Code reference:

     

# setting.py

AppID = ''
AppSecret = ''
Token = ''


# view.py

# wx.view Code

from wechatpy.utils import check_signature
from back 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

import wx.wechat as wx_wechat


# The way to connect WeChat public numbers
def serve(request):
    # GET Method for wechat public platform binding verification
    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 = 'Bad request'
        response = HttpResponse(echo_str)
    else:

        msg = parse_message(request.body)
        msg_dict = msg.__dict__['_data']
        # print(msg.id, msg.source, msg.create_time, msg.type, msg.target, msg.time, msg.__dict__['_data']['Event'], '====')
        if msg.type == 'text':
            pass
        elif msg.type == 'event':
            if msg_dict['Event'] == 'subscribe':
                    # After paying attention, save the obtained user's information to the database
                wx_wechat.subscribe(getWxUserInfo(msg.source))
            elif msg_dict['Event'] == 'unsubscribe':
                    # After taking off, change the user's attention status to no attention
                wx_wechat.unsubscribe(msg.source)
        else:
            pass
        response = HttpResponse('', 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):
    # redirect_url = "Domain name to jump: dayu1.net/home"
    return WeChatOAuth(settings.AppID, settings.AppSecret, redirect_url, scope='snsapi_userinfo ')

# Define authorization decorator
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))
                    # Here we need to deal with the code Invalid situation
                    # abort(403)
                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))



# url To configure

# wx.url Code
from django.urls import path
from . import views

urlpatterns = [
    path('wechat/', views.serve),

    path('user/info', views.get_wx_user_info)
]

Tags: Python Session Django Database xml

Posted on Tue, 05 Nov 2019 12:06:12 -0800 by steeveherris