PageRenderTime 24ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/java/com/jeecms/cms/service/WeiXinSvcImpl.java

https://gitlab.com/spiderworts/ab_pc_cms
Java | 358 lines | 307 code | 26 blank | 25 comment | 30 complexity | 080cd8c7185ad78cac503df3cd6ac318 MD5 | raw file
  1. package com.jeecms.cms.service;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.net.URI;
  5. import java.security.cert.CertificateException;
  6. import java.security.cert.X509Certificate;
  7. import java.util.HashSet;
  8. import java.util.Set;
  9. import javax.net.ssl.SSLContext;
  10. import javax.net.ssl.TrustManager;
  11. import javax.net.ssl.X509TrustManager;
  12. import org.apache.commons.lang.StringUtils;
  13. import org.apache.http.HttpEntity;
  14. import org.apache.http.HttpResponse;
  15. import org.apache.http.StatusLine;
  16. import org.apache.http.client.ClientProtocolException;
  17. import org.apache.http.client.HttpClient;
  18. import org.apache.http.client.HttpResponseException;
  19. import org.apache.http.client.ResponseHandler;
  20. import org.apache.http.client.methods.HttpGet;
  21. import org.apache.http.client.methods.HttpPost;
  22. import org.apache.http.conn.ClientConnectionManager;
  23. import org.apache.http.conn.scheme.Scheme;
  24. import org.apache.http.conn.scheme.SchemeRegistry;
  25. import org.apache.http.conn.ssl.SSLSocketFactory;
  26. import org.apache.http.entity.StringEntity;
  27. import org.apache.http.impl.client.DefaultHttpClient;
  28. import org.apache.http.util.EntityUtils;
  29. import org.json.JSONArray;
  30. import org.json.JSONException;
  31. import org.json.JSONObject;
  32. import org.slf4j.Logger;
  33. import org.slf4j.LoggerFactory;
  34. import org.springframework.beans.factory.annotation.Autowired;
  35. import org.springframework.stereotype.Service;
  36. import com.jeecms.cms.Constants;
  37. import com.jeecms.cms.entity.main.Content;
  38. import com.jeecms.cms.entity.main.ContentExt;
  39. import com.jeecms.cms.entity.main.ContentTxt;
  40. import com.jeecms.common.upload.FileUpload;
  41. import com.jeecms.common.util.PropertyUtils;
  42. import com.jeecms.common.util.StrUtils;
  43. import com.jeecms.common.web.springmvc.RealPathResolver;
  44. import com.jeecms.core.entity.CmsConfig;
  45. import com.jeecms.core.entity.CmsSite;
  46. import com.jeecms.core.manager.CmsConfigMng;
  47. /**
  48. * @author Tom
  49. */
  50. @Service
  51. public class WeiXinSvcImpl implements WeiXinSvc {
  52. private static final Logger log = LoggerFactory.getLogger(WeiXinSvcImpl.class);
  53. //微信token地址key
  54. public static final String TOKEN_KEY="weixin.address.token";
  55. //微信公众号关注用户地址key
  56. public static final String USERS_KEY="weixin.address.users";
  57. //微信发送消息地址key
  58. public static final String SEND_KEY="weixin.address.send";
  59. //微信上传地址key
  60. public static final String UPLOAD_KEY="weixin.address.upload";
  61. //每次抽取关注号数量
  62. public static final Integer USERS_QUERY_MAX=10000;
  63. public String getToken() {
  64. String tokenGetUrl=PropertyUtils.getPropertyValue(new File(realPathResolver.get(Constants.JEECMS_CONFIG)),TOKEN_KEY);
  65. CmsConfig config=configMng.get();
  66. String appid=config.getWeixinID();
  67. String secret=config.getWeixinKey();
  68. JSONObject tokenJson=new JSONObject();
  69. if(StringUtils.isNotBlank(appid)&&StringUtils.isNotBlank(secret)){
  70. tokenGetUrl+="&appid="+appid+"&secret="+secret;
  71. tokenJson=getUrlResponse(tokenGetUrl);
  72. try {
  73. return (String) tokenJson.get("access_token");
  74. } catch (JSONException e) {
  75. // TODO Auto-generated catch block
  76. e.printStackTrace();
  77. return null;
  78. }
  79. }else{
  80. return null;
  81. }
  82. }
  83. public Set<String> getUsers(String access_token) {
  84. String usersGetUrl=PropertyUtils.getPropertyValue(new File(realPathResolver.get(Constants.JEECMS_CONFIG)),USERS_KEY);
  85. usersGetUrl+="?access_token="+access_token;
  86. JSONObject data=getUrlResponse(usersGetUrl);
  87. Set<String>openIds=new HashSet<String>();
  88. Integer total=0,count=0;
  89. try {
  90. total=(Integer) data.get("total");
  91. count=(Integer) data.get("count");
  92. //总关注用户数超过默认一万
  93. if(count<total){
  94. openIds.addAll(getUsers(openIds,usersGetUrl, access_token, (String)data.get("next_openid")));
  95. }else{
  96. //有关注者 json才有data参数
  97. if(count>0){
  98. JSONObject openIdData=(JSONObject) data.get("data");
  99. JSONArray openIdArray= (JSONArray) openIdData.get("openid");
  100. for(int i=0;i<openIdArray.length();i++){
  101. openIds.add((String) openIdArray.get(i));
  102. }
  103. }
  104. }
  105. } catch (JSONException e) {
  106. // TODO Auto-generated catch block
  107. e.printStackTrace();
  108. }
  109. return openIds;
  110. }
  111. public String uploadFile(String access_token,String filePath,String type){
  112. String sendGetUrl=PropertyUtils.getPropertyValue(new File(realPathResolver.get(Constants.JEECMS_CONFIG)),UPLOAD_KEY);
  113. String url = sendGetUrl+"?access_token=" + access_token;
  114. String result = null;
  115. String mediaId="";
  116. FileUpload fileUpload = new FileUpload();
  117. try {
  118. result = fileUpload.uploadFile(url,filePath, type);
  119. JSONObject json=new JSONObject(result);
  120. mediaId=json.getString("media_id");
  121. } catch (Exception e) {
  122. // TODO Auto-generated catch block
  123. e.printStackTrace();
  124. }
  125. return mediaId;
  126. }
  127. public void sendText(String access_token,String content) {
  128. String sendGetUrl=PropertyUtils.getPropertyValue(new File(realPathResolver.get(Constants.JEECMS_CONFIG)),SEND_KEY);
  129. String url = sendGetUrl+"?access_token=" + access_token;
  130. Set<String> openIds=getUsers(access_token);
  131. //发送给所有关注者消息
  132. for(String openId:openIds){
  133. String strJson = "{\"touser\" :\""+openId+"\",";
  134. strJson += "\"msgtype\":\"text\",";
  135. strJson += "\"text\":{";
  136. strJson += "\"content\":\""+content+"\"";
  137. strJson += "}}";
  138. post(url, strJson);
  139. }
  140. }
  141. public void sendContent(String access_token,String title, String description, String url,
  142. String picurl) {
  143. String sendUrl=PropertyUtils.getPropertyValue(new File(realPathResolver.get(Constants.JEECMS_CONFIG)),SEND_KEY);
  144. sendUrl = sendUrl+"?access_token=" + access_token;
  145. Set<String> openIds=getUsers(access_token);
  146. if(description==null){
  147. description="";
  148. }
  149. //发送给所有关注者消息
  150. for(String openId:openIds){
  151. String strJson = "{\"touser\" :\""+openId+"\",";
  152. strJson += "\"msgtype\":\"news\",";
  153. strJson += "\"news\":{";
  154. strJson += "\"articles\": [{";
  155. strJson +="\"title\":\""+title+"\",";
  156. strJson +="\"description\":\""+description+"\",";
  157. strJson +="\"url\":\""+url+"\",";
  158. strJson +="\"picurl\":\""+picurl+"\"";
  159. strJson += "}]}}";
  160. post(sendUrl, strJson);
  161. }
  162. }
  163. public void sendVedio(String access_token,String title, String description, String media_id) {
  164. String sendGetUrl=PropertyUtils.getPropertyValue(new File(realPathResolver.get(Constants.JEECMS_CONFIG)),SEND_KEY);
  165. String url = sendGetUrl+"?access_token=" + access_token;
  166. Set<String> openIds=getUsers(access_token);
  167. if(description==null){
  168. description="";
  169. }
  170. //发送给所有关注者消息
  171. for(String openId:openIds){
  172. String strJson = "{\"touser\" :\""+openId+"\",";
  173. strJson += "\"msgtype\":\"video\",";
  174. strJson += "\"video\":{";
  175. strJson += "\"media_id\":\""+media_id+"\",";
  176. strJson += "\"title\":\""+title+"\",";
  177. strJson += "\"description\":\""+description+"\"";
  178. strJson += "}}";
  179. post(url, strJson);
  180. }
  181. }
  182. public void sendMessage(Integer sendType,Integer selectImg,String weixinImg,Content bean, ContentExt ext, ContentTxt txt){
  183. CmsSite site=bean.getSite();
  184. //发送微信消息
  185. if(sendType!=null&&sendType!=0){
  186. String token=weixinTokenCache.getToken();
  187. if(sendType==1){
  188. //纯文本消息
  189. sendText(token, StrUtils.removeHtmlTagP(txt.getTxt()));
  190. }else if(sendType==2){
  191. //视频消息
  192. if(StringUtils.isNotBlank(ext.getMediaPath())){
  193. String vedioPath=ext.getMediaPath();
  194. if(StringUtils.isNotBlank(site.getContextPath())){
  195. vedioPath=vedioPath.substring(site.getContextPath().length());
  196. }
  197. //上传视频
  198. String media_id=uploadFile(token, realPathResolver.get(vedioPath),"video");
  199. sendVedio(token, ext.getTitle(), ext.getDescription(), media_id);
  200. }
  201. }else if(sendType==3){
  202. if(selectImg!=null){
  203. String weixinPicUrl="";
  204. if(selectImg==0){
  205. //自定义上传
  206. if (!StringUtils.isBlank(weixinImg)) {
  207. weixinImg = site.getProtocol()+site.getDomain()+":"+site.getPort()+weixinImg;
  208. }
  209. weixinPicUrl=weixinImg;
  210. }else if(selectImg==1){
  211. //类型图
  212. weixinPicUrl=bean.getTypeImgWhole();
  213. }else if(selectImg==2){
  214. //标题图
  215. weixinPicUrl=bean.getTitleImgWhole();
  216. }else if(selectImg==3){
  217. //内容图
  218. weixinPicUrl=bean.getContentImgWhole();
  219. }
  220. sendContent(token,ext.getTitle(), ext.getDescription(), bean.getUrl(), weixinPicUrl);
  221. }
  222. }
  223. }
  224. }
  225. private Set<String> getUsers(Set<String>openIds,String url,String access_token,String next_openid) {
  226. JSONObject data=getUrlResponse(url);
  227. try {
  228. Integer count=(Integer) data.get("count");
  229. String nextOpenId=(String) data.get("next_openid");
  230. if(count>0){
  231. JSONObject openIdData=(JSONObject) data.get("data");
  232. JSONArray openIdArray= (JSONArray) openIdData.get("openid");
  233. for(int i=0;i<openIdArray.length();i++){
  234. openIds.add((String) openIdArray.get(i));
  235. }
  236. }
  237. if(StringUtils.isNotBlank(nextOpenId)){
  238. return getUsers(openIds,url, access_token, nextOpenId);
  239. }
  240. } catch (JSONException e) {
  241. // TODO Auto-generated catch block
  242. e.printStackTrace();
  243. }
  244. return openIds;
  245. }
  246. private JSONObject getUrlResponse(String url){
  247. CharsetHandler handler = new CharsetHandler("UTF-8");
  248. try {
  249. HttpGet httpget = new HttpGet(new URI(url));
  250. DefaultHttpClient client = new DefaultHttpClient();
  251. client = (DefaultHttpClient) wrapClient(client);
  252. return new JSONObject(client.execute(httpget, handler));
  253. } catch (Exception e) {
  254. e.printStackTrace();
  255. return null;
  256. }
  257. }
  258. private void post(String url, String json)
  259. {
  260. DefaultHttpClient client = new DefaultHttpClient();
  261. client = (DefaultHttpClient) wrapClient(client);
  262. HttpPost post = new HttpPost(url);
  263. try
  264. {
  265. StringEntity s = new StringEntity(json,"utf-8");
  266. s.setContentType("application/json");
  267. post.setEntity(s);
  268. HttpResponse res = client.execute(post);
  269. HttpEntity entity = res.getEntity();
  270. log.info(EntityUtils.toString(entity, "utf-8"));
  271. }
  272. catch (Exception e)
  273. {
  274. e.printStackTrace();
  275. }
  276. }
  277. private HttpClient wrapClient(HttpClient base) {
  278. try {
  279. SSLContext ctx = SSLContext.getInstance("TLS");
  280. X509TrustManager tm = new X509TrustManager() {
  281. public void checkClientTrusted(X509Certificate[] xcs,
  282. String string) throws CertificateException {
  283. }
  284. public void checkServerTrusted(X509Certificate[] xcs,
  285. String string) throws CertificateException {
  286. }
  287. public X509Certificate[] getAcceptedIssuers() {
  288. return null;
  289. }
  290. };
  291. ctx.init(null, new TrustManager[] { tm }, null);
  292. SSLSocketFactory ssf = new SSLSocketFactory(ctx);
  293. ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  294. ClientConnectionManager ccm = base.getConnectionManager();
  295. SchemeRegistry sr = ccm.getSchemeRegistry();
  296. sr.register(new Scheme("https", ssf, 443));
  297. return new DefaultHttpClient(ccm, base.getParams());
  298. } catch (Exception ex) {
  299. return null;
  300. }
  301. }
  302. private class CharsetHandler implements ResponseHandler<String> {
  303. private String charset;
  304. public CharsetHandler(String charset) {
  305. this.charset = charset;
  306. }
  307. public String handleResponse(HttpResponse response)
  308. throws ClientProtocolException, IOException {
  309. StatusLine statusLine = response.getStatusLine();
  310. if (statusLine.getStatusCode() >= 300) {
  311. throw new HttpResponseException(statusLine.getStatusCode(),
  312. statusLine.getReasonPhrase());
  313. }
  314. HttpEntity entity = response.getEntity();
  315. if (entity != null) {
  316. if (!StringUtils.isBlank(charset)) {
  317. return EntityUtils.toString(entity, charset);
  318. } else {
  319. return EntityUtils.toString(entity);
  320. }
  321. } else {
  322. return null;
  323. }
  324. }
  325. }
  326. @Autowired
  327. private RealPathResolver realPathResolver;
  328. @Autowired
  329. private CmsConfigMng configMng;
  330. @Autowired
  331. private WeixinTokenCache weixinTokenCache;
  332. }