前面已经讲过微信APP支付的统一下单、支付结果通知、申请退款的接口开发,现在我们讲述一下退款结果通知的流程开发。
官方的API地址:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_16&index=11
1、应用场景
当商户申请的退款有结果后,微信会把相关结果发送给商户,商户需要接收处理,并返回应答。
对后台通知交互时,如果微信收到商户的应答不是成功或超时,微信认为通知失败,微信会通过一定的策略定期重新发起通知,尽可能提高通知的成功率,但微信不保证通知最终能成功。 (通知频率为15/15/30/180/1800/1800/1800/1800/3600,单位:秒)
注意:同样的通知可能会多次发送给商户系统。商户系统必须能够正确处理重复的通知。
推荐的做法是,当收到通知进行处理时,首先检查对应业务数据的状态,判断该通知是否已经处理过,如果没有处理过再进行处理,如果处理过直接返回结果成功。在对业务数据进行状态检查和处理之前,要采用数据锁进行并发控制,以避免函数重入造成的数据混乱。
特别说明:退款结果对重要的数据进行了加密,商户需要用商户秘钥进行解密后才能获得结果通知的内容
2、解密方式
解密步骤如下:
(1)对加密串A做base64解码,得到加密串B
(2)对商户key做md5,得到32位小写key* ( key设置路径:微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置 )
(3)用key*对加密串B做AES-256-ECB解密(PKCS7Padding)
3、接口链接
在申请退款接口中上传参数“notify_url”以开通该功能
如果链接无法访问,商户将无法接收到微信通知。
通知url必须为直接可访问的url,不能携带参数。示例:notify_url:“https://pay.weixin.qq.com/wxpay/pay.action”
4、通知参数
字段名 | 变量名 | 必填 | 类型 | 示例值 | 描述 |
---|---|---|---|---|---|
返回状态码 | return_code | 是 | String(16) | SUCCESS | SUCCESS/FAIL |
返回信息 | return_msg | 否 | String(128) | 返回信息,如非空,为错误原因 |
以下字段在return_code为SUCCESS的时候有返回:
字段名 | 变量名 | 必填 | 类型 | 示例值 | 描述 |
---|---|---|---|---|---|
应用ID | appid | 是 | String(32) | wx8888888888888888 | 微信开放平台审核通过的应用APPID |
退款的商户号 | mch_id | 是 | String(32) | 1900000109 | 微信支付分配的商户号 |
随机字符串 | nonce_str | 是 | String(32) | 5K8264ILTKCH16CQ2502SI8ZNMTM67VS | 随机字符串,不长于32位。推荐随机数生成算法 |
加密信息 | req_info | 是 | String(1024) | 加密信息请用商户秘钥进行解密,详见解密方式 |
以下为返回的加密字段:
字段名 | 变量名 | 必填 | 类型 | 示例值 | 描述 |
---|---|---|---|---|---|
微信订单号 | transaction_id | 是 | String(32) | 1217752501201407033233368018 | 微信订单号 |
商户订单号 | out_trade_no | 是 | String(32) | 1217752501201407033233368018 | 商户系统内部的订单号 |
微信退款单号 | refund_id | 是 | String(32) | 1217752501201407033233368018 | 微信退款单号 |
商户退款单号 | out_refund_no | 是 | String(64) | 1217752501201407033233368018 | 商户退款单号 |
订单金额 | total_fee | 是 | Int | 100 | 订单总金额,单位为分,只能为整数,详见支付金额 |
应结订单金额 | settlement_total_fee | 否 | Int | 100 | 当该订单有使用非充值券时,返回此字段。应结订单金额=订单金额-非充值代金券金额,应结订单金额<=订单金额。 |
申请退款金额 | refund_fee | 是 | Int | 100 | 退款总金额,单位为分 |
退款金额 | settlement_refund_fee | 是 | Int | 100 | 退款金额=申请退款金额-非充值代金券退款金额,退款金额<=申请退款金额 |
退款状态 | refund_status | 是 | String(16) | SUCCESS | SUCCESS-退款成功 |
退款成功时间 | success_time | 否 | String(20) | 2017-12-15 09:46:01 | 资金退款至用户帐号的时间,格式2017-12-15 09:46:01 |
退款入账账户 | refund_recv_accout | 是 | String(64) | 招商银行信用卡0403 | 取当前退款单的退款入账方 |
1)退回银行卡: | |||||
{银行名称}{卡类型}{卡尾号} | |||||
2)退回支付用户零钱: | |||||
支付用户零钱 | |||||
3)退还商户: | |||||
商户基本账户 | |||||
商户结算银行账户 | |||||
4)退回支付用户零钱通: | |||||
支付用户零钱通 | |||||
退款资金来源 | refund_account | 是 | String(30) | REFUND_SOURCE_RECHARGE_FUNDS | REFUND_SOURCE_RECHARGE_FUNDS 可用余额退款/基本账户 |
退款发起来源 | refund_request_source | 是 | String(30) | API | API接口 |
5、返回参数
商户处理退款通知参数后同步返回给微信参数:
字段名 | 变量名 | 必填 | 类型 | 示例值 | 描述 |
---|---|---|---|---|---|
返回状态码 | return_code | 是 | String(16) | SUCCESS | SUCCESS/FAIL |
SUCCESS表示商户接收通知成功并校验成功 | |||||
返回信息 | return_msg | 否 | String(128) | OK | 返回信息,如非空,为错误原因 |
参数格式校验错误 |
6、代码实现
6.1基础类
WeChatConfig配置类,主要包含微信的配置信息
package com.hisap.xql.api.common.wechat;
/**
* @Author: QijieLiu
* @Description: 微信配置信息
* @Date: Created in 16:47 2018/8/14
*/
public class WeChatConfig {
public static String APP_ID = "xxxxxx";
public static String MCH_ID = "xxxxxx";
public static String MCH_KEY = "xxxxxx";
public static String APP_SECRET = "xxxxxx";
public static String UNIFIEDORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
public static String NOTIFY_URL = "http://xxx.xxx.xxx.xxx:8080/XqlApi/wechatpay/paynotify";
public static String REFUND_URL = "https://api.mch.weixin.qq.com/secapi/pay/refund";
public static String REFUND_NOTIFY_URL = "http://xxx.xxx.xxx.xxx:8080/XqlApi/wechatpay/refundnotify";
public static String TRADE_TYPE = "APP";
public static String CERT_URL="E:\\cert\\apiclient_cert.p12";
}
ResponseJson基础类,主要与APP前端进行交互
package com.hisap.xql.api.common.bean;
public class ResponseJson {
// 结果码
private String code;
// 结果说明
private String message;
// 内容
private Object data;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
6.2工具类
MD5Utils类
package com.hisap.xql.api.common.utils;
import java.security.MessageDigest;
/**
* @Author: QijieLiu
* @Description: MD5加密工具
* @Date: Created in 09:39 2018/8/17
*/
public class MD5Utils {
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();
// 获得MD5摘要算法的 MessageDigest 对象
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];
}
return new String(str);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
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" };
public static void main(String[] asd) {
String con = "hello kitty";
String str = MD5Encode(con, "UTF-8");
System.out.println(str.toUpperCase());
}
}
CommonUtil类
package com.hisap.xql.api.common.wechat;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.net.ssl.SSLContext;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import com.hisap.xql.api.common.utils.MD5Utils;
package com.data.wechat;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.Security;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLContext;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import com.data.util.MD5Utils;
/**
* @Author: QijieLiu
* @Description: 微信支付工具类
* @Date: Created in 19:39 2018/8/21
*/
public class CommonUtil {
// 微信参数配置
public static String API_KEY = WeChatConfig.MCH_KEY;
// 随机字符串生成
public static String getRandomString(int length) { // length表示生成字符串的长度
String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
// 请求xml组装
public static String getRequestXml(SortedMap<String, 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 key = (String) entry.getKey();
String value = entry.getValue().toString();
if ("attach".equalsIgnoreCase(key) || "body".equalsIgnoreCase(key)
|| "sign".equalsIgnoreCase(key)) {
sb.append("<" + key + ">" + "<![CDATA[" + value + "]]></" + key
+ ">");
} else {
sb.append("<" + key + ">" + value + "</" + key + ">");
}
}
sb.append("</xml>");
return sb.toString();
}
// 生成签名
public static String createSign(String characterEncoding,
SortedMap<String, Object> parameters) {
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
Object v = entry.getValue();
if (null != v && !"".equals(v) && !"sign".equals(k)
&& !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + API_KEY);
System.out.println(sb.toString());
String sign = MD5Utils.MD5Encode(sb.toString(), characterEncoding)
.toUpperCase();
return sign;
}
/**
* 验证回调签名
*
* @param packageParams
* @param key
* @param charset
* @return
*/
public static boolean isTenpaySign(Map<String, String> map) throws UnsupportedEncodingException {
String charset = "utf-8";
String signFromAPIResponse = map.get("sign");
if (signFromAPIResponse == null || signFromAPIResponse.equals("")) {
System.out.println("API返回的数据签名数据不存在,有可能被第三方篡改!!!");
return false;
}
System.out.println("服务器回包里面的签名是:" + signFromAPIResponse);
// 过滤空 设置 TreeMap
SortedMap<String, String> packageParams = new TreeMap<String, String>();
for (String parameter : map.keySet()) {
String parameterValue = map.get(parameter);
String v = "";
if (null != parameterValue) {
v = parameterValue.trim();
}
packageParams.put(parameter, v);
}
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);
// 将API返回的数据根据用签名算法进行计算新的签名,用来跟API返回的签名进行比较
// 算出签名
String resultSign = "";
String tobesign = sb.toString();
if (null == charset || "".equals(charset)) {
resultSign = MD5Utils.MD5Encode(tobesign, charset)
.toUpperCase();
} else {
resultSign = MD5Utils.MD5Encode(tobesign, charset)
.toUpperCase();
}
String tenpaySign = ((String) packageParams.get("sign")).toUpperCase();
return tenpaySign.equals(resultSign);
}
// 请求方法
public static String httpsRequest(String requestUrl, String requestMethod,
String outputStr) {
try {
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("content-type",
"application/x-www-form-urlencoded");
// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
return buffer.toString();
} catch (ConnectException ce) {
System.out.println("连接超时:{}" + ce);
} catch (Exception e) {
System.out.println("https请求异常:{}" + e);
}
return null;
}
// 退款的请求方法
public static String httpsRequest2(String requestUrl, String requestMethod,
String outputStr) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
StringBuilder res = new StringBuilder("");
FileInputStream instream = new FileInputStream(new File(
WeChatConfig.CERT_URL));
try {
keyStore.load(instream, "".toCharArray());
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, "1313329201".toCharArray()).build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf).build();
try {
HttpPost httpost = new HttpPost(
"https://api.mch.weixin.qq.com/secapi/pay/refund");
httpost.addHeader("Connection", "keep-alive");
httpost.addHeader("Accept", "*/*");
httpost.addHeader("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
httpost.addHeader("Host", "api.mch.weixin.qq.com");
httpost.addHeader("X-Requested-With", "XMLHttpRequest");
httpost.addHeader("Cache-Control", "max-age=0");
httpost.addHeader("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
StringEntity entity2 = new StringEntity(outputStr, Consts.UTF_8);
httpost.setEntity(entity2);
System.out.println("executing request" + httpost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpost);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: "
+ entity.getContentLength());
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(entity.getContent()));
String text = "";
res.append(text);
while ((text = bufferedReader.readLine()) != null) {
res.append(text);
System.out.println(text);
}
}
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
return res.toString();
}
// xml解析
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 = 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();
}
public static String getRefundDecrypt(String reqInfoSecret, String key) {
String result = "";
try {
Security.addProvider(new BouncyCastleProvider());
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
byte[] bt = decoder.decodeBuffer(reqInfoSecret);
String b = new String(bt);
String md5key = MD5Utils.MD5(key).toLowerCase();
SecretKey secretKey = new SecretKeySpec(md5key.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;
}
public static String setXML(String return_code, String return_msg) {
return "<xml><return_code><![CDATA[" + return_code
+ "]]></return_code><return_msg><![CDATA[" + return_msg
+ "]]></return_msg></xml>";
}
}
6.3业务类
WeChatPayController类
package com.hisap.xql.api.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hisap.xql.api.common.bean.ResponseJson;
import com.hisap.xql.api.common.constant.CodeMsg;
import com.hisap.xql.api.common.utils.CommonUtil;
import com.hisap.xql.api.common.utils.WeChatPayCommonUtil;
import com.hisap.xql.api.common.wechat.WeChatNotifyResult;
import com.hisap.xql.api.service.WeChatPayService;
/**
* @Author: QijieLiu
* @Description: 微信支付
* @Date: Created in 16:27 2018/8/14
*/
@Controller
@RequestMapping("/wechatpay")
public class WeChatPayController {
private static final Logger logger =
LoggerFactory.getLogger(WeChatPayController.class);
@Autowired
private WeChatPayService weChatPayService;
@RequestMapping("/refundnotify")
@ResponseBody
public void refundnotify(HttpServletRequest request,HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
try{
String notityXml = parseRequst(request);
logger.info("微信退款结果通知接口请求数据json:" + notityXml);
ResponseJson responseJson = weChatPayService.refundnotify(notityXml);
logger.info("微信退款结果通知接口响应数据json:" + JSON.toJSONString(responseJson, SerializerFeature.WriteNullStringAsEmpty));
if(responseJson.getCode().equals(CodeMsg.SUCCESS_CODE)){
String notifyStr = WeChatPayCommonUtil.setXML("SUCCESS", "OK");
writer.write(notifyStr);
writer.flush();
}else{
String notifyStr = WeChatPayCommonUtil.setXML("FAIL", responseJson.getMessage());
writer.write(notifyStr);
writer.flush();
}
}catch (Exception e) {
e.printStackTrace();
logger.error("微信退款结果通知接口服务端异常,异常信息---" + e.getMessage(), e);
}
finally{
writer.close();
}
}
public static String parseRequst(HttpServletRequest request) throws UnsupportedEncodingException {
request.setCharacterEncoding("utf-8");
String body = "";
try {
ServletInputStream inputStream = request.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8")); // 设置编码格式“utf-8”否则获取中文为乱码
while (true) {
String info = br.readLine();
if (info == null) {
break;
}
if (body == null || "".equals(body)) {
body = info;
} else {
body += info;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return body;
}
}
WeChatPayService接口类
package com.hisap.xql.api.service;
import java.math.BigDecimal;
import com.hisap.xql.api.common.bean.ResponseJson;
import com.hisap.xql.api.common.wechat.WeChatNotifyResult;
/**
* @Author: QijieLiu
* @Description: 微信支付
* @Date: Created in 16:35 2018/8/14
*/
public interface WeChatPayService {
ResponseJson refundnotify(String notityXml) throws Exception;
}
WeChatPayServiceImpl接口实现类
package com.hisap.xql.api.service.impl;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
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 org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.NameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hisap.xql.api.common.bean.ResponseJson;
import com.hisap.xql.api.common.constant.CodeMsg;
import com.hisap.xql.api.common.utils.Collections3;
import com.hisap.xql.api.common.utils.CommonUtil;
import com.hisap.xql.api.common.utils.DateUtil;
import com.hisap.xql.api.common.utils.StringUtil;
import com.hisap.xql.api.common.utils.TenpayHttpClient;
import com.hisap.xql.api.common.utils.VersionUtil;
import com.hisap.xql.api.common.utils.WeChatPayCommonUtil;
import com.hisap.xql.api.common.wechat.WeChatConfig;
import com.hisap.xql.api.common.wechat.WeChatNotifyResult;
import com.hisap.xql.api.common.wechat.WeChatRefundResult;
import com.hisap.xql.api.common.wechat.WeChatUniteOrderResult;
import com.hisap.xql.api.common.wechat.WeChatUtil;
import com.hisap.xql.api.dao.XqlOrderGoodsMapper;
import com.hisap.xql.api.dao.XqlOrderMapper;
import com.hisap.xql.api.dao.XqlWxRefundLogMapper;
import com.hisap.xql.api.model.XqlOrder;
import com.hisap.xql.api.model.XqlOrderGoods;
import com.hisap.xql.api.model.XqlOrderGoodsExample;
import com.hisap.xql.api.model.XqlVersion;
import com.hisap.xql.api.model.XqlWxRefundLog;
import com.hisap.xql.api.model.XqlWxRefundLogExample;
import com.hisap.xql.api.service.CommonService;
import com.hisap.xql.api.service.ErpInterfaceService;
import com.hisap.xql.api.service.WeChatPayService;
import com.hisap.xql.api.service.XqlOrderService;
import com.lijing.wechatpay.conn.PaymentTools;
import com.lijing.wechatpay.impl.PayImpl;
import com.lijing.wechatpay.util.PayMD5;
/**
* @Author: QijieLiu
* @Description: 微信支付
* @Date: Created in 16:47 2018/8/14
*/
@Service
public class WeChatPayServiceImpl implements WeChatPayService {
private static final Logger logger = LoggerFactory
.getLogger(WeChatPayServiceImpl.class);
@Autowired
CommonService commonService;
@Autowired
XqlOrderService xqlOrderServiceImpl;
@Autowired
ErpInterfaceService erpInterfaceServiceImpl;
@Autowired
XqlOrderGoodsMapper xqlOrderGoodsMapper;
@Autowired
XqlWxRefundLogMapper xqlWxRefundLogMapper;
public WeChatPayServiceImpl() {
// TODO Auto-generated constructor stub
}
/**
* 退款结果通知
*
* @param characterEncoding
* @param parameters
* @return
*/
@Override
public ResponseJson refundnotify(String notityXml) throws Exception {
ResponseJson responseJson = new ResponseJson();
logger.info("微信退款结果通知请求数据xml:" + notityXml);
Map<String, Object> refundnotifyMap = CommonUtil.doXMLParse(notityXml);
if(refundnotifyMap.get("return_code").toString().equals("SUCCESS")){
String req_info = refundnotifyMap.get("req_info").toString();
String req_info_decrypt = CommonUtil.getRefundDecrypt(req_info, WeChatConfig.MCH_KEY);
logger.info("微信退款结果通知解密后请求数据xml:" + req_info_decrypt);
if(StringUtil.isEmpty(req_info_decrypt)){
responseJson = CommonUtil.createResponseJson("40004099", "微信退款结果通知解密失败", null);
}
//添加对应的业务逻辑
Map<String, Object> refundnotifyDecryptMap = WeChatUtil.parseXmlToMap(req_info_decrypt);
XqlWxRefundLog xqlWxRefundLog = new XqlWxRefundLog();
xqlWxRefundLog.setReturnCode(StringUtil.convertNullToBlank(refundnotifyMap.get("return_code")));
xqlWxRefundLog.setReturnMsg(StringUtil.convertNullToBlank(refundnotifyMap.get("return_msg")));
xqlWxRefundLog.setAppid(StringUtil.convertNullToBlank(refundnotifyMap.get("appid")));
xqlWxRefundLog.setMchId(StringUtil.convertNullToBlank(refundnotifyMap.get("mch_id")));
xqlWxRefundLog.setNonceStr(StringUtil.convertNullToBlank(refundnotifyMap.get("nonce_str")));
xqlWxRefundLog.setTransactionId(StringUtil.convertNullToBlank(refundnotifyDecryptMap.get("transaction_id")));
xqlWxRefundLog.setOutTradeNo(StringUtil.convertNullToBlank(refundnotifyDecryptMap.get("out_trade_no")));
xqlWxRefundLog.setRefundId(StringUtil.convertNullToBlank(refundnotifyDecryptMap.get("refund_id")));
xqlWxRefundLog.setOutRefundNo(StringUtil.convertNullToBlank(refundnotifyDecryptMap.get("out_refund_no")));
xqlWxRefundLog.setTotalFee(StringUtil.convertNullToBlank(refundnotifyDecryptMap.get("total_fee")));
xqlWxRefundLog.setSettlementTotalFee(StringUtil.convertNullToBlank(refundnotifyDecryptMap.get("settlement_total_fee")));
xqlWxRefundLog.setRefundFee(StringUtil.convertNullToBlank(refundnotifyDecryptMap.get("refund_fee")));
xqlWxRefundLog.setSettlementRefundFee(StringUtil.convertNullToBlank(refundnotifyDecryptMap.get("settlement_refund_fee")));
xqlWxRefundLog.setRefundStatus(StringUtil.convertNullToBlank(refundnotifyDecryptMap.get("refund_status")));
xqlWxRefundLog.setSuccessTime(StringUtil.convertNullToBlank(refundnotifyDecryptMap.get("success_time")));
xqlWxRefundLog.setRefundRecvAccout(StringUtil.convertNullToBlank(refundnotifyDecryptMap.get("refund_recv_accout")));
xqlWxRefundLog.setRefundAccount(StringUtil.convertNullToBlank(refundnotifyDecryptMap.get("refund_account")));
xqlWxRefundLog.setRefundRequestSource(StringUtil.convertNullToBlank(refundnotifyDecryptMap.get("refund_request_source")));
XqlWxRefundLogExample xqlWxRefundLogExample = new XqlWxRefundLogExample();
XqlWxRefundLogExample.Criteria criteria = xqlWxRefundLogExample.createCriteria();
criteria.andTransactionIdEqualTo(xqlWxRefundLog.getTransactionId());
int xqlWxRefundLogCount = xqlWxRefundLogMapper.countByExample(xqlWxRefundLogExample);
if(xqlWxRefundLogCount >0){
responseJson = CommonUtil.createResponseJson(
CodeMsg.SUCCESS_CODE, CodeMsg.SUCCESS_MSG, new JSONObject());
}else{
xqlWxRefundLogMapper.insertSelective(xqlWxRefundLog);
responseJson = CommonUtil.createResponseJson(
CodeMsg.SUCCESS_CODE, CodeMsg.SUCCESS_MSG, new JSONObject());
}
}
return responseJson;
}
}
微信官方回调之后,返回参数如下:
<xml>
<return_code><![CDATA[SUCCESS]]></return_code>
<return_msg><![CDATA[OK]]></return_msg>
</xml>
退款解密的时候,我一开始报如下错误
Exception in thread "main" java.security.NoSuchAlgorithmException: Cannot find any provider supporting AES/ECB/PKCS7Padding
at javax.crypto.Cipher.getInstance(Cipher.java:524)
网上百度了一下,发现是因为某些国家的进口管制限制,Java发布的运行环境包中的加解密有一定的限制。比如默认不允许256位密钥的AES加解密,解决方法就是修改策略文件, 从官方网站下载JCE无限制权限策略文件,注意自己JDK的版本别下错了。将local_policy.jar和US_export_policy.jar这两个文件替换%JRE_HOME%\lib\security和%JDK_HOME%\jre\lib\security下原来的文件,注意先备份原文件。本人已经亲自测试过,可以使用,请放心下载。