微信公众号支付之付款
最近项目添加微信公众号内支付的功能,记录整个过程如下;
本次记录的主要是统一下单和支付结果通知两个接口,退款接口下期会讲到。
1.导入pom文件依赖
<dependency> <groupId>com.squareup.okio</groupId> <artifactId>okio</artifactId> <version>1.11.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </dependency> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk16</artifactId> <version>1.46</version> </dependency>
2.定义微信支付的数据model接收和传递相关参数
package com.tianxiapai.pub.interfaces.weixinpay.model; /** * 描述:统一下单请求参数<br> * 作者:Administrator <br> * 修改日期:2018年12月23日下午7:54:06 <br> * E-mail: @sinosoft.com.cn <br> */ public class UnifiedOrderRequest { //变量名 字段名 必填 类型 示例值 描述 private String appid;//公众账号ID-微信支付分配的公众账号ID(企业号corpid即为此appId) private String mch_id;//商户号-微信支付分配的商户号 private String device_info;//设备号-自定义参数,可以为终端设备号(门店号或收银设备ID),PC网页或公众号内支付可以传"WEB" private String nonce_str;//随机字符串-随机字符串,长度要求在32位以内。推荐随机数生成算法 private String sign;//签名-通过签名算法计算得出的签名值,详见签名生成算法 private String sign_type;//签名类型-签名类型,默认为MD5,支持HMAC-SHA256和MD5。 private String body;//商品描述-腾讯充值中心-QQ会员充值 商品简单描述,该字段请按照规范传递,具体请见参数规定 private String detail;//商品详情-单品优惠字段(暂未上线) private String attach;//附加数据 private String out_trade_no;//商户订单号 private String fee_type;//标价币种 private String total_fee;//标价金额 private String spbill_create_ip;//终端IP private String time_start;//交易起始时间 private String time_expire;//交易结束时间 private String goods_tag;//订单优惠标记 private String notify_url;//通知地址 private String trade_type;//交易类型 private String product_id;//商品ID private String limit_pay;//指定支付方式
private String openid;//用户标识 public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getMch_id() { return mch_id; } public void setMch_id(String mch_id) { this.mch_id = mch_id; } public String getDevice_info() { return device_info; } public void setDevice_info(String device_info) { this.device_info = device_info; } public String getNonce_str() { return nonce_str; } public void setNonce_str(String nonce_str) { this.nonce_str = nonce_str; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getSign_type() { return sign_type; } public void setSign_type(String sign_type) { this.sign_type = sign_type; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public String getAttach() { return attach; } public void setAttach(String attach) { this.attach = attach; } 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 getFee_type() { return fee_type; } public void setFee_type(String fee_type) { this.fee_type = fee_type; } public String getTotal_fee() { return total_fee; } public void setTotal_fee(String total_fee) { this.total_fee = total_fee; } public String getSpbill_create_ip() { return spbill_create_ip; } public void setSpbill_create_ip(String spbill_create_ip) { this.spbill_create_ip = spbill_create_ip; } public String getTime_start() { return time_start; } public void setTime_start(String time_start) { this.time_start = time_start; } public String getTime_expire() { return time_expire; } public void setTime_expire(String time_expire) { this.time_expire = time_expire; } public String getGoods_tag() { return goods_tag; } public void setGoods_tag(String goods_tag) { this.goods_tag = goods_tag; } public String getNotify_url() { return notify_url; } public void setNotify_url(String notify_url) { this.notify_url = notify_url; } public String getTrade_type() { return trade_type; } public void setTrade_type(String trade_type) { this.trade_type = trade_type; } public String getProduct_id() { return product_id; } public void setProduct_id(String product_id) { this.product_id = product_id; } public String getLimit_pay() { return limit_pay; } public void setLimit_pay(String limit_pay) { this.limit_pay = limit_pay; } public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } }
package com.tianxiapai.pub.interfaces.weixinpay.model; /** * 描述:统一下单返回参数<br> * 作者:Administrator <br> * 修改日期:2018年12月23日下午7:55:09 <br> * E-mail: @sinosoft.com.cn <br> */ public class UnifiedOrderRespose { private String return_code; //返回状态码 private String return_msg; //返回信息 private String appid; //公众账号ID private String mch_id; //商户号 private String device_info; //设备号 private String nonce_str; //随机字符串 private String sign; //签名 private String result_code; //业务结果 private String err_code; //错误代码 private String err_code_des; //错误代码描述 private String trade_type; //交易类型 private String prepay_id; //预支付交易会话标识 private String code_url; //二维码链接 public String getReturn_code() { return return_code; } public void setReturn_code(String return_code) { this.return_code = return_code; } public String getReturn_msg() { return return_msg; } public void setReturn_msg(String return_msg) { this.return_msg = return_msg; } public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getMch_id() { return mch_id; } public void setMch_id(String mch_id) { this.mch_id = mch_id; } public String getDevice_info() { return device_info; } public void setDevice_info(String device_info) { this.device_info = device_info; } public String getNonce_str() { return nonce_str; } public void setNonce_str(String nonce_str) { this.nonce_str = nonce_str; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getResult_code() { return result_code; } public void setResult_code(String result_code) { this.result_code = result_code; } public String getErr_code() { return err_code; } public void setErr_code(String err_code) { this.err_code = err_code; } public String getErr_code_des() { return err_code_des; } public void setErr_code_des(String err_code_des) { this.err_code_des = err_code_des; } public String getTrade_type() { return trade_type; } public void setTrade_type(String trade_type) { this.trade_type = trade_type; } public String getPrepay_id() { return prepay_id; } public void setPrepay_id(String prepay_id) { this.prepay_id = prepay_id; } public String getCode_url() { return code_url; } public void setCode_url(String code_url) { this.code_url = code_url; } @Override public String toString() { return "UnifiedOrderRespose [return_code=" + return_code + ", return_msg=" + return_msg + ", appid=" + appid + ", mch_id=" + mch_id + ", device_info=" + device_info + ", nonce_str=" + nonce_str + ", sign=" + sign + ", result_code=" + result_code + ", err_code=" + err_code + ", err_code_des=" + err_code_des + ", trade_type=" + trade_type + ", prepay_id=" + prepay_id + ", code_url=" + code_url + "]"; } }
package com.tianxiapai.pub.interfaces.weixinpay.model; /** * 描述:微信支付常量<br> * 作者:Administrator <br> * 修改日期:2018年12月23日下午7:56:25 <br> * E-mail: @sinosoft.com.cn <br> */ public class WXPayConstants { public enum SignType { MD5, HMACSHA256 } public static final String FAIL = "FAIL"; public static final String SUCCESS = "SUCCESS"; public static final String HMACSHA256 = "HMAC-SHA256"; public static final String MD5 = "MD5"; public static final String FIELD_SIGN = "sign"; public static final String FIELD_SIGN_TYPE = "sign_type"; }
3.定义微信支付过程中几个常用的工具类
package com.tianxiapai.pub.interfaces.weixinpay.utils;
import javax.servlet.http.HttpServletRequest;
public class IpUtil {
/**
* 获取终端IP
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader( " x-forwarded-for " );
if (ip == null || ip.length() == 0 || " unknown " .equalsIgnoreCase(ip)) {
ip = request.getHeader( " Proxy-Client-IP " );
}
if (ip == null || ip.length() == 0 || " unknown " .equalsIgnoreCase(ip)) {
ip = request.getHeader( " WL-Proxy-Client-IP " );
}
if (ip == null || ip.length() == 0 || " unknown " .equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
package com.tianxiapai.pub.interfaces.weixinpay.utils; import java.security.MessageDigest; /** * 描述:MD5工具类<br> * 作者:Administrator <br> * 修改日期:2018年12月23日下午7:58:09 <br> * E-mail: @sinosoft.com.cn <br> */ public class MD5Util { public final static String MD5(String s) { char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; try { byte[] btInput = s.getBytes(); MessageDigest mdInst = MessageDigest.getInstance("MD5"); mdInst.update(btInput); byte[] md = mdInst.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } String md5Str = new String(str); return md5Str; } catch (Exception e) { e.printStackTrace(); return null; } } }
package com.tianxiapai.pub.interfaces.weixinpay.utils; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import java.security.MessageDigest; import java.security.Security; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.UUID; import javax.crypto.Cipher; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.lang3.StringUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.core.util.QuickWriter; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; import com.thoughtworks.xstream.io.xml.XppDriver; import com.tianxiapai.pub.interfaces.weixinpay.model.UnifiedOrderRequest; import com.tianxiapai.pub.interfaces.weixinpay.model.UnifiedOrderRespose; import com.tianxiapai.pub.interfaces.weixinpay.model.WXPayConstants; import com.tianxiapai.pub.interfaces.weixinpay.model.WXPayConstants.SignType; public class WXPayUtil { private static Logger log = LoggerFactory.getLogger(WXPayUtil.class); /** * 生成订单对象信息 * * @param orderId 订单号 * @param appId 微信appId * @param mch_id 微信分配的商户ID * @param body 支付介绍主体 * @param price 支付价格(放大100倍) * @param spbill_create_ip 终端IP * @param notify_url 异步直接结果通知接口地址 * @param noncestr * @return */ public static Map<String, Object> createOrderInfo(Map<String, String> requestMap, String weiXinPayAppSecret) { // 生成订单对象 UnifiedOrderRequest unifiedOrderRequest = new UnifiedOrderRequest(); unifiedOrderRequest.setAppid(requestMap.get("appId"));// 公众账号ID unifiedOrderRequest.setBody(requestMap.get("body"));// 商品描述 unifiedOrderRequest.setMch_id(requestMap.get("mch_id"));// 商户号 unifiedOrderRequest.setNonce_str(requestMap.get("noncestr"));// 随机字符串 unifiedOrderRequest.setNotify_url(requestMap.get("notify_url"));// 通知地址 unifiedOrderRequest.setOpenid(requestMap.get("userWeixinOpenId")); unifiedOrderRequest.setDetail(requestMap.get("detail"));// 详情 unifiedOrderRequest.setOut_trade_no(requestMap.get("out_trade_no"));// 商户订单号 unifiedOrderRequest.setSpbill_create_ip(requestMap.get("spbill_create_ip"));// 终端IP unifiedOrderRequest.setTotal_fee(requestMap.get("payMoney")); // 金额需要扩大100倍:1代表支付时是0.01 unifiedOrderRequest.setTrade_type("JSAPI");// JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付 SortedMap<String, String> packageParams = new TreeMap<String, String>(); packageParams.put("appid", unifiedOrderRequest.getAppid()); packageParams.put("body", unifiedOrderRequest.getBody()); packageParams.put("mch_id", unifiedOrderRequest.getMch_id()); packageParams.put("nonce_str", unifiedOrderRequest.getNonce_str()); packageParams.put("notify_url", unifiedOrderRequest.getNotify_url()); packageParams.put("openid", unifiedOrderRequest.getOpenid()); packageParams.put("detail", unifiedOrderRequest.getDetail()); packageParams.put("out_trade_no", unifiedOrderRequest.getOut_trade_no()); packageParams.put("spbill_create_ip", unifiedOrderRequest.getSpbill_create_ip()); packageParams.put("total_fee", unifiedOrderRequest.getTotal_fee()); packageParams.put("trade_type", unifiedOrderRequest.getTrade_type()); try { unifiedOrderRequest.setSign(generateSignature(packageParams, weiXinPayAppSecret));// 签名 } catch (Exception e) { e.printStackTrace(); } // 将订单对象转为xml格式 xstream.alias("xml", UnifiedOrderRequest.class);// 根元素名需要是xml System.out.println("封装好的统一下单请求数据:" + xstream.toXML(unifiedOrderRequest).replace("__", "_")); Map<String, Object> responseMap = new HashMap<String, Object>(); responseMap.put("orderInfo_toString", xstream.toXML(unifiedOrderRequest).replace("__", "_")); responseMap.put("unifiedOrderRequest", unifiedOrderRequest); return responseMap; } /** * 生成签名 * * @param appid_value * @param mch_id_value * @param productId * @param nonce_str_value * @param trade_type * @param notify_url * @param spbill_create_ip * @param total_fee * @param out_trade_no * @return */ private static String createSign(UnifiedOrderRequest unifiedOrderRequest) { // 根据规则创建可排序的map集合 SortedMap<String, String> packageParams = new TreeMap<String, String>(); packageParams.put("appid", unifiedOrderRequest.getAppid()); packageParams.put("body", unifiedOrderRequest.getBody()); packageParams.put("mch_id", unifiedOrderRequest.getMch_id()); packageParams.put("nonce_str", unifiedOrderRequest.getNonce_str()); packageParams.put("notify_url", unifiedOrderRequest.getNotify_url()); packageParams.put("out_trade_no", unifiedOrderRequest.getOut_trade_no()); packageParams.put("spbill_create_ip", unifiedOrderRequest.getSpbill_create_ip()); packageParams.put("trade_type", unifiedOrderRequest.getTrade_type()); packageParams.put("total_fee", unifiedOrderRequest.getTotal_fee()); 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 + "&"); } } // 第二步拼接key,key设置路径:微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置 sb.append("key=" + "你的密匙"); String sign = MD5Util.MD5(sb.toString()).toUpperCase();// MD5加密 log.error("方式一生成的签名=" + sign); return sign; } private static XStream xstream = new XStream(new XppDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out) { // 对所有xml节点的转换都增加CDATA标记 boolean cdata = true; String NodeName = ""; @SuppressWarnings("unchecked") public void startNode(String name, Class clazz) { NodeName = name; super.startNode(name, clazz); } protected void writeText(QuickWriter writer, String text) { if (cdata) { if (!NodeName.equals("detail")) { writer.write(text); } else { writer.write("<![CDATA["); writer.write(text); writer.write("]]>"); } } else { writer.write(text); } } }; } }); // xml解析 public static SortedMap<String, String> doXMLParseWithSorted(String strxml) throws Exception { strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\""); if (null == strxml || "".equals(strxml)) { return null; } SortedMap<String, String> m = new TreeMap<String, String>(); 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 = 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(getChildrenText(list)); } sb.append(value); sb.append("</" + name + ">"); } } return sb.toString(); } /** * 调统一下单API * * @param orderInfo * @return */ public static UnifiedOrderRespose httpOrder(String orderInfo) { String url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); // 加入数据 conn.setRequestMethod("POST"); conn.setDoOutput(true); BufferedOutputStream buffOutStr = new BufferedOutputStream(conn.getOutputStream()); buffOutStr.write(orderInfo.getBytes("UTF-8")); buffOutStr.flush(); buffOutStr.close(); // 获取输入流 BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line = null; StringBuffer sb = new StringBuffer(); while ((line = reader.readLine()) != null) { sb.append(line); } // 将请求返回的内容通过xStream转换为UnifiedOrderRespose对象 xstream.alias("xml", UnifiedOrderRespose.class); UnifiedOrderRespose unifiedOrderRespose = (UnifiedOrderRespose) xstream.fromXML(sb.toString()); return unifiedOrderRespose; } catch (Exception e) { e.printStackTrace(); } return null; } /** * XML格式字符串转换为Map * * @param strXML XML字符串 * @return XML数据转换后的Map * @throws Exception */ public static Map<String, String> xmlToMap(String strXML) throws Exception { try { Map<String, String> data = new HashMap<String, String>(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8")); org.w3c.dom.Document doc = documentBuilder.parse(stream); doc.getDocumentElement().normalize(); NodeList nodeList = doc.getDocumentElement().getChildNodes(); for (int idx = 0; idx < nodeList.getLength(); ++idx) { Node node = nodeList.item(idx); if (node.getNodeType() == Node.ELEMENT_NODE) { org.w3c.dom.Element element = (org.w3c.dom.Element) node; data.put(element.getNodeName(), element.getTextContent()); } } try { stream.close(); } catch (Exception ex) { // do nothing } return data; } catch (Exception ex) { WXPayUtil.getLogger().warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML); throw ex; } } /** * 将Map转换为XML格式的字符串 * * @param data Map类型数据 * @return XML格式的字符串 * @throws Exception */ public static String mapToXml(Map<String, String> data) throws Exception { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); org.w3c.dom.Document document = documentBuilder.newDocument(); org.w3c.dom.Element root = document.createElement("xml"); document.appendChild(root); for (String key : data.keySet()) { String value = data.get(key); if (value == null) { value = ""; } value = value.trim(); org.w3c.dom.Element filed = document.createElement(key); filed.appendChild(document.createTextNode(value)); root.appendChild(filed); } TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(document); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(source, result); String output = writer.getBuffer().toString(); // .replaceAll("\n|\r", ""); try { writer.close(); } catch (Exception ex) { } return output; } /** * 生成带有 sign 的 XML 格式字符串 * * @param data Map类型数据 * @param key API密钥 * @return 含有sign字段的XML */ public static String generateSignedXml(final Map<String, String> data, String key) throws Exception { return generateSignedXml(data, key, SignType.MD5); } /** * 生成带有 sign 的 XML 格式字符串 * * @param data Map类型数据 * @param key API密钥 * @param signType 签名类型 * @return 含有sign字段的XML */ public static String generateSignedXml(final Map<String, String> data, String key, SignType signType) throws Exception { String sign = generateSignature(data, key, signType); data.put(WXPayConstants.FIELD_SIGN, sign); return mapToXml(data); } /** * 判断签名是否正确 * * @param xmlStr XML格式数据 * @param key API密钥 * @return 签名是否正确 * @throws Exception */ public static boolean isSignatureValid(String xmlStr, String key) throws Exception { Map<String, String> data = xmlToMap(xmlStr); if (!data.containsKey(WXPayConstants.FIELD_SIGN)) { return false; } String sign = data.get(WXPayConstants.FIELD_SIGN); return generateSignature(data, key).equals(sign); } /** * 判断签名是否正确,必须包含sign字段,否则返回false。使用MD5签名。 * * @param data Map类型数据 * @param key API密钥 * @return 签名是否正确 * @throws Exception */ public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception { return isSignatureValid(data, key, SignType.MD5); } /** * 判断签名是否正确,必须包含sign字段,否则返回false。 * * @param data Map类型数据 * @param key API密钥 * @param signType 签名方式 * @return 签名是否正确 * @throws Exception */ public static boolean isSignatureValid(Map<String, String> data, String key, SignType signType) throws Exception { if (!data.containsKey(WXPayConstants.FIELD_SIGN)) { return false; } String sign = data.get(WXPayConstants.FIELD_SIGN); return generateSignature(data, key, signType).equals(sign); } /** * 生成签名 * * @param data 待签名数据 * @param key API密钥 * @return 签名 */ public static String generateSignature(final Map<String, String> data, String key) throws Exception { return generateSignature(data, key, SignType.MD5); } /** * 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。 * * @param data 待签名数据 * @param key API密钥 * @param signType 签名方式 * @return 签名 */ public static String generateSignature(final Map<String, String> data, String key, SignType signType) throws Exception { Set<String> keySet = data.keySet(); String[] keyArray = keySet.toArray(new String[keySet.size()]); Arrays.sort(keyArray); StringBuilder sb = new StringBuilder(); for (String k : keyArray) { if (k.equals(WXPayConstants.FIELD_SIGN)) { continue; } if (StringUtils.isNotBlank(data.get(k)) && data.get(k).trim().length() > 0) // 参数值为空,则不参与签名 sb.append(k).append("=").append(data.get(k).trim()).append("&"); } sb.append("key=").append(key); if (SignType.MD5.equals(signType)) { return MD5(sb.toString()).toUpperCase(); } else if (SignType.HMACSHA256.equals(signType)) { return HMACSHA256(sb.toString(), key); } else { log.error("获取签名失败,失败原因:" + String.format("Invalid sign_type: %s", signType)); throw new Exception(String.format("Invalid sign_type: %s", signType)); } } /** * 获取随机字符串 Nonce Str * * @return String 随机字符串 */ public static String generateNonceStr() { return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32); } /** * Map转xml数据 */ public static String GetMapToXML(Map<String, String> param) { StringBuffer sb = new StringBuffer(); sb.append("<xml>"); for (Map.Entry<String, String> entry : param.entrySet()) { sb.append("<" + entry.getKey() + ">"); sb.append(entry.getValue()); sb.append("</" + entry.getKey() + ">"); } sb.append("</xml>"); return sb.toString(); } /** * 生成 MD5 * * @param data 待处理数据 * @return MD5结果 */ public static String MD5(String data) throws Exception { java.security.MessageDigest md = MessageDigest.getInstance("MD5"); byte[] array = md.digest(data.getBytes("UTF-8")); StringBuilder sb = new StringBuilder(); for (byte item : array) { sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3)); } return sb.toString().toUpperCase(); } /** * 生成 HMACSHA256 * * @param data 待处理数据 * @param key 密钥 * @return 加密结果 * @throws Exception */ public static String HMACSHA256(String data, String key) throws Exception { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256"); sha256_HMAC.init(secret_key); byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8")); StringBuilder sb = new StringBuilder(); for (byte item : array) { sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3)); } return sb.toString().toUpperCase(); } /** * 日志 * * @return */ public static Logger getLogger() { Logger logger = LoggerFactory.getLogger("wxpay java sdk"); return logger; } /** * 获取当前时间戳,单位秒 * * @return */ public static long getCurrentTimestamp() { return System.currentTimeMillis() / 1000; } /** * 获取当前时间戳,单位毫秒 * * @return */ public static long getCurrentTimestampMs() { return System.currentTimeMillis(); } /** * 生成 uuid, 即用来标识一笔单,也用做 nonce_str * * @return */ public static String generateUUID() { return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32); } /** * 支付签名 * * @param timestamp * @param noncestr * @param packages * @return * @throws UnsupportedEncodingException */ public static String paySign(String timestamp, String noncestr, String packages, String appId) { Map<String, String> paras = new HashMap<String, String>(); paras.put("appid", appId); paras.put("timestamp", timestamp); paras.put("noncestr", noncestr); paras.put("package", packages); paras.put("signType", "MD5"); StringBuffer sb = new StringBuffer(); Set es = paras.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 + "&"); } } String sign = MD5Util.MD5(sb.toString()).toUpperCase();// MD5加密 return sign; } /** * 元转换成分 * * @param amount * @return */ public static String getMoney(String amount) { if (amount == null) { return ""; } // 金额转化为分为单位 // 处理包含, ¥ 或者$的金额 String currency = amount.replaceAll("\\$|\\¥|\\,", ""); int index = currency.indexOf("."); int length = currency.length(); Long amLong = 0l; if (index == -1) { amLong = Long.valueOf(currency + "00"); } else if (length - index >= 3) { amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", "")); } else if (length - index == 2) { amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0); } else { amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00"); } return amLong.toString(); } /** * 方法名称: SortedMaptoXml<br> * 描述:请求值转换为xml格式 SortedMap转xml * 作者: WQ * 修改日期:2018年12月24日下午5:13:49 * * @param params * @return */ public static String SortedMaptoXml(SortedMap<String, String> params) { StringBuilder sb = new StringBuilder(); Set es = params.entrySet(); Iterator it = es.iterator(); sb.append("<xml>\n"); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); String k = (String) entry.getKey(); Object v = entry.getValue(); sb.append("<" + k + ">"); sb.append(v); sb.append("</" + k + ">\n"); } sb.append("</xml>"); return sb.toString(); } /** * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。 */ public static String createSign(SortedMap<String, String> packageParams, String AppKey) { 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=" + AppKey); String sign = MD5Encode(sb.toString(), "UTF-8").toUpperCase(); return sign; } 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 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]; } private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; public static String getRefundDecrypt(byte[] bt, String key) { String result = ""; try { Security.addProvider(new BouncyCastleProvider()); SecretKey secretKey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] resultbt = cipher.doFinal(bt); result = new String(resultbt,"UTF-8"); } catch (Exception e) { e.printStackTrace(); } return result; } }
5.调用微信统一下单接口
调用接口之前我们需要熟悉一下微信支付的流程。
/** * 描述:微信支付控制器<br> * 1.用户发起微信支付,初始化数据、调用统一下单接口。 * 生成JSAPI页面调用的支付参数并签名(paySign,prepay_id,nonceStr,timestamp) * 2.js如果返回Ok,提示支付成功,实际支付结果已收到通知为主。 * 3.在微信支付结果通知中,获取微信提供的最终用户支付结果信息,支付结果等信息更新用户支付记录中 * 4.根据微信支付结果通知中的微信订单号调用查询接口,如果查询是已经支付成功,则发送支付成功模板信息给客户 * * 作者:Administrator <br> * 修改日期:2018年12月23日下午8:22:09 <br> * E-mail: @sinosoft.com.cn <br> */
6.统一下单接口
/** * 支付初始化 * * @param payMoney * @return */ @RequestMapping("/toPayInit") @ResponseBody public Result<Object> toPay(@RequestBody OrderModel orderModel, HttpServletRequest request) { //TODO 项目业务校验(具体根据个人项目实际情况)
//1.用户是否登录
//2.支付金额是否正确
//3.0元支付问题 //... Map<String, Object> map = new HashMap<>(); String noncestr = WXPayUtil.generateNonceStr(); Map<String, String> requestMap = new HashMap<String, String>(); requestMap.put("appId", ""); requestMap.put("out_trade_no", "商户订单号"); requestMap.put("mch_id", weixinConfig.getMchId()); requestMap.put("payMoney", "1"); requestMap.put("spbill_create_ip", IpUtil.getIpAddr(request)); requestMap.put("notify_url", "这里设置微信支付结果通知地址URL"); requestMap.put("noncestr", noncestr); requestMap.put("body", "yyyyyyyyyyyyyyyyyyyy"); requestMap.put("detail", "xxxxxxxxx测试订单"); Map<String, Object> requestInfo = WXPayUtil.createOrderInfo(requestMap, weixinConfig.getWeiXinPayAppSecret()); String orderInfo_toString = (String) requestInfo.get("orderInfo_toString"); // 判断返回码 UnifiedOrderRespose orderResponse = WXPayUtil.httpOrder(orderInfo_toString);// 调用统一下单接口 // 根据微信文档return_code 和result_code都为SUCCESS的时候才会返回code_url log.info("支付请求数据信息:" + orderResponse.toString()); if (null != orderResponse && "SUCCESS".equals(orderResponse.getReturn_code()) && "SUCCESS".equals(orderResponse.getResult_code())) { String timestamp = String.valueOf(WXPayUtil.getCurrentTimestamp()); UnifiedOrderRequest unifiedOrderRequest = (UnifiedOrderRequest) requestInfo.get("unifiedOrderRequest"); map.put("unifiedOrderRequest", unifiedOrderRequest); SortedMap<String, String> packageParams = new TreeMap<String, String>(); packageParams.put("appId", weixinConfig.getWeiXinPayAppId()); packageParams.put("signType", "MD5"); packageParams.put("nonceStr", noncestr); packageParams.put("timeStamp", timestamp); String packages = "prepay_id=" + orderResponse.getPrepay_id(); packageParams.put("package", packages); String sign = null; // JS支付参数 map.put("appId", weixinConfig.getWeiXinPayAppId()); map.put("timeStamp", timestamp); map.put("nonceStr", noncestr); map.put("package", packages); map.put("signType", "MD5"); try { sign = WXPayUtil.generateSignature(packageParams, weixinConfig.getWeiXinPayAppSecret()); } catch (Exception e) { map.put("result", -1); e.printStackTrace(); } if (sign != null && !"".equals(sign)) { map.put("paySign", sign); map.put("result", 1); } else { map.put("result", -1); } map.put("prepay_id", orderResponse.getPrepay_id()); return new Result<Object>(map); } else { // 不成功 String text = "调用微信支付出错,返回状态码:" + orderResponse.getReturn_code() + ",返回信息:" + orderResponse.getReturn_msg(); if (orderResponse.getErr_code() != null && !"".equals(orderResponse.getErr_code())) { text = text + ",错误码:" + orderResponse.getErr_code() + ",错误描述:" + orderResponse.getErr_code_des(); } log.info("支付失败错误信息:" + text); map.put("result", -1); return new Result<Object>(map); } }
上述代码中的微信支付商户号的参数需要根据自己申请的微信支付商户号的实际参数进行配置,否则校验会不通过。
上述统一下单接口如果可以正常调用的话,传值给前端页面就可以正常调起微信支付的页面了。
7.支付结果通知接口
/** * 支付成功异步回调接口 * * @param request * @param response * @throws Exception */ @RequestMapping(value = "/paymentNotice", produces = "text/html;charset=utf-8") @ResponseBody public String WeixinParentNotifyPage(HttpServletRequest request, HttpServletResponse response) throws Exception { ServletInputStream instream = request.getInputStream(); StringBuffer sb = new StringBuffer(); int len = -1; byte[] buffer = new byte[1024]; while ((len = instream.read(buffer)) != -1) { sb.append(new String(buffer, 0, len)); } instream.close(); log.info("支付通知回调信息:" + sb.toString()); Map<String, String> map = WXPayUtil.xmlToMap(sb.toString());// 接受微信的回调的通知参数 Map<String, String> return_data = new HashMap<String, String>(); // 判断签名是否正确 if (WXPayUtil.isSignatureValid(map, weixinConfig.getWeiXinPayAppSecret())) { if (map.get("return_code").toString().equals("FAIL")) { return_data.put("return_code", "FAIL"); return_data.put("return_msg", map.get("return_msg")); } else if (map.get("return_code").toString().equals("SUCCESS")) { String result_code = map.get("result_code").toString(); String out_trade_no = map.get("out_trade_no").toString();
//根据out_trade_no商户订单号进行系统的业务逻辑判断 TODO
// 2 已支付(不确定是否支付成功)3 支付完成 4 取消支付 5支付失败
if (result_code.equals("SUCCESS")) {// 支付成功
if(支付成功){
return_data.put("return_code", "SUCCESS"); return_data.put("return_msg", "OK"); return WXPayUtil.GetMapToXML(return_data);
}else if(支付失败){
return_data.put("return_code", "FAIL");
return_data.put("return_msg", "金额异常");
return WXPayUtil.GetMapToXML(return_data);
}
}
} else {
return_data.put("return_code", "FAIL");
return_data.put("return_msg", "签名错误");
}
String xml = WXPayUtil.GetMapToXML(return_data);
log.info("支付通知回调结果:" + xml);
return xml;
}
上述代码删掉了部分项目业务逻辑,请自行根据项目实际情况填写。
可以参考官方文档:
统一下单
https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=9_20&index=1
支付结果通知
https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=9_7&index=8