微信获取用户的openid和详细信息
2014-08-13 16:41
686 查看
获取用户的信息的原理,首先用户会点击一个url,这个url会包含一个参数redirect_uri,这个url是指向微信那边的服务器的,然后微信会把这个http请求重定向到redirect_uri,即我们的后端,而且会附带一个code参数,如果我们需要获取用户的基础信息(也就是openid)就需要用这个code去访问微信的指定url来请求用户的openid,如果我们需要获取用户的详细信息(微信名称,头像),我们就需要先用code获取一个access_token,再用这个access_token来获取用户的信息
获取用户点击的那个url的方法:
#encoding=utf-8 __author__ = 'kevinlu1010@qq.com' def get_redirect_url(uri, is_info=0): ''' 获取url,改url可以访问微信的网址,然后会重定向回来我们的网址,而且附带访问的微信用户的信息 uri 需要跳转到的uri 如/cherrs is_info 是否获取详细信息,如果为1,就获取用户的详细信息,包括名字,图片,否则就获取基本信息,只有open_id 返回 url ''' pre_url = 'http://xxxx.xxxxx.com' appid = 'wxxxxxxxxxxxxxxxxxeb' scope = 'snsapi_userinfo' if is_info else 'snsapi_base' data = {'redirect_uri': pre_url + uri, 'appid': appid, 'response_type': 'code', 'scope': scope, 'state': '123'} urlencode = urllib.urlencode(data) wei_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' + urlencode + '#wechat_redirect' return wei_url
通过code获取用户open_id
def get_base_info(code): ''' 通过获取的code,访问微信的api,获取用户基本信息(只有openid) return 用户的open id ''' if not code: return '' url = 'https://api.weixin.qq.com/sns/oauth2/access_token' try: data = {'appid': const.appid, 'secret': const.secret, 'code': code, 'grant_type': 'authorization_code'} post_body = urllib.urlencode(data) f = urllib2.urlopen(url, post_body).read() r = ast.literal_eval(f) #字符串转换成字典 return r['openid'] except: return ''
通过code获取用户详细信息:
def get_detail_info(code): ''' 获取用户的详细信息 return dict {'userID':'','nickname':''m',headimgurl':''} ''' ret = {} url = 'https://api.weixin.qq.com/sns/oauth2/access_token' try: data = {'appid': const.appid, 'secret': const.secret, 'code': code, 'grant_type': 'authorization_code'} post_body = urllib.urlencode(data) f = urllib2.urlopen(url, post_body).read() r = ast.literal_eval(f) #字符串转换成字典 #获取用户详细信息 access_token = r['access_token'] ret['userID'] = r['openid'] url = 'https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN' % ( access_token, ret['userID']) f = urllib2.urlopen(url).read() r = ast.literal_eval(f) #字符串转换成字典 ret['nickname'] = urllib.unquote(r['nickname']) ret['headimgurl'] = urllib.unquote(r['headimgurl']) except urllib2.URLError, e: return ret return ret
相关文章推荐
- 微信小程序授权获取用户详细信息openid的实例详解
- 微信小程序授权获取用户详细信息openid的实例详解
- 微信小程序授权获取用户详细信息openid
- 微信小程序授权获取用户详细信息openid的实例详解
- 微信开发笔记:获取用户openid,以及用户头像昵称等信息
- 微信小程序 获取用户信息(包括openId等敏感信息)
- 微信开发--怎么获取用户的信息(openid)
- 微信小程序如何获取openid及用户信息
- 微信——获取用户基本信息及openid 、access_token、code
- PHP如何获取微信用户的 openid 和基本信息
- 微信公众号开发获取openID以及用户详细信息,超详细步骤,亲测开发
- java 更具用户微信openId获取用户基本信息
- [004]微信公众账号开发教程第1篇-根据用户openID获取用户基本信息
- 微信接口-获取用户openid基本信息
- 微信获取openID和用户信息
- .NET微信开发通过Access Token和OpenID获取用户信息
- 微信小程序开发之获取openid及用户信息
- 微信小程序 获取用户信息(包括openId等敏感信息)
- [置顶] java微信开发-之如何获取openid 和用户信息
- C#微信开发之旅(八):通过授权code以及openid获取用户信息