微信公众号开发中使用Java如何实现获取用户的信息?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
1、首先需要到微信网站去设置一下,我是直接用的微信测试号。
接口配置信息必须要填写的,所以说必须能将自己的服务发布出去
到此微信配置完毕,接下来就是直接上代码了
2、获取用户信息的方式一共是两种,前提都是用户关注微信公众号,一种是静默获取(snsapi_base,这种方式只能获取openid),另一种是授权获取(snsapi_userinfo,可以获取用户的详细信息)。
先说第一种
(1)首先需要先访问微信的链接
https://open.weixin.qq.com/connect/oauth3/authorize?appid=xxxxxxxxxxxxxxxx&redirect_uri=http://xxxxxx/open/openid&response_type=code&scope=snsapi_base
这里的 uri就是直接回掉我们的服务地址,一定要记住,服务校验的判断,我是按照来判断的echostr(第二种方式也是这样)
package net.itraf.controller; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONObject; @Controller @RequestMapping("/open") public class OpenController { @RequestMapping("/toOpenId") public @ResponseBody String getOpenId(String code,String echostr,HttpServletResponse res) throws IOException{ if(echostr==null){ String url="https://api.weixin.qq.com/sns/oauth3/access_token?appid=wx24d47d2080f54c5b&secret=95011ac70909e8cca2786217dd80ee3f&code="+code+"&grant_type=authorization_code"; System.out.println(code); String openId=""; try { URL getUrl=new URL(url); HttpURLConnection http=(HttpURLConnection)getUrl.openConnection(); http.setRequestMethod("GET"); http.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); http.setDoOutput(true); http.setDoInput(true); http.connect(); InputStream is = http.getInputStream(); int size = is.available(); byte[] b = new byte[size]; is.read(b); String message = new String(b, "UTF-8"); JSONObject json = JSONObject.parseObject(message); openId = json.getString("openid"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return openId; }else{ PrintWriter out = res.getWriter(); out.print(echostr); return null; } } //做服务器校验 @RequestMapping("/tovalid") public void valid(String echostr,HttpServletResponse res) throws IOException{ PrintWriter out = res.getWriter(); out.print(echostr); } }