<?php
/**
 * 银联商务POS通C扫B交易接口
 */
namespace Common\Vendor\Pay\Driver;
class Chinaums extends \Common\Vendor\Pay\Pay {
    protected $gateway = 'https://mobl-test.chinaums.com/netpay-route-server/api/';//请求银联接口地址   
    protected $config = array('config_partner' => '','config_key' => '','config_account' => '');
    protected $from='WWW.TEST.COM';
    protected $msgSrcId=3194;
    //检查账户是否正确
    public function check() {
        if (!$this->config['config_partner'] || !$this->config['config_account'] || !$this->config['config_key']) {
            E("参数设置有误！");
        }
        if($this->config['config_account']!='898340149000005'){
            $this->from='WWW.SJZJTWL.COM';
            $this->msgSrcId=$this->config['config_other'];
            $this->gateway='https://qr.chinaums.com/netpay-route-server/api/';
        }
        return true;
    }
    /**
     * 请求接口，传递参数
     * @param PayVo $vo
     * @return mixed
     */
    public function buildRequestForm(\Common\Vendor\Pay\PayVo $vo) {
        $other_param=$vo->getParam();
        $param = array(
            'msgId'            => $this->config['config_other'],//消息ID，原样返回不必填
            'msgSrc'           => $this->from,//消息来源
            'msgType'          => 'bills.getQRCode',//消息类型
            'requestTimestamp' => time_format(NOW_TIME,'Y-m-d H:i:s'),//报文请求时间，格式yyyy-MM-dd HH:mm:ss
            'mid'              => $this->config['config_account'],//商户号
            'tid'              => $this->config['config_partner'],//终端号
            'instMid'          => 'QRPAYDEFAULT',//业务类型
            'notifyUrl'        => $this->config['notify_url'],//异步通知地址
            'signType'         => 'MD5',
        );
       // print_r($param);exit;
      
        if($other_param['is_decca']==1){
            $param['memberId']=$other_param['memberId'];
        }else{
            // $param['billNo']=$this->msgSrcId.$vo->getOrderNo();1027注释
            // $param['billDate']=time_format(NOW_TIME,'Y-m-d');1027注释
            // $param['totalAmount']=$vo->getFee()*100;1027注释
            $param['walletOption']='SINGLE';
        }
        //验签方式
        $param['sign'] = $this->createSign($param);
        $result=$this->curlinit($this->gateway, $param);
       // print_r($result);exit;
        if($this->verifyNotify($result)){
            $result=array('status'=>1,'url'=>$result['billQRCode']);

            // $AC_ID=$_SERVER['HTTP_X_APICLOUD_APPID']; 
            // if($AC_ID){
            //     $result=array('status'=>1,'url'=>$result['billQRCode']);
            // }else{
            //     $result="<script type=\"text/javascript\">
            //     window.onload = function(){location.href='".$result['billQRCode']."';};
            //     </script>";
            // }
            return $result;
        }else{
            $result=array('status'=>0,'msg'=>'验签失败');
            return $result;
        }
    }
    
    /**
     * 订单退款
     * @param  [type] $out_trade_no  商家订单号
     * @param  [type] $trade_no      支付交易号
     * @param  [type] $refund_amount 退款金额
     * @return [type] $refund_sn     退款单号
     */
    public function refund($out_trade_no,$trade_no,$refund_amount,$refund_sn){
        if(empty($out_trade_no))return false;
        $out_trade_no=$this->msgSrcId.$out_trade_no;
        $res=array('status'=>0,'msg'=>'');
        $param = array(
            'msgId'            => $this->config['config_other'],//消息ID，原样返回不必填
            'msgSrc'           => $this->from,//消息来源
            'msgType'          => 'bills.refund',//消息类型
            'requestTimestamp' => time_format(NOW_TIME,'Y-m-d H:i:s'),//报文请求时间，格式yyyy-MM-dd HH:mm:ss
            'mid'              => $this->config['config_account'],//商户号
            'tid'              => $this->config['config_partner'],//终端号
            'instMid'          => 'QRPAYDEFAULT',//业务类型
            'billNo'           => $out_trade_no,//账单号
            'billDate'         => time_format(NOW_TIME,'Y-m-d'),//账单日期，格式yyyy-MM-dd
            'refundAmount'     => $refund_amount*100,//要退货的金额(分)
            'signType'         => 'MD5',
            'walletOption'     => 'SINGLE',
        );
        //验签方式
        $param['sign'] = $this->createSign($param);
        $result=$this->curlinit($this->gateway, $param);
        if($this->verifyNotify($result) && $result['errCode']=='SUCCESS'){
            $payment_refund = idtoname($refund_sn,'PaymentRefund','*','refund_sn');
            $status =1;
            D('Common/OrderInfo')->payment_refund($refund_sn,$status);           
            $info['status'] = true;
            $info['money'] = $payment_refund['money'];
            $info['out_trade_no'] = $payment_refund['order_id'];
            $info['pay_sn'] = $payment_refund['trade_no'];
            D('Common/OrderInfo')->refund_order($info);
            $res['status'] = 1;
			$res['msg'] = '退款成功';
        }else{
            $res['msg'] = $result['errMsg'];
        }return $res;
    }    
    /**
     * 订单查询
     * @param  [type] $out_trade_no  商家订单号
     * @param  [type] $trade_no      支付交易号
     * @param  [type] $refund_amount 退款金额
     * @return [type] $refund_sn     退款单号
     */
    public function query($out_trade_no,&$succCode=0,$transaction_id=''){
        if(empty($out_trade_no))return false;
        $out_trade_no=$this->msgSrcId.$out_trade_no;
        $res=array('status'=>0,'msg'=>'');
        $param = array(
            'msgId'            => $this->config['config_other'],//消息ID，原样返回不必填
            'msgSrc'           => $this->from,//消息来源
            'msgType'          => 'bills.query',//消息类型
            'requestTimestamp' => time_format(NOW_TIME,'Y-m-d H:i:s'),//报文请求时间，格式yyyy-MM-dd HH:mm:ss
            'mid'              => $this->config['config_account'],//商户号
            'tid'              => $this->config['config_partner'],//终端号
            'instMid'          => 'QRPAYDEFAULT',//业务类型
            'billNo'           => $out_trade_no,//账单号
            'billDate'         => time_format(NOW_TIME,'Y-m-d'),//账单日期，格式yyyy-MM-dd
            'signType'         => 'MD5',
            'walletOption'     => 'SINGLE',
        );
        //验签方式
        $param['sign'] = $this->createSign($param);
        $result=$this->curlinit($this->gateway, $param);
        if($this->verifyNotify($result)){
            $res=$result;
            $res['status'] = 1;
        }else{
            $res['msg'] = $result['errMsg'];
        }return $res;
    }
    /**
     * 获取返回时的签名验证结果
     * @param $para_temp 通知返回来的参数数组
     * @param $sign 返回的签名结果
     * @return 签名验证结果
     */
    protected function getSignVerify($param, $sign) {
        unset($param['sign'],$param['apitype'],$param['method']);
        $mysgin = $this->createSign($param);
        if ($mysgin == $sign){return true;}else{return false;}
    }
    public function get_pay_code($info='') {}
    /**
     * 针对notify_url验证消息是否是支付宝发出的合法消息
     * @return 验证结果
     */
    public function verifyNotify($notify) {
        //生成签名结果
        $isSign = $this->getSignVerify($notify, $notify["sign"]);
        if ($isSign) {
        $this->setInfo($notify);return true;}else {return false;}
    }
    /**
     * curl 请求
     * @param string $url请求地址
     * @param array $post 参数
     */
    private function curlinit($url,$post){
        if(is_array($post))$post=json_encode($post);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);      
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);      
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($ch, CURLOPT_POST, true);            
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        $content = curl_exec($ch); 
        curl_close($ch); 
        $res = json_decode($content,true);
        return $res;
   }
    /**
     * 创建签名
     * @param type $params
     */
    protected function createSign($params) {
        ksort($params);
        $arg = '';
        foreach ($params as $key => $value) {
            $arg .= "{$key}={$value}&";
        }
        $arg=rtrim($arg,'&');
        return strtoupper(md5($arg . $this->config['config_key']));
    }
    protected function setInfo($notify) {
        $info = array();
        $billPayment=is_array($notify['billPayment'])?$notify['billPayment']:json_decode($notify['billPayment'],1);
        //支付状态
        $info['status']=$notify['billStatus']=='PAID'?true:false;
        $info['money'] = $notify['totalAmount']/100;
        $info['out_trade_no'] = substr($notify['billNo'],strlen($this->msgSrcId));
        $info['pay_sn'] = $billPayment['targetOrderId'];//银联流水号
        if(str_exists($billPayment['targetSys'],'Alipay')){
            $pay_code='HANCHAO_S_Alipay';
        }else{
            $pay_code='HANCHAO_S_WEIXIN';
        }
        if($notify['memberId']){
            $info['shop_id']=$notify['memberId'];
        }
        if($notify['notifyId']){
            $info['notifyId']=$notify['notifyId'];
        }
        $info['pay_code']=$pay_code;
        $this->info = $info;
    }
}
?>