天天看点

微信静默获取openid

一、获取Appid和APPsecret备用

登录微信公众平台 > 基本配置
微信静默获取openid
注意:现版本微信公众平台不再保存APPsecret,获取之后如果丢失就要重置才能重新获取,请妥善保管。

二、配置网页授权域名

登录微信公众平台 > 公众号设置 > 功能设置 > 网页授权域名
微信静默获取openid

下载下来的文件放在项目文件夹根目录!服务器必须配置到80端口!

以tomcat为例,假设域名为www.abc.com,项目名为ary:

  1. 将域名和ip绑定,tomcat端口配置为80
  2. 将ary.war放到webapps下
  3. 启动tomcat解压war包
  4. 将文件放到ary文件夹下
  5. 将授权域名设置为www.abc.com/ary(注意不要http://)
  6. 在微信客户端中打开
    https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=http://www.abc.com/ary&response_type=code&scope=snsapi_base#wechat_redirect      
    测试是否配置成功(此处redirect_uri需要加http://,否则会出现redirect_uri与配置不同的错误)

三、关键代码

    1、回调方法

    /**
     * 微信回调
     * @param request
     * @param response
     */
    @RequestMapping("/callBack")
    public void callBack(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取其他参数
            Integer id = Integer.parseInt(request.getParameter("id"));
            // 调用微信授权跳转获取openid
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            request.setCharacterEncoding("UTF-8");
            //这里要将你的授权回调地址处理一下,否则微信识别不了
            String redirect_uri = URLEncoder.encode("http://www.abc.com/ary/toPlayerInfo?id=" + competitorID, "UTF-8");
            //简单获取openid的话参数response_type与scope与state参数固定写死即可
            StringBuffer url = new StringBuffer("https://open.weixin.qq.com/connect/oauth2/authorize?redirect_uri=" + redirect_uri +
                    "&appid=APPID&response_type=code&scope=snsapi_base&state=1#wechat_redirect");
            //这里千万不要使用get请求,单纯的将页面跳转到该url即可
            response.sendRedirect(url.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }           

    2、获取openid的页面

    /**
     * 根据id跳转到详情页
     * @param request
     * @return
     */
    @RequestMapping("/toPlayerInfo")
    public ModelAndView toPlayerInfo(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        ModelAndView mav = new ModelAndView();
        // 获取openid
        response.setContentType("text/html");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String code = request.getParameter("code");//获取code
        Map params = new HashMap();
        params.put("appid", "wx1c96a0ac8e1f95f0");
        params.put("secret", "aca13e16ae0d17c8da2966c1ed4ea680");
        params.put("grant_type", "authorization_code");
        params.put("code", code);
        String result = HttpGetUtil.httpRequestToString(
                "https://api.weixin.qq.com/sns/oauth2/access_token", params);
        JSONObject jsonObject = JSONObject.fromObject(result);
        String openid = jsonObject.get("openid").toString();
        // 获取选手id
        Integer id = Integer.parseInt(request.getParameter("id"));
        // 根据id查询player
        String playerJson = competitorService.CompetitorFindById(id);
        Competitor playerInfo = JsonUtil.jsonToBean(playerJson, Competitor.class);
        // 获取图片路径
        String[] pictureList = playerInfo.getPicture().split(",");
        mav.addObject("playerInfo",playerInfo);
        mav.addObject("pictureList",pictureList);
        mav.addObject("openid",openid);
        mav.setViewName("playerInfo");
        return mav;
    }           

    3、HttpGetUtil

public class HttpGetUtil {

    public static String httpRequestToString(String url,
                                             Map<String,String> params) {
        String result = null;
        try {
            InputStream is = httpRequestToStream(url,  params);
            BufferedReader in = new BufferedReader(new InputStreamReader(is,
                    "UTF-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            result = buffer.toString();
        } catch (Exception e) {
            return null;
        }
        return result;
    }

    private static InputStream httpRequestToStream(String url,
                                                   Map<String, String> params) {
        InputStream is = null;
        try {
            String parameters = "";
            boolean hasParams = false;
            for(String key : params.keySet()){
                String value = URLEncoder.encode(params.get(key), "UTF-8");
                parameters += key +"="+ value +"&";
                hasParams = true;
            }
            if(hasParams){
                parameters = parameters.substring(0, parameters.length()-1);
            }

            url += "?"+ parameters;

            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setConnectTimeout(50000);
            conn.setReadTimeout(50000);
            conn.setDoInput(true);
            //设置请求方式,默认为GET
            conn.setRequestMethod("GET");
            
            is = conn.getInputStream();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}           
用到的工具类请自行查找

继续阅读