Java微信APP支付-申請退款
前面已經講過微信APP支付的統一下單、支付結果通知的介面開發,現在我們講述一下申請退款的流程開發。
1、應用場景
當交易發生之後一段時間內,由於買家或者賣家的原因需要退款時,賣家可以通過退款介面將支付款退還給買家,微信支付將在收到退款請求並且驗證成功之後,按照退款規則將支付款按原路退到買家帳號上。
注意:
1、交易時間超過一年的訂單無法提交退款;
2、微信支付退款支援單筆交易分多次退款,多次退款需要提交原支付訂單的商戶訂單號和設定不同的退款單號。申請退款總金額不能超過訂單金額。 一筆退款失敗後重新提交,請不要更換退款單號,請使用原商戶退款單號。
3、請求頻率限制:150qps,即每秒鐘正常的申請退款請求次數不超過150次
錯誤或無效請求頻率限制:6qps,即每秒鐘異常或錯誤的退款申請請求不超過6次
4、每個支付訂單的部分退款次數不能超過50次
2、介面連結
介面連結:https://api.mch.weixin.qq.com/secapi/pay/refund
3、是否需要證書
請求需要雙向證書。 詳見證書使用
4、請求引數
欄位名 | 變數名 | 必填 | 型別 | 示例值 | 描述 |
---|---|---|---|---|---|
公眾賬號ID | appid | 是 | String(32) | wx8888888888888888 | 微信分配的公眾賬號ID(企業號corpid即為此appId) |
商戶號 | mch_id | 是 | String(32) | 1900000109 | 微信支付分配的商戶號 |
隨機字串 | nonce_str | 是 | String(32) | 5K8264ILTKCH16CQ2502SI8ZNMTM67VS | 隨機字串,不長於32位。推薦隨機數生成演算法 |
簽名 | sign | 是 | String(32) | C380BEC2BFD727A4B6845133519F3AD6 | |
簽名型別 | sign_type | 否 | String(32) | HMAC-SHA256 | 簽名型別,目前支援HMAC-SHA256和MD5,預設為MD5 |
微信訂單號 | transaction_id | 二選一 | String(32) | 1217752501201407033233368018 | 微信生成的訂單號,在支付通知中有返回 |
商戶訂單號 | out_trade_no | String(32) | 1217752501201407033233368018 | 商戶系統內部訂單號,要求32個字元內,只能是數字、大小寫字母_-|*@ ,且在同一個商戶號下唯一。 | |
商戶退款單號 | out_refund_no | 是 | String(64) | 1217752501201407033233368018 | 商戶系統內部的退款單號,商戶系統內部唯一,只能是數字、大小寫字母_-|*@ ,同一退款單號多次請求只退一筆。 |
訂單金額 | total_fee | 是 | Int | 100 | 訂單總金額,單位為分,只能為整數,詳見支付金額 |
退款金額 | refund_fee | 是 | Int | 100 | 退款總金額,訂單總金額,單位為分,只能為整數,詳見支付金額 |
退款貨幣種類 | refund_fee_type | 否 | String(8) | CNY | 退款貨幣型別,需與支付一致,或者不填。符合ISO 4217標準的三位字母程式碼,預設人民幣:CNY,其他值列表詳見貨幣型別 |
退款原因 | refund_desc | 否 | String(80) | 商品已售完 | 若商戶傳入,會在下發給使用者的退款訊息中體現退款原因 |
退款資金來源 | refund_account | 否 | String(30) | REFUND_SOURCE_RECHARGE_FUNDS |
僅針對老資金流商戶使用 REFUND_SOURCE_UNSETTLED_FUNDS---未結算資金退款(預設使用未結算資金退款) REFUND_SOURCE_RECHARGE_FUNDS---可用餘額退款 |
退款結果通知url | notify_url | 否 | String(256) | https://weixin.qq.com/notify/ |
非同步接收微信支付退款結果通知的回撥地址,通知URL必須為外網可訪問的url,不允許帶引數 如果引數中傳了notify_url,則商戶平臺上配置的回撥地址將不會生效 |
5、程式碼實現
5.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;
}
}
5.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;
/**
* @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<>();
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(
"/home/apiclient_cert.p12"));
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 setXML(String return_code, String return_msg) {
return "<xml><return_code><![CDATA[" + return_code
+ "]]></return_code><return_msg><![CDATA[" + return_msg
+ "]]></return_msg></xml>";
}
}
5.3業務類
這裡我就只貼出Service層程式碼,其餘程式碼都類似,引數這裡只需要兩個,一個是微信訂單號,還有一個是訂單金額與退款金額,我們這裡兩個金額是一致的,注意一下這裡的退款金額單位是分,而支付寶是元。當然這裡也可以新增對應的業務邏輯,我們這裡不需要。
private boolean refundWeChat(String transactionId, Long orderAmount)
throws RuntimeException {
TreeMap<String, Object> parameters = new TreeMap<String, Object>();
parameters.put("appid", WeChatConfig.APP_ID);
parameters.put("mch_id", WeChatConfig.MCH_ID);
parameters.put("nonce_str", CommonUtil.getRandomString(32));
parameters.put("transaction_id", transactionId);
parameters.put("out_refund_no", CommonUtil.getRandomString(32));
parameters.put("total_fee", orderAmount);
parameters.put("refund_fee", orderAmount);
parameters.put("notify_url", WeChatConfig.REFUND_NOTIFY_URL);
String sign = CommonUtil.createSign("UTF-8", parameters);
parameters.put("sign", sign);
String resContent = "";
String tosend = CommonUtil.getRequestXml(parameters);
try {
resContent = CommonUtil.httpsRequest2(WeChatConfig.REFUND_URL, "POST", tosend);
Map<String, String> map = CommonUtil.doXMLParse(resContent);
if (map.get("return_code").toString().equalsIgnoreCase("SUCCESS")) {
if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
//此處可以新增退款成功業務邏輯
return true;
} else {
//此處可以新增退款失敗業務邏輯
return false;
}
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
微信支付的申請退款就講到這裡,下一章講述微信退款結果通知介面開發。