<?php
/**
 * 支付宝支付
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */

namespace Common\Vendor\Pay\Driver;
class Scanalipay extends \Common\Vendor\Pay\Pay {
    protected $gateway = 'https://scan.95epay.cn/ScanCodePayment.action';
    protected $verify_url = 'http://notify.alipay.com/trade/notify_query.do';
    protected $config = array('email' => '','key' => '','partner' => '');
    public function check() {
        if (!$this->config['config_account'] || !$this->config['config_key']) {
            E("参数设置有误！");
        }return true;
    }
    public function buildRequestForm(\Common\Vendor\Pay\PayVo $vo) {
        $param=$vo->getParam();
        $is_wxsmall=$param['is_wxsmall'];
        $param = array(
            'MerNo' => $this->config['config_account'],
            'isSubMerPay' => 0,
            'TranCode' => 'SMZF010',
            'BillNo' => $vo->getOrderNo(),
            'Amount' => $vo->getFee(),
            'NotifyURL' => $this->config['notify_url'],
            'return_url' => $this->config['return_url'],
            'PayType' =>'SMZF',
            'PaymentType' =>'WXZF',
            'subject' => $vo->getTitle(),
            'desc' => $vo->getBody(),
//            'userId' =>"oK-890wx4mblQ4mDtqhcu_jh5PQo",
            'userId' =>$vo->getUserOpenid(),
        );
        ksort($param);reset($param);
        $arg = '';
        foreach ($param as $key => $value) {
            if ($value) {
                $arg .= "$key=$value&";
            }
        }
        $sign_str="Amount=".$vo->getFee()."&BillNo=".$vo->getOrderNo()."&MerNo=".$this->config['config_account']."&PayType=SMZF&".strtoupper(md5($this->config['config_key']));
        $param['MD5info'] = strtoupper(md5($sign_str));
        $result =$this->curl_post_https($this->gateway, $param);
        $result=json_decode($result,1);
        if(empty($result[0]['wxjsapiStr'])){
            echo $result[0]['respMess'];exit;
        }
        $wxjsapiStr=$result[0]['wxjsapiStr'];
        $channelNo=$result[0]['channelNo'];
        $OrderNo=$result[0]['orderNo'];
        $map=$data=array();
        $map['order_sn']=$vo->getOrderNo();
        $data['serial_number']=$OrderNo;
        M("PayLog")->where($map)->save($data);
        if($is_wxsmall){
            $return=array('status'=>0,'msg'=>"支付失败");
            if($result[0]['respMess']=="success"){
                $return['status']=1;
                $return['msg']="预支付回调成功";
                $return['wxsmallcode'] = json_decode($result[0]['wxjsapiStr']);
            }
            return $return;exit;
        }else {
            if ($param['PaymentType'] == 'WXZF') {
                $sHtml = "<script type=\"text/javascript\">";
                $sHtml .= " function onBridgeReady(){
                WeixinJSBridge.invoke(
                       'getBrandWCPayRequest',
                       " . $wxjsapiStr . ",
                       function(res){

                            if(res.err_msg=='get_brand_wcpay_request:fail'){
                                alert('支付失败');
                                 window.location.href='" . U('Mobile/Member/index') . "';
                            }
                            if(res.err_msg=='get_brand_wcpay_request:cancel '){
                                alert('支付取消');
                                window.location.href='" . U('Mobile/Member/index') . "';
                            }
                           if(res.err_msg == 'get_brand_wcpay_request:ok' ) {
                            alert('恭喜您支付成功');
                             window.location.href='" . U('Mobile/Member/index') . "';
                           }     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                       }
                   );}
            if (typeof WeixinJSBridge == \"undefined\"){
                   if( document.addEventListener ){
                       document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                   }else if (document.attachEvent){
                       document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                       document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                   }
                }else{
                   onBridgeReady();
                }";
                $sHtml .= "</script>";
            }
        }
        echo $sHtml;
        return $sHtml;
    }
    private function curl_post_https($url,$data){ // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }
    public function get_pay_code($info='')
	{
		if(empty($info))$info=$this->config;
        if($info)
		{
			/*$html = "<div style='float:left;margin: 10px 0px;color: #777;'><input type='radio' class='check_box_h' name='paytype' value=".$info['id']." />&nbsp;".$info['name']."：</div>";
			if($info['logo']!='')$html .= "<div style='padding-left:10px;'><img src='".$info['logo']."' /></div>";
			$html .= "<div style='float:left; padding-left:10px;'>".h($info['content'])."</div>";
			*/$html="<li><input type='hidden' name='paytype' value=".$info['id']." />".$info['name']."</li>";
            return $html;
		}else{return '';}
	}
    /**
     * 获取返回时的签名验证结果
     * @param $para_temp 通知返回来的参数数组
     * @param $sign 返回的签名结果
     * @return 签名验证结果
     */
    protected function getSignVerify($param, $sign) {
        $sign_str="Amount=".$param['Amount']."&BillNo=".$param['BillNo']."&MerNo=".$param['MerNo']."&Succeed=".$param['Succeed']."&".strtoupper(md5($this->config['config_key']));
        $mysgin = strtoupper(md5($sign_str));
        if ($mysgin == $sign){return true;}else{return false;}
    }
    /**
     * 针对notify_url验证消息是否是支付宝发出的合法消息
     * @return 验证结果
     */
    public function verifyNotify($notify) {
        //生成签名结果
        $this->setInfo($notify);return true;
        $isSign = $this->getSignVeryfy($notify, $notify["MD5info"]);
        if ($isSign) {
        $this->setInfo($notify);return true;}else {return false;}
    }
    public function verifyNotifys($notify) {
        //生成签名结果
        $isSign = $this->getSignVeryfy($notify, $notify["sign"]);
        if ($isSign) {
        $this->setInfo($notify);return true;}else {return false;}
    }
    protected function setInfo($notify) {
        $info = array();
        //支付状态
        if($notify['Succeed']){
            $info['status']=true;
        }else{
            $info['status']=false;
        }
        $info['money'] = $notify['Amount'];
        $info['out_trade_no'] = $notify['BillNo'];
        $info['pay_note'] = $notify['Orderno'];//双乾流水号
        $info['pay_sn'] = $notify['bankOrderNo'];
        $this->info = $info;
    }
    /**
     * @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){
        $refund_amount = floatval($refund_amount);
        if(empty($out_trade_no) || empty($trade_no) || empty($refund_amount))return false;
        //获取双乾流水号
        $map=array();
        $map['order_sn']=$out_trade_no;
        $order_no=M("PayLog")->where($map)->getField('serial_number');
        $param=array(
            'merchantno'=>$this->config['config_account'],
            'merchantOrderNo'=>$out_trade_no,
            'orderNo'=>$order_no,
            'amount'=>$refund_amount,
            'refundReason'=>"退款",
        );
        $sign_str="merchantno=".$this->config['config_account']."&merchantOrderNo=".$out_trade_no."&orderNo=".$order_no."&amount=".$refund_amount."&".strtoupper(md5($this->config['config_key']));
        $param['md5Info'] = strtoupper(md5($sign_str));
        $result =$this->curl_post_https("https://scan.95epay.cn/merApplyRefund.action", $param);
        //print_r($result);
        $result=json_decode($result,1);
        if($result['result']=="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'] = '退款成功';
        }
        return $res;
    }
}
?>