上代码
后端Python程序
# coding:utf-8
from flask import Flask, request, abort, render_template
import urllib2
import json
app = Flask(__name__)
WECHAT_APPID = "自己的appid"
WECHAT_APPSECRET = "自己的appsecret"
@app.route("/wechat8000/index")
def index():
"""主页"""
code = request.args.get("code")
if code is None:
abort(400)
# 向微信获取access_token
url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code" \
% (WECHAT_APPID, WECHAT_APPSECRET, code)
resp = urllib2.urlopen(url)
# 微信返回的数据是json格式的
resp_json_data = resp.read()
resp_dict_data = json.loads(resp_json_data)
# 提取access_token
access_token = resp_dict_data.get("access_token")
if not access_token:
return resp_dict_data.get("errmsg")
else:
open_id = resp_dict_data.get("openid")
# 向微信获取用户资料
url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN" % (access_token, open_id)
resp = urllib2.urlopen(url)
user_json_data = resp.read()
user_dict_data = json.loads(user_json_data)
if "errcode" in user_dict_data:
return resp_dict_data.get("errmsg")
else:
return render_template("index.html", user=user_dict_data)
if __name__ == '__main__':
app.run(port=8000, debug=True)
前端index.html文件代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{user["nickname"]}}的个人主页</title>
</head>
<body>
<img alt="头像" src="{{user['headimgurl']}}" width="60">
<table>
<tr>
<th>openid</th>
<td>{{user["openid"]}}</td>
</tr>
<tr>
<th>昵称</th>
<td>{{user["nickname"]}}</td>
</tr>
<tr>
<th>性别</th>
<td>
{% if 1 == user["sex"] %}
男
{% elif 2 == user["sex"] %}
女
{% else %}
未知
{% endif %}
</td>
</tr>
<tr>
<th>省份</th>
<td>{{user["province"]}}</td>
</tr>
<tr>
<th>城市</th>
<td>{{user["city"]}}</td>
</tr>
<tr>
<th>国家</th>
<td>{{user["country"]}}</td>
</tr>
</table>
</body>
</html>