package com.hx.mp.util; import com.hx.util.StringUtils; import net.sf.json.JSONException; import net.sf.json.JSONObject; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.sql.Timestamp; import java.text.MessageFormat; import java.util.Date; /** * 微信小程序工具类 */ public class MpUtil { /** 请求access_token */ public static final String URL_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}"; /** 请求服务器IP地址 */ public static final String URL_SERVER_ADDR = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token="; /** 微信js的code换去sessionKey */ public static final String JSCODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&grant_type=authorization_code&js_code="; /** 请求小程序码 **/ public static final String URL_WXACODE = "https://api.weixin.qq.com/wxa/getwxacode?access_token="; /** 请求小程序码-无数量限制 **/ public static final String URL_WXACODEUNLIMIT = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="; /** 请求小程序二维码 */ public static final String URL_QRCODE = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="; /** 发模版消息 */ public static final String URL_SEND_TEMP_MSG = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="; /** 设置发票授权字段 */ public static final String URL_SET_TICKET_FIELD = "https://api.weixin.qq.com/card/invoice/setbizattr?action=set_auth_field&access_token="; /** 获取发票ticket */ public static final String URL_GET_TICKET_TICKET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=wx_card&access_token="; /** 获取发票授权页链接 */ public static final String URL_GET_TICKET_AUTH_LINK = "https://api.weixin.qq.com/card/invoice/getauthurl?access_token="; /** 查询发票授权字段 */ public static final String URL_GET_AUTH_FIELD = "https://api.weixin.qq.com/card/invoice/getauthdata?access_token="; /** 设置 支付后开发票 */ public static final String URL_SET_PAY_INVOICE = "https://api.weixin.qq.com/card/invoice/setbizattr?action=set_pay_mch&access_token="; /** 查询支付后开发票 */ public static final String URL_GET_PAY_INVOICE = "https://api.weixin.qq.com/card/invoice/setbizattr?action=get_pay_mch&access_token="; /** 发送客服消息 */ public static final String URL_SEND_KF_MSG = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="; /************************************************* * 小程序 *************************/ /** 利用code换取sessionKey */ public static JSONObject jsCode2session(String code, String appId, String appSecret) { JSONObject obj = new JSONObject(); String url = StringUtils.format(JSCODE2SESSION_URL, appId, appSecret) + code; obj = HttpURLUtil(url, null); return obj; } /** 获取小程序二维码图片 */ public static String getQrCode(String accessToken, String jsonParam) throws Exception { JSONObject obj = HttpURLUtilJson(URL_QRCODE + accessToken, jsonParam); String qrStr = obj.optString("data"); return qrStr; } /** 从weixin接口获取Access_token **/ public static JSONObject getApplication_Access_tokenForUrl(String appId, String appSecret) throws Exception { String url = MessageFormat.format(URL_ACCESS_TOKEN, appId, appSecret); JSONObject obj = HttpURLUtil(url, null); return obj; } /** 请求http协议 获取信息工具 **/ public static InputStream HttpURLUtilStream(String url, String data) { HttpURLConnection con = null; URL u = null; try { u = new URL(url); con = (HttpURLConnection) u.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setReadTimeout(200000); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (data != null) { OutputStream os = con.getOutputStream(); os.write(data.getBytes("utf-8")); } if (con.getResponseCode() != 200) throw new RuntimeException("请求url失败"); return con.getInputStream(); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.disconnect(); } } return null; } /** 获取二维码图片 **/ public static JSONObject HttpURLUtilJson(String urlx, String objx) { JSONObject jo = new JSONObject(); try { // 创建url资源 URL url = new URL(urlx); // 建立http连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置允许输出 conn.setDoOutput(true); conn.setDoInput(true); // 设置不用缓存 conn.setUseCaches(false); // 设置传递方式 conn.setRequestMethod("POST"); // 设置维持长连接 conn.setRequestProperty("Connection", "Keep-Alive"); // 设置文件字符集: conn.setRequestProperty("Charset", "UTF-8"); // 设置文件类型: conn.setRequestProperty("contentType", "application/json"); // 开始连接请求 conn.connect(); OutputStream out = conn.getOutputStream(); // 写入请求的字符串 out.write(objx.getBytes()); out.flush(); out.close(); // 请求返回的状态 if (conn.getResponseCode() == 200) { // 请求返回的数据 InputStream in = conn.getInputStream(); try { ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] temp = new byte[1024]; int rc = 0; while ((rc = in.read(temp, 0, 100)) > 0) { swapStream.write(temp, 0, rc); } byte[] buffer = swapStream.toByteArray(); String base64 = Base64.encodeBase64String(buffer); jo.put("data", base64); } catch (Exception e1) { e1.printStackTrace(); } } else { // System.out.println("no++"); } } catch (Exception e) { e.printStackTrace(); } return jo; } /** 请求http协议 获取信息工具 **/ public static JSONObject HttpURLUtil(String url, String data) { HttpURLConnection con = null; URL u = null; String wxMsgXml = null; JSONObject obj = null; try { u = new URL(url); con = (HttpURLConnection) u.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setReadTimeout(5000); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (data != null) { OutputStream os = con.getOutputStream(); os.write(data.getBytes("utf-8")); } if (con.getResponseCode() != 200) throw new RuntimeException("请求url失败"); // 读取返回内容 wxMsgXml = IOUtils.toString(con.getInputStream(), "utf-8"); obj = JSONObject.fromObject(wxMsgXml); // //System.out.println("HttpURLUtil:"+wxMsgXml); } catch (Exception e) { e.printStackTrace(); obj = new JSONObject(); try { obj.put("status", 1); obj.put("errMsg", e.getMessage()); } catch (JSONException e1) { e1.printStackTrace(); } } finally { if (con != null) { con.disconnect(); } } return obj; } /** 发送模版消息 **/ public static JSONObject sendTempMsg(String accessToken, String jsonStr) { JSONObject obj = HttpURLUtil(URL_SEND_TEMP_MSG + accessToken, jsonStr); return obj; } public static Integer DateToTimestamp(Date time) { Timestamp ts = new Timestamp(time.getTime()); return (int) ((ts.getTime()) / 1000); } /** * 发送链接客服消息 * * @throws JSONException */ public static String sendKfLinkMsg(String at, String openId, String title, String description, String url, String imgUrl) throws JSONException { String result = "fail"; JSONObject obj = new JSONObject(); obj.put("touser", openId); obj.put("msgtype", "link"); JSONObject pObj = new JSONObject(); pObj.put("title", title); pObj.put("description", description); pObj.put("url", url); pObj.put("thumb_url", imgUrl); obj.put("link", pObj); JSONObject rObj = HttpURLUtil(URL_SEND_KF_MSG + at, obj.toString()); // System.out.println("rObj==="+rObj); if (rObj != null) { if (rObj.optInt("errcode", -1) == 0) { result = "suc"; } else { result = rObj.optString("errmsg"); } } rObj = null; obj = null; return result; } /** * 发送图片客户消息 * * @param access_token * access_token * @param toUser * 用户openid * @param media_id * 素材id * @return */ public static String sendKfImageMsg(String access_token, String toUser, String media_id) { String result = "fail"; try { JSONObject obj = new JSONObject(); obj.put("touser", toUser); obj.put("msgtype", "image"); JSONObject pObj = new JSONObject(); pObj.put("media_id", media_id); obj.put("image", pObj); JSONObject rObj = HttpURLUtil(URL_SEND_KF_MSG + access_token, obj.toString()); System.out.println("rObj==" + rObj.toString()); if (rObj != null) { if (rObj.optInt("errcode", -1) == 0) { result = "suc"; } else { result = rObj.optString("errmsg"); } } rObj = null; obj = null; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 发送文本客户消息 * * @param access_token * access_token * @param toUser * 用户openid * @return */ public static String sendKfTextMsg(String access_token, String toUser, String content) { String result = "fail"; try { JSONObject obj = new JSONObject(); obj.put("touser", toUser); obj.put("msgtype", "text"); JSONObject pObj = new JSONObject(); pObj.put("content", content); obj.put("text", pObj); JSONObject rObj = HttpURLUtil(URL_SEND_KF_MSG + access_token, obj.toString()); if (rObj != null) { if (rObj.optInt("errcode", -1) == 0) { result = "suc"; } else { result = rObj.optString("errmsg"); } } rObj = null; obj = null; } catch (Exception e) { e.printStackTrace(); } return result; } /** 获取小程序码图片 */ public static String getWXACode(String accessToken, String jsonParam, String path) throws Exception { JSONObject obj = HttpURLUtilJson(URL_WXACODE + accessToken, jsonParam); String qrStr = obj.optString("data"); return qrStr; } /** 获取小程序码图片 */ public static String getWXACodeUnlimit(String accessToken, String jsonParam, String path) throws Exception { JSONObject obj = HttpURLUtilJson(URL_WXACODEUNLIMIT + accessToken, jsonParam); String qrStr = obj.optString("data"); return qrStr; } }