微信公众号开发——获取openId

微信公众号开发——获取用户openId

	/**
	 * 
	 * 获取用户openID
	 * @param course
	 * @return
	 * @throws UnsupportedEncodingException 
	 */

	@RequestMapping(value = "/obtainOpenid" , method = RequestMethod.POST)
	public String obtainOpenid(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		request = attributes.getRequest();

		 // 获取openid
        response.setContentType("text/html");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //String code = request.getParameter("code");//获取code
        String code = userCourse.getCode();
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", WXConfig.appid);
        params.put("secret",WXConfig.appSecret);
        params.put("grant_type", "authorization_code");
        params.put("code", code);
        String result = HttpUtil.httpRequestToString(
                "https://api.weixin.qq.com/sns/oauth2/access_token", params);
        JSONObject jsonObject = JSONObject.fromObject(result);
        String openid = jsonObject.get("openid").toString();
      
		return openid ;
	}

HttpUtil.httpRequestToString代码

public static String httpRequestToString(String url, Map<String, String> params) {
		String result = null;
		try {
			InputStream is = httpRequestToStream(url, params);
			BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = in.readLine()) != null) {
				buffer.append(line);
			}
			result = buffer.toString();
		} catch (Exception e) {
			return null;
		}
		return result;
	}

你可能感兴趣的:(java,支付)