标签:use stc method lan image img 返回 tle index
weixin4j封装好的SnsComponent组件中的方法可以执行该步骤
WeixinUserInfoController :
package com.baigehuidi.demo.controller; import com.baigehuidi.demo.loader.WeixinInsLoader; import com.baigehuidi.demo.weixin4j.WeixinException; import com.baigehuidi.demo.weixin4j.model.sns.SnsUser; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/user") public class WeixinUserInfoController { @RequestMapping("/getSnsUserInfoByCode") public Map getSnsUserInfoByCode(@RequestBody String code) throws WeixinException { Map map = new HashMap(); System.out.println("code:"+code); SnsUser snsUser = WeixinInsLoader.getWeixinInstance().sns().getSnsUserByCode(code); map.put("SnsUser",snsUser); return map; } }
这个控制层通过传入code返回SnsUser的用户实例.
前端是Ajax请求:
index.jsp : (或是什么html 也可以执行ajax请求)
前端继而解析json将用户的头像昵称等展示在页面之上.
<%@ page import="com.baigehuidi.demo.weixin4j.model.sns.SnsUser" %> <%@ page import="com.baigehuidi.demo.weixin4j.component.SnsComponent" %> <%@ page import="com.baigehuidi.demo.weixin4j.Weixin" %><%-- Created by IntelliJ IDEA. User: SeeClanUkyo Date: 2018/12/10 Time: 8:41 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>首页</title> <script src="http://www.jq22.com/jquery/jquery-3.3.1.js"></script> </head> <body> index.jsp <%--<% String code = request.getParameter("code");%>--%> <%--<%= code %>--%> <%--<% Weixin weixin = new Weixin();%>--%> <%--<% SnsUser snsUser = weixin.sns().getSnsUserByCode(code);%>--%> <%--<%=snsUser.getNickname()%>--%> <!-- <button id="btn">btn</button> --> <!-- 通过ajax获取的用户信息封装在data中,可以根据需要获取不同的参数,如 --> <script> // $("#btn").click(getSnsUser); // function getSnsUser(){ // alert("getSnsUser begin") $.ajax({ url:"/user/getSnsUserInfoByCode", data:"<%=request.getParameter("code")%>", contentType:"application/json", dataType:"json", method:"POST", success:function(data){ alert(JSON.stringify(data)); //将数据反填到html或jsp页面上 } }); // } </script> </body> </html>
每个code只能使用一次,一次后作废.
当用户退出网页,再次点击网页授权,会再获取code值,再次执行如上操作.
其它的操作可见下图:
[微信开发] - weixin4j获取网页授权后的code进而获取用户信息
标签:use stc method lan image img 返回 tle index
原文地址:https://www.cnblogs.com/ukzq/p/10099715.html