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

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_38423105/article/details/80632397

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;
	}
展开阅读全文

没有更多推荐了,返回首页