如何实现支付宝沙箱退款功能
既然做到了退款这步,说明支付功能已经搞定了。就直接从代码说了,不谈基础配置了。
支付宝沙箱退款api地址:https://docs.open.alipay.com/api_1/alipay.trade.refund
提示:我的代码只实现了简单的部分退款功能(同时为两件及两件以上商品支付可以只对其中一件商品进行退款操作)。
代码:
package com.yc.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipayConfig.AlipayConfig;
import com.yc.po.TradePO;
@WebServlet("/out.action")
public class AliPayOut extends BaseServlet {
/**
*
*/
private static final long serialVersionUID = 8640834714652684896L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
AlipayConfig.sign_type);
AlipayTradeRefundRequest req = new AlipayTradeRefundRequest();
TradePO po = parserRequestToObject(request, TradePO.class);
String no = po.getTrade_no();
String mn = po.getRefund_amount();
// 订单支付时传入的商户订单号,不能和 trade_no同时为空
String trade_no = "4674334545";
// 需要退款的金额
String refund_amount = "199.00";
// 表示支持部分退款
String out_request_no = "HZ01RF001";
req.setBizContent("{\"trade_no\":\"" + trade_no + "\"," + "\"refund_amount\":\"" + refund_amount + "\","
+ "\"out_request_no\":\"" + out_request_no + "\"}");
AlipayTradeRefundResponse resp = null;
try {
resp = alipayClient.execute(req);
} catch (AlipayApiException e) {
e.printStackTrace();
}
if (resp.isSuccess()) {
int i = 1;
toPrintString(response, i);
} else {
System.out.println("调用失败");
}
}
}
调用以上代码即可完成部分退款功能。