<?php
namespace Payment;
use Our\ApiConst;

/**
 * User: liuyuzhen
 * Date: 2018/7/3
 * Time: 18:13
 * Description:
 */

class Alipay {

    public function doPay($order){
        $orderAmount = round($order['orderAmount']/\Our\ApiConst::hundred,\Our\ApiConst::two);
        if(APP_ENV == 'develop'||APP_ENV == 'test'||APP_ENV == 'pre'){
            $orderAmount = 0.01;
        }
        $aop = new \Alipay\aop\AopClient();
        $aop->gatewayUrl = \Our\PayConst::alipayGatewayUrl;
        $aop->appId = \Our\PayConst::alipayAppId;
        $aop->rsaPrivateKey = \Our\PayConst::merchantPrivateKey;
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = \Our\PayConst::alipaySignType;
        $aop->alipayrsaPublicKey = \Our\PayConst::alipayPublicKey;
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        $request = new \Alipay\aop\request\AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数，这里只需要传入业务参数
        $bizcontent = "{\"body\":\"订单号".implode(',',$order['orderSns'])."\","
            . "\"subject\": \"r|".$order['paySn']."\","
            . "\"out_trade_no\": \"".$order['paySn']."\","
            . "\"timeout_express\": \"30m\","
            . "\"total_amount\": \"".$orderAmount."\","
            . "\"product_code\":\"QUICK_MSECURITY_PAY\""
            . "}";
        $notifyUrl  = \Our\NameConst::httpPrefix.$_SERVER['SERVER_NAME'].\Our\PayConst::aliAppNotifyUrl;
        $request->setNotifyUrl($notifyUrl);
        $request->setBizContent($bizcontent);
//这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->sdkExecute($request);
//htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
        $pay_url = htmlspecialchars($response);//就是orderString 可以直接给客户端请求，无需再做处理。
		$pay_url = str_replace('&amp;','&',$pay_url);
        $returnData = array(
            'credential'=>array(\Our\NameConst::aliApiChannel=>array('sign_string'=>$pay_url)),
            'app_id'=>\Our\PayConst::alipayAppId
        );
        return $returnData;
    }

    private function getRandomString($len, $chars=null)
    {
        if (is_null($chars)) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }
    public function refund($order){
        $refundAmount = round($order['refundAmount']/\Our\ApiConst::hundred,\Our\ApiConst::two);
        if(APP_ENV == 'develop'||APP_ENV == 'test'||APP_ENV == 'pre' || APP_ENV=='ccwdevelop'){
            $refundAmount = 0.01;
        }
        $aop =  new \Alipay\aop\AopClient();
        $aop->gatewayUrl =\Our\PayConst::alipayGatewayUrl;
        $aop->appId =\Our\PayConst::alipayAppId;
        $aop->rsaPrivateKey =\Our\PayConst::merchantPrivateKey;
        $aop->alipayrsaPublicKey=\Our\PayConst::alipayPublicKey;
        $aop->apiVersion =\Our\PayConst::alipayApiVersion;
        $aop->signType = \Our\PayConst::alipaySignType;
        $aop->postCharset=\Our\PayConst::alipayCharset;
        $aop->format=\Our\PayConst::format;
        $outRequestNo=$this->getRandomString(ApiConst::nine);
//        require_once BASE_ROOT_PATH.'/core/payment/alipay/aop/request/AlipayTradeRefundRequest.php';
//        //require_once 'aop/request/AlipayTradeRefundRequest.php';
        $request = new \Alipay\aop\request\AlipayTradeRefundRequest();
        $request->setBizContent("{" .
            "\"out_trade_no\":\"{$order['outTradeNo']}\"," .
            "\"refund_amount\":{$refundAmount}," .
            "\"refund_reason\":\"正常退款\"," .
            "\"out_request_no\":\"{$outRequestNo}\"," .
            "\"store_id\":\"{$order['storeId']}\"" .
            "}");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $result=$result->$responseNode;
        return $result;
        //   $resultCode = $result->$responseNode->code;
//        if(!empty($resultCode)&&$resultCode == 10000){
//           return true;
//        } else {
//           return false;
//        }
    }


    /**
     * 类实例
     *
     */
    private static $_instance = null;

    /**
     * 单例模式获取类实例
     *
     */
    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
}