微信——获取用户基本信息及openid 、access_token、code

获取用户信息,需要获取 access_tokenopenid

然后调用接口https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

access_token:公众号的全局唯一票据,

获取access_token,需要调用https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

参数是否必须说明
grant_type 获取access_token填写client_credential
appid 第三方用户唯一凭证
secret 第三方用户唯一凭证密钥,即appsecret

openid:普通用户的标识,对当前公众号唯一

获取openid需要先获取code

获取code需要调用接口

https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=现在访问的方法的url&response_type=code&scope=snsapi_userinfo&state=STATE

获取code后,

再调用接口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

 

posted @ 2016-02-19 15:52  我是那叶子  阅读(33168)  评论(0编辑  收藏  举报