白羽
2018-06-20
来源 :网络
阅读 1509
评论 0
摘要:本文将带你了解微信公众号之智能绑定实现步骤,希望本文对大家学微信有所帮助。
微信公众号智能绑定功能所有的步骤都是以模拟实现的。
1.模拟打开微信公众帐号登录页面;
URL地址:https://mp.weixin.qq.com/
2.读取自己微信公众帐号的用户名和密码;
此处用户名和密码可以持久化到内存,文件,数据库,缓存中都可以,因为在此操作过程中需要多次验证。
3.配置微信公众号接入的URL和Token;
此处可以和步骤2一样选择持久化。(持久化可以应对多个微信公众帐号操作)
4.模拟微信公众号成功登录;
此处有时候因网络原因需要重试几次。
5.设置开发模式,服务器回调;
成功建立连接,启用开发模式此处模拟提交URL和Token。
6.完成步骤5后,在开发者页面读取AppId和AppSecret让其持久化;
此处根据请求到的页面代码,可以使用正则表达式或者使用:Document、Elements 对象定位AppId和AppSecret的位置,便于获取值。
7.在微信公众号设置页面,获取微信公众号信息持久化到数据库中;
如:公众号名称,原始帐号ID,公众号头像及二维码(此处头像可以下载保存到自己的服务器中),公众号类型等。
8.成功完成以上步骤后,可以根据自己的需求调用微信相关API获取数据。
a.获取粉丝信息持久化到数据库中。
b.创建自定义菜单。
说明:因为此处模拟人工操作,后期微信页面布局及页面相关属性变化,则智能绑定功能会失效,此时需要修改步骤5、7的内容。
如果后期微信公众号登录只能通过扫描二维码登录则智能绑定功能完全失效,目前企业号使用的就是扫描二维码+密码登录方式。
具体实现过程如下:
1.智能绑定核心类:
[java] view plain copy
1. import java.io.IOException;
2.
3. import org.apache.commons.codec.digest.DigestUtils;
4. import org.apache.commons.httpclient.Cookie;
5. import org.apache.commons.httpclient.HttpClient;
6. import org.apache.commons.httpclient.HttpException;
7. import org.apache.commons.httpclient.HttpStatus;
8. import org.apache.commons.httpclient.NameValuePair;
9. import org.apache.commons.httpclient.methods.GetMethod;
10. import org.apache.commons.httpclient.methods.PostMethod;
11. import org.apache.commons.lang.StringUtils;
12. import org.apache.commons.logging.Log;
13. import org.apache.commons.logging.LogFactory;
14. import org.jsoup.Jsoup;
15. import org.jsoup.nodes.Document;
16. import org.jsoup.select.Elements;
17. import org.oms.wechat.pojo.WechatAccountInfo;
18. import org.oms.wechat.pojo.WechatDevInfo;
19.
20. import com.alibaba.fastjson.JSON;
21. import com.alibaba.fastjson.JSONObject;
22.
23. /**
24. * 智能绑定核心类
25. *
26. * @author sunlight
27. *
28. */
29. public class SmartBindUtil {
30. public final static Log log = LogFactory.getLog(SmartBindUtil.class);
31. // 微信URL
32. public final static String HOST_URL = "https://mp.weixin.qq.com";
33. // 微信登陆地址
34. public final static String LOGIN_URL = "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN";
35. // 微信登出地址
36. public final static String LOGOUT_URL = "//mp.weixin.qq.com/cgi-bin/logout?t=wxm-logout&lang=zh_CN&token=";
37. // 主页地址
38. public final static String INDEX_URL = "//mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token=";
39. // 微信账号信息
40. public final static String ACCOUNT_INFO_URL = "//mp.weixin.qq.com/cgi-bin/settingpage?t=setting/index&action=index&lang=zh_CN&token=";
41. // 开发者页面地址
42. public final static String DEV_URL = "https://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&lang=zh_CN&token=";
43. // 切换开发模式
44. public final static String DEV_UPDATE_RUL = "https://mp.weixin.qq.com/misc/skeyform?form=advancedswitchform&lang=zh_CN&flag=1&type=2";
45. // 服务器配置提交地址
46. public final static String DEV_SERVICE_URL = "https://mp.weixin.qq.com/advanced/callbackprofile?t=ajax-response&lang=zh_CN&token=";
47. // 获取ACCESS_TOKEN接口
48. public final static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
49. // 获取粉丝列表
50. public final static String FANS_URL = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=%s";
51. // 获取粉丝信息
52. public final static String FANS_INFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN";
53. // 删除自定义菜单
54. public final static String MENU_DELETE_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=%s";
55. // 创建自定义菜单
56. public final static String MENU_CREATE_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s";
57.
58. // 模拟请求所用的参数设置
59. public final static String COOKIE_H = "Cookie";
60. public final static String CONNECTION_H = "Connection";
61. public final static String CONNECTION = "keep-alive";
62. public final static String HOST_H = "Host";
63. public final static String HOST = "mp.weixin.qq.com";
64. public final static String REFERER_H = "Referer";
65. public final static String REFERER = "https://mp.weixin.qq.com/";
66. public final static String USER_AGENT_H = "User-Agent";
67. public final static String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36";
68. public final static String ACCEPT_H = "Accept";
69. public final static String ACCEPT = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
70. public final static String ACCEPT_ENCODEING_H = "Accept-Encoding";
71. public final static String ACCEPT_ENCODEING = "gzip,deflate,sdch";
72. public final static String ACCEPT_LANGUAGE_H = "Accept-Language";
73. public final static String ACCEPT_LANGUAGE = "zh-CN,zh;q=0.8";
74. public final static String CONTENT_TYPE_H = "Content-Type";
75. public final static String CONTENT_TYPE = "application/x-www-form-urlencoded; charset=UTF-8";
76. public final static String XMLHTTP_REQUEST_H = "X-Requested-With";
77. public final static String XMLHTTP_REQUEST = "XMLHttpRequest";
78. public final static String UTF_8 = "UTF-8";
79.
80. private HttpClient client = new HttpClient();
81. private boolean isLogin = false;
82. private String cookiestr;
83. private String loginUser;
84. private String loginPwd;
85. private String token;
86.
87. public SmartBindUtil(String loginUser, String loginPwd) {
88. super();
89. this.loginUser = loginUser;
90. this.loginPwd = loginPwd;
91. }
92.
93. /**
94. * 得到AppId,AppSecret
95. *
96. * @return
97. */
98. public WechatDevInfo getWechatDev() {
99. int staus = login();
100. if (staus == HttpStatus.SC_OK) {
101. isLogin = true;
102. return getWechatDevInfo();
103. } else {
104. return null;
105. }
106. }
107.
108. public int login() {
109. if (isLogin) {
110. return HttpStatus.SC_OK;
111. }
112. PostMethod post = new PostMethod(LOGIN_URL);
113. setHeader(post);
114. setLoginParams(post);
115. log.info("正在登陆微信公众平台...");
116. try {
117. System.setProperty("jsse.enableSNIExtension", "false");
118. int status = client.executeMethod(post);
119. if (status == HttpStatus.SC_OK) {
120. log.info("登陆成功");
121. String res = post.getResponseBodyAsString();
122. JSONObject retcode = JSON.parseObject(res);
123. int ret = Integer.parseInt(retcode.getJSONObject("base_resp")
124. .getString("ret"));
125. if (ret == 0) {
126. log.info("微信端验证成功");
127. Cookie[] cookies = client.getState().getCookies();
128. StringBuffer cookie = new StringBuffer();
129. for (Cookie c : cookies) {
130. cookie.append(c.getName()).append("=")
131. .append(c.getValue()).append(";");
132. }
133. this.cookiestr = cookie.toString();
134. log.info("正在获取token...");
135. String redirect_url = retcode.getString("redirect_url");
136. if (redirect_url != null
137. && redirect_url.trim().length() > 0) {
138. String[] ss = StringUtils.split(redirect_url, "?");
139. String[] ps = null;
140. if (ss.length == 2) {
141. if (!StringUtils.isBlank(ss[1])
142. && ss[1].indexOf("&") != -1)
143. ps = StringUtils.split(ss[1], "&");
144. } else if (ss.length == 1) {
145. if (!StringUtils.isBlank(ss[0])
146. && ss[0].indexOf("&") != -1)
147. ps = StringUtils.split(ss[0], "&");
148. }
149. if (ps != null) {
150. for (String p : ps) {
151. if (StringUtils.isBlank(p)) {
152. continue;
153. }
154. String[] tk = StringUtils.split(p, "=");
155. if (tk[0] != null
156. && "token".equals(tk[0].trim()
157. .toLowerCase())) {
158. token = tk[1];
159. break;
160. }
161. }
162. }
163. log.info("获取token成功...");
164. }
165. log.info("正在进入微信首页...");
166. return index();
167. } else {
168. log.info("微信端验证失败code: " + ret);
169. return ret;
170. }
171. } else {
172. System.err.println("Method failed: " + post.getStatusLine());
173. log.info("网络连接错误");
174. return -1;
175. }
176. } catch (Exception e) {
177. log.error(e.getMessage(), e);
178. e.printStackTrace();
179. return -1;
180. } finally {
181. post.releaseConnection();
182. }
183. }
184.
185. /**
186. * 切换开发模式/编辑模式
187. *
188. * @param flag
189. * 开启1关闭0
190. * @param type
191. * 开发模式2编辑模式1
192. * @return
193. */
194. public Result<Integer> enabledDev(int flag, int type) {
195. Result<Integer> result = new Result<Integer>();
196. int staus = login();
197. if (staus == HttpStatus.SC_OK) {
198. isLogin = true;
199. PostMethod post = new PostMethod(DEV_UPDATE_RUL);
200. setHeader(post);
201. NameValuePair[] params = new NameValuePair[] {
202. new NameValuePair("flag", "" + flag),
203. new NameValuePair("type", "" + type),
204. new NameValuePair("token", token) };
205. post.setRequestBody(params);
206. try {
207. log.info("正在切换开发模式/编辑模式...");
208. staus = client.executeMethod(post);
209. if (staus == HttpStatus.SC_OK) {
210. log.info("服务器连接成功");
211. String res = post.getResponseBodyAsString();
212. JSONObject retcode = JSON.parseObject(res);
213. JSONObject base = retcode.getJSONObject("base_resp");
214. result.setObject(Integer.parseInt(base.getString("ret")));
215. result.setMsg(base.getString("err_msg"));
216. } else {
217. result.setObject(staus);
218. result.setMsg("网络连接错误,请稍后再试");
219. }
220. } catch (Exception e) {
221. log.error(e.getMessage(), e);
222. result.setObject(staus);
223. result.setMsg("网络连接错误,请稍后再试");
224. } finally {
225. post.releaseConnection();
226. }
227. } else {
228. result.setObject(staus);
229. result.setMsg("服务器登陆失败,请稍后再试");
230. }
231. return result;
232. }
233.
234. /**
235. * 设置开发模式,服务器回调
236. *
237. * @param url
238. * @param callback_token
239. * @return
240. */
241. public Result<Integer> setDevServiceUrl(String url, String callback_token) {
242. Result<Integer> result = new Result<Integer>();
243. int staus = login();
244. if (staus == HttpStatus.SC_OK) {
245. isLogin = true;
246. PostMethod post = new PostMethod(DEV_SERVICE_URL + token);
247. setHeader(post);
248. NameValuePair[] params = new NameValuePair[] {
249. new NameValuePair("url", "" + url),
250. new NameValuePair("callback_token", callback_token) };
251. post.setRequestBody(params);
252. try {
253. log.info("正在设置公众平台回调...");
254. staus = client.executeMethod(post);
255. if (staus == HttpStatus.SC_OK) {
256. log.info("服务器连接成功");
257. String res = post.getResponseBodyAsString();
258. // TODO............
259. System.out.println("res========" + res);
260. JSONObject retcode = JSON.parseObject(res);
261. staus = Integer.parseInt(retcode.getString("ret"));
262. result.setObject(Integer.parseInt(retcode.getString("ret")));
263. result.setMsg(retcode.getString("msg"));
264. } else {
265. result.setObject(staus);
266. result.setMsg("网络连接错误,请稍后再试");
267. }
268. } catch (Exception e) {
269. log.info(e.getMessage(), e);
270. result.setObject(staus);
271. result.setMsg("网络连接错误,请稍后再试");
272. } finally {
273. post.releaseConnection();
274. }
275. } else {
276. result.setObject(staus);
277. result.setMsg("服务器登陆失败,请稍后再试");
278. }
279. return result;
280. }
281.
282. /**
283. * 得到微信公众平台个人信息
284. *
285. * @return
286. */
287. public WechatAccountInfo getAccount() {
288. // TODO获取微信账号基本信息
289. log.info("获取账户信息...");
290. WechatAccountInfo account = null;
291. GetMethod get = new GetMethod(ACCOUNT_INFO_URL + token);
292. setHeader(get);
293. try {
294. int status = client.executeMethod(get);
295. if (status == HttpStatus.SC_OK) {
296. log.info("已经连接,正在接收数据");
297. String res = get.getResponseBodyAsString();
298. Document doc = Jsoup.parseBodyFragment(res);
299. Elements eles = doc.select("#settingArea .meta_content");
300. if (eles != null && eles.size() > 0) {
301. account = new WechatAccountInfo();
302. account.setAccountName(eles.get(0).text());
303. account.setHeadImage(HOST_URL
304. + eles.get(1).select("img").attr("src"));
305. account.setAccountId(eles.get(3).text());
306. account.setWechatNumber(eles.get(4).text());
307. account.setType(eles.get(5).text());
308. account.setAuthenticate(eles.get(6).text());
309. }
310. }
311. } catch (Exception e) {
312. log.error("网络连接发生错误", e);
313. } finally {
314. get.releaseConnection();
315. }
316. return account;
317. }
318.
319. /**
320. * 得到AppId,AppSecret
321. *
322. * @return
323. */
324. public WechatDevInfo getWechatDevInfo() {
325. // TODO 得到AppId,AppSecret
326. log.info("获取appid,appsecret信息...");
327. WechatDevInfo devInfo = null;
328. GetMethod get = new GetMethod(DEV_URL + token);
329. setHeader(get);
330. try {
331. int status = client.executeMethod(get);
332. if (status == HttpStatus.SC_OK) {
333. log.info("已经连接,正在接收数据");
334. String res = get.getResponseBodyAsString();
335. Document doc = Jsoup.parseBodyFragment(res);
336. Elements eles = doc.select(".developer_info_wrp");
337. if (eles != null && eles.size() > 0) {
338. Elements datas = eles.select(".frm_vertical_pt");
339. devInfo = new WechatDevInfo();
340. devInfo.setAppId(datas.get(0).text());
341. devInfo.setAppSecret(datas.get(1).text()
342. .replaceAll("重置", "").trim());
343. }
344. }
345. } catch (Exception e) {
346. e.printStackTrace();
347. } finally {
348. get.releaseConnection();
349. }
350. return devInfo;
351. }
352.
353. /**
354. * 登出操作
355. *
356. * @return 异常CODE
357. * @throws HttpException
358. * @throws IOException
359. */
360. public int logout() throws HttpException, IOException {
361. log.info("退出服务...");
362. GetMethod get = new GetMethod(LOGOUT_URL + token);
363. setHeader(get);
364. int status = client.executeMethod(get);
365. get.releaseConnection();
366. return status;
367. }
368.
369. /**
370. * 进入微信首页
371. *
372. * @return 异常CODE
373. * @throws HttpException
374. * @throws IOException
375. */
376. private int index() throws HttpException, IOException {
377. GetMethod get = new GetMethod(INDEX_URL + token);
378. setHeader(get);
379. int status = client.executeMethod(get);
380. get.releaseConnection();
381. return status;
382. }
383.
384. private void setHeader(PostMethod post) {
385. post.setRequestHeader(CONNECTION_H, CONNECTION);
386. post.setRequestHeader(HOST_H, HOST);
387. post.setRequestHeader(REFERER_H, REFERER);
388. post.setRequestHeader(USER_AGENT_H, USER_AGENT);
389. if (this.cookiestr != null && this.cookiestr.length() > 0) {
390. post.setRequestHeader(COOKIE_H, this.cookiestr);
391. }
392. }
393.
394. private void setHeader(GetMethod get) {
395. get.setRequestHeader(CONNECTION_H, CONNECTION);
396. get.setRequestHeader(HOST_H, HOST);
397. get.setRequestHeader(REFERER_H, REFERER);
398. get.setRequestHeader(USER_AGENT_H, USER_AGENT);
399. if (this.cookiestr != null && this.cookiestr.length() > 0) {
400. get.setRequestHeader(COOKIE_H, this.cookiestr);
401. }
402. }
403.
404. private void setLoginParams(PostMethod post) {
405. post.setRequestHeader(CONTENT_TYPE_H, CONTENT_TYPE);
406. post.setRequestHeader(XMLHTTP_REQUEST_H, XMLHTTP_REQUEST);
407. NameValuePair[] params = new NameValuePair[] {
408. new NameValuePair("username", this.loginUser),
409. new NameValuePair("pwd", DigestUtils.md5Hex(this.loginPwd
410. .getBytes())), new NameValuePair("f", "json"),
411. new NameValuePair("imgcode", "") };
412. post.setQueryString(params);
413. }
414. }
智能绑定执行类:
[java] view plain copy
1. import org.oms.wechat.pojo.WechatAccountInfo;
2. import org.oms.wechat.pojo.WechatDevInfo;
3. /**
4. * 智能绑定执行类
5. * @author Sunlight
6. *
7. */
8. public class WechatBind {
9. private static String msg;
10. private static String url="//omsvip.sinaapp.com/coreServlet";
11. private static String token="weixinCourse";
12.
13. public static String SmartBind(String username, String password) {
14. // 开始绑定帐号
15. // 初始化登录信息
16. SmartBindUtil smartBind = new SmartBindUtil(username, password);
17. //登录成功后,在开发者中心获取开发者ID(AppId、AppSecret)
18. WechatDevInfo devInfo=smartBind.getWechatDev();
19. System.out.println("devInfo="+devInfo);
20. //获取微信公众号设置基本信息(名称、头像、类型、认证情况等)
21. WechatAccountInfo account = smartBind.getAccount();
22. if (account == null) {
23. msg = "{success:false,msg:\"登陆微信服务器失败,请检查用户名/密码是否正确\"}";
24. }
25. System.out.println("account="+account);
26.
27. // 启动开发模式
28. if (msg == null) {
29. Result<Integer> result = smartBind.enabledDev(1, 2);
30. if (result.getObject() != 0) {
31. msg = "{success:false,msg:\"" + result.getMsg() + "\"}";
32. }
33. }
34. // 验证服务器接口回调,此处修改服务器配置中的URL和Token
35. if (msg == null) {
36. Result<Integer> result = smartBind.setDevServiceUrl(url, token);
37. if (result.getObject() != 0) {
38. msg = "{success:false,msg:\"" + result.getMsg() + "\"}";
39. }
40. }
41. if(msg==null){
42. msg="智能绑定成功!";
43. }
44. return msg;
45. }
46. }
Result<T>.class 这个可以不要,也可以在前面文章中拷贝!
需要用到的2个Pojo 公众号信息类,代码如下:
[java] view plain copy
1. /**
2. * 微信账号基本信息
3. *
4. * @author sunlight
5. *
6. */
7. public class WechatAccountInfo {
8. /**
9. * 原始ID
10. */
11. private String accountId;
12. /**
13. * 名称
14. */
15. private String accountName;
16. /**
17. * 微信头像
18. */
19. private String headImage;
20. /**
21. * 微信号
22. */
23. private String wechatNumber;
24. /**
25. * 账号类型
26. */
27. private String type;
28. /**
29. * 认证情况
30. */
31. private String authenticate;
32.
33. public String getAccountId() {
34. return accountId;
35. }
36.
37. public void setAccountId(String accountId) {
38. this.accountId = accountId;
39. }
40.
41. public String getAccountName() {
42. return accountName;
43. }
44.
45. public void setAccountName(String accountName) {
46. this.accountName = accountName;
47. }
48.
49. public String getHeadImage() {
50. return headImage;
51. }
52.
53. public void setHeadImage(String headImage) {
54. this.headImage = headImage;
55. }
56.
57. public String getWechatNumber() {
58. return wechatNumber;
59. }
60.
61. public void setWechatNumber(String wechatNumber) {
62. this.wechatNumber = wechatNumber;
63. }
64.
65. public String getType() {
66. return type;
67. }
68.
69. public void setType(String type) {
70. this.type = type;
71. }
72.
73. public String getAuthenticate() {
74. return authenticate;
75. }
76.
77. public void setAuthenticate(String authenticate) {
78. this.authenticate = authenticate;
79. }
80.
81. @Override
82. public String toString() {
83. return "WechatAccountInfo [accountId=" + accountId + ", accountName="
84. + accountName + ", headImage=" + headImage + ", wechatNumber="
85. + wechatNumber + ", type=" + type + ", authenticate="
86. + authenticate + "]";
87. }
88.
89. }
开发者信息类:
[java] view plain copy
1. /**
2. * 微信开发者信息
3. *
4. * @author sunlight
5. *
6. */
7. public class WechatDevInfo {
8. private String appId;
9. private String appSecret;
10.
11. public String getAppId() {
12. return appId;
13. }
14.
15. public void setAppId(String appId) {
16. this.appId = appId;
17. }
18.
19. public String getAppSecret() {
20. return appSecret;
21. }
22.
23. public void setAppSecret(String appSecret) {
24. this.appSecret = appSecret;
25. }
26.
27. @Override
28. public String toString() {
29. return "WechatDevInfo [appId=" + appId + ", appSecret=" + appSecret
30. + "]";
31. }
32.
33. }
最后附上执行结果:

注意:因为微信公众号页面等相关调整频繁,因此智能绑定微信公众号只是模拟用户登录,所以微信公众号官网页面等相关信息发生变化会导致智能绑定功能失效!
因此,微信修改一次我们的代码也会变化一次。
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之微信频道!
喜欢 | 0
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号