Java-微信授权获取openid

微信授权

回调域名需要和公众号后台设置一致,否则微信回调请求不到 

    @RequestMapping("/wxLogin")
    public String wxLogin() throws IOException {
        
        //域名
        String sym = "http://www.baidu.com";
        //这里是回调的url
        String redirectUri = URLEncoder.encode(sys + "/api/callBack", "UTF-8");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" +
                微信商户的appid +
                "&redirect_uri=" + redirectUri +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=STATE" +
                "#wechat_redirect";

        //可以替换STATE携带需要的参数到微信回调的接口里
        //JSONObject jsonObject = new JSONObject();
        //jsonObject.put("A",需要携带的参数);
        //String s = jsonObject.toString();
        //url = url.replace("STATE", URLEncoder.encode(s, "UTF-8"));

        
        return url;
    }

 微信授权回调

    @RequestMapping("callBack")
    public String callBack(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //获取回调地址中的code
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        //从state里拿到携带来的参数
        //JSONObject object1 = JSONObject.parseObject(state);
        //String A = object1.getString("A");

        String appId = "xxxxxxxxxxx";
        //开发者密码
        String secret = "xxxxxxxxxxxxxxxxxxxxxxxx";

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + appId  +
                "&secret=" + secret  +
                "&code=" + code +
                "&grant_type=authorization_code";
        //获取openId
        String data = HttpUtils.doGet(url);
        AccessToken accessToken = JSONObject.parseObject(data, AccessToken.class);
        return accessToken.getOpenid();
    }

工具类

 

public class HttpUtils {
    public static String doGet(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpurl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(60000);
            connection.connect();
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return result;
    }

    public static String doPost(String httpUrl, String param) {

        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(60000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            os = connection.getOutputStream();
            os.write(param.getBytes());
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return result;
    }
}

 

 

public class AccessToken {
    private String accessToken;
    private String expiresIn;
    private String refreshToken;
    private String openid;
    private String scope;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据提供的引用内容,Java代码中的getopenid方法是用于获取微信公众号的openid的。该方法接收一个名为code的参数,通过调用微信API来获取openid。具体的步骤如下: 1. 首先,需要设置公众号的appid和secret。 2. 然后,设置响应头,允许跨域请求。 3. 构建微信登录的URL,包括appid、secret、code和授权类型等参数。 4. 发送GET请求到微信登录URL,获取返回的JSON字符串。 5. 解析JSON字符串,提取其中的openid字段作为结果。 6. 最后,将openid返回。 根据提供的代码,无法确定具体的错误原因。但是根据错误代码40029,这可能是由于code参数无效或过期导致的。建议检查传递给getopenid方法的code参数是否正确,并确保它是最新的。 请注意,以上回答是基于提供的引用内容,可能不完整或有遗漏。如果需要更详细的帮助,请提供更多相关的代码或信息。 #### 引用[.reference_title] - *1* *2* [微信公众号获取openidjava后端+html实现)](https://blog.csdn.net/weixin_43767744/article/details/121747536)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [微信公众号根据openid获取unionid](https://blog.csdn.net/qq_39418742/article/details/126197895)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值