JAVA获取微信小程序openid和获取公众号openid,以及通过openid获取用户信息

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/nulinulizainulilx/article/details/85159013

一,首先说明下这个微信的openid
  为了识别用户,每个用户针对每个公众号会产生一个安全的OpenID,如果需要在多公众号、移动应用之间做用户共通,则需前往微信开放平台,将这些公众号和应用绑定到一个开放平台账号下,绑定后,一个用户虽然对多个公众号和应用有多个不同的OpenID,但他对所有这些同一开放平台账号下的公众号和应用,只有一个UnionID

我用简单自己理解的话来说就是 这个 你在每个公众号 或者小程序 都是在这个小程序或者这个公众号下会有一个openid 你去别的公众号 或者 小程序 这个是会改变的 但是unionid是不管你在哪个小程序或者公众号是唯一不变的。

微信官方提供了 了一个 可以通过用户的openid来获取用户信息,前提是用户必须关注了你的公众号,这个好像要做的话需要关联一个需要三百块钱认证的那个啥来着。这个就先不说了吧,现在我们要说的问题是如何获取openid

二,小程序获取openid
1,工具类

/**
 * 微信小程序获取openid
 * @author Mr.Lin
 */
public class GetOpenIDUtil {
	// 网页授权接口
//	public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";//
//	public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code";
	public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code";
    public  static Map<String,Object> oauth2GetOpenid(String appid,String code,String appsecret) {
        String requestUrl = GetPageAccessTokenUrl.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);  
        HttpClient client = null;  
        Map<String,Object> result =new HashMap<String,Object>();  
        try {     
            client = new DefaultHttpClient();  
            HttpGet httpget = new HttpGet(requestUrl);  
            ResponseHandler<String> responseHandler = new BasicResponseHandler();  
            String response = client.execute(httpget, responseHandler);  
            JSONObject OpenidJSONO=JSONObject.fromObject(response);
            String openid =String.valueOf(OpenidJSONO.get("openid"));
            String session_key=String.valueOf(OpenidJSONO.get("session_key"));
            String unionid=String.valueOf(OpenidJSONO.get("unionid"));
            String errcode=String.valueOf(OpenidJSONO.get("errcode"));
            String errmsg=String.valueOf(OpenidJSONO.get("errmsg"));

            result.put("openid", openid);
            result.put("sessionKey", session_key);
            result.put("unionid", unionid);
            result.put("errcode", errcode);
            result.put("errmsg", errmsg);
        } catch (Exception e) {
            e.printStackTrace();   
        } finally {  
            client.getConnectionManager().shutdown();  
        }  
        return result;  
    }  
}

2,接口

/**
     * 小程序换取openid
     *
     * @param code 识别得到用户id必须的一个值 得到网页授权凭证和用户id
     * @return
     */
    @RequestMapping("/get/openid")
    public @ResponseBody
    Object GetOpenid(String 你的小程序APPID, String code, String 你的小程序对应秘钥) {
        if (code == null || code.length() == 0) {
            throw new CustomException("code不能为空!");
        }
        return GetOpenIDUtil.oauth2GetOpenid(appid, code, appsecret);

    }
    这个code的话我这个一般是前端生成比较好,所以你后台的话,把接口给前端,让他那边传个code


三,获取公众号openid~

1,工具类

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 = null;
                try {
                    value = URLEncoder.encode(params.get(key), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                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;
    }

    public static String  GetCodeRequest1 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
    public static String getCodeRequest(String appid){
        HttpClient client = null;
        String result = null;
        String appId = appid;
        String REDIRECT_URI= "";//回调请求地址
        String SCOPE="snsapi_base";

        GetCodeRequest1  = GetCodeRequest1.replace("APPID", urlEnodeUTF8(appId));
        GetCodeRequest1  = GetCodeRequest1.replace("REDIRECT_URI",urlEnodeUTF8(REDIRECT_URI));
        GetCodeRequest1 = GetCodeRequest1.replace("SCOPE", SCOPE);
        result = GetCodeRequest1;

        System.out.println(REDIRECT_URI);

        return result;
    }
    public static String urlEnodeUTF8(String str){
        String result = str;
        try {
            result = URLEncoder.encode(str,"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

2,接口

@RequestMapping("/get/gzh/openid")
    public @ResponseBody
    String GetGZHOpenid(HttpServletRequest request, HttpServletResponse response) throws IOException {


        String code = request.getParameter("code");//获取code
        Map params = new HashMap();
        params.put("secret", 你的公众号秘钥);
        params.put("appid", 你的公众号APPID);
        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();
        LOGGER.debug("code------" + code);
        LOGGER.debug("得到的openid为:" + openid);
        return openid;

    }

四,通过微信获取的openid来获取用户信息

1,工具类

/**
 * 获取accessToken
 *
 */
public class GetAccessTokenUtil {
    // 网页授权接口
    public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    public static Map<String, String> getAccessToken(String appid, String appsecret) {
        String requestUrl = GetPageAccessTokenUrl.replace("APPID", appid).replace("APPSECRET", appsecret);
        HttpClient client = null;
        Map<String, String> result = new HashMap<String, String>();
        String accessToken = null;
        try {
            client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(requestUrl);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = client.execute(httpget, responseHandler);
            JSONObject OpenidJSONO = JSONObject.fromObject(response);
            accessToken = String.valueOf(OpenidJSONO.get("access_token"));
            result.put("accessToken", accessToken);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getConnectionManager().shutdown();
        }
        return result;
    }
}

//通过openid获取用户的信息,这个看你需要获取用户的哪些信息,
//  https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839   这个是微信官方的获取unionid机制  用户信息
public class GetBasicInformation {
    // 网页授权接口
    public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

    public static Map<String, String> getAccessToken(String access_token, String openid) {
        String requestUrl = GetPageAccessTokenUrl.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
        HttpClient client = null;
        Map<String, String> result = new HashMap<String, String>();
        try {
            client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(requestUrl);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = client.execute(httpget, responseHandler);
            JSONObject OpenidJSONO = JSONObject.fromObject(response);

//            String accessToken = String.valueOf(OpenidJSONO.get("access_token"));
            String subscribe = String.valueOf(OpenidJSONO.get("subscribe"));
            String nickname = new String(String.valueOf(OpenidJSONO.get("nickname")).getBytes("ISO8859-1"),"UTF-8");
            String sex = String.valueOf(OpenidJSONO.get("sex"));
            String language = String.valueOf(OpenidJSONO.get("language"));
            String city = new String(String.valueOf(OpenidJSONO.get("city")).getBytes("ISO8859-1"),"UTF-8");
            String province = new String(String.valueOf(OpenidJSONO.get("province")).getBytes("ISO8859-1"),"UTF-8");
            String country = new String(String.valueOf(OpenidJSONO.get("country")).getBytes("ISO8859-1"),"UTF-8");
            String headimgurl = String.valueOf(OpenidJSONO.get("headimgurl"));
            String subscribeTime = String.valueOf(OpenidJSONO.get("subscribe_time"));
            String unionid = String.valueOf(OpenidJSONO.get("unionid"));
//            String accessToken =new String(String.valueOf(OpenidJSONO.get("access_token")).getBytes("ISO8859-1"),"UTF-8");
//            String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8");
//            String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8");
//            String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8");
//            String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8");
//            String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8");
//            String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8");
//            String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8");
//            String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8");
//            String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8");
//            String openid =new String(String.valueOf(OpenidJSONO.get("openid")).getBytes("ISO8859-1"),"UTF-8");

//            String openid = String.valueOf(OpenidJSONO.get("openid"));
//            result.put("accessToken", accessToken);
            result.put("subscribe", subscribe);
            result.put("nickname", nickname);
            result.put("sex", sex);
            result.put("language", language);
            result.put("city", city);
            result.put("province", province);
            result.put("country", country);
            result.put("headimgurl", headimgurl);
            result.put("subscribeTime", subscribeTime);
            result.put("unionid", unionid);
            
//            System.out.println(accessToken+"==================="+unionid);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getConnectionManager().shutdown();
        }
        return result;
    }
}

2,接口

/**
     * 微信公众号获取微信unionid和其他个人信息   需要关注公众号
     *
     * @param openid
     * @return
     */
    @RequestMapping("/basic/Information")
    public @ResponseBody
    Map basicInformation(String openid) {
        //得到access_token
        String accessToken = GetAccessTokenUtil.getAccessToken(你的公众号APPID, 你的公众号APPID对应的秘钥).get("accessToken");
        LOGGER.debug("accessToken------" + accessToken);
        return GetBasicInformation.getAccessToken(accessToken, openid);
    }


总结:这个就是微信小程序和微信公众号获取openid  以及通过openid获取unionid以及用户信息的代码,微信开发文档上面看感觉功力不深厚是很难看懂的,这个我也是通过网上或者同事慢慢总结出来的。  请大家多多指教,谢谢!
[这是我博客园地址](https://www.cnblogs.com/lxwt/p/10154540.html)
展开阅读全文

没有更多推荐了,返回首页