微信公众平台获取用户信息

     最近公司做一个活动,通过微信分享,要获取用户信息,这里涉及到微信的几个接口,顺便查了一些资料,这里记录一下微信公众账号获取用户信息的一些流程和用到的接口所需要的一些参数的含义。

    微信公众平台获取用户信息的基本原理:

    如果用户在微信中(Web微信除外)访问公众号的第三方网页,公众号开发者可以通过此接口获取当前用户基本信息(包括昵称、性别、城市、国家)。利用用户信息,可以实现体验优化、用户来源统计、帐号绑定、用户身份鉴权等功能。请注意,“获取用户基本信息接口是在用户和公众号产生消息交互时,才能根据用户OpenID获取用户基本信息,而网页授权的方式获取用户基本信息,则无需消息交互,只是用户进入到公众号的网页,就可弹出请求用户授权的界面,用户授权后,就可获得其基本信息(此过程甚至不需要用户已经关注公众号。)”。

  1. 引导用户进入授权页面同意授权,获取code
  2. 通过code换取网页授权access_token(与基础支持中的access_token不同)
  3. 如果需要,开发者可以刷新网页授权access_token,避免过期
  4. 通过网页授权access_token和openid获取用户基本信息

第一步:用户同意授权,获取code,code在这里可以理解为你在获取用户信息之前必须获得的一个钥匙,拥有了他,你才能通过其他接口获取你想要的信息。

获取code的接口:
                            
参考链接(请在微信客户端中打开此链接体验)
Scope为snsapi_base
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=http%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirect
Scope为snsapi_userinfo
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect

参数说明

参数是否必须说明
appid公众号的唯一标识
redirect_uri授权后重定向的回调链接地址,请使用urlencode对链接进行处理 比如是在朋友圈分享的一个活动链接,这个参数的值就是那个活动的url地址
response_type返回类型,请填写code
scope应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息
state重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值
#wechat_redirect无论直接打开还是做页面302重定向时候,必须带此参数

下图为scope等于snsapi_userinfo时的授权页面:

网页授权

用户同意授权后

如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数redirect_uri?state=STATE

code说明 :
code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。

第二步:通过code换取网页授权access_token

首先请注意,这里通过code换取的网页授权access_token,与基础支持中的access_token不同。公众号可通过下述接口来获取网页授权access_token。如果网页授权的作用域为snsapi_base,则本步骤中获取到网页授权access_token的同时,也获取到了openid,snsapi_base式的网页授权流程即到此为止。  

请求方法

获取code后,请求以下链接获取access_token: 
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

参数说明

参数是否必须说明
appid公众号的唯一标识,相当于用户名
secret公众号的appsecret,

App Secret简称API接口密钥,是跟App Key配套使用的,可以简单理解成是密码 

code填写第一步获取的code参数
grant_type填写为authorization_code

返回说明

正确时返回的JSON数据包如下:

{
   "access_token":"ACCESS_TOKEN",
   "expires_in":7200,
   "refresh_token":"REFRESH_TOKEN",
   "openid":"OPENID",
   "scope":"SCOPE"
}
参数描述
access_token网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
expires_inaccess_token接口调用凭证超时时间,单位(秒)
refresh_token用户刷新access_token
openid用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID
scope用户授权的作用域,使用逗号(,)分隔


错误时微信会返回JSON数据包如下(示例为Code无效错误):

{"errcode":40029,"errmsg":"invalid code"}

第三步:刷新access_token(如果需要)

由于access_token拥有较短的有效期,当access_token超时后,可以使用refresh_token进行刷新,refresh_token拥有较长的有效期(7天、30天、60天、90天),当refresh_token失效的后,需要用户重新授权。

请求方法

获取第二步的refresh_token后,请求以下链接获取access_token: 
https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
参数是否必须说明
appid公众号的唯一标识
grant_type填写为refresh_token
refresh_token填写通过access_token获取到的refresh_token参数

返回说明

正确时返回的JSON数据包如下:

{
   "access_token":"ACCESS_TOKEN",
   "expires_in":7200,
   "refresh_token":"REFRESH_TOKEN",
   "openid":"OPENID",
   "scope":"SCOPE"
}
参数描述
access_token网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
expires_inaccess_token接口调用凭证超时时间,单位(秒)
refresh_token用户刷新access_token
openid用户唯一标识
scope用户授权的作用域,使用逗号(,)分隔


错误时微信会返回JSON数据包如下(示例为Code无效错误):

{"errcode":40029,"errmsg":"invalid code"}

全局返回码说明

第四步:拉取用户信息(需scope为 snsapi_userinfo)

如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了。

请求方法

http:GET(请使用https协议)
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

参数说明

参数描述
access_token网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
openid用户的唯一标识
lang返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语

返回说明

正确时返回的JSON数据包如下:

{
   "openid":" OPENID",
   " nickname": NICKNAME,
   "sex":"1",
   "province":"PROVINCE"
   "city":"CITY",
   "country":"COUNTRY",
    "headimgurl":    "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46", 
	"privilege":[
	"PRIVILEGE1"
	"PRIVILEGE2"
    ]
    "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
参数描述
openid用户的唯一标识
nickname用户昵称
sex用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
province用户个人资料填写的省份
city普通用户个人资料填写的城市
country国家,如中国为CN
headimgurl用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空
privilege用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
unionid只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。详见:获取用户个人信息(UnionID机制)


错误时微信会返回JSON数据包如下(示例为openid无效):

{"errcode":40003,"errmsg":" invalid openid "}


下面是获取用户信息的部分源码:
第一步应该是获取code,我这里没有源码,但前面已经给出接口了。
 
public ModelAndView getWeixinInfo(HttpServletRequest request,HttpServletResponse response)
	{
		ModelAndView mv=new ModelAndView("/activity/template/weixin_test.jsp");
		String code=request.getParameter("code");
		//公众账号的id,相当于用户名
		String appid="qq123456";
		//在申请公共账号时,微信平台给的一个相当于密码
		String appsecret="da154d5a4d5asd5ad4";
		String res1="",res2="",url1="",url2="";
		String access_token="";
		String openid="";
		url1="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+appsecret+"&code="+code+"&grant_type=authorization_code";
		res1=StringUtil.getUrlTxtWithCharSet(url1,"GBK");
		
		JSONObject object=null;
		try {
			object = new JSONObject(res1);
			access_token=object.get("access_token").toString();
			openid=object.getString("openid").toString();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		url2="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
		res2=StringUtil.getUrlTxtWithCharSet("https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN","utf-8",3000,3000);
		JSONObject userInfo=null;
		try {
			//获取用户信息
			userInfo = new JSONObject(res2);
			openid=userInfo.get("openid ").toString();
			String nickname=userInfo.getString("nickname ").toString();
			String sex =userInfo.getString("sex").toString();
			String city =userInfo.getString("city").toString();
			String headimgurl  =userInfo.getString("headimgurl").toString();
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		request.setAttribute("res1", res1);
		request.setAttribute("res2", res2);
		request.setAttribute("url1",url1 );
		request.setAttribute("url2",url2 );
		request.setAttribute("access_token",access_token );
		request.setAttribute("openid", openid);
		return mv;
	}


     
getUrlTxtWithCharSet方法:
       <pre name="code" class="java">public static String  getUrlTxtWithCharSet(String strurl,String CharSet) {
		return getUrlTxtWithCharSet(strurl, CharSet, 0, 0);
	}
	
	public static String  getUrlTxtWithCharSet(String strurl,String CharSet,int connDelay,int readDelay) {
		StringBuffer sb=new StringBuffer();
		BufferedReader reader=null;
		String line=null;
		String result = "";
		String contentType = "";
		System.out.println("request:"+strurl);
		try {
			URL url=new URL(strurl);
			HttpURLConnection connection=(HttpURLConnection)url.openConnection();
			if(connDelay!=0&&readDelay!=0)
			{
				connection.setConnectTimeout(connDelay);
				connection.setReadTimeout(readDelay);
			}
//			connection.setRequestMethod("GET");
//			connection.setDoOutput(true);
//			connection.setDoInput(true);
//			OutputStream os = connection.getOutputStream();
			reader=new BufferedReader(new InputStreamReader(connection.getInputStream(),CharSet));		
			while ((line=reader.readLine())!=null) {
				sb.append(line);
			}
			result = sb.toString();
			contentType = connection.getContentType();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			MailUtil.sendGetUrlTxtExceptionMail(e, strurl, result);
		}
		try{
			contentType = ((contentType==null)?"":contentType);
			if(!StringUtil.isNullStr(result) && contentType.contains("text/xml")){
				//检查xml是否正确,不正确则发邮件
//				DocumentHelper.parseText(result);
				SAXBuilder builder = new SAXBuilder();
				builder.build(new StringReader(result));
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			MailUtil.sendGetUrlTxtExceptionMail(null, strurl, result);
		}
		finally{
			try {
				reader.close();
			} catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
		}
		return result;
		
	}

     这部分源码少了获取code的那一步。 
    本来想写点自己的见解的,谁知写起来后都是复制粘贴的,觉得有点失败,感觉还是没有研究透彻,没有成为自己的东西,如果你看到这篇文章,觉得对自己有帮助,我就非常高兴了。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值