1.打開pycharm-->新建django項目
項目文檔結構如下:
執行遷移命令 生成數據庫
python manage.py makemigrations python manage.py migrate
2.安裝微信框架wechatpy
官方文檔:https://wechatpy.readthedocs.io/zh_CN/master/install.html
pip install wechatpy # with cryptography (推薦) pip install wechatpy[cryptography] # with pycryptodome pip install wechatpy[pycrypto]
3.內外網穿透
使用工具花生殼下載地址:https://hsk.oray.com/download/
設置內網ip和端口
4.登錄微信服務號設置可信域名-IP白名單
1.微信設置-->公眾號設置
2.點擊業務域名
3.瀏覽器訪問如下, 確認無誤點擊保存按鈕
4.以此設置可信域名
5.設置IP白名單
微信設置-->安全中心-->點擊查看
5.獲取微信用戶信息
微信服務號后台-->開發-->基本設置-->查看服務號appid
請求地址url:http://i157422s94.iok.la/userinfo
微信地址:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx975992a7ef6d6c9d&redirect_uri=http%3A%2F%2Fi157422s94.iok.la%2Fuserinfo&response_type=code&scope=snsapi_userinfo#wechat_redirect
微信掃碼查看實例:
效果圖:
源碼
wechatDemo-->urls.py
"""wechatDemo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app import views urlpatterns = [ path('admin/', admin.site.urls), # 微信認證文件建議使用nginx配置 path('MP_verify_b1reLtO1xRzEjqxJ.txt', views.wechatauth), # 微信登錄頁面userinfo path('userinfo', views.userinfo), ]
app-->views.py
from wechatpy.oauth import WeChatOAuth from django.shortcuts import render, redirect from django.http import JsonResponse, HttpResponse, HttpResponseRedirect # Create your views here. AppID = "服務號APPID" AppSecret = "服務號AppSecret" # 微信認證文件,建議通過nginx配置 def wechatauth(request): return HttpResponse("b1reLtO1xRzEjqxJ") # 定義授權裝飾器 def getWeChatOAuth(redirect_url): return WeChatOAuth(AppID, AppSecret, redirect_url, 'snsapi_userinfo') 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 print(url) if code: try: wechat_oauth.fetch_access_token(code) user_info = wechat_oauth.get_user_info() print(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 # 獲取用戶信息UserInfo @oauth def userinfo(request): user_info = request.session.get('user_info') return render(request, 'userinfo.html', {"user_info": user_info})
templates-->userinfo.html
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>用戶信息</title> <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0" name="viewport"/> <meta content="yes" name="apple-mobile-web-app-capable"/> <meta content="black" name="apple-mobile-web-app-status-bar-style"/> <meta content="telephone=no" name="format-detection"/> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- 可選的 Bootstrap 主題文件(一般不用引入) --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </head> <body> <div class="container-fluid"> <table class="table table-bordered table-striped"> <thead> <tr> <th>屬性</th> <th>值</th> </tr> </thead> <tbody> <tr> <th scope="row"> <code>微信頭像</code> </th> <td><img src="{{ user_info.headimgurl }}" alt=""/></td> </tr> <tr> <th scope="row"> <code>openid</code> </th> <td>{{ user_info.openid }}</td> </tr> <tr> <th scope="row"> <code>昵稱</code> </th> <td>{{ user_info.nickname }}</td> </tr> <tr> <th scope="row"> <code>性別</code> </th> <td>{{ user_info.sex }}</td> </tr> <tr> <th scope="row"> <code>語言</code> </th> <td>{{ user_info.language }}</td> </tr> <tr> <th scope="row"> <code>城市</code> </th> <td>{{ user_info.country }}-{{ user_info.province }}-{{ user_info.city }}</td> </tr> <tr> <th scope="row"> <code>標簽</code> </th> <td>{{ user_info.privilege }}</td> </tr> </tbody> </table> </div> </body> </html>