<?php

declare (strict_types = 1);
namespace library\utils;
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-10-04 18:31
// +----------------------------------------------------------------------

use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Config;
class alipay {

    private $config;

    public function __construct($config = [])
    {
        if(empty($config)) $config = config('alipay');
        $this->config = $config;
        Factory::setOptions($this->getOptions());
    }

    /**
     * 手机支付
     * @param $data
     */
    public function wapPay($data) {
        $alipay = config('alipay');
        $result = Factory::payment()
                    ->wap()
                    ->pay($data['name'],$data['order_id'], $data['money'],$alipay['returnUrl'],$alipay['returnUrl']);
        return $result->body;
    }

    /**
     * 电脑支付
     * @param $data
     * @return \Alipay\EasySDK\Payment\Page\Models\AlipayTradePagePayResponse
     * @throws \Exception
     */
    public function pay($data) {
        $alipay = config('alipay');
        $result = Factory::payment()->page()->pay($data['name'],
            $data['order_id'],
            $data['money'],
            $alipay['returnUrl']
            );
        return $result;
    }

    /**
     * 支付验证
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public function verifyNotify($data) {
        $result = Factory::payment()->common()->verifyNotify($data);
        return $result;
    }

    /**
     * 查询订单号
     * @param $outTradeNo
     * @throws \Exception
     */
    public function query($outTradeNo){
        $result = Factory::payment()->common()->query($outTradeNo);
        return $result;
    }

    /**
     * 转账操作
     * @param $bank
     * @param $trans_amount
     * @param $name
     * @throws \Exception
     */
    public function accountTransfer($bank,$trans_amount,$name){
        $data = [];
        $data['out_biz_no'] = md5($bank . time());
        $data['trans_amount'] = $trans_amount;
        $data['product_code'] = 'TRANS_ACCOUNT_NO_PWD';
        $data['biz_scene'] = 'DIRECT_TRANSFER';
        $data['order_title'] = '提现转账';
        $data['payee_info'] = [
                'identity' => $bank,
            'identity_type' => 'ALIPAY_LOGON_ID',
            'name'          => $name
        ];
        require_once ROOT . '/../vendor/alipaysdk/oldsdk/AopCertClient.php';
        require_once ROOT . '/../vendor/alipaysdk/oldsdk/request/AlipayFundTransUniTransferRequest.php';
        $aop = new \AopCertClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $this->config['appId'];
        $aop->rsaPrivateKey = $this->config['merchantPrivateKey'];
        $aop->alipayrsaPublicKey=  $aop->getPublicKey($this->config['alipayCertPath']);
        $aop->appCertSN = $aop->getCertSN($this->config['merchantCertPath']);//调用getCertSN获取证书序列号
        $aop->alipayRootCertSN = $aop->getRootCertSN($this->config['alipayRootCertPath']);
        $aop->isCheckAlipayPublicCert = true;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='utf-8';
        $aop->format='json';
        $request = new \AlipayFundTransUniTransferRequest();
        $request->setBizContent(json_encode($data,\JSON_UNESCAPED_UNICODE));
        $result = $aop->execute ( $request);
        if($result->alipay_fund_trans_uni_transfer_response->code == 10000) {
            return ['code'=>1000,
                    'msg'=>'成功',
                    'out_biz_no'=>$data['out_biz_no'],
                    'pay_fund_order_id' => $result->alipay_fund_trans_uni_transfer_response->pay_fund_order_id,
                    'order_id' => $result->alipay_fund_trans_uni_transfer_response->order_id
            ];
        } else {
            return ['code'=>-1000,'msg'=>$result->alipay_fund_trans_uni_transfer_response->sub_msg,'orderId'=>$data['out_biz_no']];
        }
    }

    function getOptions()
    {
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';
        $options->appId = $this->config['appId'];
        //请填写您的应用私钥
        $options->merchantPrivateKey =  $this->config['merchantPrivateKey'];
        //支付宝公钥证书
        $options->alipayCertPath =  $this->config['alipayCertPath'];
        //请填写您的支付宝根证书文件路径
        $options->alipayRootCertPath = $this->config['alipayRootCertPath'];
        //请填写您的应用公钥证书文件路径
        $options->merchantCertPath = $this->config['merchantCertPath'];
        //请填写您的支付类接口异步通知接收服务地址
        $options->notifyUrl = $this->config['notifyUrl'];
        //可设置AES密钥，调用AES加解密相关接口时需要（可选）
       // $options->encryptKey = "<-- 请填写您的AES密钥，例如：aa4BtZ4tspm2wnXLb1ThQA== -->";
        return $options;
    }

}