公众号 java后端 获取code, openid、unionid, 用户信息

public class WxGzhUtils {


    public static String getCodeByUrl(String appid,String url){
        String path = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
                appid+"&redirect_uri="+url+"&response_type=code&scope=SCOPE&state=123#wechat_redirect&connect_redirect=1";
        String res[] = requestJson(path);
        JSONObject jsonObject = JSON.parseObject(res[0]);

        //重定向的url,包含code
        String ss = jsonObject.toString();
        int i = ss.indexOf("=");
        String code = ss.substring(i+1,ss.indexOf("&"));

        return code;

    }



    /**
     * 获取openid  access_token
     * @param appid
     * @param secret
     * @param code
     * @return
     */
    public static Map getOpenId(String appid, String secret, String code){
        String path = " https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid +
                "&secret="+secret+"&code="+code+"&grant_type=authorization_code";

        String res[] = requestJson(path);
        JSONObject jsonObject = JSON.parseObject(res[0]);
        String openid = jsonObject.getString("openid");
        String access_token = jsonObject.getString("access_token");
        Map<String,Object> map = new HashMap<>();
        map.put("openid",openid);
        map.put("access_token",access_token);

        return map;
    }


    /**
     * 获取用户信息
     * @param openid
     * @param access_token
     * @return
     */

    public static Map getUserInfo(String openid,String access_token){
        String path = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
        String res[] = requestJson(path);
        JSONObject jsonObject = JSON.parseObject(res[0]);
        //map对象
        Map<String, Object> map =new HashMap<>();

        //循环转换
        Iterator it =jsonObject.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
            map.put(entry.getKey(), entry.getValue());
        }

        return map;


    }



//get请求
    private static String[] requestJson(String url) {
        return request(url);
    }
    private static String[] request(String connurl) {
        String[] resultStr = new String[]{"", ""};
        StringBuilder resultData = new StringBuilder("");
        HttpURLConnection conn = null;
        try {
            URL url = new URL(connurl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setUseCaches(false);
            int mTimeout = 10000;
            conn.setConnectTimeout(mTimeout);
            conn.connect();
            int resultCode = conn.getResponseCode();
            InputStreamReader in;
            if (resultCode == 200) {
                in = new InputStreamReader(conn.getInputStream());
                BufferedReader buffer = new BufferedReader(in);
                String inputLine;
                while ((inputLine = buffer.readLine()) != null) {
                    resultData.append(inputLine);
                    resultData.append("\n");
                }
                buffer.close();
                in.close();
            }
            resultStr[0] = resultData.toString();
            resultStr[1] = resultCode + "";
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return resultStr;
    }
 }
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Java 后端获取 openID 是指在 Java 后端代码获取用户微信公众号或小程序的 openID,以便后续进行用户信息的判断和业务逻辑的处理。下面我们一起看看具体的实现过程。 1. 授权获取 code 用户在微信公众号或小程序中点击登录按钮后,会跳转到微信的授权页面。我们需要在 Java 后端代码中,通过构造微信授权链接,将用户引导到该页面。 授权链接示例:https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect 参数说明: - appid:微信公众号或小程序的 appid - redirect_uri:回调地址,即用户在授权后跳转的链接 - response_type:授权类型,固定填写 code - scope:授权范围,snsapi_base 表示只获取用户的 openID - state:用于登录验证等操作,可以为空 - #wechat_redirect:固定的参数,表示要进行授权操作 2. 获取 access_token 获取 code 后,我们需要在 Java 后端代码中使用该 code 去换取 access_token,从而获取用户的 openID获取 access_token 的请求示例:https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code 参数说明: - appid:微信公众号或小程序的 appid - secret:应用的 app secret,推荐通过配置文件等方式进行安全保护 - code授权码,即用户同意授权获取到的 code - grant_type:固定填写 authorization_code 3. 解析 openID 获取 access_token 后,我们就可以通过 API 获取用户的基本信息,其中包括用户的 openID。 通过 access_token 获取用户信息请求示例:https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN 参数说明: - access_token:获取到的访问令牌 - openid:用户的 openID - lang:语言版本,可为空,zh_CN 表示简体中文 以上就是 Java 后端获取 openID 的详细操作流程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值