微信授权登陆:

我采用的是自定义的子菜单:登陆微信公众平台

第一步:用户同意授权、获取code

第二步:通过code换取网页授权access_token

详细步骤参考微信公众号平台

在页面地址输入授权后的url:

eg:

scope为snsapi_userinfo
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect

 访问页面:

微信授权成功后,获取微信用户的基本信息

拉取用户的基本信息,只需要access_token、openid

请求url:

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

获取用户信息的方法:

 //获取用户的微信头像
    public static String getSnsapiUserinfo(String openId) throws Exception{
    	logger.debug("getAccessToken,accessToken=" + accessToken);
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";
        String webStr = HttpUtil.sendGetRequest(url, HttpUtil.CHARACTER_ENCODING);
		logger.debug("getSnsapiUserinfo,webStr=" + webStr);
		HashMap map = (HashMap) JSONUtil.deserialize(webStr);
		String headimgurl = (String) map.get("headimgurl");
		return headimgurl;
    }

 发生get请求,获取返回的信息

  /**
     * 发送get请求,获取返回html
     * 
     * @param strUrl
     *            请求地址
     * @param encode
     *            页面编码
     * @return
     * @throws Exception
     */
    public static String sendGetRequest(String strUrl, String encode) throws Exception {
        URL newUrl = new URL(strUrl);
        HttpURLConnection hConnect = (HttpURLConnection) newUrl.openConnection();
        InputStream is = hConnect.getInputStream();
        String str = inputStreamToString(is, encode);
        is.close();
        hConnect.disconnect();
        return str;
    }

获取accesstoken和openid 

 //获取企业号调用的临时token
	public static String getAccessToken() throws Exception {
		Date now = new Date();
		if (accessToken != null
				&& accessTokenGetTime != null
				&& now.getTime() - accessTokenGetTime.getTime() <= 1000 * 60 * 30) {
			return accessToken;
		} else {
			String webStr = HttpUtil.sendGetRequest(getTokenUrl(), HttpUtil.CHARACTER_ENCODING);
			logger.debug("getAccessToken,webStr=" + webStr);
			HashMap map = (HashMap) JSONUtil.deserialize(webStr);
			String token = (String) map.get("access_token");
			accessToken = token;
			accessTokenGetTime = now;
			return token;
		}
	}
	
	//通过微信code获取openid
	public static String getOpenId(String code) throws Exception {
			String webStr = HttpUtil.sendGetRequest(getTokenUrlfw(code), HttpUtil.CHARACTER_ENCODING);
			logger.debug("getAccessToken,webStr=" + webStr);
			HashMap map = (HashMap) JSONUtil.deserialize(webStr);
			String openid = (String) map.get("openid");
			accessToken=(String) map.get("access_token");
			return openid;
	}

 

 

相关文章: