1. WeixinPay(生成二维码,及回调方法案例)
import java.awt.image.BufferedImage;import java.io.*;import java.net.URLEncoder;import java.util.*;import javax.imageio.ImageIO;import javax.servlet.http.HttpServletRequest;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;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.servlet.ModelAndView;@RestController@RequestMapping("/weixin")public class WeixinPay { public static Logger lg = Logger.getLogger(WeixinPay.class); private static final int BLACK = 0xff000000; private static final int WHITE = 0xFFFFFFFF; /** * 获取微信支付的二维码地址 * * @return * @throws Exception * @author chenp */ public static String getCodeUrl(WeChatParams ps) throws Exception { /** * 账号信息 */ String appid = WeChatConfig.APPID;//微信服务号的appid String mch_id = WeChatConfig.MCHID; //微信支付商户号 String key = WeChatConfig.APIKEY; // 微信支付的API密钥 String notify_url = WeChatConfig.WECHAT_NOTIFY_URL_PC;//回调地址【注意,这里必须要使用外网的地址】 String ufdoder_url = WeChatConfig.UFDODER_URL;//微信下单API地址 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);//额外的参数【业务类型+会员ID+支付类型】 String sign = PayForUtil.createSign("UTF-8", packageParams, key); //获取签名 packageParams.put("sign", sign); String requestXML = PayForUtil.getRequestXml(packageParams);//将请求参数转换成String类型// lg.info("微信支付请求参数的报文" + requestXML); String resXml = HttpUtil.postData(ufdoder_url, requestXML); //解析请求之后的xml参数并且转换成String类型 Map map = XMLUtil.doXMLParse(resXml);// lg.info("微信支付响应参数的报文" + resXml); String urlCode = (String) map.get("code_url"); return urlCode; } /** * 将路径生成二维码图片 * * @param content * @param response * @author chenp */ @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 { System.out.println(image); ImageIO.write(image, "png", response.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } catch (WriterException e1) { e1.printStackTrace(); } } /** * 类型转换 * * @param matrix * @return * @author chenp */ 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 static boolean 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(); //解析xml成map Map<String, String> m = new HashMap<String, String>(); m = XMLUtil.doXMLParse(sb.toString()); //过滤空 设置 TreeMap 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); } // 微信支付的API密钥 String key = WeChatConfig.APIKEY; // key 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");//是否关注公众号 //附加参数【商标申请_0bda32824db44d6f9611f1047829fa3b_15460】--【业务类型_会员ID_订单号】 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(); System.out.println(true); return true; } else { lg.info("通知签名验证失败"); System.out.println(false); return false; } }}
2. WeChatConfig(微信支付配置)
/** * 微信支付配置文件 * * @author chenp */public class WeChatConfig { /** * 微信服务号APPID */ public static String APPID = "wx76c8ad8ab54e6682"; /** * 微信支付的商户号 */ public static String MCHID = "1537414481"; /** * 微信支付的API密钥 */ public static String APIKEY = "38f50b7bc07c66b63d638ae851d50165"; /** * 微信支付成功之后的回调地址【注意:当前回调地址必须是公网能够访问的地址】 */ public static String WECHAT_NOTIFY_URL_PC = "http://kyhvip.zicp.vip/Commercialization/wxPays"; /** * 微信统一下单API地址 */ public static String UFDODER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder"; /** * true为使用真实金额支付,false为使用测试金额支付(1分) */ public static String WXPAY = "";}
3. PayForUtil(判断签名)
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); /** * 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。 * * @return boolean */ 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); } /** * @param characterEncoding 编码格式 * @param parameters 请求参数 * @return * @author chenp * @Description:sign签名 */ 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; } /** * @param parameters 请求参数 * @return * @author chenp * @Description:将请求参数转换为xml格式的string */ 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(); } /** * 取出一个指定长度大小的随机正整数. * * @param length int 设定所取出随机数的长度。length小于11 * @return int 返回生成的随机数。 */ 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)); } /** * 获取当前时间 yyyyMMddHHmmss * * @return String * @author chenp */ public static String getCurrTime() { Date now = new Date(); SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss"); String s = outFormat.format(now); return s; } /** * 获取本机IP地址 * * @return * @author chenp */ 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; }}
4. MD5Util(加密类)
import java.security.MessageDigest;/** * Md5加密类 * * @author chenp */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"};}
5. HttpUtil(Http请求)
private final static int CONNECT_TIMEOUT = 5000; // in milliseconds 连接超时的时间 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); } /** * post数据请求 * * @param urlStr * @param data * @param contentType * @return */ 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; }}
6. WeChatParams(支付参数实体类)
/** * 微信支付需要的一些参数 * * @author chenp *///@Data//此注解代替了set、get方法,如果不想用这个注解也可以自己写set、get方法。public class WeChatParams { public String total_fee;//订单金额【备注:以分为单位】 public String body;//商品名称 public String out_trade_no;//商户订单号 public String attach;//附加参数 public String memberid;//会员ID public String getTotal_fee() { return total_fee; } public void setTotal_fee(String total_fee) { this.total_fee = total_fee; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getOut_trade_no() { return out_trade_no; } public void setOut_trade_no(String out_trade_no) { this.out_trade_no = out_trade_no; } public String getAttach() { return attach; } public void setAttach(String attach) { this.attach = attach; } public String getMemberid() { return memberid; } public void setMemberid(String memberid) { this.memberid = memberid; }}
7. XMLUtil(xml解析类)
/** * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。 * * @param strxml * @return * @throws JDOMException * @throws IOException */ 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; } /** * 获取子结点的xml * * @param children * @return String */ 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(); }}
8. 支付案例,及回调案例
/**订单支付案例*/ @RequestMapping("/wxPay") public void wxPay(WeChatParams ps, HttpServletResponse response,HttpServletRequest request) { double a = 0.01; int soloa = (int) (a*100); ps.setBody("天赐场测试订单"); ps.setTotal_fee(""+soloa); ps.setOut_trade_no("OR2019090210022"); ps.setAttach("xiner"); ps.setMemberid("888"); String urlCode = null; try { urlCode = WeixinPay.getCodeUrl(ps); } catch (Exception e) { e.printStackTrace(); } WeixinPay.encodeQrcode(urlCode,response); }/**订单支付回调方法*/ @RequestMapping(value = "/wxPays") public void wxPays(HttpServletResponse response,HttpServletRequest request) throws Exception { boolean b = false; b = WeixinPay.wechat_notify_url_pc(request, response); if (true){ login(); }else { response.sendRedirect("/index/logins"); } }
9.所需依赖
<!--微信支付依赖--> <dependency> <groupId>jdom</groupId> <artifactId>jdom</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.11.1</version> </dependency>