微信之获取微信的openid(二)详细版
第一步 :配置测试号,网页授权获取用户基本信息。
该授权回掉页面域名为ngrok 映射的域名,我的映射地址是127.0.0.1:8080。
到此微信配置完毕,接下来就是直接上代码了
2.用户同意授权
我是把这个url写在微信菜单下的,当进入这个页面的时候就让用户同意。注意:好像是静默授权的,用户不知道
参数:appid:公众号的唯一标识
redirect_uri:重定向的url,就是授权后要跳转的页面
scope:应用授权作用域
snsapi_base:不弹出授权页面,直接跳转,只能获取用户openid
snsapi_userinfo:弹出授权页面,可通过openid拿到昵称、性别、所在地
state:重定向后带的参数
2.用户同意后会产生一个code,只有5分钟时间的有效期。
先说第一种
(1)首先需要先访问微信的链接
这里的 uri就是直接回掉我们的服务地址,一定要记住,服务校验的判断,我是按照来判断的echostr(第二种方式也是这样)
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/oauth2/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); } }
第二种
(1)
https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxxxxxxx&redirect_uri=http:// 域名
/open/openid&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/weixin") public class Oauth2Action { @RequestMapping("/oauth") public void auth(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String echostr = request.getParameter("echostr"); if(echostr==null){ String appId = "wx24d47d2080f54c5b"; String appSecret = "95011ac70909e8cca2786217dd80ee3f"; //拼接 String get_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + "appid=" + appId + "&secret=" + appSecret + "&code=CODE&grant_type=authorization_code"; String get_userinfo = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN"; request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String code = request.getParameter("code"); System.out.println("******************code=" + code); get_access_token_url = get_access_token_url.replace("CODE", code); String json = HttpsGetUtil.doHttpsGetJson(get_access_token_url); JSONObject jsonObject = JSONObject.fromObject(json); String access_token = jsonObject.getString("access_token"); String openid = jsonObject.getString("openid"); get_userinfo = get_userinfo.replace("ACCESS_TOKEN", access_token); get_userinfo = get_userinfo.replace("OPENID", openid); String userInfoJson = HttpsGetUtil.doHttpsGetJson(get_userinfo); JSONObject userInfoJO = JSONObject.fromObject(userInfoJson); String user_openid = userInfoJO.getString("openid"); String user_nickname = userInfoJO.getString("nickname"); String user_sex = userInfoJO.getString("sex"); String user_province = userInfoJO.getString("province"); String user_city = userInfoJO.getString("city"); String user_country = userInfoJO.getString("country"); String user_headimgurl = userInfoJO.getString("headimgurl"); response.setContentType("text/html; charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method \n"); out.println("openid:" + user_openid + "\n\n"); out.println("nickname:" + user_nickname + "\n\n"); out.println("sex:" + user_sex + "\n\n"); out.println("province:" + user_province + "\n\n"); out.println("city:" + user_city + "\n\n"); out.println("country:" + user_country + "\n\n"); out.println("<img src=/" + user_headimgurl + "/"); out.println(">"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); }else{ PrintWriter out = response.getWriter(); out.print(echostr); } } }
import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class HttpsGetUtil { public static String doHttpsGetJson(String Url) { String message = ""; try { System.out.println("doHttpsGetJson");//TODO:dd URL urlGet = new URL(Url); HttpURLConnection http = (HttpURLConnection) urlGet.openConnection(); http.setRequestMethod("GET"); //必须是get方式请求 24 http.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); http.setDoOutput(true); http.setDoInput(true); System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒28 System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒29 30 http.connect(); InputStream is =http.getInputStream(); int size =is.available(); byte[] jsonBytes =new byte[size]; is.read(jsonBytes); message=new String(jsonBytes,"UTF-8"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return message; } }
本文来自博客园,作者:King-DA,转载请注明原文链接:https://www.cnblogs.com/qingmuchuanqi48/p/11628667.html