微信——獲取用戶基本信息及openid 、access_token、code

獲取用戶信息,須要獲取 access_tokenopenidredis

而後調用接口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:普通用戶的標識,對當前公衆號惟一函數

獲取openid須要先獲取codeurl

獲取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
相關文章
相關標籤/搜索