python 微信开发入门篇-获取微信用户信息(一)
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>