- package com.wxpay.util;
-
-
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.net.URL;
- import java.net.URLConnection;
-
-
- import org.apache.log4j.Logger;
-
-
-
-
-
-
-
- public class HttpUtil {
-
- private final static int CONNECT_TIMEOUT = 5000;
- private final static String DEFAULT_ENCODING = "UTF-8";
- private static Logger lg=Logger.getLogger(HttpUtil.class);
-
- public static String postData(String urlStr, String data){
- return postData(urlStr, data, null);
- }
-
-
-
-
-
-
-
- public static String postData(String urlStr, String data, String contentType){
- BufferedReader reader = null;
- try {
- URL url = new URL(urlStr);
- URLConnection conn = url.openConnection();
- conn.setDoOutput(true);
- conn.setConnectTimeout(CONNECT_TIMEOUT);
- conn.setReadTimeout(CONNECT_TIMEOUT);
- if(contentType != null)
- conn.setRequestProperty("content-type", contentType);
- OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
- if(data == null)
- data = "";
- writer.write(data);
- writer.flush();
- writer.close();
-
- reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
- StringBuilder sb = new StringBuilder();
- String line = null;
- while ((line = reader.readLine()) != null) {
- sb.append(line);
- sb.append("\r\n");
- }
- return sb.toString();
- } catch (IOException e) {
- lg.info("Error connecting to " + urlStr + ": " + e.getMessage());
- } finally {
- try {
- if (reader != null)
- reader.close();
- } catch (IOException e) {
- }
- }
- return null;
- }
- }
-
- package com.wxpay.util;
-
-
- import java.security.MessageDigest;
-
-
-
-
-
- public class MD5Util {
-
- private static String byteArrayToHexString(byte b[]) {
- StringBuffer resultSb = new StringBuffer();
- for (int i = 0; i < b.length; i++)
- resultSb.append(byteToHexString(b[i]));
-
- return resultSb.toString();
- }
-
- private static String byteToHexString(byte b) {
- int n = b;
- if (n < 0)
- n += 256;
- int d1 = n / 16;
- int d2 = n % 16;
- return hexDigits[d1] + hexDigits[d2];
- }
-
- public static String MD5Encode(String origin, String charsetname) {
- String resultString = null;
- try {
- resultString = new String(origin);
- MessageDigest md = MessageDigest.getInstance("MD5");
- if (charsetname == null || "".equals(charsetname))
- resultString = byteArrayToHexString(md.digest(resultString
- .getBytes()));
- else
- resultString = byteArrayToHexString(md.digest(resultString
- .getBytes(charsetname)));
- } catch (Exception exception) {
- }
- return resultString;
- }
-
- private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
- "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
-
- }
-
-
- package com.wxpay.util;
-
-
- import java.net.Inet4Address;
- import java.net.InetAddress;
- import java.net.InterfaceAddress;
- import java.net.NetworkInterface;
- import java.net.SocketException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.Enumeration;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
- import java.util.SortedMap;
-
-
- import org.apache.log4j.Logger;
-
-
- public class PayForUtil {
-
- private static Logger lg=Logger.getLogger(PayForUtil.class);
-
-
-
-
-
- public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
- StringBuffer sb = new StringBuffer();
- Set es = packageParams.entrySet();
- Iterator it = es.iterator();
- while(it.hasNext()) {
- Map.Entry entry = (Map.Entry)it.next();
- String k = (String)entry.getKey();
- String v = (String)entry.getValue();
- if(!"sign".equals(k) && null != v && !"".equals(v)) {
- sb.append(k + "=" + v + "&");
- }
- }
- sb.append("key=" + API_KEY);
-
-
- String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
- String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();
-
- return tenpaySign.equals(mysign);
- }
-
-
-
-
-
-
-
-
-
-
- public static String createSign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
- StringBuffer sb = new StringBuffer();
- Set es = packageParams.entrySet();
- Iterator it = es.iterator();
- while (it.hasNext()) {
- Map.Entry entry = (Map.Entry) it.next();
- String k = (String) entry.getKey();
- String v = (String) entry.getValue();
- if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
- sb.append(k + "=" + v + "&");
- }
- }
- sb.append("key=" + API_KEY);
- String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
- return sign;
- }
-
-
-
-
-
-
-
-
- public static String getRequestXml(SortedMap<Object, Object> parameters) {
- StringBuffer sb = new StringBuffer();
- sb.append("<xml>");
- Set es = parameters.entrySet();
- Iterator it = es.iterator();
- while (it.hasNext()) {
- Map.Entry entry = (Map.Entry) it.next();
- String k = (String) entry.getKey();
- String v = (String) entry.getValue();
- if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
- sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
- } else {
- sb.append("<" + k + ">" + v + "</" + k + ">");
- }
- }
- sb.append("</xml>");
- return sb.toString();
- }
-
-
-
-
-
-
-
-
- public static int buildRandom(int length) {
- int num = 1;
- double random = Math.random();
- if (random < 0.1) {
- random = random + 0.1;
- }
- for (int i = 0; i < length; i++) {
- num = num * 10;
- }
- return (int) ((random * num));
- }
-
-
-
-
-
-
- public static String getCurrTime() {
- Date now = new Date();
- SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
- String s = outFormat.format(now);
- return s;
- }
-
-
-
-
-
- public static String localIp(){
- String ip = null;
- Enumeration allNetInterfaces;
- try {
- allNetInterfaces = NetworkInterface.getNetworkInterfaces();
- while (allNetInterfaces.hasMoreElements()) {
- NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
- List<InterfaceAddress> InterfaceAddress = netInterface.getInterfaceAddresses();
- for (InterfaceAddress add : InterfaceAddress) {
- InetAddress Ip = add.getAddress();
- if (Ip != null && Ip instanceof Inet4Address) {
- ip = Ip.getHostAddress();
- }
- }
- }
- } catch (SocketException e) {
- lg.warn("获取本机Ip失败:异常信息:"+e.getMessage());
- }
- return ip;
- }
-
- }
-
- package com.wxpay.util;
-
-
- import com.iptop.service.base.ConfigProperties;
-
-
-
-
-
-
-
- public class WeChatConfig {
-
-
-
-
- public static String APPID=ConfigProperties.get("APPID");
- public static String APPID_APP=ConfigProperties.get("APPID_APP");
-
-
-
- public static String MCHID=ConfigProperties.get("MCHID");
- public static String MCHID_APP=ConfigProperties.get("MCHID_APP");
-
-
-
- public static String APIKEY=ConfigProperties.get("APIKEY");
- public static String APIKEY_APP=ConfigProperties.get("APIKEY_APP");
-
-
-
- public static String WECHAT_NOTIFY_URL_PC=ConfigProperties.get("WECHAT_NOTIFY_URL_PC");
- public static String WECHAT_NOTIFY_URL_APP=ConfigProperties.get("WECHAT_NOTIFY_URL_APP");
-
-
-
- public static String UFDODER_URL=ConfigProperties.get("UFDODER_URL");
-
-
-
- public static String WXPAY=ConfigProperties.get("WXPAY");
-
- }
-
- package com.wxpay.util;
-
-
-
-
-
- public class WeChatParams {
-
- public String total_fee;
- public String body;
- public String out_trade_no;
- public String attach;
- public String memberid;
-
- }
-
- package com.wxpay.util;
-
-
- import java.io.ByteArrayInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
-
-
- import org.jdom.Document;
- import org.jdom.Element;
- import org.jdom.JDOMException;
- import org.jdom.input.SAXBuilder;
-
-
- public class XMLUtil {
-
-
-
-
-
-
-
-
- public static Map doXMLParse(String strxml) throws JDOMException, IOException {
- strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
-
- if(null == strxml || "".equals(strxml)) {
- return null;
- }
-
- Map m = new HashMap();
-
- InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
- SAXBuilder builder = new SAXBuilder();
- Document doc = builder.build(in);
- Element root = doc.getRootElement();
- List list = root.getChildren();
- Iterator it = list.iterator();
- while(it.hasNext()) {
- Element e = (Element) it.next();
- String k = e.getName();
- String v = "";
- List children = e.getChildren();
- if(children.isEmpty()) {
- v = e.getTextNormalize();
- } else {
- v = XMLUtil.getChildrenText(children);
- }
-
- m.put(k, v);
- }
-
-
- in.close();
-
- return m;
- }
-
-
-
-
-
-
- public static String getChildrenText(List children) {
- StringBuffer sb = new StringBuffer();
- if(!children.isEmpty()) {
- Iterator it = children.iterator();
- while(it.hasNext()) {
- Element e = (Element) it.next();
- String name = e.getName();
- String value = e.getTextNormalize();
- List list = e.getChildren();
- sb.append("<" + name + ">");
- if(!list.isEmpty()) {
- sb.append(XMLUtil.getChildrenText(list));
- }
- sb.append(value);
- sb.append("</" + name + ">");
- }
- }
-
- return sb.toString();
- }
-
- }
-
-
-
- package com.wxpay.util;
-
-
- import java.awt.image.BufferedImage;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.net.URLEncoder;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.SortedMap;
- import java.util.TreeMap;
- import javax.imageio.ImageIO;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.commons.lang.StringUtils;
- import org.apache.log4j.Logger;
- import com.google.zxing.BarcodeFormat;
- import com.google.zxing.MultiFormatWriter;
- import com.google.zxing.WriterException;
- import com.google.zxing.common.BitMatrix;
-
-
- public class WeixinPay {
-
- public static Logger lg=Logger.getLogger(WeixinPay.class);
- private static final int BLACK = 0xff000000;
- private static final int WHITE = 0xFFFFFFFF;
-
-
-
-
-
-
-
- public static String getCodeUrl(WeChatParams ps) throws Exception {
-
-
-
- String appid = WeChatConfig.APPID;
- String mch_id = WeChatConfig.MCHID;
- String key = WeChatConfig.APIKEY;
- String notify_url = WeChatConfig.WECHAT_NOTIFY_URL_PC;
- String ufdoder_url=WeChatConfig.UFDODER_URL;
- String trade_type = "NATIVE";
-
-
-
-
- String currTime = PayForUtil.getCurrTime();
- String strTime = currTime.substring(8, currTime.length());
- String strRandom = PayForUtil.buildRandom(4) + "";
- String nonce_str = strTime + strRandom;
-
-
-
-
- SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
- packageParams.put("appid", appid);
- packageParams.put("mch_id", mch_id);
- packageParams.put("nonce_str", nonce_str);
- packageParams.put("body", ps.body);
- packageParams.put("out_trade_no", ps.out_trade_no+nonce_str);
- packageParams.put("total_fee", ps.total_fee);
- packageParams.put("spbill_create_ip", PayForUtil.localIp());
- packageParams.put("notify_url", notify_url);
- packageParams.put("trade_type", trade_type);
- packageParams.put("attach", ps.attach);
-
-
- String sign = PayForUtil.createSign("UTF-8", packageParams,key);
- packageParams.put("sign", sign);
-
- String requestXML = PayForUtil.getRequestXml(packageParams);
- lg.info("微信支付请求参数的报文"+requestXML);
- String resXml = HttpUtil.postData(ufdoder_url,requestXML);
- Map map = XMLUtil.doXMLParse(resXml);
- lg.info("微信支付响应参数的报文"+resXml);
- String urlCode = (String) map.get("code_url");
-
- return urlCode;
- }
-
-
-
-
-
-
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- public static void encodeQrcode(String content,HttpServletResponse response){
-
- if(StringUtils.isBlank(content))
- return;
- MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
- Map hints = new HashMap();
- BitMatrix bitMatrix = null;
- try {
- bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 250, 250,hints);
- BufferedImage image = toBufferedImage(bitMatrix);
-
- try {
- ImageIO.write(image, "png", response.getOutputStream());
- } catch (IOException e) {
- e.printStackTrace();
- }
- } catch (WriterException e1) {
- e1.printStackTrace();
- }
- }
-
-
-
-
-
-
- public static BufferedImage toBufferedImage(BitMatrix matrix) {
- int width = matrix.getWidth();
- int height = matrix.getHeight();
- BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
- for (int x = 0; x < width; x++) {
- for (int y = 0; y < height; y++) {
- image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);
- }
- }
- return image;
- }
-
- public static String UrlEncode(String src) throws UnsupportedEncodingException {
- return URLEncoder.encode(src, "UTF-8").replace("+", "%20");
- }
-
- }
-
-
-
-
-
-
-
- @RequestMapping(value="wechat_notify_url_pc",method=RequestMethod.POST)
- public void wechat_notify_url_pc(HttpServletRequest request,HttpServletResponse response) throws Exception{
-
-
- InputStream inputStream ;
- StringBuffer sb = new StringBuffer();
- inputStream = request.getInputStream();
- String s ;
- BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
- while ((s = in.readLine()) != null){
- sb.append(s);
- }
- in.close();
- inputStream.close();
-
-
- Map<String, String> m = new HashMap<String, String>();
- m = XMLUtil.doXMLParse(sb.toString());
-
-
- SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
- Iterator<String> it = m.keySet().iterator();
- while (it.hasNext()) {
- String parameter = it.next();
- String parameterValue = m.get(parameter);
-
- String v = "";
- if(null != parameterValue) {
- v = parameterValue.trim();
- }
- packageParams.put(parameter, v);
- }
-
- String key = WeChatConfig.APIKEY;
-
- lg.info("微信支付返回回来的参数:"+packageParams);
-
- if(PayForUtil.isTenpaySign("UTF-8", packageParams,key)) {
-
-
-
- String resXml = "";
- if("SUCCESS".equals((String)packageParams.get("result_code"))){
-
-
- String app_id = (String)packageParams.get("appid");
- String mch_id = (String)packageParams.get("mch_id");
- String openid = (String)packageParams.get("openid");
- String is_subscribe = (String)packageParams.get("is_subscribe");
-
-
- String attach = (String)packageParams.get("attach");
-
- String out_trade_no = (String)packageParams.get("out_trade_no");
-
- String total_fee = (String)packageParams.get("total_fee");
-
- String transaction_id = (String)packageParams.get("transaction_id");
-
- String time_end=(String)packageParams.get("time_end");
-
- lg.info("app_id:"+app_id);
- lg.info("mch_id:"+mch_id);
- lg.info("openid:"+openid);
- lg.info("is_subscribe:"+is_subscribe);
- lg.info("out_trade_no:"+out_trade_no);
- lg.info("total_fee:"+total_fee);
- lg.info("额外参数_attach:"+attach);
- lg.info("time_end:"+time_end);
-
-
- lg.info("支付成功");
-
- resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
- + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
-
- } else {
- lg.info("支付失败,错误信息:" + packageParams.get("err_code"));
- resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
- + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
- }
-
-
-
- BufferedOutputStream out = new BufferedOutputStream(
- response.getOutputStream());
- out.write(resXml.getBytes());
- out.flush();
- out.close();
- } else{
- lg.info("通知签名验证失败");
- }
-
- }
