一直常用的是微信,突然客户说他要支付宝,就去翻了一下文档和各种百度总结记录一下。
有了支付宝支付后面退款就简单操作了,个人引入的SDK是放在extend里面的,然后需要注意的是php7.2的SDK里面的AopClient.php会有方法要报错对应修改即可。
直接上代码
/**
* 统一收单交易退款接口
* @param string $out_trade_no 订单支付时传入的商户订单号
* @param string $refund_fee 需要退款的金额
* @return array
*/
public function payRefundAli($out_trade_no = "", $refund_fee = "0.00",$platform_id="",$transaction_id="")
{
require '../extend/alipay/aop/AopClient.php';
require '../extend/alipay/aop/request/AlipayTradeRefundRequest.php';
$aop = new \AopClient;
$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';;
$aop->appId = "支付宝";
$aop->rsaPrivateKey = "支付宝私钥";
$aop->alipayrsaPublicKey ="支付宝公钥";
$aop->apiVersion = '1.0';
$aop->signType = 'RSA2';
$aop->postCharset = 'utf-8';
$aop->format = 'json';
$request = new \AlipayTradeRefundRequest;
// //TODO 方便多次退款的设置
$out_request_no = $out_trade_no.rand(1000,9999);
$request->setBizContent("{" .
//订单支付时传入的商户订单号,不能和 trade_no同时为空。
"\"out_trade_no\":\"$out_trade_no\"," .
//支付宝交易号,和商户订单号不能同时为空
"\"trade_no\":\"$transaction_id\"," .
//需要退款的金额,该金额不能大于订单金额,单位为元,支持两位小数 c
"\"refund_amount\":$refund_fee," .
//标识一次退款请求,同一笔交易多次退款需要保证唯一,如需部分退款,则此参数必传
"\"out_request_no\":\"$out_request_no\"" .
" }");
$result = $aop->execute($request);
$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
$resultCode = $result->$responseNode->code;
if (!empty($resultCode) && $resultCode == 10000) {
$status = 1;
$message = "退款成功";
} else {
$status = 0;
$message = $result->alipay_trade_refund_response->sub_msg;
}
//echo $message;
return $message;
}
/**
* 调用退款接口
* @param string $order_id 订单支付时传入的商户订单号
* @param string $amount 需要退款的金额
* @param array $info 含有订单金额 支付成功返回的交易单号transaction_id
* @return array
*/
public function refund($order_id,$info,$amount)
{
$appid = config('base.web_appid');
$mch_id = config('base.wev_mch_id');
$key = config('base.web_appsecret');
$apiKey = config('base.web_apiKey');
$wxPay = new WxpayService($mch_id, $appid, $key, $apiKey);
$order_no = $order_id;//退款的订单号
$total_fee = intval($info['amount'] * 100);;//订单金额
$refund_fee = intval($amount * 100);//退款的金额
$transaction_id = $info['transaction_id'];
$notify_url = 'https://xxxx/refundNotify';
$result = $wxPay->wx_refund($appid, $mch_id, $order_no, $notify_url, $total_fee, $refund_fee, $transaction_id, $apiKey);
if ($result){
return $result;
}else{
return false;
}
}
//退款回调
public function refundNotify(){
$data = file_get_contents('php://input');
if (empty($data)){
$data=$GLOBALS['HTTP_RAW_POST_DATA'];;
}
$arr = xmlToArray($data);
//判断返回状态
if($arr['return_code'] == 'SUCCESS'){
$req_info = $arr['req_info'];
$rep=$this->decipheringReqInfo($req_info);
if($rep["refund_status"] == "SUCCESS") {
//修改订单状态
return '<xml> <return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
}
}
return '<xml> <return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
}
//题外话:测试的时候发现退款1元扣除了0.01的费用,所以总的账户金额会有额外的支出,要稍微注意下