当前位置: 移动技术网 > IT编程>开发语言>Java > 微信公众平台开发实战Java版之微信获取用户基本信息

微信公众平台开发实战Java版之微信获取用户基本信息

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

在关注者与公众号产生消息交互后,公众号可获得关注者的openid(加密后的微信号,每个用户对每个公众号的openid是唯一的。对于不同公众号,同一用户的openid不同)。

公众号可通过本接口来根据openid获取用户基本信息,包括昵称、头像、性别、所在城市、语言和关注时间。

开发者可通过openid来获取用户基本信息。请使用https协议。

我们可以看看官方的文档:获取用户的基本信息。

接口调用请求说明

 http请求方式: get

https://api.weixin.qq.com/cgi-bin/user/info?access_token=access_token&openid=openid&lang=zh_cn

参数说明

参数 是否必须 说明
access_token 调用接口凭证
openid 普通用户的标识,对当前公众号唯一
lang 返回国家地区语言版本,zh_cn 简体,zh_tw 繁体,en 英语

返回说明

正常情况下,微信会返回下述json数据包给公众号:

 {
  "subscribe": 1, 
  "openid": "o6_bmjrptlm6_2sgvt7hmzopfl2m", 
  "nickname": "band", 
  "sex": 1, 
  "language": "zh_cn", 
  "city": "广州", 
  "province": "广东", 
  "country": "中国", 
  "headimgurl":  "http://wx.qlogo.cn/mmopen/g3monuztnhkdmzicilibx6iafqac56vxlsufpb6n5wksyvy0chqkkiajsgq1dzutogvllrhjberqq4emsv84eavhiaiceqxibjxcfhe/0", 
  "subscribe_time": 1382694957,
  "unionid": " o6_bmasdasdsad6_2sgvt7hmzopfl"
  "remark": "",
  "groupid": 0
} 

参数说明

参数 说明
subscribe 用户是否订阅该公众号标识,值为0时,代表此用户没有关注该公众号,拉取不到其余信息。
openid 用户的标识,对当前公众号唯一
nickname 用户的昵称
sex 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
city 用户所在城市
country 用户所在国家
province 用户所在省份
language 用户的语言,简体中文为zh_cn
headimgurl 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像url将失效。
subscribe_time 用户关注时间,为时间戳。如果用户曾多次关注,则取最后关注时间
unionid 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。详见:获取用户个人信息(unionid机制)
remark 公众号运营者对粉丝的备注,公众号运营者可在微信公众平台用户管理界面对粉丝添加备注
groupid 用户所在的分组id

错误时微信会返回错误码等信息,json数据包示例如下(该示例为appid无效错误):

 {"errcode":40013,"errmsg":"invalid appid"} 

根据上面的信息,我们定义一个用户信息类来存放用户的基本信息。

package com.souvc.weixin.pojo;
/**
* 类名: weixinuserinfo </br>
* 描述: 微信用户的基本信息 </br>
* 开发人员: souvc </br>
* 创建时间: 2015-11-27 </br>
* 发布版本:v1.0 </br>
 */
public class weixinuserinfo {
  // 用户的标识
  private string openid;
  // 关注状态(1是关注,0是未关注),未关注时获取不到其余信息
  private int subscribe;
  // 用户关注时间,为时间戳。如果用户曾多次关注,则取最后关注时间
  private string subscribetime;
  // 昵称
  private string nickname;
  // 用户的性别(1是男性,2是女性,0是未知)
  private int sex;
  // 用户所在国家
  private string country;
  // 用户所在省份
  private string province;
  // 用户所在城市
  private string city;
  // 用户的语言,简体中文为zh_cn
  private string language;
  // 用户头像
  private string headimgurl;
  public string getopenid() {
    return openid;
  }
  public void setopenid(string openid) {
    this.openid = openid;
  }
  public int getsubscribe() {
    return subscribe;
  }
  public void setsubscribe(int subscribe) {
    this.subscribe = subscribe;
  }
  public string getsubscribetime() {
    return subscribetime;
  }
  public void setsubscribetime(string subscribetime) {
    this.subscribetime = subscribetime;
  }
  public string getnickname() {
    return nickname;
  }
  public void setnickname(string nickname) {
    this.nickname = nickname;
  }
  public int getsex() {
    return sex;
  }
  public void setsex(int sex) {
    this.sex = sex;
  }
  public string getcountry() {
    return country;
  }
  public void setcountry(string country) {
    this.country = country;
  }
  public string getprovince() {
    return province;
  }
  public void setprovince(string province) {
    this.province = province;
  }
  public string getcity() {
    return city;
  }
  public void setcity(string city) {
    this.city = city;
  }
  public string getlanguage() {
    return language;
  }
  public void setlanguage(string language) {
    this.language = language;
  }
  public string getheadimgurl() {
    return headimgurl;
  }
  public void setheadimgurl(string headimgurl) {
    this.headimgurl = headimgurl;
  }
} 

我们先来看看获取用户信息的接口:

https://api.weixin.qq.com/cgi-bin/user/info?access_token=access_token&openid=openid&lang=zh_cn

根据分析,获取用户的基本信息需要一个token。

package com.souvc.weixin.pojo;
/**
* 类名: token </br>
* 描述: 凭证 </br>
* 开发人员: souvc </br>
* 创建时间: 2015-11-27 </br>
* 发布版本:v1.0 </br>
 */
public class token {
  // 接口访问凭证
  private string accesstoken;
  // 凭证有效期,单位:秒
  private int expiresin;
  public string getaccesstoken() {
    return accesstoken;
  }
  public void setaccesstoken(string accesstoken) {
    this.accesstoken = accesstoken;
  }
  public int getexpiresin() {
    return expiresin;
  }
  public void setexpiresin(int expiresin) {
    this.expiresin = expiresin;
  }
}

https请求,需要的信任管理器

package com.souvc.weixin.util;
import java.security.cert.certificateexception;
import java.security.cert.x509certificate;
import javax.net.ssl.x509trustmanager;
/**
* 类名: myx509trustmanager </br>
* 描述:信任管理器 </br>
* 开发人员: souvc </br>
* 创建时间: 2015-11-27 </br>
* 发布版本:v1.0 </br>
 */
public class myx509trustmanager implements x509trustmanager {
  // 检查客户端证书
  public void checkclienttrusted(x509certificate[] chain, string authtype) throws certificateexception {
  }
  // 检查服务器端证书
  public void checkservertrusted(x509certificate[] chain, string authtype) throws certificateexception {
  }
  // 返回受信任的x509证书数组
  public x509certificate[] getacceptedissuers() {
    return null;
  }
}

封装了一个公共类:

package com.souvc.weixin.util;
import java.io.bufferedreader;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.io.unsupportedencodingexception;
import java.net.connectexception;
import java.net.url;
import javax.net.ssl.httpsurlconnection;
import javax.net.ssl.sslcontext;
import javax.net.ssl.sslsocketfactory;
import javax.net.ssl.trustmanager;
import net.sf.json.jsonexception;
import net.sf.json.jsonobject;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import com.souvc.weixin.pojo.token;
/**
* 类名: commonutil </br>
* 描述: 通用工具类 </br>
* 开发人员: souvc </br>
* 创建时间: 2015-11-27 </br>
* 发布版本:v1.0 </br>
 */
public class commonutil {
  private static logger log = loggerfactory.getlogger(commonutil.class);
  // 凭证获取(get)
  public final static string token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=appsecret";
  /**
   * 发送https请求
   * 
   * @param requesturl 请求地址
   * @param requestmethod 请求方式(get、post)
   * @param outputstr 提交的数据
   * @return jsonobject(通过jsonobject.get(key)的方式获取json对象的属性值)
   */
  public static jsonobject httpsrequest(string requesturl, string requestmethod, string outputstr) {
    jsonobject jsonobject = null;
    try {
      // 创建sslcontext对象,并使用我们指定的信任管理器初始化
      trustmanager[] tm = { new myx509trustmanager() };
      sslcontext sslcontext = sslcontext.getinstance("ssl", "sunjsse");
      sslcontext.init(null, tm, new java.security.securerandom());
      // 从上述sslcontext对象中得到sslsocketfactory对象
      sslsocketfactory ssf = sslcontext.getsocketfactory();
      url url = new url(requesturl);
      httpsurlconnection conn = (httpsurlconnection) url.openconnection();
      conn.setsslsocketfactory(ssf);
      conn.setdooutput(true);
      conn.setdoinput(true);
      conn.setusecaches(false);
      // 设置请求方式(get/post)
      conn.setrequestmethod(requestmethod);
      // 当outputstr不为null时向输出流写数据
      if (null != outputstr) {
        outputstream outputstream = conn.getoutputstream();
        // 注意编码格式
        outputstream.write(outputstr.getbytes("utf-8"));
        outputstream.close();
      }
      // 从输入流读取返回内容
      inputstream inputstream = conn.getinputstream();
      inputstreamreader inputstreamreader = new inputstreamreader(inputstream, "utf-8");
      bufferedreader bufferedreader = new bufferedreader(inputstreamreader);
      string str = null;
      stringbuffer buffer = new stringbuffer();
      while ((str = bufferedreader.readline()) != null) {
        buffer.append(str);
      }
      // 释放资源
      bufferedreader.close();
      inputstreamreader.close();
      inputstream.close();
      inputstream = null;
      conn.disconnect();
      jsonobject = jsonobject.fromobject(buffer.tostring());
    } catch (connectexception ce) {
      log.error("连接超时:{}", ce);
    } catch (exception e) {
      log.error("https请求异常:{}", e);
    }
    return jsonobject;
  }
  /**
   * 获取接口访问凭证
   * 
   * @param appid 凭证
   * @param appsecret 密钥
   * @return
   */
  public static token gettoken(string appid, string appsecret) {
    token token = null;
    string requesturl = token_url.replace("appid", appid).replace("appsecret", appsecret);
    // 发起get请求获取凭证
    jsonobject jsonobject = httpsrequest(requesturl, "get", null);
    if (null != jsonobject) {
      try {
        token = new token();
        token.setaccesstoken(jsonobject.getstring("access_token"));
        token.setexpiresin(jsonobject.getint("expires_in"));
      } catch (jsonexception e) {
        token = null;
        // 获取token失败
        log.error("获取token失败 errcode:{} errmsg:{}", jsonobject.getint("errcode"), jsonobject.getstring("errmsg"));
      }
    }
    return token;
  }
  /**
   * url编码(utf-8)
   * 
   * @param source
   * @return
   */
  public static string urlencodeutf8(string source) {
    string result = source;
    try {
      result = java.net.urlencoder.encode(source, "utf-8");
    } catch (unsupportedencodingexception e) {
      e.printstacktrace();
    }
    return result;
  }
  /**
   * 根据内容类型判断文件扩展名
   * 
   * @param contenttype 内容类型
   * @return
   */
  public static string getfileext(string contenttype) {
    string fileext = "";
    if ("image/jpeg".equals(contenttype))
      fileext = ".jpg";
    else if ("audio/mpeg".equals(contenttype))
      fileext = ".mp3";
    else if ("audio/amr".equals(contenttype))
      fileext = ".amr";
    else if ("video/mp4".equals(contenttype))
      fileext = ".mp4";
    else if ("video/mpeg4".equals(contenttype))
      fileext = ".mp4";
    return fileext;
  }
}

获取用户基本信息的方法:

/**
   * 获取用户信息
   * 
   * @param accesstoken 接口访问凭证
   * @param openid 用户标识
   * @return weixinuserinfo
   */
  public static weixinuserinfo getuserinfo(string accesstoken, string openid) {
    weixinuserinfo weixinuserinfo = null;
    // 拼接请求地址
    string requesturl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=access_token&openid=openid";
    requesturl = requesturl.replace("access_token", accesstoken).replace("openid", openid);
    // 获取用户信息
    jsonobject jsonobject = commonutil.httpsrequest(requesturl, "get", null);
    if (null != jsonobject) {
      try {
        weixinuserinfo = new weixinuserinfo();
        // 用户的标识
        weixinuserinfo.setopenid(jsonobject.getstring("openid"));
        // 关注状态(1是关注,0是未关注),未关注时获取不到其余信息
        weixinuserinfo.setsubscribe(jsonobject.getint("subscribe"));
        // 用户关注时间
        weixinuserinfo.setsubscribetime(jsonobject.getstring("subscribe_time"));
        // 昵称
        weixinuserinfo.setnickname(jsonobject.getstring("nickname"));
        // 用户的性别(1是男性,2是女性,0是未知)
        weixinuserinfo.setsex(jsonobject.getint("sex"));
        // 用户所在国家
        weixinuserinfo.setcountry(jsonobject.getstring("country"));
        // 用户所在省份
        weixinuserinfo.setprovince(jsonobject.getstring("province"));
        // 用户所在城市
        weixinuserinfo.setcity(jsonobject.getstring("city"));
        // 用户的语言,简体中文为zh_cn
        weixinuserinfo.setlanguage(jsonobject.getstring("language"));
        // 用户头像
        weixinuserinfo.setheadimgurl(jsonobject.getstring("headimgurl"));
      } catch (exception e) {
        if (0 == weixinuserinfo.getsubscribe()) {
          log.error("用户{}已取消关注", weixinuserinfo.getopenid());
        } else {
          int errorcode = jsonobject.getint("errcode");
          string errormsg = jsonobject.getstring("errmsg");
          log.error("获取用户信息失败 errcode:{} errmsg:{}", errorcode, errormsg);
        }
      }
    }
    return weixinuserinfo;
  } 

测试的方法:注意将以下替换为自己的appid和秘钥。

public static void main(string args[]) {
    // 获取接口访问凭证
    string accesstoken = commonutil.gettoken("xxxx", "xxxx").getaccesstoken();
    /**
     * 获取用户信息
     */
    weixinuserinfo user = getuserinfo(accesstoken, "ook-yujvd9geegh6nrien-gnlrvw");
    system.out.println("openid:" + user.getopenid());
    system.out.println("关注状态:" + user.getsubscribe());
    system.out.println("关注时间:" + user.getsubscribetime());
    system.out.println("昵称:" + user.getnickname());
    system.out.println("性别:" + user.getsex());
    system.out.println("国家:" + user.getcountry());
    system.out.println("省份:" + user.getprovince());
    system.out.println("城市:" + user.getcity());
    system.out.println("语言:" + user.getlanguage());
    system.out.println("头像:" + user.getheadimgurl());
  } 

效果如下:

openid:ook-yujvd9geegh6nrien-gnlrvw
关注状态:1
关注时间:1449021142
昵称:风少
性别:1
国家:中国
省份:广东
城市:广州
语言:zh_cn
头像:

以上内容给大家介绍了微信公众平台开发实战java版之微信获取用户基本信息,希望本文分享对大家今后的工作学习有所帮助,同时感谢大家一直以来对移动技术网网站的支持。

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

相关文章:

验证码:
移动技术网