微信公众号 网页授权开发

来源:互联网 发布:淘宝网女士夏季服装 编辑:程序博客网 时间:2024/05/19 04:06

自己第一篇有关技术的文章,写出来是为了不忘记,记录一下。同样也希望大家能一起讨论讨论。(博主用的是Java)

微信公众平台 开发文档中网页授权https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

博主来大概组织一下来怎么描述这个接口吧,能看懂我就不描述了(spring & spring-mvc环境下)。

@RequestMapping("login")
public String toLogin(HttpServletRequest request,HttpServletResponse response ) throws Exception{

String appID ="微信公众号appid";
String appSecret ="微信公众号appSecret";

String code = request.getParameter("code");
String openid = null;


//1、微信公众号要跳转的链接,后台对应的代码中,首先获取code,如果code不存在,则进行重定向
if(code == null){
String str = request.getRequestURL().toString();
//授权重定向
//str = java.net.URLEncoder.encode(str);
String url2 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appID+"&redirect_uri="+str+"&response_type=code&scope=snsapi_userinfo&state=9144#wechat_redirect";
response.sendRedirect(url2);
return null;
}
//2、重定向后的链接是用户授权的页面,用户点击同意授权后,会重定向上面要跳转的链接 str
//获取用户openid,access_token
HttpClientBase hcb = new HttpClientBase();
hcb.setCharset("utf-8");

String jsondata = hcb.get("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appID+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code");
//3、通过调用该接口就能获取到用户的opendid和用户access_token
JSONObject jsobj = new JSONObject(jsondata);
if(jsobj.has("openid")&&jsobj.has("access_token")){
openid = jsobj.getString("openid");
String access_token = jsobj.getString("access_token");
request.getSession().setAttribute("openid", openid);
String url="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
//4、调用该接口获取用户的资料
String jsondata2 = hcb.get(url);
JSONObject jsobj2=new JSONObject(jsondata2);
/* openid 用户的唯一标识
nickname 用户昵称
sex 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
province 用户个人资料填写的省份
city 普通用户个人资料填写的城市
country 国家,如中国为CN
headimgurl 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。
privilege 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)

unionid 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。*/

String nickname=jsobj2.getString("nickname");
String headimgurl=jsobj2.getString("headimgurl");//用户头像的url

}
//JSONObject 用的是阿里巴巴的 HttpClientBase自己写的类,上网搜一下HttpClient怎么用就可以了,不用写得太复杂
/*----------------------------------------------------------------------------------*/


return "magicbookproject/index";
}

阅读全文
0 0
原创粉丝点击