微信公众号开发二:关于授权网页获取用户微信信息注册用户的开发

最近准备开发一个微网站,其中一项功能即通过用户授权获取微信信息登录网站,下面上步骤:

1.点击网站登录按钮,访问微信的网页授权的接口获取code

接口为:https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect   

appid:自己的公众平台appid

redirect_uri:获取授权后要访问的路径,需要进行百分号url编码才可以使用

response_type:返回类型为code

scope:授权作用域1.snsapi_base:不弹出授权页面,只能获取用用户的openid。

     2.snsapi_userinfo:弹出授权提示,能获取其他基本信息

state:a-zA-Z0-9任意参考数值

2.当获取授权后接口会直接去调用redirect_url参数的地址(redirect_uri/?code=CODE&state=STATE),在redirect_url方法中通过code获取access_token

获取code后,请求以下链接获取access_token:  https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code        

扫描二维码关注公众号,回复: 3699055 查看本文章

secret:公众号的appsecret

code:访问地址中的code参数

将获取的access_token放在其基类中

http:GET(请使用https协议) https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN        

 获取类中的access_token和openid请求该方法获取用户基本信息。

贴代码:

访问授权接口链接:

String strurl="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9cb8ac6a08f43586&redirect_uri=http%3a%2f%2fnumgl.gjsrj.com%2fweixin%2fusergetOAuth&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
		 // 创建URL对象
        URL myURL;
		try {
			myURL = new URL(strurl);
			 // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
	        HttpsURLConnection httpsConn = (HttpsURLConnection) myURL
	                .openConnection();
	        // 取得该连接的输入流,以读取响应内容
	        InputStreamReader insr = new InputStreamReader(httpsConn
	                .getInputStream());
	        // 读取服务器的响应内容并显示
	        int respInt = insr.read();
	        while (respInt != -1) {
	            System.out.print((char) respInt);
	            respInt = insr.read();
	        }
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

获取授权后执行的方法:

public String getOAuth(){
		   // 用户同意授权后,能获取到code
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String yaoqingma=request.getParameter("");
        ActionContext.getContext().getSession().put("code", code);
        
        // 用户同意授权
        if (!"authdeny".equals(code)) {
            //1. 获取网页授权access_token
            WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken("wx9cb8ac6a08f43586", "49242de7af92e28caeaf85277069f6f9", code);
            //2. 网页授权接口访问凭证
            String accessToken = weixinOauth2Token.getAccessToken();
            //用户标识
            String openId = weixinOauth2Token.getOpenId();
            //获取用户信息
            SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken, openId);
            ActionContext.getContext().getSession().put("snsUserInfo", snsUserInfo);
            //设置要传递的参数
            //request.setAttribute("snsUserInfo", snsUserInfo);
            //request.setAttribute("state", state);
        }
		return "success";
	}

工具类:1.获取access_token的工具类(注意:网页授权跟基础支持中的access_token不同, 这里通过code换取的是一个特殊的网页授权access_token ,为两个不同的接口

/**
     * 获取网页授权凭证access_token对象
     * 
     * @param appId 公众账号的唯一标识
     * @param appSecret 公众账号的密钥
     * @param code
     * @return WeixinAouth2Token
     */
    public static WeixinOauth2Token getOauth2AccessToken(String appId, String appSecret, String code) {
        WeixinOauth2Token wat = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        requestUrl = requestUrl.replace("APPID", appId);
        requestUrl = requestUrl.replace("SECRET", appSecret);
        requestUrl = requestUrl.replace("CODE", code);
        // 获取网页授权凭证
        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
        if (null != jsonObject) {
            try {
                wat = new WeixinOauth2Token();
                wat.setAccessToken(jsonObject.getString("access_token"));
                wat.setExpiresIn(jsonObject.getInt("expires_in"));
                wat.setRefreshToken(jsonObject.getString("refresh_token"));
                wat.setOpenId(jsonObject.getString("openid"));
                wat.setScope(jsonObject.getString("scope"));
            } catch (Exception e) {
                wat = null;
                int errorCode = jsonObject.getInt("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                log.error("获取网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
            }
        }
        return wat;
    }

 /**
     * 通过网页授权获取用户信息
     * 
     * @param accessToken 网页授权接口调用凭证
     * @param openId 用户标识
     * @return SNSUserInfo
     */
    @SuppressWarnings( { "deprecation", "unchecked" })
    public static SNSUserInfo getSNSUserInfo(String accessToken, String openId) {
        SNSUserInfo snsUserInfo = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        // 通过网页授权获取用户信息
        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                snsUserInfo = new SNSUserInfo();
                // 用户的标识
                snsUserInfo.setOpenId(jsonObject.getString("openid"));
                // 昵称
                snsUserInfo.setNickname(jsonObject.getString("nickname"));
                // 性别(1是男性,2是女性,0是未知)
                snsUserInfo.setSex(jsonObject.getInt("sex"));
                // 用户所在国家
                snsUserInfo.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                snsUserInfo.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                snsUserInfo.setCity(jsonObject.getString("city"));
                // 用户头像
                snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
                // 用户特权信息
                snsUserInfo.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class));
            } catch (Exception e) {
                snsUserInfo = null;
                int errorCode = jsonObject.getInt("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                log.error("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg);
            }
        }
        return snsUserInfo;
    }
}



猜你喜欢

转载自blog.csdn.net/sdx1237/article/details/78558664
今日推荐