<?php
/**
 *
 * ============================================================================
 * * 版权�?�? 运游�? * *
 * 网站地址: http://www.zhizhuchuxing.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改�?
 * 使用；不允许对程序代码以任何形式任何目的的再发布�?
 * ============================================================================
 * Author By: 倪宗�?
 * PhpStorm AliPayService.php
 * Create By 2016/12/12 14:32 $
 */


namespace common\util;

class AliPay
{
    private static $aliPayConfig = null;

    /**
     * Des:扫描支付
     * Name: unifiedOrderByOrderIdForSao
     * @param $par
     * @return array
     * @author 倪宗锋
     */
    public function unifiedOrderByOrderIdForSao($par)
    {
        $siteConfig = Util::getSiteConfig();
        $aliPay = new AliPay();
        //交易参数
        $params['body'] = $par['name'];
        $params['subject'] = $par['name'];
        $params['order_id'] = $par['order_id'] . '_' . rand(100, 999);
        $params['price'] = $par['total_fee'];
        $params['timeout_express'] = '1m';
        $params['goType'] = 3;
        $params['method'] = 'alipay.trade.precreate';
        $getUrl = $aliPay->getAliPayUrl($params);
        $url = $siteConfig['host_name'] . '/fx/?r=weChat/we-chat/q-code&qCode=' . urlencode($getUrl['data']['codUrl']) . '&_math=' . rand(100, 999);
        return Util::returnArrSu('', array('codUrl' => $url, 'price' => $par['total_fee']));
    }

    /**
     * Function Description:支付宝web支付
     * Function Name: webPay
     * @param $param array
     * @return array
     *
     * @author nzf
     */
    public function webPay($param)
    {
        //交易参数
        $params['body'] = $param['name'];
        $params['subject'] = $param['name'];
        $params['order_id'] = $param['order_id'];
        $params['price'] = $param['total_fee'];
        $params['timeout_express'] = '1m';
        $params['goType'] = 2;
        $params['method'] = 'alipay.trade.wap.pay';
        $return = static::getAliPayUrl($params);
        return $return;
    }

    /********************通用方法**************************/
    /**
     * Function Description:获取阿里支付pay
     * Function Name: getAliPayUrl
     * @param $params array
     *
     * @return array
     *
     * @author 倪宗�?
     */
    private static function getAliPayUrl($params)
    {
        $config = self::getAliPayConfig();
        $sysParams = self::getSysParams();
        $sysParams["method"] = $params['method'];
        //交易参数
        $body['productCode'] = 'QUICK_WAP_PAY';
        $body['body'] = $params['body'];
        $body['subject'] = $params['subject'];
        $body['out_trade_no'] = $params['order_id'];
        $body['total_amount'] = $params['price'];
        $body['timeout_express'] = $config['timeout'];

        $sysParams['biz_content'] = json_encode($body);
        if ($params['goType'] == 1) {//如果是页面跳�?
            $sysParams['sign'] = urlencode(static::getSign($sysParams));
            $paramString = static::getSignContent($sysParams);
            $requestUrl = $config['gatewayUrl'] . "?" . $paramString;
            return Util::returnArrSu('', ['payData' => $requestUrl]);
        } elseif ($params['goType'] == 2) {//如果是参数返�?
            $sysParams['sign'] = static::getSign($sysParams);
            $result = self::buildRequestForm($sysParams);
            return Util::returnArrSu('', ['payData' => $result]);
        } else {
            $sysParams['sign'] = urlencode(static::getSign($sysParams));
            $paramString = static::getSignContent($sysParams);
            $requestUrl = $config['gatewayUrl'] . "?" . $paramString;
            $curl = new CurlInterface('', 5);
            $result = $curl->execute($requestUrl, 'GET');
            $result = json_decode($result, true);
            $return['codUrl'] = '';
            if ($result['alipay_trade_precreate_response']['code'] == '10000') {
                $return['codUrl'] = $result['alipay_trade_precreate_response']['qr_code'];
            }
            return Util::returnArrSu('', $return);
        }
    }

    /**
     * Function Description:取消订单
     * Function Name: cancelOrder
     * @param $params
     *
     * @return array
     *
     * @author 倪宗�?
     */
    public static function cancelOrder($params)
    {
        $config = self::getAliPayConfig();
        $sysParams = self::getSysParams();
        $sysParams["method"] = 'alipay.trade.refund';
        $body = array(
            'out_trade_no' => $params['order_id'],//订单�?
            'refund_amount' => $params['refund_fee'],//退款金额
            'refund_reason' => $params['memo'],
            'out_request_no' => $params['order_id'] . '-' . date('YmdHis') . rand(100, 999)//�?款原�?
        );
        $sysParams['biz_content'] = json_encode($body);
        $sysParams['sign'] = static::getSign($sysParams);
        $sysParams['sign'] = urlencode(static::getSign($sysParams));
        $paramString = static::getSignContent($sysParams);
        $requestUrl = $config['gatewayUrl'] . "?" . $paramString;
        //调用�?款接�?
        $curlInterface = new CurlInterface($sysParams, 5);
        $result = $curlInterface->execute($requestUrl, 'GET');
        $result = json_decode(mb_convert_encoding($result, 'utf-8'), true);
        if (isset($result['alipay_trade_refund_response']) && $result['alipay_trade_refund_response']['code'] == '10000') {
            return Util::returnArrSu();
        }
        return Util::returnArrEr('退款失败！');
    }

    /**
     * Function Description:获取系统通用参数
     * Function Name: getSysParams
     *
     * @return mixed
     *
     * @author 倪宗�?
     */
    private static function getSysParams()
    {
        $config = self::getAliPayConfig();
        $siteConfig = Util::getSiteConfig();
        //组装系统参数
        $sysParams["app_id"] = $config['app_id'];
        $sysParams["version"] = '1.0';
        $sysParams["format"] = 'json';
        $sysParams["sign_type"] = 'RSA';

        $sysParams["timestamp"] = date("Y-m-d H:i:s");
        $sysParams["alipay_sdk"] = 'alipay-sdk-php-20160411';
        $sysParams["prod_code"] = '';
        $sysParams["notify_url"] = $siteConfig['host_name'] . $siteConfig['notify_url'];
//        $sysParams["return_url"] = $config['return_url'];
        $sysParams["charset"] = $config['charset'];
        return $sysParams;
    }

    /**
     * Function Description:建立请求，以表单HTML形式构�?�（默认�?
     * Function Name: buildRequestForm
     * @param $para_temp
     *
     * @return string 提交表单HTML文本
     *
     * @author 倪宗�?
     */
    protected static function buildRequestForm($para_temp)
    {
        $config = self::getAliPayConfig();
        $sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='" . $config['gatewayUrl'] . "?charset=" . trim($config['charset']) . "' method='get'>";
        while (list ($key, $val) = each($para_temp)) {
            if (false === static::checkEmpty($val)) {
                $val = str_replace("'", "&apos;", $val);
                $sHtml .= "<input type='hidden' name='" . $key . "' value='" . $val . "'/>";
            }
        }
        return $sHtml;
    }

    /**
     * Function Description:获取签名
     * Function Name: getSign
     * @param $params
     *
     * @return string
     *
     * @author 倪宗�?
     */
    public static function getSign($params)
    {
        if (isset($params['sign'])) {
            unset($params['sign']);
        }
        $content = self::getSignContent($params);
        $config = self::getAliPayConfig();
        $priKey = $config['merchant_private_key'];
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($priKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        openssl_sign($content, $sign, $res);
        $sign = base64_encode($sign);
        return $sign;
    }

    /**
     * Function Description:获取参数配置
     * Function Name: getAliPayConfig
     *
     * @return array
     *
     * @author 倪宗�?
     */
    public static function getAliPayConfig()
    {
        if (self::$aliPayConfig == null) {
            $payConfig = require ROOT_PATH . '/common/config/aliConfig/payConfig.php';
            $siteConfig = Util::getSiteConfig();
            self::$aliPayConfig = $payConfig[$siteConfig['aliPay']];
        }
        return self::$aliPayConfig;
    }

    /**
     * Function Description:将数组转换为符合阿里支付的路由参�?
     * Function Name: getSignContent
     * @param $params
     *
     * @return string
     *
     * @author 倪宗�?
     */
    public static function getSignContent($params)
    {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === self::checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = self::characet($v, 'utf-8');

                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }

    /**
     * Function Description:校验$value是否非空
     * Function Name: checkEmpty
     * @param $value
     *
     * @return bool
     *
     * @author 倪宗�?
     */
    private static function checkEmpty($value)
    {
        if (!isset($value)) {
            return true;
        }
        if ($value === null) {
            return true;
        }
        if (trim($value) === "") {
            return true;
        }
        return false;
    }

    /**
     * Function Description:转换字符集编�?
     * Function Name: characet
     * @param $data
     * @param $targetCharset
     *
     * @return string
     *
     * @author 倪宗�?
     */
    private static function characet($data, $targetCharset)
    {
        if (!empty($data)) {
            $fileType = 'utf-8';
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset);
            }
        }
        return $data;
    }
}