先分享一下支付宝退款的程序源码(我这段代码是通过配置证书而不是字符串秘钥的方式)
sdk下载地址:https://opendocs.alipay.com/open/54/103419#%E8%8E%B7%E5%8F%96%20Alipay%20SDK
public function refund($refund) { $appCertPath = THINK_PATH."Library/Vendor/alipay-sdk-PHP-4.9.1/aop/cert/appCertPublicKey_2016071801632148.crt"; $alipayCertPath = THINK_PATH."Library/Vendor/alipay-sdk-PHP-4.9.1/aop/cert/alipayCertPublicKey_RSA2.crt"; $rootCertPath = THINK_PATH."Library/Vendor/alipay-sdk-PHP-4.9.1/aop/cert/alipayRootCert.crt"; require_once THINK_PATH.'Library/Vendor/alipay-sdk-PHP-4.9.1/aop/AopCertClient.php'; require_once THINK_PATH.'Library/Vendor/alipay-sdk-PHP-4.9.1/aop/request/AlipayTradeRefundRequest.php'; $aop = new \AopCertClient(); //网关与证书配置 $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do'; $aop->appId = '应用id'; $aop->rsaPrivateKey = '用工具生成的RSA私钥,去头去尾去空格'; $aop->alipayrsaPublicKey=$aop->getPublicKey($alipayCertPath);//'请填写支付宝公钥,一行字符串'; $aop->isCheckAlipayPublicCert = true; $aop->appCertSN = $aop->getCertSN($appCertPath); $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath); //算法编码与格式配置 $aop->apiVersion = '1.0'; $aop->signType = 'RSA2'; $aop->postCharset='UTF-8'; $aop->format='json'; //参数内容配置 $request = new \AlipayTradeRefundRequest (); $parameter = array( "out_trade_no"=>$this->payInfo['order_id'],//自己商城系统内的订单号,也是原来被付款的订单号 "refund_amount"=>$this->payInfo['amount'],//退款金额 "refund_reason"=>"正常退款" ); $request->setBizContent(json_encode($parameter)); $result = $aop->execute ( $request); $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response"; $resultCode = $result->$responseNode->code;
//以下是退款成功后的回调商城对应的操作,与支付宝退款无关
$orderRefund = new OrderRefund(); if(!empty($resultCode)&&$resultCode == 10000){ $orderRefund->returnOkCallback($refund,"成功提交退款至支付宝账户"); } else { $orderRefund->returnErrorCallback($refund,"提交退款至支付宝账户失败"); } }
1.首先你在支付宝平台上要有自己的应用,https://open.alipay.com/platform/developerIndex.htm,没有则创建
$aop->appId 即我们创建的应用id
2.配置秘钥,下载官方工具生成,文档地址:https://opendocs.alipay.com/open/291/105971,生成证书也在该文档中
$aop->rsaPrivateKey
3.参数内容中我还有一个订单的详情内容没有配置,只是一个简单的退款,如果你想丰富你的退款商品或者订单信息,查看官方退款接口文档
https://opendocs.alipay.com/apis/api_1/alipay.trade.refund
遇到的坑汇总一下
1.明明信息都是对的,接口返回证书错误,更改了sdk中一处精度的问题,AopCertClient.php的135行
/** * 0x转高精度数字 * @param $hex * @return int|string */ function hex2dec($hex) { $dec = 0; $len = strlen($hex); for ($i = 1; $i <= $len; $i++) { $dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i)))); } //return round($dec,0); return $dec; }
----------------------------------------------------------------
愿每个程序员都少走弯路,少踩坑,多分享帮助更多的人