Django+wechatpy接入微信公衆平臺以及受權登陸

  1. 肯定Django環境能夠正常運行,環境搭建見:Linux 搭建Nginx+uwsgi+Django環境
  2. 安裝 wechatpy[cryptography]html

    sudo pip3 install wechatpy[cryptography]
  3. 修改settings.py
    1. 接入微信公衆號的鏈接去掉csrf驗證,詳情參考:解決Django+Vue先後端分離的跨域問題及關閉csrf驗證的後半部分
    2. 在settings.py 加入微信公衆號配置python

      AppID = ''
      AppSecret = ''
      Token = ''
  4. 接入
    1. Django接入微信公衆號代碼數據庫

      # wx.view代碼
      
      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
      
      
      # 鏈接微信公衆號的方法
      def serve(request):
          # GET 方式用於微信公衆平臺綁定驗證
          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(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':
                          # 關注後 將獲取的用戶的信息保存到數據庫
                      wx_wechat.subscribe(getWxUserInfo(msg.source))
                  elif msg_dict['Event'] == 'unsubscribe':
                          # 取關後,將用戶的關注狀態更改成 未關注
                      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):
          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))
                          # 這裏須要處理請求裏包含的 code 無效的狀況
                          # 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))
      # wx.url代碼
      from django.urls import path
      from . import views
      
      urlpatterns = [
          path('wechat/', views.serve),
      
          path('user/info', views.get_wx_user_info)
      ]

      這樣等後臺配置完畢後,就能夠經過訪問get_wx_user_info方法來獲取當前受權登陸的用戶的信息django

    2. 微信後臺設置
      1. 參考:接入指南
      2. 微信公衆平臺後臺登陸地址
        1. 正式地址
        2. 測試帳號地址

如需轉載請註明出處:http://www.javashuo.com/article/p-rotgjiet-kd.html後端

相關文章
相關標籤/搜索