package com.shhxzq.fin.lifeapp.biz.utils; import org.apache.log4j.Logger; import com.alibaba.fastjson.JSONObject; import com.shhxzq.fin.lifeapp.model.constants.CreditConstants; /** * 微信工具类 * @author Gxx */ public class WeiXinUtils { /** * 日志处理器 */ private static Logger logger = BaseUuidLoggerUtils.getBaseUuidLogger(); /** * 获取token URL */ public static final String WEI_XIN_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + PropertyUtils.getInstance().getProperty(CreditConstants.WEI_XIN_CORP_ID) + "&corpsecret=" + PropertyUtils.getInstance().getProperty(CreditConstants.WEI_XIN_CORP_SECRET); /** * 发送微信通知 URL */ public static final String NOTIFY_URL_PREF = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="; /** * 获取token * @return */ private static String getToken() { logger.info("发送微信通知,获取token,url:" + WEI_XIN_TOKEN_URL); String response = HttpClientUtils.getWebContentByGet(WEI_XIN_TOKEN_URL); logger.info("发送微信通知,获取token,返回:" + response); /** * 返回: * { * "access_token":"fEXdGO2Hn0PPcV9Qvzbc3RuR6mu2frF7r7oeEQZKLyJtwhKhdCRa-VarrU3-f_TR", * "expires_in":7200 * } */ return (String)JSONObject.parseObject(response).get("access_token"); } /** * 发送微信通知 */ public static synchronized void notify(String msg) { try { /** * 0.判断是否要发送 */ logger.info("发送微信通知:" + msg); if(!CreditConstants.Y.equals(PropertyUtils.getInstance().getProperty(CreditConstants.WEI_XIN_NOTIFY_SWITCH))){ logger.info("微信通知发送开关不为Y,不发送!"); return; } /** * 1.获取token */ String token = WeiXinUtils.getToken(); String notifyUrl = NOTIFY_URL_PREF + token; JSONObject jsonbody=new JSONObject(); jsonbody.put("agentid", PropertyUtils.getInstance().getProperty(CreditConstants.WEI_XIN_AGENT_ID)); jsonbody.put("msgtype", "text"); jsonbody.put("safe", "0") ; jsonbody.put("toparty", PropertyUtils.getInstance().getProperty(CreditConstants.WEI_XIN_TO_PARTY)); JSONObject sonjsonbody=new JSONObject(); sonjsonbody.put("content", msg); jsonbody.put("text", sonjsonbody); logger.info("发送微信通知,发送,url:" + notifyUrl + ",json=" + jsonbody); /** * 2.发送通知 */ String response = HttpClientUtils.getWebContentByPost(notifyUrl, jsonbody.toString()); logger.info("发送微信通知,发送,返回:" + response); /** * 返回: * { * "errcode":0, * "errmsg":"ok" * } */ if(new Integer(0).equals((Integer)JSONObject.parseObject(response).get("errcode"))) { logger.info("发送成功!"); } else { logger.error("发送失败!"); } } catch (Exception e) { logger.error("发送微信通知异常", e); } } /** * main方法 * @param param * @throws Exception */ public static void main(String[] param) throws Exception { notify("总笔数[0]笔,正常[0]笔,余额不足[0]笔,黑名单[0]笔,其他异常[0]笔"); } }