天天看点

微信获取openId--java

微信获取openId首先需要获取code,通过code代换出openId。现在我们通过微信测试号来获取openId:

配置好微信测试号后首先需要一个微信号关注测试号

微信获取openId--java

直接通过微信号扫描测试号管理中的测试号二维码关注公众号即可。

公众号一般都是直接将微信链接嵌入公众号窗口中,所以我们首先先拼接微信链接

可以参考:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect 
           
微信获取openId--java

redirect_uri中可以定义一个参数来存放访问的URL,获取openId是可以将该路径解析出来进行跳转到任意路径

@Controller
@RequestMapping("********")
public class WxLoginController{
	
	/**
	 * 授权后重定向的回调链接地址
	 */
	@RequestMapping("*****")
	public String wxLogin(HttpServletRequest request, HttpServletResponse response) {
		String str = getUrl(request);
		System.out.println("str:"+str);
		try {
			//获取解析code
			String code=str.substring(str.indexOf("code=") + 5, str.indexOf("&st"));
			System.out.println("code:"+code);
			String openId = getOpenId(code);
			System.out.println("openId:"+openId);
			//解析授权后重定向的回调链接地址上面的附带参数 visitUrl:参数名
			//String visitUrl = request.getParameter("visitUrl");//根据需求添加
			//System.out.println("visitUrl:"+visitUrl);
			//return "redirect:"+visitUrl;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取openId
	 */
	public String getOpenId(String code) {
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=AppId&secret=AppSecret&code=CODE&grant_type=authorization_code";
		url = url.replace("AppId", "wxb855e55aad41adaf").replace("AppSecret", "80b202958d244b1c6e4ef242ad95da06").replace("CODE", code);
		System.out.println("url:"+url);
		String jsonResult = loadJSON(url);
		String ss = jsonResult.substring(jsonResult.indexOf("openid") + 9, jsonResult.indexOf("scope") - 3);
		return ss;
	}
	public static String getUrl(HttpServletRequest req) {
		String reqUrl = req.getRequestURL().toString();
		String queryString = req.getQueryString();
		if (queryString != null) {
			reqUrl += "?" + queryString;
		}
		return reqUrl;
	}
	public static String loadJSON(String url){
		StringBuilder json=new StringBuilder();
		BufferedReader in = null;
		try{
			URL oracle =new URL(url);
			URLConnection yc = oracle.openConnection();
			in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
			String inputLine =null;
			while ((inputLine=in.readLine())!=null){
				json.append(inputLine);
			}
		}catch(MalformedURLException e){
			System.out.println("HttpJSONTest ,MalformedURLException" + e.getMessage());
		}catch(IOException e){
			System.out.println("HttpJSONTest io" + e.getMessage());
		}
		finally{
			try {
				if(in != null){
					in.close();
				}
			} catch (Exception e2) {
				System.out.println("HttpJSONTest in.close()" + e2.getMessage());
			}
		}
		return json.toString();
	}
}