1. 程式人生 > >[微信開發] - weixin4j獲取網頁授權後的code進而獲取用戶信息

[微信開發] - weixin4j獲取網頁授權後的code進而獲取用戶信息

port -c ota UNC ets ces rip return mage

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進而獲取用戶信息