微信支付-获取openId

获取openId

    /**
     * 获取用户openID
     * @Author  yuhao
     * @param code
     * @return  String
     * @Date	2018年9月3日
     */
    public static String getOpenId(String code){
        System.out.println("code: " + code);
        if (code != null) {
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                    + "appid="+ APP_ID
                    + "&secret="+ APP_SECRET
                    + "&code=" + code + "&grant_type=authorization_code";
            String returnData = getReturnData(url);

            JSONObject jsonObject;
            try {
                jsonObject = JSONObject.parseObject(returnData);
                String openid = jsonObject.getString("openid");
                //String access_token = jsonObject.getString("access_token");
                System.out.println("openid:" + openid);
                return openid;
            } catch (Exception e) {
                jsonObject = JSONObject.parseObject(returnData);
                String errcode = jsonObject.getString("errcode");
                System.out.println("errcode:" + errcode);
            }
        }
        System.out.println("code为空");
        return "";
    }
    public static String getReturnData(String urlString) {
        String res = "";
        try {
            URL url = new URL(urlString);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url
                    .openConnection();
            conn.connect();
            java.io.BufferedReader in = new java.io.BufferedReader(
                    new java.io.InputStreamReader(conn.getInputStream(),
                            "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line;
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

 

你可能感兴趣的:(微信支付-获取openId)