获取微信openid(静默式不需要用户同意)

1.微信公众号 -->功能设置-->配置网页授权域名

2.准备2个url,一个访问地址获取code,另一个获取openid


	String url = "https://open.weixin.qq.com/connect/oauth2/authorize"
				+ "?appid=APPID"
				+ "&redirect_uri=REDIRECT_URI"
				+ "&response_type=code"
				+ "&scope=snsapi_base"
				+ "&state=STATE"
				+ "#wechat_redirect";


String url = "https://api.weixin.qq.com/sns/oauth2/access_token"
				+ "?appid=AppId"
				+ "&secret=AppSecret"
				+ "&code=CODE"
				+ "&grant_type=authorization_code";

3.用户访问此接口 

@GetMapping("/getCode")
public void getCode(HttpServletRequest request, HttpServletResponse response) throws ClientProtocolException, IOException {
    String url = WxUtils.getOpenIdUrl("xiaoming");
    System.out.println("微信网址:"+url);
    response.sendRedirect(url);
}
@GetMapping("/getOpenId")
public Map<String,Object> getOpenId(HttpServletRequest request, HttpServletResponse response) throws ClientProtocolException, IOException {
    Map<String,Object> map = new HashMap<String,Object>();  
    String code = request.getParameter("code");//微信会返回code值,用code获取openid
    String openId = WxUtils.getOpendId(code);
    map.put("openId", openId);
    return map;}


4.getOpenId(code)方法介绍

public static String getopendid(String code) throws ParseException, IOException {
		
		String appid = "xxx";
		String secret = "xxx";
		
		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", appid)
    		.replace("AppSecret", secret)
                .replace("CODE", code);
		
		HttpGet get = HttpClientConnectionManager.getGetMethod(url);
		HttpResponse response = httpclient.execute(get);
		String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
		JSONObject jsonTexts = (JSONObject) JSON.parse(jsonStr);
		
		String openid = "";
		if (jsonTexts.get("openid")!=null) {
			openid = jsonTexts.get("openid").toString();
		}
		return openid;
	}

猜你喜欢

转载自blog.csdn.net/qq_38423105/article/details/80632397