In the previous article, we talked about a series of development articles about Wechat, including token acquisition, menu creation and so on. In this article, we will talk about how to get the information of Wechat users in the development of Wechat public platform. In the previous article, we said that the connection between Wechat users and Wechat public accounts can be linked through Openid, so we use openid to get the information of Wechat users. . Two simple scenarios are implemented: (1) When new users of Wechat pay attention to our Wechat public platform, we automatically reply to an image message, and then the title of the image message is: [Respect: XXX, hello! ] And the picture in the text message is the user's Weixin avatar, as follows: (2) The pc interface shows the user's nickname, gender, avatar.
(1) Focus on the implementation of passive reply to graphics and text messages.
We can refer to the documents for obtaining information about micro-credit users. http://mp.weixin.qq.com/wiki/1/8a5ce6257f1d3b2afb20f83e72b72ce9.html .
(1) Acquisition and Implementation of User Wechat Message
After the follower interacts with the public number, the public number can get the follower's OpenID (encrypted micro-signal, each user's OpenID for each public number is unique). For different public numbers, the same user's openid is different. Public numbers can access basic user information according to OpenID through this interface, including nicknames, avatars, gender, city, language and attention time.
http Request mode: GET https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
Here I write a method class GetUseInfo.java, in which we only need to pass in openid to return (nickname, image, gender [other parameters can be obtained by ourselves). The code is as follows:
1 package com.gede.wechat.common; 2 import java.util.HashMap; 3 import com.gede.web.util.GlobalConstants; 4 import com.gede.wechat.response.UserInfo; 5 import com.gede.wechat.util.HttpUtils; 6 7 import net.sf.json.JSONObject; 8 /** 9 * @author gede 10 * @version date: 2019 May 29, 2000, 11:52:26 a.m. 11 * @description : 12 */ 13 public class GetUseInfo { 14 /** 15 * @Description: Getting User Wechat Information through openid 16 * @param @param openid 17 * @param @return 18 * @param @throws Exception 19 * @author dapengniao 20 * @date 2016 March 18, 2000, 2:01:30 p.m. 21 */ 22 public static HashMap<String, String> Openid_userinfo(String openid) 23 throws Exception { 24 HashMap<String, String> params = new HashMap<String, String>(); 25 UserInfo ui=null; 26 params.put("access_token", 27 GlobalConstants.getInterfaceUrl("access_token")); //Obtained in the timer token 28 params.put("openid", openid); //User's openid 29 params.put("lang", "zh_CN"); 30 String subscribers = HttpUtils.sendGet( 31 GlobalConstants.getInterfaceUrl("OpenidUserinfoUrl"), params); 32 System.out.println(subscribers); 33 params.clear(); 34 //Here the return parameters are nicknames, avatars, and gender only. 35 String nickname=JSONObject.fromObject(subscribers).getString("nickname"); 36 String headimgurl=JSONObject.fromObject(subscribers).getString("headimgurl"); 37 String sex=JSONObject.fromObject(subscribers).getString("sex"); 38 39 ui=new UserInfo(nickname,headimgurl,sex); 40 params.put("nickname", 41 nickname); //Nickname? 42 params.put("headimgurl", 43 headimgurl); //image 44 params.put("sex", sex); //Gender 45 46 return params; 47 } 48 }
(2) Focus on the implementation of reply graphics and text messages
In the first part, it is said that the event of obtaining the openid of the follower in our scenario is the user's attention event, and we are also passively responding to the graphic message to the follower in the event of concern. The implementation process is as follows:
-
openid is acquired through attention events, and user information interface is invoked to acquire the relevant interface of the followers.
-
In passive response to attention events, title s and pictures of text messages are set to reply to the followers.
The simple code is implemented as follows:
1 NewsMessage newmsg = new NewsMessage(); 2 newmsg.setToUserName(openid); 3 newmsg.setFromUserName(mpid); 4 newmsg.setCreateTime(new Date().getTime()); 5 newmsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS); 6 if (map.get("Event").equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) { // Concerned events 7 System.out.println("==============This is an event of concern!"); 8 try { 9 HashMap<String, String> userinfo = GetUseInfo.Openid_userinfo(openid); 10 Article article = new Article(); 11 article.setDescription("Welcome to Goethe's Personal Blog: The Way for Rookie Programmers to Grow up!"); // Description of Graphic and Textual Messages 12 article.setPicUrl(userinfo.get("headimgurl")); // Graphic Message Picture Address 13 article.setTitle("Honorific:" + userinfo.get("nickname") + ",Hello!"); // Graphic and Textual Message Title 14 article.setUrl("https://www.cnblogs.com/gede"); // Image & Text url link 15 List<Article> list = new ArrayList<Article>(); 16 list.add(article); // Here you send a single text, and if you need to send multiple text, here you are. list Adding more than one Article Yes! 17 newmsg.setArticleCount(list.size()); 18 newmsg.setArticles(list); 19 return MessageUtil.newsMessageToXml(newmsg); 20 } catch (Exception e) { 21 // TODO Auto-generated catch block 22 System.out.println("====Code problematic amount☺!"); 23 } 24 25 }
Ultimately we can take a look at our results. In order to see the effect is very intuitive, I first cancel the focus and then pay attention to it again, as follows:
(2) Displaying Users in pc Interface
(1) Add jsp pages that need to be used.
(1) Add home.jsp in webi-nfo directory. The simple home jump interface is not directly used to add code friendliness.
1 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 2 <%@ page session="false" %> 3 <html> 4 <head> 5 </head> 6 <body> 7 <h1>Welcome to Mychat</h1> 8 <a href="<c:url value="/userinfo" />">UserInfo</a> | 9 </body> 10 </html>
(2) Add userinfo.jsp to webi-nfo directory. Through the above passive response, we can easily find that the most important thing to obtain user information is to get the openid corresponding to the relevant public number, so here comes a simple form submission.
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 3 <html> 4 <head> 5 <title>input OppenId</title> 6 </head> 7 <body> 8 <form action="userinfo/register" > 9 <h1>Please enter the user openid:<input name="openid" type="text"></h1> 10 <input type="submit"> 11 </form> 12 </body> 13 </html>
(3) Add user.jsp in webi-nfo directory. This interface is used to display user information when the request is successful.
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 3 <html> 4 <head> 5 <title>User</title> 6 </head> 7 <body> 8 <div class="userView"> 9 <div class="spittleMessage"><c:out value="${gui.nickname}" /></div> 10 <div> 11 <span class="spittleTime"><c:out value="${gui.sex}" /></span> 12 </div> 13 <img alt="" width="300" height="300" src="${gui.headimgurl}"> 14 </div> 15 </body> 16 </html>
(2) Add Openid_userinfo1 method in GetUseInfo. The name here is more casual. Previously, we defined a static final class to get user information, but when placed in mvc, it is a bit abrupt. So we rewrote a class method called Openid_userinfo1. The return type is a userinfo class. Here we use the userinfo class to encapsulate and return the user information found.
1. Adding UserInfo Entity Classes
1 package com.gede.wechat.message.response; 2 /** 3 * @author gede 4 * @version date: 2019 May 29, 2000, 11:54:03 a.m. 5 * @description : 6 */ 7 public class UserInfo { 8 public String nickname; //nickname 9 public String headimgurl; //Head portrait 10 public String sex; //Gender 11 public UserInfo(String nickname, String headimgurl, String sex) { 12 super(); 13 this.nickname = nickname; 14 this.headimgurl = headimgurl; 15 this.sex = sex; 16 } 17 public String getNickname() { 18 return nickname; 19 } 20 public void setNickname(String nickname) { 21 this.nickname = nickname; 22 } 23 public String getHeadimgurl() { 24 return headimgurl; 25 } 26 public void setHeadimgurl(String headimgurl) { 27 this.headimgurl = headimgurl; 28 } 29 public String getSex() { 30 return sex; 31 } 32 public void setSex(String sex) { 33 this.sex = sex; 34 } 35 36 }
(2) Add Openid_userinfo1 method in GetUseInfo, the simple code is as follows:
1 public UserInfo Openid_userinfo1(String openid) 2 throws Exception { 3 HashMap<String, String> params = new HashMap<String, String>(); 4 UserInfo ui=null; 5 params.put("access_token", 6 GlobalConstants.getInterfaceUrl("access_token")); //Obtained in the timer token 7 params.put("openid", openid); //User's openid 8 params.put("lang", "zh_CN"); 9 String subscribers = HttpUtils.sendGet( 10 GlobalConstants.getInterfaceUrl("OpenidUserinfoUrl"), params); 11 System.out.println(subscribers); 12 params.clear(); 13 //Here the return parameters are nicknames, avatars, and gender only. 14 String nickname=JSONObject.fromObject(subscribers).getString("nickname"); 15 String headimgurl=JSONObject.fromObject(subscribers).getString("headimgurl"); 16 String sex=JSONObject.fromObject(subscribers).getString("sex"); 17 18 ui=new UserInfo(nickname,headimgurl,sex); 19 params.put("nickname", 20 nickname); //Nickname? 21 params.put("headimgurl", 22 headimgurl); //image 23 params.put("sex", sex); //Gender 24 25 return ui; 26 }
(3) Configure our relevant controller.
First, we add houme parsing attempt. The simple code is as follows. If you don't understand it, you can see my Spring below. There are details in it.
package com.gede.wechat.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import static org.springframework.web.bind.annotation.RequestMethod.*; @Controller public class HomeController { @RequestMapping(value="/",method=GET) public String home(){ //Home page is parsed as home.jsp return "home"; } }
First, we redefine our GetUser Controller access information controller. The simple code is as follows:
1 package com.gede.wechat.controller; 2 import javax.servlet.http.HttpServletRequest; 3 import static org.springframework.web.bind.annotation.RequestMethod.GET; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.stereotype.Controller; 6 import org.springframework.ui.Model; 7 import org.springframework.web.bind.annotation.PathVariable; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 import org.springframework.web.bind.annotation.RequestMethod; 10 11 import com.gede.wechat.common.GetUseInfo; 12 import com.gede.wechat.menu.MenuMain; 13 14 15 /** 16 * @author gede 17 * @version date: 2019 May 29, 2000, 12:04:08 p.m. 18 * @description : 19 */ 20 @Controller 21 @RequestMapping("/userinfo") 22 public class GetUserController { 23 private GetUseInfo gui; 24 @RequestMapping(method=RequestMethod.GET) 25 public String userinfo(){ 26 //Response hyperlink, return userinfo.jsp 27 return "userinfo"; 28 } 29 @RequestMapping(value="/register",method=RequestMethod.GET) 30 public String register(HttpServletRequest request){ 31 //adopt request Obtain input Submitted in openid 32 String openid=request.getParameter("openid"); 33 //openid Redirected forwarding for parameters 34 return "redirect:/userinfo/"+openid; 35 } 36 @RequestMapping(value="/{openid}") 37 public String search(@PathVariable("openid") String openid,Model model) throws Exception{ 38 //@PathVariable Get the passed-in through path resolution openid 39 gui=new GetUseInfo(); 40 model.addAttribute("gui", gui.Openid_userinfo1(openid)); 41 return "user"; 42 } 43 }
At this time, our PC interface configuration is completed. Run the project. Enter in the browser address bar: http://zqfbk.iok.la/mychat It's accessible.
This is the end of the implementation of access to user information through openid.