<?php

namespace app\lib\utils;

use think\Config;
use think\Exception;
use think\Log;

require_once ALI_PATH.'/Alipay/aop/AopClient.php';
require_once ALI_PATH.'/Alipay/aop/request/AlipayFundTransToaccountTransferRequest.php';
require_once ALI_PATH.'/Alipay/aop/AopClient.php';
require_once ALI_PATH.'/Alipay/aop/request/AlipayTradeAppPayRequest.php';
require_once ALI_PATH.'/Alipay/aop/request/AlipayTradeCreateRequest.php';
require_once ALI_PATH.'/Alipay/aop/request/AlipayTradeRefundRequest.php';

class AliPay
{
    /**
     * 支付宝小程序提现打款
     */
    public static function aliWithdraw($cash_sn, $ali_account, $amount, $realname, $error)
    {
        $aop = new \AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2021003129690572'; //支付宝APPID
        $aop->rsaPrivateKey = "MIIEowIBAAKCAQEAs6n3G2GNRWnXt+msp/l/iY/TnTwmDXhMFSgKST2w0lP68RoTBwUF7kpHH8w8ZAVaeSaEk7Bdf2DfDDWaxbZyat9uA4V3XOzP7joyw/A0GMOxI5rjEH2T03lLPrfgia7sRGTbV8mIsNgdROV0pQj8pOcvEYF9udN6XJ1B2GD2Tuew1Tls/WsI4p1g7fPRAvRUVcW7Km80vRn6/ReTpSaI+hTTPyfT+QD4ZGaeiticvMXKuUDjVQTzgfxnlmjO+iaaP3J1c1SapYHc6cmvnZjFJUB3mdJcREP1YkTj4Sxwa8tA8/m2PtMVXF9DiQGtg2TBtlEUihHEUWBJRCUQqjcc2wIDAQABAoIBAEpaQquQOZjKbr3r9MonVQKnBRqDM/RLHqF6ypb48t54Zte0xL8Y8xVko/6i1TNHi+Orbx531JnMi0JQRNch5EQaZzsJ1xYb4wliCHRSSh0dj4d+qA3BCpZwEhXInyIbxCeh3ax8+RbGuYYzt4w9JeFQ04fZISDwRilh40gbCJQqVsiV9DBMkGPUZkszrXHJuhPYqzPZDig69miJlBAdPYFlQ9PRNCXaUA0fmzX9aVTKemvxsr/AwJ9bOLOkGyWDTSvH5c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zCbsqwjs/YIVN352INrzFMdRDx2K5OTztUut4Jyapn58QI/awedDYZ8wsZP13Tgkj2Tat8KpDYfAU9AEwK/5yCqWm9+sK1tNv/nLgTgkDzaOtX1xsf9SmG0QtqanoCLOhlReOY+bBMsIIErswNoY8xHphFPJjNy9HizlSn2t5KP32+Y+PiF25hrX2fSYE/LXrOsKAyTZ/emSWZiF6fSdRXVLkXS3VeJLvb0YZcBbcxkpPOQCnNkNIig0uf9JzuTAfshOZHdeQ7zhxjT5PPLhKsyPVN7yb/96ifQ/wyYiQwIDAQAB";
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        $request = new \AlipayFundTransToaccountTransferRequest();
        $request->setBizContent("{" .
            "\"out_biz_no\":\"" . $cash_sn . "\"," . //商户生成订单号
            "\"payee_type\":\"ALIPAY_LOGONID\"," . //收款方支付宝账号类型
            "\"payee_account\":\"" . $ali_account . "\"," . //收款方账号
            "\"amount\":\"" . $amount . "\"," . //总金额
            "\"payee_real_name\":\"" . $realname . "\"," . //收款方姓名
            "\"remark\":\"" . '点点达提现' . "\"" . //转账备注
            "}");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        //修改转账日志
        if (!empty($resultCode) && $resultCode == 10000) {
            //转账成功处理返回
            return true;
        } else {
            //转账失败原因提示
            $error->code = -3;
            $error->msg = $result->$responseNode->sub_msg;
            return $error;
        }
    }

    /**
     * 支付宝退款
     */
    public static function alipayRefund($order_sn,$refund_amount){
        //组装系统参数
        $data = [
            'out_trade_no' => $order_sn,
            'refund_amount' => $refund_amount,
            'refund_reason' =>'同意退款'
        ];
        $sysparams = json_encode($data, JSON_UNESCAPED_UNICODE);
        Log::record('支付宝退款参数集：'.$sysparams,'debug');

        //发起退款
        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->appId = Config::get('alipay.appId');
            $aop->rsaPrivateKey = Config::get('alipay.rsaPrivateKey');
            $aop->alipayrsaPublicKey = Config::get('alipay.alipayrsaPublicKey');

            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.open.public.template.message.industry.modify
            $request = new \AlipayTradeRefundRequest();
            //SDK已经封装掉了公共参数，这里只需要传入业务参数
            $request->setBizContent($sysparams);
            $response = $aop->execute($request);
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            Log::record('支付宝退款结果集：'.json_encode($response->$responseNode,JSON_FORCE_OBJECT),'debug');
            $resultCode = $response->$responseNode->code;
            return $resultCode;
        } catch (Exception $e) {
            Log::record( $order_sn."调起支付宝退款失败".$e->getMessage(),'debug');
            return false;
//            $this->error('调起支付宝退款失败！' . $e->getMessage());
        }
    }
}
