当前位置: 移动技术网 > IT编程>开发语言>Java > Java微信公众平台开发(十)--微信用户信息的获取

Java微信公众平台开发(十)--微信用户信息的获取

2019年05月30日  | 移动技术网IT编程  | 我要评论

前面的文章有讲到微信的一系列开发文章,包括token获取、菜单创建等,在这一篇将讲述在微信公众平台开发中如何获取微信用户的信息,在上一篇我们有说道微信用户和微信公众账号之间的联系可以通过openid关联,所以在这里我们就采用openid去获取用户微信信息。并实现两个个简单场景应用:(一)当微信新用户关注我们的微信公众平台的时候我们自动回复一篇图文消息,然后在图文消息中标题为:【尊敬的:xxx,你好!】,而且在图文消息中的图片就是用户的微信头像,如下图:(二)pc界面显示用户的昵称,性别,头像

 

(一)关注被动回复图文消息的实现。

有关获取微信用户信息的文档我们可以参照: 。

(一)用户微信消息的获取实现

在关注者与公众号产生消息交互后,公众号可获得关注者的openid(加密后的微信号,每个用户对每个公众号的openid是唯一的。对于不同公众号,同一用户的openid不同)。公众号可通过本接口来根据openid获取用户基本信息,包括昵称、头像、性别、所在城市、语言和关注时间。

http请求方式: get https://api.weixin.qq.com/cgi-bin/user/info?access_token=access_token&openid=openid&lang=zh_cn

在这里我写了一个方法类getuseinfo.java,在方法中我们只需要传入openid即可返回(昵称,图像、性别【其他参数可自行获取】),代码实现如下:

 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年5月29日 上午11:52:26
11 * @description :
12 */
13 public class getuseinfo {
14     /**
15      * @description: 通过openid获取用户微信信息
16      * @param @param openid
17      * @param @return
18      * @param @throws exception   
19      * @author dapengniao
20      * @date 2016年3月18日 下午2:01:30
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"));  //定时器中获取到的token
28         params.put("openid", openid);  //需要获取的用户的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         //这里返回参数只取了昵称、头像、和性别
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); //昵称
42         params.put("headimgurl",
43                 headimgurl);  //图像
44         params.put("sex", sex);  //性别
45        
46         return params;
47     }
48 }

(二)关注回复图文消息实现

在第一部分中有说道【在关注者与公众号产生消息交互后,公众号可获得关注者的openid】,在我们的场景中获取关注者openid的事件就是用户的关注事件,同时我们也是在关注事件中给关注者被动回复图文消息,其实现过程:

  • 通过关注事件获取到openid,调用获取用户信息接口获取关注者相关接口;

  • 在关注事件被动回复中设置图文消息的title以及图片,回复给关注者;

简单代码实现如下:

 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)) { // 关注事件
 7             system.out.println("==============这是关注事件!");
 8             try {
 9                 hashmap<string, string> userinfo = getuseinfo.openid_userinfo(openid);
10                 article article = new article();
11                 article.setdescription("欢迎来到歌德的个人博客:菜鸟程序员成长之路!"); // 图文消息的描述
12                 article.setpicurl(userinfo.get("headimgurl")); // 图文消息图片地址
13                 article.settitle("尊敬的:" + userinfo.get("nickname") + ",你好!"); // 图文消息标题
14                 article.seturl("https://www.cnblogs.com/gede"); // 图文url链接
15                 list<article> list = new arraylist<article>();
16                 list.add(article); // 这里发送的是单图文,如果需要发送多图文则在这里list中加入多个article即可!
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("====代码有问题额☺!");
23             }
24 
25         }

最终我们可以来看看我们的成果,这里为了看到效果很直观我先取消关注然后再次关注的,如下图:

(二)pc界面显示用户

(一)添加需要用到的jsp页面。

①在webi-nfo目录下添加home.jsp。简单的home跳转界面,之所以不直接使用跳转后界面是为了添加代码的友好性。

 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>

②在webi-nfo目录下添加userinfo.jsp。 通过上面被动回复我们不难发现,获取用户信息最重要的是要得到相关公众号对应的openid,所以这里来一个简单的表单提交。

 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>输入oppenid</title>
 6   </head>
 7   <body>
 8       <form action="userinfo/register" >
 9           <h1>请输入用户openid:<input name="openid" type="text"></h1>
10           <input type="submit">
11       </form>
12   </body>
13 </html>

③在webi-nfo目录下添加user.jsp。这个界面是用来请求成功以后,展示用户信息的界面。

 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>

(二)在getuseinfo中添加openid_userinfo1方法。这里起名比较随便。之前我们获取用户信息是定义了一个静态static final类,但是当放在mvc中时,就有点突兀。所以我们重新写了一个名为openid_userinfo1的类方法。其返回类型时一个userinfo类。这里我们使用userinfo类来对查到的用户信息进行封装,返回。

①添加userinfo实体类

 1 package com.gede.wechat.message.response;
 2 /**
 3 * @author gede
 4 * @version date:2019年5月29日 上午11:54:03
 5 * @description :
 6 */
 7 public class userinfo {
 8     public string nickname;    //用户昵称
 9     public string headimgurl;  //头像
10     public string sex;            //性别
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 }

②在getuseinfo中添加openid_userinfo1方法,简单代码如下:

 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"));  //定时器中获取到的token
 7         params.put("openid", openid);  //需要获取的用户的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         //这里返回参数只取了昵称、头像、和性别
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); //昵称
21         params.put("headimgurl",
22                 headimgurl);  //图像
23         params.put("sex", sex);  //性别
24        
25         return ui;
26     }

(三)配置我们相关的controller。

①首先我们添加houme解析试图。简单代码如下,有不懂的可以去看我下的spring,里面有详解。

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.jsp
        return "home";
    }
}

①再定义我们的getusercontrollerh获取信息控制器,简单代码如下:

 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年5月29日 下午12:04:08
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         //响应超链接,返回userinfo.jsp
27         return "userinfo";
28     }
29     @requestmapping(value="/register",method=requestmethod.get)
30     public string register(httpservletrequest request){
31         //通过request获取input中提交的openid
32         string openid=request.getparameter("openid");
33         //openid为参数的重定向转发
34         return "redirect:/userinfo/"+openid;
35     }
36     @requestmapping(value="/{openid}")
37     public string search(@pathvariable("openid") string openid,model model) throws exception{
38         //@pathvariable通过路径解析来获取传过来的openid
39         gui=new getuseinfo();
40         model.addattribute("gui", gui.openid_userinfo1(openid));
41         return "user";
42     }
43 }

这个时候我们的pc界面配置也就完成了。运行项目。在浏览器地址栏中输入:.就可以访问到了。

到这里通过openid获取用户信息的实现就结束啦。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网