<?php
/**
 * 双乾支付
 */
namespace Common\Vendor\Pay\Driver;
class Mmscan extends \Common\Vendor\Pay\Pay {
   protected $gateway = 'https://service.95epay.cn/ScanCodePayment.action';//请求双乾接口地址
    //检查账户是否正确
    public function check() {
        if (!$this->config['config_account'] || !$this->config['config_key']) {
            E("参数设置有误！");
        }return true;
    }

    /**
     * 请求接口，传递参数
     * @param PayVo $vo
     * @return mixed
     */
    public function buildRequestForm(\Common\Vendor\Pay\PayVo $vo) {
        $pay_info=$vo->getParam();
        $param = array(
            'MerNo' => $this->config['config_account'],//商户号
            'isSubMerPay' => 0,//是否是会员交易
            'SubMerNo' => '',//如果是会员交易此参数必须有值(会员商户号)
            'TranCode' => $pay_info['tran_code'],//交易服务码
            'BillNo' => $vo->getOrderNo(),//订单编号
            'Amount' => $vo->getFee(),//订单金额
            'PayType' =>'SMZF',//同道类型(扫码支付)
            'PaymentType' =>$pay_info['pay_type'],//支付类型(WXZF[微信支付]，ZFBZF[支付宝支付])
            'subject' => $vo->getTitle(),//支付描述
            'NotifyURL' => $this->config['notify_url'],//异步通知地址
            'return_url' => $this->config['return_url'],
        );
        if($param['TranCode']=='SMZF003'){
            $param['scene']=$pay_info['scene'];//支付场景 1--条码支付 2--声波支付
            $param['authCode']=$vo->getProduct_id();//支付授权码
        }
        if($param['TranCode']=='SMZF010'){
            $param['userId']=$pay_info['user_id']; //用户公众号或服务窗下对应的用户id
        }
        //验签方式
        $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));//return $param;
        $result=$this->curl_post_https($this->gateway, $param);
        if($param['TranCode']=='SMZF010'){
            $result=json_decode($result,1);
            $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($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>";
            }else{
                $sHtml="
                  <script  type=\"text/javascript\" src=\"__ROOT__/Public/script/jquery.min.js\"></script>
                    <script>
                        AlipayJSBridge.call('tradePay',{
                            tradeNO: $channelNo
                        }, function(result){
                        });
                    </script>
                ";
            }
            return $sHtml;
        }else{
            return $result;
        }
    }
    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格式
    }
    /**
     * 获取返回时的签名验证结果
     * @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;}
    }
    public function get_pay_code($info='') { }
    /**
     * 针对notify_url验证消息是否是支付宝发出的合法消息
     * @return 验证结果
     */
    public function verifyNotify($notify) {
        //生成签名结果
        $isSign = $this->getSignVerify($notify, $notify["MD5info"]);
        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;
    }
}
?>