[微信开发] - weixin4j关键类解析
TokenUtil :
- get()获取我方自定义的token(从配置文件或数据库)
- checkSignature(Str..... (服务器配置连接验证有效性)
- /*
- * 微信公众平台(JAVA) SDK
- *
- * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved.
- *
- */
- package com.baigehuidi.demo.weixin4j.util;
- import com.baigehuidi.demo.weixin4j.Configuration;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.List;
- /**
- *
- * <p>
- * Title: 微信公众平台Token算法工具类</p>
- *
- * <p>
- * Description: 为应用提供URL算法<br /> 根据不同的URL返回不同的Token,以适应多微站的需求<br />
- * 例如:Url:http://www.weixin4j.org/api/tiexinqiao<br />
- * 则默认Token:为jEvQdLxi0PvtgK8N+HzUpA==<br /> 根据配置的系统Token不同,而改变</p>
- *
- * @author 杨启盛<qsyang@ansitech.com>
- * @since 0.0.1
- */
- public class TokenUtil {
- //此加密密钥用于加密公众号Token,一经配置,不能修改,一旦修改,所有公众号需要重新填写Token
- private static String systemToken = null;
- /**
- * 获取配置文件配置的Token
- *
- * @return 微站Token
- */
- public static String get() {
- if (systemToken == null) {
- systemToken = Configuration.getProperty("weixin4j.token", "baige");
- }
- return systemToken;
- }
- /**
- * 加密/校验流程如下:
- *
- * <p>
- * 1. 将token、timestamp、nonce三个参数进行字典序排序<br>
- * 2.将三个参数字符串拼接成一个字符串进行sha1加密<br>
- * 3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信<br>
- * </p>
- *
- * @param token Token验证密钥 是服务器内部的,(数据库存好的,这里的token在properties配置文件中)
- * @param signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数,nonce参数
- * @param timestamp 时间戳
- * @param nonce 随机数
- * @return 验证成功返回true,否则返回false
- */
- public static boolean checkSignature(String token, String signature, String timestamp, String nonce) {
- List<String> params = new ArrayList<String>();
- params.add(token);
- params.add(timestamp);
- params.add(nonce);
- //1. 将token、timestamp、nonce三个参数进行字典序排序
- Collections.sort(params, new Comparator<String>() {
- @Override
- public int compare(String o1, String o2) {
- return o1.compareTo(o2);
- }
- });
- //2. 将三个参数字符串拼接成一个字符串进行sha1加密
- String temp = SHA1.encode(params.get(0) + params.get(1) + params.get(2));
- //3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
- return temp.equals(signature);
- }
- }
这里的get获取的是自己服务器数据库中或springboot配置文件中的自己设定好的token,用来跟服务器端的进行比对.
其后几个消息处理器和事件处理器也是很重要的,而且要将自己配置好的该类(或者如果使用weixin4j.jar则需要继承这些处理器类)
K神全栈 < 这个是weixin4j的官方微信平台
其中提到了Weixin对象是整个weixin4j的核心
Weixin类 :
- /*
- * 微信公众平台(JAVA) SDK
- **/
- package com.baigehuidi.demo.weixin4j;
- import com.baigehuidi.demo.weixin4j.component.*;
- import com.baigehuidi.demo.weixin4j.loader.DefaultTicketLoader;
- import com.baigehuidi.demo.weixin4j.loader.DefaultTokenLoader;
- import com.baigehuidi.demo.weixin4j.loader.ITicketLoader;
- import com.baigehuidi.demo.weixin4j.loader.ITokenLoader;
- import com.baigehuidi.demo.weixin4j.model.base.Token;
- import com.baigehuidi.demo.weixin4j.model.js.Ticket;
- import com.baigehuidi.demo.weixin4j.model.js.TicketType;
- import java.io.Serializable;
- import java.util.HashMap;
- import java.util.Map;
- /**
- * 微信平台基础支持对象
- *
- * @author 杨启盛<qsyang@ansitech.com>
- * @since 0.0.1
- */
- public class Weixin extends WeixinSupport implements Serializable {
- /**
- * 同步锁
- */
- private final static byte[] LOCK = new byte[0];
- /**
- * 公众号开发者ID
- */
- private final String appId;
- /**
- * 公众号开发者密钥
- */
- private final String secret;
- /**
- * 公众号名称
- */
- private String name;
- /**
- * 公众号配置
- *
- * @since 0.1.3
- */
- private final WeixinConfig weixinConfig;
- /**
- * 微信支付配置
- *
- * @since 0.1.3
- */
- private final WeixinPayConfig weixinPayConfig;
- /**
- * AccessToken加载器
- */
- protected ITokenLoader tokenLoader = new DefaultTokenLoader();
- /**
- * Ticket加载器
- */
- protected ITicketLoader ticketLoader = new DefaultTicketLoader();
- /**
- * 新增组件
- */
- private final Map<String, AbstractComponent> components = new HashMap<String, AbstractComponent>();
- /**
- * 单公众号,并且只支持一个公众号方式
- * @param
- */
- public Weixin() {
- this(Configuration.getOAuthAppId(), Configuration.getOAuthSecret(),Configuration.getName());
- }
- /**
- * 多公众号,同一个环境中使用方式
- *
- * @param appId 公众号开发者AppId
- * @param secret 公众号开发者秘钥
- */
- public Weixin(String appId, String secret, String name) {
- this.appId = appId;
- this.secret = secret;
- this.name = name;
- weixinConfig = new WeixinConfig();
- weixinConfig.setAppid(appId);
- weixinConfig.setSecret(secret);
- weixinConfig.setOriginalid(Configuration.getProperty("weixin4j.oauth.originalid"));
- weixinConfig.setEncodingtype(Configuration.getIntProperty("weixin4j.oauth.encodingtype"));
- weixinConfig.setEncodingaeskey(Configuration.getProperty("weixin4j.oauth.encodingaeskey"));
- weixinConfig.setOauthUrl(Configuration.getProperty("weixin4j.oauth.url"));
- weixinConfig.setApiDomain(Configuration.getProperty("weixin4j.api.domain"));
- weixinPayConfig = new WeixinPayConfig();
- weixinPayConfig.setPartnerId(Configuration.getProperty("weixin4j.pay.partner.id"));
- weixinPayConfig.setPartnerKey(Configuration.getProperty("weixin4j.pay.partner.key"));
- weixinPayConfig.setNotifyUrl(Configuration.getProperty("weixin4j.pay.notify_url"));
- weixinPayConfig.setCertPath(Configuration.getProperty("weixin4j.http.cert.path"));
- weixinPayConfig.setCertSecret(Configuration.getProperty("weixin4j.http.cert.secret"));
- }
- /**
- * 外部配置注入方式,更灵活
- *
- * @param weixinConfig 微信公众号配置
- * @since 0.1.3
- */
- public Weixin(WeixinConfig weixinConfig) {
- this(weixinConfig, null);
- }
- /**
- * 外部配置注入方式(带微信支付),更灵活
- *
- * @param weixinPayConfig 微信支付配置
- * @since 0.1.3
- */
- public Weixin(WeixinPayConfig weixinPayConfig) {
- this.appId = Configuration.getOAuthAppId();
- this.secret = Configuration.getOAuthSecret();
- weixinConfig = new WeixinConfig();
- weixinConfig.setAppid(Configuration.getOAuthAppId());
- weixinConfig.setSecret(Configuration.getOAuthSecret());
- weixinConfig.setOriginalid(Configuration.getProperty("weixin4j.oauth.originalid"));
- weixinConfig.setEncodingtype(Configuration.getIntProperty("weixin4j.oauth.encodingtype"));
- weixinConfig.setEncodingaeskey(Configuration.getProperty("weixin4j.oauth.encodingaeskey"));
- weixinConfig.setOauthUrl(Configuration.getProperty("weixin4j.oauth.url"));
- weixinConfig.setApiDomain(Configuration.getProperty("weixin4j.api.domain"));
- this.weixinPayConfig = weixinPayConfig;
- }
- /**
- * 外部配置注入方式(带微信支付),更灵活
- *
- * @param weixinConfig 微信公众号配置
- * @param weixinPayConfig 微信支付配置
- * @since 0.1.3
- */
- public Weixin(WeixinConfig weixinConfig, WeixinPayConfig weixinPayConfig) {
- this.appId = weixinConfig.getAppid();
- this.secret = weixinConfig.getSecret();
- this.weixinConfig = weixinConfig;
- this.weixinPayConfig = weixinPayConfig;
- }
- public String getAppId() {
- return appId;
- }
- public String getSecret() {
- return secret;
- }
- public String getName() {
- return name;
- }
- /**
- * 获取Token对象
- *
- * @return Token对象
- * @throws WeixinException
- * @since 0.1.0
- */
- public Token getToken() throws WeixinException {
- Token token = tokenLoader.get();
- if (token == null) {
- synchronized (LOCK) {
- token = tokenLoader.get();
- if (token == null) {
- token = base().token();
- tokenLoader.refresh(token);
- }
- }
- }
- return token;
- }
- /**
- * 获取jsapi开发ticket
- *
- * @return jsapi_ticket
- * @throws WeixinException
- */
- public Ticket getJsApiTicket() throws WeixinException {
- Ticket ticket = ticketLoader.get(TicketType.JSAPI);
- if (ticket == null) {
- synchronized (LOCK) {
- ticket = ticketLoader.get(TicketType.JSAPI);
- if (ticket == null) {
- ticket = js().getJsApiTicket();
- ticketLoader.refresh(ticket);
- }
- }
- }
- return ticket;
- }
- public BaseComponent base() {
- String key = BaseComponent.class.getName();
- if (components.containsKey(key)) {
- return (BaseComponent) components.get(key);
- }
- BaseComponent component = new BaseComponent(this);
- components.put(key, component);
- return component;
- }
- public JsSdkComponent js() {
- String key = JsSdkComponent.class.getName();
- if (components.containsKey(key)) {
- return (JsSdkComponent) components.get(key);
- }
- JsSdkComponent component = new JsSdkComponent(this);
- components.put(key, component);
- return component;
- }
- public UserComponent user() {
- String key = UserComponent.class.getName();
- if (components.containsKey(key)) {
- return (UserComponent) components.get(key);
- }
- UserComponent component = new UserComponent(this);
- components.put(key, component);
- return component;
- }
- public SnsComponent sns() {
- String key = SnsComponent.class.getName();
- if (components.containsKey(key)) {
- return (SnsComponent) components.get(key);
- }
- SnsComponent component = new SnsComponent(this);
- components.put(key, component);
- return component;
- }
- public SnsComponent sns(String authorize_url) {
- String key = SnsComponent.class.getName();
- if (components.containsKey(key)) {
- return (SnsComponent) components.get(key);
- }
- SnsComponent component = new SnsComponent(this, authorize_url);
- components.put(key, component);
- return component;
- }
- public TagsComponent tags() {
- String key = TagsComponent.class.getName();
- if (components.containsKey(key)) {
- return (TagsComponent) components.get(key);
- }
- TagsComponent component = new TagsComponent(this);
- components.put(key, component);
- return component;
- }
- public GroupsComponent groups() {
- String key = GroupsComponent.class.getName();
- if (components.containsKey(key)) {
- return (GroupsComponent) components.get(key);
- }
- GroupsComponent component = new GroupsComponent(this);
- components.put(key, component);
- return component;
- }
- public PayComponent pay() {
- String key = PayComponent.class.getName();
- if (components.containsKey(key)) {
- return (PayComponent) components.get(key);
- }
- PayComponent component = new PayComponent(this);
- components.put(key, component);
- return component;
- }
- public RedpackComponent redpack() {
- String key = RedpackComponent.class.getName();
- if (components.containsKey(key)) {
- return (RedpackComponent) components.get(key);
- }
- RedpackComponent component = new RedpackComponent(this);
- components.put(key, component);
- return component;
- }
- //消息发送组件
- public MessageComponent message() {
- String key = MessageComponent.class.getName();
- if (components.containsKey(key)) {
- return (MessageComponent) components.get(key);
- }
- MessageComponent component = new MessageComponent(this);
- components.put(key, component);
- return component;
- }
- //创建自定义菜单组件
- public MenuComponent menu() {
- String key = MenuComponent.class.getName();
- if (components.containsKey(key)) {
- return (MenuComponent) components.get(key);
- }
- MenuComponent component = new MenuComponent(this);
- components.put(key, component);
- return component;
- }
- public MediaComponent media() {
- String key = MediaComponent.class.getName();
- if (components.containsKey(key)) {
- return (MediaComponent) components.get(key);
- }
- MediaComponent component = new MediaComponent(this);
- components.put(key, component);
- return component;
- }
- @Deprecated
- public FileComponent file() {
- String key = FileComponent.class.getName();
- if (components.containsKey(key)) {
- return (FileComponent) components.get(key);
- }
- FileComponent component = new FileComponent(this);
- components.put(key, component);
- return component;
- }
- public MaterialComponent material() {
- String key = MaterialComponent.class.getName();
- if (components.containsKey(key)) {
- return (MaterialComponent) components.get(key);
- }
- MaterialComponent component = new MaterialComponent(this);
- components.put(key, component);
- return component;
- }
- public QrcodeComponent qrcode() {
- String key = QrcodeComponent.class.getName();
- if (components.containsKey(key)) {
- return (QrcodeComponent) components.get(key);
- }
- QrcodeComponent component = new QrcodeComponent(this);
- components.put(key, component);
- return component;
- }
- /**
- * 获取微信配置对象
- *
- * @return 微信配置对象
- * @since 0.1.3
- */
- public WeixinConfig getWeixinConfig() {
- return weixinConfig;
- }
- /**
- * 获取微信支付配置对象
- *
- * @return 微信支付配置对象
- * @since 0.1.3
- */
- public WeixinPayConfig getWeixinPayConfig() {
- return weixinPayConfig;
- }
- }
Weixin类创建的weixin对象主要提供我们需要和微信公众平台接口交互的所有组件类.
在util包中的CommonUtil : 新加入方法 获取微信服务器ip地址集
- package com.baigehuidi.demo.weixin4j.util;
- import com.baigehuidi.demo.loader.WeixinInsLoader;
- import com.baigehuidi.demo.weixin4j.WeixinException;
- import java.io.UnsupportedEncodingException;
- import java.util.List;
- import static java.net.URLEncoder.encode;
- public class CommonUtil {
- /**
- * URL编码 转换url路径拼接微信api路径
- * @param source
- * @return
- */
- public static String urlEncodeUTF8(String source){
- String resultURL = source;
- try {
- resultURL = encode(source,"utf-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } finally {
- }
- return resultURL;
- }
- /**
- * 获取微信服务器ip地址集
- * @return callbackIps
- */
- public static List<String> getWeixinIPs(){
- try {
- List<String> callbackIps = WeixinInsLoader.getWeixinInstance().base().getCallbackIp();
- System.out.println("获取微信服务器ip地址中...");
- return callbackIps;
- } catch (WeixinException e) {
- System.out.println("获取微信服务器ip地址失败...");
- e.printStackTrace();
- return null;
- } finally {
- }
- }
- }
测试了下获取了218条ip地址
component包中的UserComponent类,是用户管理组件,
其内方法有设置用户备注名,(批量)获取用户基本信息(包括UnionID机制,几个不同类型的构造器),获取所有用户列表(以及从哪个openid开始获取),获取标签下所有粉丝列表(以及从哪个openid开始获取).
其中可以必能用到的就是获取用户基本信息了.(批量获取的为接收 String[] openids )
- /*
- * 微信公众平台(JAVA) SDK*/
- package com.baigehuidi.demo.weixin4j.component;
- import com.alibaba.fastjson.JSONArray;
- import com.alibaba.fastjson.JSONObject;
- import com.baigehuidi.demo.weixin4j.Configuration;
- import com.baigehuidi.demo.weixin4j.Weixin;
- import com.baigehuidi.demo.weixin4j.WeixinException;
- import com.baigehuidi.demo.weixin4j.http.HttpsClient;
- import com.baigehuidi.demo.weixin4j.http.Response;
- import com.baigehuidi.demo.weixin4j.model.user.Data;
- import com.baigehuidi.demo.weixin4j.model.user.Followers;
- import com.baigehuidi.demo.weixin4j.model.user.User;
- import org.springframework.util.StringUtils;
- import java.util.ArrayList;
- import java.util.List;
- /**
- * 用户管理组件
- *
- * @author 杨启盛<qsyang@ansitech.com>
- * @since 0.1.0
- */
- public class UserComponent extends AbstractComponent {
- public UserComponent(Weixin weixin) {
- super(weixin);
- }
- /**
- * 设置用户备注名
- *
- * @param openid 用户标识
- * @param remark 新的备注名,长度必须小于30字符
- * @throws WeixinException
- */
- public void updateRemark(String openid, String remark) throws WeixinException {
- //内部业务验证
- if (StringUtils.isEmpty(openid)) {
- throw new IllegalArgumentException("openid can't be null or empty");
- }
- if (StringUtils.isEmpty(remark)) {
- throw new IllegalArgumentException("remark can't be null or empty");
- }
- //拼接参数
- JSONObject postParam = new JSONObject();
- postParam.put("openid", openid);
- postParam.put("remark", remark);
- //创建请求对象
- HttpsClient http = new HttpsClient();
- //调用获取access_token接口
- Response res = http.post("https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=" + weixin.getToken().getAccess_token(), postParam);
- //根据请求结果判定,是否验证成功
- JSONObject jsonObj = res.asJSONObject();
- if (jsonObj == null) {
- throw new WeixinException(getCause(-1));
- }
- if (Configuration.isDebug()) {
- System.out.println("updateremark返回json:" + jsonObj.toString());
- }
- //判断是否修改成功
- //正常时返回 {"errcode": 0, "errmsg": "ok"}
- //错误时返回 示例:{"errcode":40013,"errmsg":"invalid appid"}
- int errcode = jsonObj.getIntValue("errcode");
- //登录成功,设置accessToken和过期时间
- if (errcode != 0) {
- //返回异常信息
- throw new WeixinException(getCause(errcode));
- }
- }
- /**
- * 获取用户基本信息(包括UnionID机制)
- *
- * @param openid 普通用户的标识,对当前公众号唯一
- * @return 用户对象
- * @throws WeixinException
- */
- public User info(String openid) throws WeixinException {
- //默认简体中文
- return info(openid, "zh_CN");
- }
- /**
- * 获取用户基本信息(包括UnionID机制)
- *
- * @param openid 普通用户的标识,对当前公众号唯一
- * @param lang 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语
- * @return 用户对象
- * @throws WeixinException
- */
- public User info(String openid, String lang) throws WeixinException {
- if (StringUtils.isEmpty(openid)) {
- throw new IllegalArgumentException("openid can't be null or empty");
- }
- if (StringUtils.isEmpty(lang)) {
- throw new IllegalArgumentException("lang can't be null or empty");
- }
- //拼接参数
- String param = "?access_token=" + weixin.getToken().getAccess_token() + "&openid=" + openid + "&lang=" + lang;
- //创建请求对象
- HttpsClient http = new HttpsClient();
- //调用获取access_token接口
- Response res = http.get("https://api.weixin.qq.com/cgi-bin/user/info" + param);
- //根据请求结果判定,是否验证成功
- JSONObject jsonObj = res.asJSONObject();
- if (jsonObj == null) {
- return null;
- }
- if (Configuration.isDebug()) {
- System.out.println("getUser返回json:" + jsonObj.toString());
- }
- Object errcode = jsonObj.get("errcode");
- if (errcode != null) {
- //返回异常信息
- throw new WeixinException(getCause(jsonObj.getIntValue("errcode")));
- }
- //设置公众号信息
- return JSONObject.toJavaObject(jsonObj, User.class);
- }
- /**
- * 获取用户基本信息(包括UnionID机制)
- *
- * @param openids 普通用户的标识数组,对当前公众号唯一
- * @return 用户对象
- * @throws WeixinException
- */
- public List<User> batchGet(String[] openids) throws WeixinException {
- if (openids == null || openids.length == 0) {
- throw new IllegalArgumentException("openids can't be null or empty");
- }
- return batchGet(openids, "zh_CN");
- }
- /**
- * 获取用户基本信息(包括UnionID机制)
- *
- * @param openids 普通用户的标识数组,对当前公众号唯一
- * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语,默认为zh-CN
- * @return 用户对象
- * @throws WeixinException
- */
- public List<User> batchGet(String[] openids, String lang) throws WeixinException {
- if (StringUtils.isEmpty(lang)) {
- throw new IllegalArgumentException("lang can't be null or empty");
- }
- String[] langs = new String[openids.length];
- for (int i = 0; i < langs.length; i++) {
- langs[i] = lang;
- }
- return batchGet(openids, langs);
- }
- /**
- * (批量)获取用户基本信息(包括UnionID机制)
- *
- * @param openids 普通用户的标识数组,对当前公众号唯一
- * @param langs 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语,默认为zh-CN
- * @return 用户对象
- * @throws WeixinException
- */
- public List<User> batchGet(String[] openids, String[] langs) throws WeixinException {
- //内部业务验证
- if (openids == null || openids.length == 0) {
- throw new IllegalArgumentException("openids can't be null or empty");
- }
- if (langs == null || langs.length == 0) {
- throw new IllegalArgumentException("langs can't be null or empty");
- }
- if (openids.length != langs.length) {
- throw new IllegalArgumentException("openids length are not same to langs length");
- }
- //拼接参数
- JSONObject postUserList = new JSONObject();
- JSONArray userList = new JSONArray();
- for (int i = 0; i < openids.length; i++) {
- JSONObject postUser = new JSONObject();
- postUser.put("openid", openids[i]);
- postUser.put("lang", langs[i]);
- userList.add(postUser);
- }
- postUserList.put("user_list", userList);
- //创建请求对象
- HttpsClient http = new HttpsClient();
- //调用获取access_token接口
- Response res = http.post("https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" + weixin.getToken().getAccess_token(), postUserList);
- //根据请求结果判定,是否验证成功
- JSONObject jsonObj = res.asJSONObject();
- if (jsonObj == null) {
- return null;
- }
- if (Configuration.isDebug()) {
- System.out.println("batchGetUser返回json:" + jsonObj.toString());
- }
- Object errcode = jsonObj.get("errcode");
- if (errcode != null) {
- //返回异常信息
- throw new WeixinException(getCause(jsonObj.getIntValue("errcode")));
- }
- //获取用户列表
- JSONArray userlistArray = jsonObj.getJSONArray("user_info_list");
- List<User> users = new ArrayList<User>();
- for (Object userObj : userlistArray) {
- //转换为User对象
- users.add(JSONObject.toJavaObject((JSONObject) userObj, User.class));
- }
- return users;
- }
- /**
- * 获取所有用户列表
- *
- * 公众号粉丝数量超过1万,推荐使用请分页获取。
- *
- * @return 关注者列表对象
- * @throws WeixinException
- */
- public Followers getAll() throws WeixinException {
- Followers allFollower = new Followers();
- int toatl = 0;
- int count = 0;
- Data data = new Data();
- data.setOpenid(new ArrayList<String>());
- allFollower.setData(data);
- String next_openid = "";
- do {
- Followers f = get(next_openid);
- if (f == null) {
- break;
- }
- if (f.getCount() > 0) {
- count += f.getCount();
- toatl += f.getTotal();
- List<String> openids = f.getData().getOpenid();
- for (String openid : openids) {
- allFollower.getData().getOpenid().add(openid);
- }
- }
- next_openid = f.getNext_openid();
- } while (next_openid != null && !next_openid.equals(""));
- allFollower.setCount(count);
- allFollower.setTotal(toatl);
- return allFollower;
- }
- /**
- * 获取用户列表
- *
- * @param next_openid 第一个拉取的OPENID,不填默认从头开始拉取
- * @return 关注者列表对象
- * @throws WeixinException
- */
- public Followers get(String next_openid) throws WeixinException {
- //拼接参数
- String param = "?access_token=" + weixin.getToken().getAccess_token() + "&next_openid=";
- //第一次获取不添加参数
- if (next_openid != null && !next_openid.equals("")) {
- param += next_openid;
- }
- //创建请求对象
- HttpsClient http = new HttpsClient();
- //调用获取access_token接口
- Response res = http.get("https://api.weixin.qq.com/cgi-bin/user/get" + param);
- //根据请求结果判定,是否验证成功
- JSONObject jsonObj = res.asJSONObject();
- if (jsonObj == null) {
- return null;
- }
- if (Configuration.isDebug()) {
- System.out.println("getUserList返回json:" + jsonObj.toString());
- }
- Object errcode = jsonObj.get("errcode");
- if (errcode != null) {
- //返回异常信息
- throw new WeixinException(getCause(jsonObj.getIntValue("errcode")));
- }
- return (Followers) JSONObject.toJavaObject(jsonObj, Followers.class);
- }
- /**
- * 获取标签下所有粉丝列表
- *
- * @param tagid 标签ID
- * @return 关注者对象
- * @throws WeixinException
- */
- public Followers tagGetAll(int tagid) throws WeixinException {
- Followers allFollower = new Followers();
- int toatl = 0;
- int count = 0;
- Data data = new Data();
- data.setOpenid(new ArrayList<String>());
- allFollower.setData(data);
- String next_openid = "";
- do {
- Followers f = tagGet(tagid, next_openid);
- if (f == null) {
- break;
- }
- if (f.getCount() > 0) {
- count += f.getCount();
- toatl += f.getTotal();
- List<String> openids = f.getData().getOpenid();
- for (String openid : openids) {
- allFollower.getData().getOpenid().add(openid);
- }
- }
- next_openid = f.getNext_openid();
- } while (next_openid != null && !next_openid.equals(""));
- allFollower.setCount(count);
- allFollower.setTotal(toatl);
- return allFollower;
- }
- /**
- * 获取标签下粉丝列表
- *
- * <p>
- * 通过公众号,返回用户对象,进行用户相关操作</p>
- *
- * @param tagid 标签ID
- * @param next_openid 第一个拉取的OPENID,不填默认从头开始拉取
- * @return 关注者对象
- * @throws WeixinException when Weixin service or network is unavailable, or
- * the user has not authorized
- */
- public Followers tagGet(int tagid, String next_openid) throws WeixinException {
- //拼接参数
- String param = "?access_token=" + weixin.getToken().getAccess_token() + "&tagid=" + tagid + "&next_openid=";
- //第一次获取不添加参数
- if (next_openid != null && !next_openid.equals("")) {
- param += next_openid;
- }
- //创建请求对象
- HttpsClient http = new HttpsClient();
- //调用获取标签下粉丝列表接口
- Response res = http.get("https://api.weixin.qq.com/cgi-bin/user/tag/get" + param);
- //根据请求结果判定,是否验证成功
- JSONObject jsonObj = res.asJSONObject();
- Followers follower = null;
- if (jsonObj != null) {
- if (Configuration.isDebug()) {
- System.out.println("getTagUserList返回json:" + jsonObj.toString());
- }
- Object errcode = jsonObj.get("errcode");
- if (errcode != null) {
- //返回异常信息
- throw new WeixinException(getCause(jsonObj.getIntValue("errcode")));
- }
- follower = (Followers) JSONObject.toJavaObject(jsonObj, Followers.class);
- }
- return follower;
- }
- }
其中返回数据如果开通了微信开放平台对微信平台进行绑定的话,还会返回unionID
[微信开发] - weixin4j关键类解析的更多相关文章
- java 微信开发 常用工具类(xml传输和解析 json转换对象)
与微信通信常用工具(xml传输和解析) package com.lownsun.wechatOauth.utl; import java.io.IOException; import java.io. ...
- [微信开发] - weixin4j获取网页授权后的code进而获取用户信息
weixin4j封装好的SnsComponent组件中的方法可以执行该步骤 WeixinUserInfoController : package com.baigehuidi.demo.control ...
- java 微信开发的工具类WeChatUtils
import com.alibaba.fastjson.JSONObject;import com.bhudy.entity.BhudyPlugin;import com.bhudy.service. ...
- 用thinkphp进行微信开发的整体设计思考
用thinkphp进行微信开发的整体设计思考 http://www.2cto.com/weixin/201504/388423.html 2015-04-09 0个评论 作者:明 ...
- java微信开发API解析(二)-获取消息和回复消息
java微信开发API解析(二)-获取消息和回复消息 说明 * 本演示样例依据微信开发文档:http://mp.weixin.qq.com/wiki/home/index.html最新版(4/3/20 ...
- [微信开发] - 使用weixin4j进行二次开发
1. 服务器连接配置OK, 配置文件在classpath:weixin4j.properties中 # weixin4j-spring-demo### 使用weixin4j(岸思版)springboo ...
- 【Spring注解驱动开发】AOP核心类解析,这是最全的一篇了!!
写在前面 昨天二狗子让我给他讲@EnableAspectJAutoProxy注解,讲到AnnotationAwareAspectJAutoProxyCreator类的源码时,二狗子消化不了了.这不,今 ...
- 用RegularJS开发小程序 — mpregular解析
本文来自网易云社区. Mpregular 是基于 RegularJS(简称 Regular) 的小程序开发框架.开发者可以将直接用 RegularJS 开发小程序,或者将现有的 RegularJS 应 ...
- h5 录音 自动生成proto Js语句 UglifyJS-- 对你的js做了什么 【原码笔记】-- protobuf.js 与 Long.js 【微信开发】-- 发送模板消息 能编程与会编程 vue2入坑随记(二) -- 自定义动态组件 微信上传图片
得益于前辈的分享,做了一个h5录音的demo.效果图如下: 点击开始录音会先弹出确认框: 首次确认允许后,再次录音不需要再确认,但如果用户点击禁止,则无法录音: 点击发送 将录音内容发送到对话框中.点 ...
随机推荐
- 在linux下安装Avria(小红伞)
1.下载AntiVir PersonalEdition Classic for linux http://www.free-av.com/ 2.解压: tar zxvf antivir.tar.gz ...
- oracle如何四舍五入?
转自:http://www.jb51.net/article/84924.htm 取整(向下取整): 复制代码代码如下: select floor(5.534) from dual;select tr ...
- Oracle Database Memory Structures
Oracle Database creates and uses memory structures for various purposes. For example, memory stores ...
- Css-常用css初始化
/*PC初始化*/ * {;;; } body, html { width: 100%; height: 100%; min-width: 1024px; } body { font-size: 14 ...
- 常用meta标签及说明
1.charset 定义文档的字符编码 例如: <meta charset="UTF-8"> 2. name 把 content 属性关联到一个名称,其属性有 ...
- model 模型层
using System; namespace MODEL { [Serializable] /// <summary> /// 作者: liuhaitao /// 描述: 实体层 -- ...
- jenkins之升级
首先查看系统war包放置的位置 rpm -ql jenkins 下载一个war包 下载地址 https://mirrors.tuna.tsinghua.edu.cn/jenkins/war/2.61/ ...
- CodeForces Roads not only in Berland(并查集)
H - Roads not only in Berland Time Limit:2000MS Memory Limit:262144KB 64bit IO Format:%I64d ...
- 解决Android版Firefox字体显示过大的问题
在用Android版Firefox查看博客园首页发现中间区域的字体显示非常大,开始以为是首页css对移动版浏览器支持不好. 后来发现原来这是Firefox for Android的知名bug: Tha ...
- acceptorThreadCount
Apache Tomcat 7 Configuration Reference (7.0.92) - The HTTP Connector https://tomcat.apache.org/tomc ...