微信OAuth2.0网页授权snsapi_userinfo方式java版

来源:互联网 发布:中国真实gdp季度数据 编辑:程序博客网 时间:2024/06/06 12:47

更新日期:2017.1.15日

实现条件:

1.企业认证的服务号(这里不讲解如何认证,按着微信要求来就行);
2.已经备案的域名;
3.备案域名指向的服务器;

步骤一:域名配置

登陆微信公众号,依次点击”公众号设置”—”功能设置”,点击”设置”,填写你的域名,切记,该域名一定要备案,且不能带有端口号

这里写图片描述
这里写图片描述

点击那个”MP_verify_EGe29o4NesM6yKU1.txt(点击下载)”,将会下载一个文本文档,将其放到你的网站根目录下,我用的是tomcat,放到root下面即可,保证输入”域名/MP_verify_EGe29o4NesM6yKU1.txt”能访问通就行,显示的是文本文档的内容这里我的就是”www.sygrun.com/MP_verify_EGe29o4NesM6yKU1.txt”,这里着重说一下,如果你的域名没有备案,千万不要这么干,这个微信的文本文档很坑,如果你的域名没备案,你还把这个txt放到网站下了,那么,微信会把你提交给通讯管理局,然后你的网站就上了黑名单,通过域名直接访问80端口就会失效,不得不说,真的很坑!

步骤二:构造网页授权地址

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4b3e3811a3c0a5ba&redirect_uri=https%3a%2f%2fwww.sygrun.com%2fjhzq%2fweixin%2foauth&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect

其中粗体部分,换成你自己对应的信息,我这种是需要用户手动确认授权的,可以获取详细信息,只获取open id的我觉得没啥太大意义。
上面地址中的redirect_uri是回掉地址,我的地址是https://www.sygrun.com/jhzq/weixin/oauth,就是授权之后微信会像这个地址中发请求,记得要urlEncode,网上教程一堆,我这里就不贴了,另外更方便的方法是,百度搜索在线urlEncode,地址主要是就用一次,也不怎么需要变动。

另外,微信建议使用https协议,对于那些没有https证书的亲们,可以参考http://blog.csdn.net/xt371389/article/details/54314183,免费https证书配置。但是微信并没有强制要求,只是建议,估计http协议应该也是没问题。

然后就是把这个地址挂在你想放置的地方。我放在了微信的菜单里,当然你也可以放在按钮上,超链接等。不过切记,一定是在微信里点击才好使

步骤三:回调代码

直接上代码,我这里用的是spring,另外我喜欢直接贴全码,记得上别人的博客,总是看见class,却不知道用的哪个包,

用户点击上面构造地址之后,微信会请求你的回调地址,并且带上code,
如edirect_uri/?code=CODE&state=STATE。其中state是你之前构造时候设置的参数,具体内容随意

package com.redyl.production.jhscco.action.mobile;import java.io.IOException;import javax.annotation.Resource;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.freelance.common.util.tool.JsonUtil;import com.redyl.production.jhscco.biz.weixin.AccountSetBiz;import com.redyl.production.jhscco.domain.weixin.AccountSet;import com.redyl.production.jhscco.mp.initiative.client.oauth.WeixinOauthCodeEntity;import com.redyl.production.jhscco.mp.initiative.client.oauth.WeixinOauthInfoEntity;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@Controller@RequestMapping("/weixin")public class Oauth2Action {    private static final Logger logger = LoggerFactory.getLogger(Oauth2Action.class);    @Resource    private AccountSetBiz accountSetBiz;    @RequestMapping("/oauth")    public ModelAndView auth(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {//我是从数据库里查的appid和AppSecret,其实直接填就可以        AccountSet accountSet = accountSetBiz.queryAccount(null);        String appId = accountSet.getAppId();        String appSecret = accountSet.getAppSecret();        String openid = "";        String access_token = "";//授权后跳转的页面        ModelAndView modelAndView = new ModelAndView("/weixin/oauth");//拼接        String get_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?"                + "appid="                + appId                + "&secret="                + appSecret                + "&code=CODE&grant_type=authorization_code";                //获取code        String code = request.getParameter("code");        logger.info("code" + code);        get_access_token_url = get_access_token_url.replace("CODE", code);//获得请求类httpClient         CloseableHttpClient httpClient = getHttpClient();        try {            //用get方法发送http请求            HttpGet get = new HttpGet(get_access_token_url);            logger.info("执行get请求:...." + get.getURI());            CloseableHttpResponse httpResponse = null;            //发送get请求            httpResponse = httpClient.execute(get);            try {                //response实体                HttpEntity entity = httpResponse.getEntity();                if (null != entity) {                    String json = EntityUtils.toString(entity);                    logger.info("响应状态码:" + httpResponse.getStatusLine());                    logger.info("-------------------------------------------------");                    logger.info("响应内容:" + json);                    logger.info("-------------------------------------------------");                    WeixinOauthCodeEntity weixinOauthCodeEntity = JsonUtil.fromJson(java.net.URLDecoder.decode(json, "GBK"), WeixinOauthCodeEntity.class);                    openid = weixinOauthCodeEntity.getOpenid();                    access_token = weixinOauthCodeEntity.getAccess_token();                    logger.info("获得openid为:" + openid);                    logger.info("获得access_token为:" + access_token);                }            } finally {                httpResponse.close();            }        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                closeHttpClient(httpClient);            } catch (IOException e) {                e.printStackTrace();            }        }        //拉取详细信息        String get_user_info = "https://api.weixin.qq.com/sns/userinfo?"                + "access_token=" + access_token                + "&openid=" + openid + "&lang=zh_CN";        logger.info(get_user_info);        CloseableHttpClient httpClient2 = getHttpClient();        try {            //用get方法发送http请求            HttpGet get = new HttpGet(get_user_info);            logger.info("执行get请求:...." + get.getURI());            CloseableHttpResponse httpResponse = null;            //发送get请求            httpResponse = httpClient2.execute(get);            try {                //response实体                HttpEntity entity = httpResponse.getEntity();                if (null != entity) {                    String jsons = EntityUtils.toString(entity);                    String json=new String(jsons.getBytes("ISO-8859-1"),"UTF-8");                    logger.info("响应状态码:" + httpResponse.getStatusLine());                    logger.info("-------------------------------------------------");                    logger.info("响应内容:" + json);                    logger.info("-------------------------------------------------");                    WeixinOauthInfoEntity weixinOauthInfoEntity = JsonUtil.fromJson(json, WeixinOauthInfoEntity.class);                    logger.info("城市--" + weixinOauthInfoEntity.getCity());                    logger.info("国家--" + weixinOauthInfoEntity.getCountry());                    logger.info("头像--" + weixinOauthInfoEntity.getHeadimgurl());                    logger.info("昵称--" + weixinOauthInfoEntity.getNickname());                    logger.info("省份--" + weixinOauthInfoEntity.getProvince());                    modelAndView.addObject("openid", weixinOauthInfoEntity.getOpenid());                    modelAndView.addObject("nickname", weixinOauthInfoEntity.getNickname());                    modelAndView.addObject("sex", weixinOauthInfoEntity.getSex());                    modelAndView.addObject("province", weixinOauthInfoEntity.getProvince());                    modelAndView.addObject("city", weixinOauthInfoEntity.getCity());                    modelAndView.addObject("headimgurl", weixinOauthInfoEntity.getHeadimgurl());                }            } finally {                httpResponse.close();            }        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                closeHttpClient(httpClient2);            } catch (IOException e) {                e.printStackTrace();            }        }        return modelAndView;    }    private CloseableHttpClient getHttpClient() {        return HttpClients.createDefault();    }    private void closeHttpClient(CloseableHttpClient client) throws IOException {        if (client != null) {            client.close();        }    }}
package com.redyl.production.jhscco.mp.initiative.client.oauth;/** * Created by zyw157 on 2017/1/13. */public class WeixinOauthInfoEntity {    private String openid;    private String nickname;    private String sex;    private String province;    private String city;    private String country;    private String headimgurl;    public String getOpenid() {        return openid;    }    public void setOpenid(String openid) {        this.openid = openid;    }    public String getNickname() {        return nickname;    }    public void setNickname(String nickname) {        this.nickname = nickname;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public String getProvince() {        return province;    }    public void setProvince(String province) {        this.province = province;    }    public String getCity() {        return city;    }    public void setCity(String city) {        this.city = city;    }    public String getCountry() {        return country;    }    public void setCountry(String country) {        this.country = country;    }    public String getHeadimgurl() {        return headimgurl;    }    public void setHeadimgurl(String headimgurl) {        this.headimgurl = headimgurl;    }}

特别说一点,这里微信返回的json的编码格式是ISO-8859-1,这个问题困扰了我好久,搞了一下午,所以我们需要对json转码
String json=new String(jsons.getBytes("ISO-8859-1"),"UTF-8");

最后欢迎大家提问探讨

0 0
原创粉丝点击