微信授权获取微信用户个人信息

因为经常要用进行微信H5开发,所以对网页授权做下记录

准备: 需要一个已认证的微信服务号(认证貌似要交钱的)
然后进入微信公共平台进行设置

1.设置域名目录http://www.cnblogs.com/txw1958/p/weixin71-oauth20.html

2.获取appid 和 secret http://jingyan.baidu.com/article/6525d4b12af618ac7c2e9468.html

开发:

1.发起微信授权请求

https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={回调地址}&response_type=code&scope=snsapi_userinfo&state={自定义参数}&connect_redirect=1#wechat_redirect
成功发起的话 微信会将一个code和state(原样返回)给你的回调地址

2.上面的回调地址中进行处理

    a.请求access_token和openid
String uri = "https://api.weixin.qq.com/sns/oauth2/access_token";
PostMethod postMethod = new PostMethod(uri);
postMethod.setParameter("appid", appid);
postMethod.setParameter("secret", secret);
postMethod.setParameter("code", code);
postMethod.setParameter("grant_type", "authorization_code");

int statusCode = httpClient.executeMethod(postMethod);
if(statusCode == HttpStatus.SC_OK){
String result = T.stringValue(postMethod.getResponseBodyAsString(),"");
access_token = JsonUtils.getText(result, "access_token");
openid = JsonUtils.getText(result, "openid");
}

b.通过access_token和openid获取用户信息

uri = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
使用httpclient调用 返回的是一个json对象其中nickname是昵称headimgurl是头像地址

3.程序的其他处理

1.必须用utf-8编码(昵称中某些表情符号解析会有问题)
2.可以将获取的用户信息保存下来,对于同一个微信用户在同一个服务号下的openid是不变且唯一的

你可能感兴趣的:(微信授权获取微信用户个人信息)