首页 > 上网技巧 > 电脑小技巧 > Java微信APP支付之申请退款

Java微信APP支付之申请退款

时间:2018-09-13 10:14 作者:QQ地带 我要评论

前面已经讲过微信APP支付的统一下单、支付结果通知的接口开发,现在我们讲述一下申请退款的流程开发。
 
官方的API地址:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_4&index=6
 
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;
}
}
微信支付的申请退款就讲到这里,下一章讲述微信退款结果通知接口开发。

标签: 微信支付
顶一下
(0)
0%
踩一下
(0)
0%

Google提供的广告