2022年 11月 3日

python中实现微信登录

微信登录流程图:

视频效果:

flask项目实现微信登录

1. view代码

  1. from flask import Flask, render_template
  2. from flask import Markup
  3. from flask import redirect
  4. from flask import request
  5. from flask import jsonify
  6. from python_weixin_master.weixin.client import WeixinAPI
  7. # from python_weixin_master.weixin.oauth2 import OAuth2AuthExchangeError
  8. app = Flask(__name__)
  9. APP_ID = 'wxa77a00333cd8d99a'
  10. APP_SECRET = '6f616f770203c4cc930829f6fdfc2396'
  11. REDIRECT_URI = 'http://127.0.0.1:5000/role'
  12. @app.route("/role")
  13. def role():
  14. code = request.args.get('code')
  15. api = WeixinAPI(appid=APP_ID,
  16. app_secret=APP_SECRET,
  17. redirect_uri=REDIRECT_URI)
  18. auth_info = api.exchange_code_for_access_token(code=code)
  19. """
  20. auth_info = {
  21. 'access_token': 'OezXcEiiBSKSxW0eoylIsl6sxHRfhXg1no5ObdGufYhRIubP2m3FUdv-Cop3t3S_xwMbBWQ',
  22. 'refresh_token': 'OezXcEiiBSKSxW0eoylIeGXVsfdajniiwsVJiT7fTv7j5jCAxg',
  23. 'openid': u'oV02tuA8Wt6Kk7S0pVydThYvmSJA',
  24. 'expires_in': 7200,
  25. 'scope': u'snsapi_login'}
  26. """
  27. api = WeixinAPI(access_token=auth_info['access_token'])
  28. resp = api.user(openid=auth_info['openid'])
  29. # 此时的resp中已经获取到了用户的所有信息:dict类型
  30. # openid,nickname,sex,language,city,province,country,headimagurl
  31. # print(resp)
  32. # 校验access_token是否过期
  33. # v = api.validate_token(openid=auth_info['openid'])
  34. # print(v) # :{'errcode': 0, 'errmsg': 'ok'}
  35. # return jsonify(resp)
  36. return render_template("index.html", **resp)
  37. # @app.route("/login")
  38. # def login():
  39. # api = WeixinAPI(appid=APP_ID,
  40. # app_secret=APP_SECRET,
  41. # redirect_uri=REDIRECT_URI)
  42. # redirect_uri = api.get_authorize_login_url(scope=("snsapi_base",))
  43. # return redirect(redirect_uri)
  44. @app.route("/wx_login")
  45. def login():
  46. return render_template("wx.html")
  47. if __name__ == "__main__":
  48. app.run(debug=True)

2. wx.html代码

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title></title>
  6. <script src="static/jquery-1.12.4.min.js"></script>
  7. </head>
  8. <body>
  9. <button id="wx_login">微信登录</button>
  10. <script>
  11. $("#wx_login").click(function () {
  12. {#let url = encodeURIComponent(window.location.href); // 注意一定要encodeURIComponent#}
  13. let url = encodeURIComponent("http://127.0.0.1:5000/role"); // 注意一定要encodeURIComponent
  14. let url2 =
  15. `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa77a00333cd8d99a&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect`
  16. window.location.href = url2
  17. })
  18. </script>
  19. </body>
  20. </html>

3. index.html代码

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>微信登录成功页面</title>
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. </head>
  8. <body>
  9. {# {#}
  10. {# "city": "Tongzhou",#}
  11. {# "country": "CN",#}
  12. {# "headimgurl": "https://thirdwx.qlogo.cn/mmopen/vi_32/ibucZH2uiaQEMMzNB4M5ibQa2snJo79SibExXxLymQLrAAdO6KxXkO7qzBwGEkdOWXL4sic1DoeGut9uUShF7WUibicDA/132",#}
  13. {# "language": "zh_CN",#}
  14. {# "nickname": "M\u20f0a\u20f0y\u20f0a\u20f0n\u20f0a\u20f0n\u20f0",#}
  15. {# "openid": "o3uhR6v4Py3UGLtQGWzsmp9IgEfo",#}
  16. {# "privilege": [],#}
  17. {# "province": "Beijing",#}
  18. {# "sex": 1#}
  19. {#}#}
  20. <img src="{{ headimgurl }}" alt="头像"> <br>
  21. 国家:{{ country }}<br>
  22. 省份:{{ province }}<br>
  23. 城市:{{ city }}<br>
  24. 昵称:{{ nickname }}<br>
  25. 性别:{% if sex == 1 %}男{% elif sex == 0 %}女{% else %}未知{% endif %}
  26. </body>
  27. </html>

 

3.  依赖包需要下载下来放到环境中的site-packages里面

下载地址:https://github.com/mayanan-python/weixin-login

4. 微信公众平台链接:

http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

5. 此处需要关注:

6. 此处需要设置项目的根url:

 此处写域名和端口号

7. 项目依赖

  1. flask
  2. simplejson
  3. requests
  4. chardet
  5. six
  6. xmltodict
  7. pycryptodome
  8. requests_pkcs12