阅读微信开放文档可知,如果只要获取用户openid,建立数据库存储用户信息,实现下图流程即可,
前端引导用户点击链接:https://open.weixin.qq.com/connect/oauth2/authorize?appid=填写你的appid&redirect_uri=填写你的回调地址,即获取code之后要到哪里&response_type=code&scope=snsapi_base&state=1#wechat_redirect
后端代码如下:下面的代码填写公众号appid和secret即可使用
# -*- encoding:utf-8-*-
import os
import sys
import json
import web
import requests
# 1 第一步:用户同意授权,获取code
# 2 第二步:通过code换取网页授权access_token
# 3 第三步:刷新access_token(如果需要)
# 4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
# 5 附:检验授权凭证(access_token)是否有效
render=web.template.render("templates") #这是前端页面,即最终用户看到的页面,templates是html所在文件夹,如不需要可删去此行
class Getopenid(object):
def GET(self):
data=web.input()
if len(data)==0:
return "请重新点击链接"
self.appid = '' # 填写你的公众号appid
self.secret = '' # 填写你的公众号secret
code=data.code #获取微信服务器返回的code
#https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code,这是微信开放文档中说明的以此获取用户信息
get_access_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code' % (
self.appid, self.secret, code)
result = requests.get(get_access_url)
result = result.json()
openid = result["openid"] #到这里就得到了openid
return render.reg(openid) #将openid返回到前端,reg是html文件名称,openid是返回参数,如不需要可删去此行
接着上一篇微信开发公众号博客到目前为止,实现的功能是:测试号和后端服务器绑定,获取用户openid返回前端
整个逻辑框架如下图:
info文件下:
其中_init_.py是空白文件,具体了解python语法
templates文件下:
其中reg.html就是上面的代码所指的html文件,具体可以了解web.py文档中的render。 https://webpy.org/docs/0.3/templetor
main.py代码:
# -*- coding: utf-8 -*-
# filename: main.py
import web
import json
import time
import requests
from handle import Handle #这些是根据我的文件放置import,具体改成你的
from handle import test_send
import access_token
from handle import Handle
from test.test import test
from info.getOpenid import Getopenid
from mysql.insertMysql import Mysql
from altermysql.mysql import AlterMysql
from alterinfo.getopenid import getopenid
from InfoAlterGetOpenid.getOpenid import Getopenid2
urls = (
'/wx', 'Handle',
'/test', 'test_send',
'/myweb/info','Getopenid', #主要是这里,引导用户点击完链接获取code之后,我的回调地址是回到这里,所以我填写的是http://e441d4bf.ngrok.io/myweb/info
'/myweb/test','test',
'/myweb/mysql','Mysql',
'/myweb/altermysql','AlterMysql',
'/myweb/alteropenid','getopenid',
'/myweb/InfoAlterGetOpenid','Getopenid'
)
if __name__ == '__main__':
app = web.application(urls, globals())
app.run()
到这里就完成了图示的①②③④⑤个步骤了