微信openId的获取

       要获取微信的openid首先需要获取到code值。获取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 公众号唯一标识
redirect_uri
授权后重定向的回调链接地址,请使用urlencode对链接进行处理
response_type
返回类型,请填写code
scope
 
       
应用授权作用域,snsapi_base
 (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo 
(弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,
即使在未关注的情况下,只要用户授权,也能获取其信息
state
 
       
重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
#wechat_redirect
 
       
无论直接打开还是做页面302重定向时候,必须带此参数

               请求过后回调地址会带上code参数值

               然后根据code值查询到openId,一个微信号与一个微信公众号只有唯一的openid

            

/**
 * 获取验证码
 * @param appId
 * @param appSecret
 * @param code
 * @return result
 */
public static String getOauth2AccessToken(String appId, String appSecret,
			String code) {
		System.out.println(appId);
		System.out.println(appSecret);
		System.out.println(code);
		//url获取openid地址
		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);
		// 提交请求
		String result = httpRequest(requestUrl, "GET", null);
		System.out.println(result);
		return result;
	}

 
private static String httpRequest(String url, String method, String jsonStr) {

		try {

			URL urlGet = new URL(url);

			HttpURLConnection http = (HttpURLConnection) urlGet

			.openConnection();

			http.setRequestMethod(method); // 必须是get方式请求

			http.setRequestProperty("Content-Type",

			"application/x-www-form-urlencoded");

			http.setDoOutput(true);

			http.setDoInput(true);

			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒

			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

			http.connect();
			if (method.equals("POST") && !StringUtil.isEmpty(jsonStr)) {
				// POST请求
				DataOutputStream out = new DataOutputStream(
						http.getOutputStream());
				out.write(jsonStr.getBytes("UTF-8"));

				out.flush();
				out.close();
			}
			InputStream is = http.getInputStream();

			int size = is.available();

			byte[] jsonBytes = new byte[size];

			is.read(jsonBytes);

			String result = new String(jsonBytes, "UTF-8");

			System.out.println(result);
			return result;

		} catch (Exception e) {

			e.printStackTrace();
			return "error";

		}
	}


你可能感兴趣的:(微信公众号开发,openid,微信)