获取用户信息,须要获取 access_token、openidredis
而后调用接口https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CNjson
access_token:公众号的全局惟一票据,
api
获取access_token,须要调用https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRETapp
参数 | 是否必须 | 说明 |
---|---|---|
grant_type | 是 | 获取access_token填写client_credential |
appid | 是 | 第三方用户惟一凭证 |
secret | 是 | 第三方用户惟一凭证密钥,即appsecret |
获取openid须要先获取code,url
获取code须要调用接口spa
https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=如今访问的方法的url&response_type=code&scope=snsapi_userinfo&state=STATEcode
获取code后,orm
再调用接口https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid&secret=secret&code=code&grant_type=authorization_code以获取openid对象
具体代码
def get_user_id(self,code):
"""
获取code
openid
:return:
"""
#getwx() 方法获取appid
wxinfo = self.getwx()
#获取正在访问的模块的路径(手机上的)
urls="{}://{}{}".format(self.request.protocol,self.request.host,self.request.uri)
#获取code
if code == 'mistake':
codeurl='https://open.weixin.qq.com/connect/oauth2/authorize?appid='+wxinfo['appid']+'&redirect_uri={}&response_type=code&scope=snsapi_userinfo&state=STATE'.format(urls)
self.redirect(codeurl)
else:
#若是存在code 则调用weixin()函数,获取openid
openid=self.weixin(code)
return openid
def getwx(self):
"""
#获取appid和secret
:return:
"""
db_wx = self.db.query(Wx)
db_wx = db_wx.first()
return {'appid':db_wx.appid,'secret':db_wx.secret}
def weixin(self,code):
"""
获取openid :普通用户的标识,对当前公众号惟一
:return:
"""
#getwx() 方法获取appid和secret
wxinfo = self.getwx()
opidurl="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+wxinfo['appid']+"&secret="+wxinfo['secret']+"&code="+code+"&grant_type=authorization_code"
#先使用opreq = urllib2.Request(opidurl)实例化一个resquest对象,
opreq = urllib2.Request(opidurl)
#接下来使用urllib2.urlopen(opreq)来打开这个网页
opreq_data = urllib2.urlopen(opreq)
#read() 不带参数的read是将文件全部内容读入到 一个字符串中
opres = opreq_data.read()
opres=json_decode(opres)
openid= opres['openid']
return openid
def accesstokens(self):
"""
获取 token
token:access_token是公众号的全局惟一票据
:return:
"""
token = self.redis.get("wx_token")
if not token:
#getwx() 方法获取appid和secret
wxinfo = self.getwx()
url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+wxinfo['appid']+"&secret="+wxinfo['secret']+""
req = urllib2.Request(url)
res_data = urllib2.urlopen(req)
res = res_data.read()
res=json_decode(res)
token=str(res['access_token'])
self.redis.set("wx_token",token,ex=3600)
return token