TokenUtil :

  1. get()获取我方自定义的token(从配置文件或数据库)
  2. checkSignature(Str..... (服务器配置连接验证有效性)
  1. /*
  2. * 微信公众平台(JAVA) SDK
  3. *
  4. * Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved.
  5. *
  6. */
  7. package com.baigehuidi.demo.weixin4j.util;
  8.  
  9. import com.baigehuidi.demo.weixin4j.Configuration;
  10.  
  11. import java.util.ArrayList;
  12. import java.util.Collections;
  13. import java.util.Comparator;
  14. import java.util.List;
  15.  
  16. /**
  17. *
  18. * <p>
  19. * Title: 微信公众平台Token算法工具类</p>
  20. *
  21. * <p>
  22. * Description: 为应用提供URL算法<br /> 根据不同的URL返回不同的Token,以适应多微站的需求<br />
  23. * 例如:Url:http://www.weixin4j.org/api/tiexinqiao<br />
  24. * 则默认Token:为jEvQdLxi0PvtgK8N+HzUpA==<br /> 根据配置的系统Token不同,而改变</p>
  25. *
  26. * @author 杨启盛<qsyang@ansitech.com>
  27. * @since 0.0.1
  28. */
  29. public class TokenUtil {
  30.  
  31. //此加密密钥用于加密公众号Token,一经配置,不能修改,一旦修改,所有公众号需要重新填写Token
  32. private static String systemToken = null;
  33.  
  34. /**
  35. * 获取配置文件配置的Token
  36. *
  37. * @return 微站Token
  38. */
  39. public static String get() {
  40. if (systemToken == null) {
  41. systemToken = Configuration.getProperty("weixin4j.token", "baige");
  42. }
  43. return systemToken;
  44. }
  45.  
  46. /**
  47. * 加密/校验流程如下:
  48. *
  49. * <p>
  50. * 1. 将token、timestamp、nonce三个参数进行字典序排序<br>
  51. * 2.将三个参数字符串拼接成一个字符串进行sha1加密<br>
  52. * 3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信<br>
  53. * </p>
  54. *
  55. * @param token Token验证密钥 是服务器内部的,(数据库存好的,这里的token在properties配置文件中)
  56. * @param signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数,nonce参数
  57. * @param timestamp 时间戳
  58. * @param nonce 随机数
  59. * @return 验证成功返回true,否则返回false
  60. */
  61. public static boolean checkSignature(String token, String signature, String timestamp, String nonce) {
  62. List<String> params = new ArrayList<String>();
  63. params.add(token);
  64. params.add(timestamp);
  65. params.add(nonce);
  66. //1. 将token、timestamp、nonce三个参数进行字典序排序
  67. Collections.sort(params, new Comparator<String>() {
  68. @Override
  69. public int compare(String o1, String o2) {
  70. return o1.compareTo(o2);
  71. }
  72. });
  73. //2. 将三个参数字符串拼接成一个字符串进行sha1加密
  74. String temp = SHA1.encode(params.get(0) + params.get(1) + params.get(2));
  75. //3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
  76. return temp.equals(signature);
  77. }
  78. }

这里的get获取的是自己服务器数据库中或springboot配置文件中的自己设定好的token,用来跟服务器端的进行比对.

其后几个消息处理器和事件处理器也是很重要的,而且要将自己配置好的该类(或者如果使用weixin4j.jar则需要继承这些处理器类)

K神全栈 < 这个是weixin4j的官方微信平台

其中提到了Weixin对象是整个weixin4j的核心

Weixin类 :

  1. /*
  2. * 微信公众平台(JAVA) SDK
  3. **/
  4. package com.baigehuidi.demo.weixin4j;
  5.  
  6. import com.baigehuidi.demo.weixin4j.component.*;
  7. import com.baigehuidi.demo.weixin4j.loader.DefaultTicketLoader;
  8. import com.baigehuidi.demo.weixin4j.loader.DefaultTokenLoader;
  9. import com.baigehuidi.demo.weixin4j.loader.ITicketLoader;
  10. import com.baigehuidi.demo.weixin4j.loader.ITokenLoader;
  11. import com.baigehuidi.demo.weixin4j.model.base.Token;
  12. import com.baigehuidi.demo.weixin4j.model.js.Ticket;
  13. import com.baigehuidi.demo.weixin4j.model.js.TicketType;
  14.  
  15. import java.io.Serializable;
  16. import java.util.HashMap;
  17. import java.util.Map;
  18.  
  19. /**
  20. * 微信平台基础支持对象
  21. *
  22. * @author 杨启盛<qsyang@ansitech.com>
  23. * @since 0.0.1
  24. */
  25. public class Weixin extends WeixinSupport implements Serializable {
  26.  
  27. /**
  28. * 同步锁
  29. */
  30. private final static byte[] LOCK = new byte[0];
  31. /**
  32. * 公众号开发者ID
  33. */
  34. private final String appId;
  35. /**
  36. * 公众号开发者密钥
  37. */
  38. private final String secret;
  39. /**
  40. * 公众号名称
  41. */
  42. private String name;
  43. /**
  44. * 公众号配置
  45. *
  46. * @since 0.1.3
  47. */
  48. private final WeixinConfig weixinConfig;
  49. /**
  50. * 微信支付配置
  51. *
  52. * @since 0.1.3
  53. */
  54. private final WeixinPayConfig weixinPayConfig;
  55. /**
  56. * AccessToken加载器
  57. */
  58. protected ITokenLoader tokenLoader = new DefaultTokenLoader();
  59. /**
  60. * Ticket加载器
  61. */
  62. protected ITicketLoader ticketLoader = new DefaultTicketLoader();
  63. /**
  64. * 新增组件
  65. */
  66. private final Map<String, AbstractComponent> components = new HashMap<String, AbstractComponent>();
  67.  
  68. /**
  69. * 单公众号,并且只支持一个公众号方式
  70. * @param
  71. */
  72. public Weixin() {
  73. this(Configuration.getOAuthAppId(), Configuration.getOAuthSecret(),Configuration.getName());
  74. }
  75.  
  76. /**
  77. * 多公众号,同一个环境中使用方式
  78. *
  79. * @param appId 公众号开发者AppId
  80. * @param secret 公众号开发者秘钥
  81. */
  82. public Weixin(String appId, String secret, String name) {
  83. this.appId = appId;
  84. this.secret = secret;
  85. this.name = name;
  86. weixinConfig = new WeixinConfig();
  87. weixinConfig.setAppid(appId);
  88. weixinConfig.setSecret(secret);
  89. weixinConfig.setOriginalid(Configuration.getProperty("weixin4j.oauth.originalid"));
  90. weixinConfig.setEncodingtype(Configuration.getIntProperty("weixin4j.oauth.encodingtype"));
  91. weixinConfig.setEncodingaeskey(Configuration.getProperty("weixin4j.oauth.encodingaeskey"));
  92. weixinConfig.setOauthUrl(Configuration.getProperty("weixin4j.oauth.url"));
  93. weixinConfig.setApiDomain(Configuration.getProperty("weixin4j.api.domain"));
  94. weixinPayConfig = new WeixinPayConfig();
  95. weixinPayConfig.setPartnerId(Configuration.getProperty("weixin4j.pay.partner.id"));
  96. weixinPayConfig.setPartnerKey(Configuration.getProperty("weixin4j.pay.partner.key"));
  97. weixinPayConfig.setNotifyUrl(Configuration.getProperty("weixin4j.pay.notify_url"));
  98. weixinPayConfig.setCertPath(Configuration.getProperty("weixin4j.http.cert.path"));
  99. weixinPayConfig.setCertSecret(Configuration.getProperty("weixin4j.http.cert.secret"));
  100. }
  101.  
  102. /**
  103. * 外部配置注入方式,更灵活
  104. *
  105. * @param weixinConfig 微信公众号配置
  106. * @since 0.1.3
  107. */
  108. public Weixin(WeixinConfig weixinConfig) {
  109. this(weixinConfig, null);
  110. }
  111.  
  112. /**
  113. * 外部配置注入方式(带微信支付),更灵活
  114. *
  115. * @param weixinPayConfig 微信支付配置
  116. * @since 0.1.3
  117. */
  118. public Weixin(WeixinPayConfig weixinPayConfig) {
  119. this.appId = Configuration.getOAuthAppId();
  120. this.secret = Configuration.getOAuthSecret();
  121. weixinConfig = new WeixinConfig();
  122. weixinConfig.setAppid(Configuration.getOAuthAppId());
  123. weixinConfig.setSecret(Configuration.getOAuthSecret());
  124. weixinConfig.setOriginalid(Configuration.getProperty("weixin4j.oauth.originalid"));
  125. weixinConfig.setEncodingtype(Configuration.getIntProperty("weixin4j.oauth.encodingtype"));
  126. weixinConfig.setEncodingaeskey(Configuration.getProperty("weixin4j.oauth.encodingaeskey"));
  127. weixinConfig.setOauthUrl(Configuration.getProperty("weixin4j.oauth.url"));
  128. weixinConfig.setApiDomain(Configuration.getProperty("weixin4j.api.domain"));
  129. this.weixinPayConfig = weixinPayConfig;
  130. }
  131.  
  132. /**
  133. * 外部配置注入方式(带微信支付),更灵活
  134. *
  135. * @param weixinConfig 微信公众号配置
  136. * @param weixinPayConfig 微信支付配置
  137. * @since 0.1.3
  138. */
  139. public Weixin(WeixinConfig weixinConfig, WeixinPayConfig weixinPayConfig) {
  140. this.appId = weixinConfig.getAppid();
  141. this.secret = weixinConfig.getSecret();
  142. this.weixinConfig = weixinConfig;
  143. this.weixinPayConfig = weixinPayConfig;
  144. }
  145.  
  146. public String getAppId() {
  147. return appId;
  148. }
  149.  
  150. public String getSecret() {
  151. return secret;
  152. }
  153.  
  154. public String getName() {
  155. return name;
  156. }
  157.  
  158. /**
  159. * 获取Token对象
  160. *
  161. * @return Token对象
  162. * @throws WeixinException
  163. * @since 0.1.0
  164. */
  165. public Token getToken() throws WeixinException {
  166. Token token = tokenLoader.get();
  167. if (token == null) {
  168. synchronized (LOCK) {
  169. token = tokenLoader.get();
  170. if (token == null) {
  171. token = base().token();
  172. tokenLoader.refresh(token);
  173. }
  174. }
  175. }
  176. return token;
  177. }
  178.  
  179. /**
  180. * 获取jsapi开发ticket
  181. *
  182. * @return jsapi_ticket
  183. * @throws WeixinException
  184. */
  185. public Ticket getJsApiTicket() throws WeixinException {
  186. Ticket ticket = ticketLoader.get(TicketType.JSAPI);
  187. if (ticket == null) {
  188. synchronized (LOCK) {
  189. ticket = ticketLoader.get(TicketType.JSAPI);
  190. if (ticket == null) {
  191. ticket = js().getJsApiTicket();
  192. ticketLoader.refresh(ticket);
  193. }
  194. }
  195. }
  196. return ticket;
  197. }
  198.  
  199. public BaseComponent base() {
  200. String key = BaseComponent.class.getName();
  201. if (components.containsKey(key)) {
  202. return (BaseComponent) components.get(key);
  203. }
  204. BaseComponent component = new BaseComponent(this);
  205. components.put(key, component);
  206. return component;
  207. }
  208.  
  209. public JsSdkComponent js() {
  210. String key = JsSdkComponent.class.getName();
  211. if (components.containsKey(key)) {
  212. return (JsSdkComponent) components.get(key);
  213. }
  214. JsSdkComponent component = new JsSdkComponent(this);
  215. components.put(key, component);
  216. return component;
  217. }
  218.  
  219. public UserComponent user() {
  220. String key = UserComponent.class.getName();
  221. if (components.containsKey(key)) {
  222. return (UserComponent) components.get(key);
  223. }
  224. UserComponent component = new UserComponent(this);
  225. components.put(key, component);
  226. return component;
  227. }
  228.  
  229. public SnsComponent sns() {
  230. String key = SnsComponent.class.getName();
  231. if (components.containsKey(key)) {
  232. return (SnsComponent) components.get(key);
  233. }
  234. SnsComponent component = new SnsComponent(this);
  235. components.put(key, component);
  236. return component;
  237. }
  238.  
  239. public SnsComponent sns(String authorize_url) {
  240. String key = SnsComponent.class.getName();
  241. if (components.containsKey(key)) {
  242. return (SnsComponent) components.get(key);
  243. }
  244. SnsComponent component = new SnsComponent(this, authorize_url);
  245. components.put(key, component);
  246. return component;
  247. }
  248.  
  249. public TagsComponent tags() {
  250. String key = TagsComponent.class.getName();
  251. if (components.containsKey(key)) {
  252. return (TagsComponent) components.get(key);
  253. }
  254. TagsComponent component = new TagsComponent(this);
  255. components.put(key, component);
  256. return component;
  257. }
  258.  
  259. public GroupsComponent groups() {
  260. String key = GroupsComponent.class.getName();
  261. if (components.containsKey(key)) {
  262. return (GroupsComponent) components.get(key);
  263. }
  264. GroupsComponent component = new GroupsComponent(this);
  265. components.put(key, component);
  266. return component;
  267. }
  268.  
  269. public PayComponent pay() {
  270. String key = PayComponent.class.getName();
  271. if (components.containsKey(key)) {
  272. return (PayComponent) components.get(key);
  273. }
  274. PayComponent component = new PayComponent(this);
  275. components.put(key, component);
  276. return component;
  277. }
  278.  
  279. public RedpackComponent redpack() {
  280. String key = RedpackComponent.class.getName();
  281. if (components.containsKey(key)) {
  282. return (RedpackComponent) components.get(key);
  283. }
  284. RedpackComponent component = new RedpackComponent(this);
  285. components.put(key, component);
  286. return component;
  287. }
  288.  
  289. //消息发送组件
  290. public MessageComponent message() {
  291. String key = MessageComponent.class.getName();
  292. if (components.containsKey(key)) {
  293. return (MessageComponent) components.get(key);
  294. }
  295. MessageComponent component = new MessageComponent(this);
  296. components.put(key, component);
  297. return component;
  298. }
  299.  
  300. //创建自定义菜单组件
  301. public MenuComponent menu() {
  302. String key = MenuComponent.class.getName();
  303. if (components.containsKey(key)) {
  304. return (MenuComponent) components.get(key);
  305. }
  306. MenuComponent component = new MenuComponent(this);
  307. components.put(key, component);
  308. return component;
  309. }
  310.  
  311. public MediaComponent media() {
  312. String key = MediaComponent.class.getName();
  313. if (components.containsKey(key)) {
  314. return (MediaComponent) components.get(key);
  315. }
  316. MediaComponent component = new MediaComponent(this);
  317. components.put(key, component);
  318. return component;
  319. }
  320.  
  321. @Deprecated
  322. public FileComponent file() {
  323. String key = FileComponent.class.getName();
  324. if (components.containsKey(key)) {
  325. return (FileComponent) components.get(key);
  326. }
  327. FileComponent component = new FileComponent(this);
  328. components.put(key, component);
  329. return component;
  330. }
  331.  
  332. public MaterialComponent material() {
  333. String key = MaterialComponent.class.getName();
  334. if (components.containsKey(key)) {
  335. return (MaterialComponent) components.get(key);
  336. }
  337. MaterialComponent component = new MaterialComponent(this);
  338. components.put(key, component);
  339. return component;
  340. }
  341.  
  342. public QrcodeComponent qrcode() {
  343. String key = QrcodeComponent.class.getName();
  344. if (components.containsKey(key)) {
  345. return (QrcodeComponent) components.get(key);
  346. }
  347. QrcodeComponent component = new QrcodeComponent(this);
  348. components.put(key, component);
  349. return component;
  350. }
  351.  
  352. /**
  353. * 获取微信配置对象
  354. *
  355. * @return 微信配置对象
  356. * @since 0.1.3
  357. */
  358. public WeixinConfig getWeixinConfig() {
  359. return weixinConfig;
  360. }
  361.  
  362. /**
  363. * 获取微信支付配置对象
  364. *
  365. * @return 微信支付配置对象
  366. * @since 0.1.3
  367. */
  368. public WeixinPayConfig getWeixinPayConfig() {
  369. return weixinPayConfig;
  370. }
  371. }

Weixin类创建的weixin对象主要提供我们需要和微信公众平台接口交互的所有组件类.

这篇文章的链接


在util包中的CommonUtil : 新加入方法 获取微信服务器ip地址集

  1. package com.baigehuidi.demo.weixin4j.util;
  2.  
  3. import com.baigehuidi.demo.loader.WeixinInsLoader;
  4. import com.baigehuidi.demo.weixin4j.WeixinException;
  5.  
  6. import java.io.UnsupportedEncodingException;
  7. import java.util.List;
  8.  
  9. import static java.net.URLEncoder.encode;
  10.  
  11. public class CommonUtil {
  12.  
  13. /**
  14. * URL编码 转换url路径拼接微信api路径
  15. * @param source
  16. * @return
  17. */
  18. public static String urlEncodeUTF8(String source){
  19. String resultURL = source;
  20. try {
  21. resultURL = encode(source,"utf-8");
  22. } catch (UnsupportedEncodingException e) {
  23. e.printStackTrace();
  24. } finally {
  25. }
  26.  
  27. return resultURL;
  28.  
  29. }
  30.  
  31. /**
  32. * 获取微信服务器ip地址集
  33. * @return callbackIps
  34. */
  35. public static List<String> getWeixinIPs(){
  36. try {
  37. List<String> callbackIps = WeixinInsLoader.getWeixinInstance().base().getCallbackIp();
  38. System.out.println("获取微信服务器ip地址中...");
  39. return callbackIps;
  40. } catch (WeixinException e) {
  41. System.out.println("获取微信服务器ip地址失败...");
  42. e.printStackTrace();
  43. return null;
  44. } finally {
  45. }
  46.  
  47. }
  48. }

测试了下获取了218条ip地址


component包中的UserComponent类,是用户管理组件,

其内方法有设置用户备注名,(批量)获取用户基本信息(包括UnionID机制,几个不同类型的构造器),获取所有用户列表(以及从哪个openid开始获取),获取标签下所有粉丝列表(以及从哪个openid开始获取).

其中可以必能用到的就是获取用户基本信息了.(批量获取的为接收 String[] openids )

  1. /*
  2. * 微信公众平台(JAVA) SDK*/
  3. package com.baigehuidi.demo.weixin4j.component;
  4.  
  5. import com.alibaba.fastjson.JSONArray;
  6. import com.alibaba.fastjson.JSONObject;
  7. import com.baigehuidi.demo.weixin4j.Configuration;
  8. import com.baigehuidi.demo.weixin4j.Weixin;
  9. import com.baigehuidi.demo.weixin4j.WeixinException;
  10. import com.baigehuidi.demo.weixin4j.http.HttpsClient;
  11. import com.baigehuidi.demo.weixin4j.http.Response;
  12. import com.baigehuidi.demo.weixin4j.model.user.Data;
  13. import com.baigehuidi.demo.weixin4j.model.user.Followers;
  14. import com.baigehuidi.demo.weixin4j.model.user.User;
  15. import org.springframework.util.StringUtils;
  16.  
  17. import java.util.ArrayList;
  18. import java.util.List;
  19.  
  20. /**
  21. * 用户管理组件
  22. *
  23. * @author 杨启盛<qsyang@ansitech.com>
  24. * @since 0.1.0
  25. */
  26. public class UserComponent extends AbstractComponent {
  27.  
  28. public UserComponent(Weixin weixin) {
  29. super(weixin);
  30. }
  31.  
  32. /**
  33. * 设置用户备注名
  34. *
  35. * @param openid 用户标识
  36. * @param remark 新的备注名,长度必须小于30字符
  37. * @throws WeixinException
  38. */
  39. public void updateRemark(String openid, String remark) throws WeixinException {
  40. //内部业务验证
  41. if (StringUtils.isEmpty(openid)) {
  42. throw new IllegalArgumentException("openid can't be null or empty");
  43. }
  44. if (StringUtils.isEmpty(remark)) {
  45. throw new IllegalArgumentException("remark can't be null or empty");
  46. }
  47. //拼接参数
  48. JSONObject postParam = new JSONObject();
  49. postParam.put("openid", openid);
  50. postParam.put("remark", remark);
  51. //创建请求对象
  52. HttpsClient http = new HttpsClient();
  53. //调用获取access_token接口
  54. Response res = http.post("https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=" + weixin.getToken().getAccess_token(), postParam);
  55. //根据请求结果判定,是否验证成功
  56. JSONObject jsonObj = res.asJSONObject();
  57. if (jsonObj == null) {
  58. throw new WeixinException(getCause(-1));
  59. }
  60. if (Configuration.isDebug()) {
  61. System.out.println("updateremark返回json:" + jsonObj.toString());
  62. }
  63. //判断是否修改成功
  64. //正常时返回 {"errcode": 0, "errmsg": "ok"}
  65. //错误时返回 示例:{"errcode":40013,"errmsg":"invalid appid"}
  66. int errcode = jsonObj.getIntValue("errcode");
  67. //登录成功,设置accessToken和过期时间
  68. if (errcode != 0) {
  69. //返回异常信息
  70. throw new WeixinException(getCause(errcode));
  71. }
  72. }
  73.  
  74. /**
  75. * 获取用户基本信息(包括UnionID机制)
  76. *
  77. * @param openid 普通用户的标识,对当前公众号唯一
  78. * @return 用户对象
  79. * @throws WeixinException
  80. */
  81. public User info(String openid) throws WeixinException {
  82. //默认简体中文
  83. return info(openid, "zh_CN");
  84. }
  85.  
  86. /**
  87. * 获取用户基本信息(包括UnionID机制)
  88. *
  89. * @param openid 普通用户的标识,对当前公众号唯一
  90. * @param lang 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语
  91. * @return 用户对象
  92. * @throws WeixinException
  93. */
  94. public User info(String openid, String lang) throws WeixinException {
  95. if (StringUtils.isEmpty(openid)) {
  96. throw new IllegalArgumentException("openid can't be null or empty");
  97. }
  98. if (StringUtils.isEmpty(lang)) {
  99. throw new IllegalArgumentException("lang can't be null or empty");
  100. }
  101. //拼接参数
  102. String param = "?access_token=" + weixin.getToken().getAccess_token() + "&openid=" + openid + "&lang=" + lang;
  103. //创建请求对象
  104. HttpsClient http = new HttpsClient();
  105. //调用获取access_token接口
  106. Response res = http.get("https://api.weixin.qq.com/cgi-bin/user/info" + param);
  107. //根据请求结果判定,是否验证成功
  108. JSONObject jsonObj = res.asJSONObject();
  109. if (jsonObj == null) {
  110. return null;
  111. }
  112. if (Configuration.isDebug()) {
  113. System.out.println("getUser返回json:" + jsonObj.toString());
  114. }
  115. Object errcode = jsonObj.get("errcode");
  116. if (errcode != null) {
  117. //返回异常信息
  118. throw new WeixinException(getCause(jsonObj.getIntValue("errcode")));
  119. }
  120. //设置公众号信息
  121. return JSONObject.toJavaObject(jsonObj, User.class);
  122. }
  123.  
  124. /**
  125. * 获取用户基本信息(包括UnionID机制)
  126. *
  127. * @param openids 普通用户的标识数组,对当前公众号唯一
  128. * @return 用户对象
  129. * @throws WeixinException
  130. */
  131. public List<User> batchGet(String[] openids) throws WeixinException {
  132. if (openids == null || openids.length == 0) {
  133. throw new IllegalArgumentException("openids can't be null or empty");
  134. }
  135. return batchGet(openids, "zh_CN");
  136. }
  137.  
  138. /**
  139. * 获取用户基本信息(包括UnionID机制)
  140. *
  141. * @param openids 普通用户的标识数组,对当前公众号唯一
  142. * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语,默认为zh-CN
  143. * @return 用户对象
  144. * @throws WeixinException
  145. */
  146. public List<User> batchGet(String[] openids, String lang) throws WeixinException {
  147. if (StringUtils.isEmpty(lang)) {
  148. throw new IllegalArgumentException("lang can't be null or empty");
  149. }
  150. String[] langs = new String[openids.length];
  151. for (int i = 0; i < langs.length; i++) {
  152. langs[i] = lang;
  153. }
  154. return batchGet(openids, langs);
  155. }
  156.  
  157. /**
  158. * (批量)获取用户基本信息(包括UnionID机制)
  159. *
  160. * @param openids 普通用户的标识数组,对当前公众号唯一
  161. * @param langs 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语,默认为zh-CN
  162. * @return 用户对象
  163. * @throws WeixinException
  164. */
  165. public List<User> batchGet(String[] openids, String[] langs) throws WeixinException {
  166. //内部业务验证
  167. if (openids == null || openids.length == 0) {
  168. throw new IllegalArgumentException("openids can't be null or empty");
  169. }
  170. if (langs == null || langs.length == 0) {
  171. throw new IllegalArgumentException("langs can't be null or empty");
  172. }
  173. if (openids.length != langs.length) {
  174. throw new IllegalArgumentException("openids length are not same to langs length");
  175. }
  176. //拼接参数
  177. JSONObject postUserList = new JSONObject();
  178. JSONArray userList = new JSONArray();
  179. for (int i = 0; i < openids.length; i++) {
  180. JSONObject postUser = new JSONObject();
  181. postUser.put("openid", openids[i]);
  182. postUser.put("lang", langs[i]);
  183. userList.add(postUser);
  184. }
  185. postUserList.put("user_list", userList);
  186. //创建请求对象
  187. HttpsClient http = new HttpsClient();
  188. //调用获取access_token接口
  189. Response res = http.post("https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" + weixin.getToken().getAccess_token(), postUserList);
  190. //根据请求结果判定,是否验证成功
  191. JSONObject jsonObj = res.asJSONObject();
  192. if (jsonObj == null) {
  193. return null;
  194. }
  195. if (Configuration.isDebug()) {
  196. System.out.println("batchGetUser返回json:" + jsonObj.toString());
  197. }
  198. Object errcode = jsonObj.get("errcode");
  199. if (errcode != null) {
  200. //返回异常信息
  201. throw new WeixinException(getCause(jsonObj.getIntValue("errcode")));
  202. }
  203. //获取用户列表
  204. JSONArray userlistArray = jsonObj.getJSONArray("user_info_list");
  205. List<User> users = new ArrayList<User>();
  206. for (Object userObj : userlistArray) {
  207. //转换为User对象
  208. users.add(JSONObject.toJavaObject((JSONObject) userObj, User.class));
  209. }
  210. return users;
  211. }
  212.  
  213. /**
  214. * 获取所有用户列表
  215. *
  216. * 公众号粉丝数量超过1万,推荐使用请分页获取。
  217. *
  218. * @return 关注者列表对象
  219. * @throws WeixinException
  220. */
  221. public Followers getAll() throws WeixinException {
  222. Followers allFollower = new Followers();
  223. int toatl = 0;
  224. int count = 0;
  225. Data data = new Data();
  226. data.setOpenid(new ArrayList<String>());
  227. allFollower.setData(data);
  228. String next_openid = "";
  229. do {
  230. Followers f = get(next_openid);
  231. if (f == null) {
  232. break;
  233. }
  234. if (f.getCount() > 0) {
  235. count += f.getCount();
  236. toatl += f.getTotal();
  237. List<String> openids = f.getData().getOpenid();
  238. for (String openid : openids) {
  239. allFollower.getData().getOpenid().add(openid);
  240. }
  241. }
  242. next_openid = f.getNext_openid();
  243. } while (next_openid != null && !next_openid.equals(""));
  244. allFollower.setCount(count);
  245. allFollower.setTotal(toatl);
  246. return allFollower;
  247. }
  248.  
  249. /**
  250. * 获取用户列表
  251. *
  252. * @param next_openid 第一个拉取的OPENID,不填默认从头开始拉取
  253. * @return 关注者列表对象
  254. * @throws WeixinException
  255. */
  256. public Followers get(String next_openid) throws WeixinException {
  257. //拼接参数
  258. String param = "?access_token=" + weixin.getToken().getAccess_token() + "&next_openid=";
  259. //第一次获取不添加参数
  260. if (next_openid != null && !next_openid.equals("")) {
  261. param += next_openid;
  262. }
  263. //创建请求对象
  264. HttpsClient http = new HttpsClient();
  265. //调用获取access_token接口
  266. Response res = http.get("https://api.weixin.qq.com/cgi-bin/user/get" + param);
  267. //根据请求结果判定,是否验证成功
  268. JSONObject jsonObj = res.asJSONObject();
  269. if (jsonObj == null) {
  270. return null;
  271. }
  272. if (Configuration.isDebug()) {
  273. System.out.println("getUserList返回json:" + jsonObj.toString());
  274. }
  275. Object errcode = jsonObj.get("errcode");
  276. if (errcode != null) {
  277. //返回异常信息
  278. throw new WeixinException(getCause(jsonObj.getIntValue("errcode")));
  279. }
  280. return (Followers) JSONObject.toJavaObject(jsonObj, Followers.class);
  281. }
  282.  
  283. /**
  284. * 获取标签下所有粉丝列表
  285. *
  286. * @param tagid 标签ID
  287. * @return 关注者对象
  288. * @throws WeixinException
  289. */
  290. public Followers tagGetAll(int tagid) throws WeixinException {
  291. Followers allFollower = new Followers();
  292. int toatl = 0;
  293. int count = 0;
  294. Data data = new Data();
  295. data.setOpenid(new ArrayList<String>());
  296. allFollower.setData(data);
  297. String next_openid = "";
  298. do {
  299. Followers f = tagGet(tagid, next_openid);
  300. if (f == null) {
  301. break;
  302. }
  303. if (f.getCount() > 0) {
  304. count += f.getCount();
  305. toatl += f.getTotal();
  306. List<String> openids = f.getData().getOpenid();
  307. for (String openid : openids) {
  308. allFollower.getData().getOpenid().add(openid);
  309. }
  310. }
  311. next_openid = f.getNext_openid();
  312. } while (next_openid != null && !next_openid.equals(""));
  313. allFollower.setCount(count);
  314. allFollower.setTotal(toatl);
  315. return allFollower;
  316. }
  317.  
  318. /**
  319. * 获取标签下粉丝列表
  320. *
  321. * <p>
  322. * 通过公众号,返回用户对象,进行用户相关操作</p>
  323. *
  324. * @param tagid 标签ID
  325. * @param next_openid 第一个拉取的OPENID,不填默认从头开始拉取
  326. * @return 关注者对象
  327. * @throws WeixinException when Weixin service or network is unavailable, or
  328. * the user has not authorized
  329. */
  330. public Followers tagGet(int tagid, String next_openid) throws WeixinException {
  331. //拼接参数
  332. String param = "?access_token=" + weixin.getToken().getAccess_token() + "&tagid=" + tagid + "&next_openid=";
  333. //第一次获取不添加参数
  334. if (next_openid != null && !next_openid.equals("")) {
  335. param += next_openid;
  336. }
  337. //创建请求对象
  338. HttpsClient http = new HttpsClient();
  339. //调用获取标签下粉丝列表接口
  340. Response res = http.get("https://api.weixin.qq.com/cgi-bin/user/tag/get" + param);
  341. //根据请求结果判定,是否验证成功
  342. JSONObject jsonObj = res.asJSONObject();
  343. Followers follower = null;
  344. if (jsonObj != null) {
  345. if (Configuration.isDebug()) {
  346. System.out.println("getTagUserList返回json:" + jsonObj.toString());
  347. }
  348. Object errcode = jsonObj.get("errcode");
  349. if (errcode != null) {
  350. //返回异常信息
  351. throw new WeixinException(getCause(jsonObj.getIntValue("errcode")));
  352. }
  353. follower = (Followers) JSONObject.toJavaObject(jsonObj, Followers.class);
  354. }
  355. return follower;
  356. }
  357. }

获取用户基本信息(UnionID机制)

其中返回数据如果开通了微信开放平台对微信平台进行绑定的话,还会返回unionID


[微信开发] - weixin4j关键类解析的更多相关文章

  1. java 微信开发 常用工具类(xml传输和解析 json转换对象)

    与微信通信常用工具(xml传输和解析) package com.lownsun.wechatOauth.utl; import java.io.IOException; import java.io. ...

  2. [微信开发] - weixin4j获取网页授权后的code进而获取用户信息

    weixin4j封装好的SnsComponent组件中的方法可以执行该步骤 WeixinUserInfoController : package com.baigehuidi.demo.control ...

  3. java 微信开发的工具类WeChatUtils

    import com.alibaba.fastjson.JSONObject;import com.bhudy.entity.BhudyPlugin;import com.bhudy.service. ...

  4. 用thinkphp进行微信开发的整体设计思考

    用thinkphp进行微信开发的整体设计思考 http://www.2cto.com/weixin/201504/388423.html 2015-04-09      0个评论       作者:明 ...

  5. java微信开发API解析(二)-获取消息和回复消息

    java微信开发API解析(二)-获取消息和回复消息 说明 * 本演示样例依据微信开发文档:http://mp.weixin.qq.com/wiki/home/index.html最新版(4/3/20 ...

  6. [微信开发] - 使用weixin4j进行二次开发

    1. 服务器连接配置OK, 配置文件在classpath:weixin4j.properties中 # weixin4j-spring-demo### 使用weixin4j(岸思版)springboo ...

  7. 【Spring注解驱动开发】AOP核心类解析,这是最全的一篇了!!

    写在前面 昨天二狗子让我给他讲@EnableAspectJAutoProxy注解,讲到AnnotationAwareAspectJAutoProxyCreator类的源码时,二狗子消化不了了.这不,今 ...

  8. 用RegularJS开发小程序 — mpregular解析

    本文来自网易云社区. Mpregular 是基于 RegularJS(简称 Regular) 的小程序开发框架.开发者可以将直接用 RegularJS 开发小程序,或者将现有的 RegularJS 应 ...

  9. h5 录音 自动生成proto Js语句 UglifyJS-- 对你的js做了什么 【原码笔记】-- protobuf.js 与 Long.js 【微信开发】-- 发送模板消息 能编程与会编程 vue2入坑随记(二) -- 自定义动态组件 微信上传图片

    得益于前辈的分享,做了一个h5录音的demo.效果图如下: 点击开始录音会先弹出确认框: 首次确认允许后,再次录音不需要再确认,但如果用户点击禁止,则无法录音: 点击发送 将录音内容发送到对话框中.点 ...

随机推荐

  1. 在linux下安装Avria(小红伞)

    1.下载AntiVir PersonalEdition Classic for linux http://www.free-av.com/ 2.解压: tar zxvf antivir.tar.gz ...

  2. oracle如何四舍五入?

    转自:http://www.jb51.net/article/84924.htm 取整(向下取整): 复制代码代码如下: select floor(5.534) from dual;select tr ...

  3. Oracle Database Memory Structures

    Oracle Database creates and uses memory structures for various purposes. For example, memory stores ...

  4. Css-常用css初始化

    /*PC初始化*/ * {;;; } body, html { width: 100%; height: 100%; min-width: 1024px; } body { font-size: 14 ...

  5. 常用meta标签及说明

    1.charset   定义文档的字符编码 例如: <meta charset="UTF-8"> 2. name  把 content 属性关联到一个名称,其属性有   ...

  6. model 模型层

    using System; namespace MODEL { [Serializable] /// <summary> /// 作者: liuhaitao /// 描述: 实体层 -- ...

  7. jenkins之升级

    首先查看系统war包放置的位置 rpm -ql jenkins 下载一个war包 下载地址 https://mirrors.tuna.tsinghua.edu.cn/jenkins/war/2.61/ ...

  8. CodeForces Roads not only in Berland(并查集)

    H - Roads not only in Berland Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d ...

  9. 解决Android版Firefox字体显示过大的问题

    在用Android版Firefox查看博客园首页发现中间区域的字体显示非常大,开始以为是首页css对移动版浏览器支持不好. 后来发现原来这是Firefox for Android的知名bug: Tha ...

  10. acceptorThreadCount

    Apache Tomcat 7 Configuration Reference (7.0.92) - The HTTP Connector https://tomcat.apache.org/tomc ...