微信内支付 PC扫码支付

//懒人 代码也整的乱 还有H5支付 懒得整理了   没有自己构造方法 方法里面引用的是微信支付官方的DEMO

public function notify(){
            //存储微信的回调
      $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
            
                //将XML转为array
                libxml_disable_entity_loader(true);
                $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
                // 商户订单号
                $out_trade_no = $data['out_trade_no'];
                //file_put_contents('sql.txt',$out_trade_no);die;
                //-------------更新支付状态---
                $data =array('oderstate' =>'1' );
               db('wxpay')->where('order_num',$out_trade_no)->update($data);
            //  file_put_contents('sql1.txt',$sql);die;
           
}


public function wxpay(){
       if (isMobile()){
              //微信内支付
              
                header('Content-Type: text/html; charset=utf-8');   
                $order_sn = date('YmdHis').rand(1000,9999);   
                ini_set('date.timezone','Asia/Shanghai');
                require_once  "/public/weixin/lib/WxPay.Api.php";
                require_once "/public/weixin/example/WxPay.JsApiPay.php";
                //require_once '../public/static/wxpay/example/log.php';
                //$logHandler= new \CLogFileHandler("/public/weixin/logs/".date('Y-m-d').'.log');
                //$log = \Log::Init($logHandler, 15);
                $userid =input('nid');
                $proid = input('aid');
                $catid = input('catid');  
                 if($proid){
                    $rows_pay=db('article')->where('id',$proid)->find();   
                    
                    if($rows_pay){
                        $price = $rows_pay['price'];
                        $protitle = $rows_pay['title'];
                        
                    }else{
                        $price = null;
                        exit;
                    }
                }          
                
            if($price && $proid && $userid){
            $price1 = sprintf("%.0f",$price * 100);
            $ymurl = 'http://'.$_SERVER['HTTP_HOST'];
            $aaaa=$this->notify();
            $notify_url = "http://".$_SERVER['HTTP_HOST']."/index.php/home/index/notify";
            /*'/public/weixin/notify.php';*/
            $order_sn = date('YmdHis').rand(1000,9999);//订单编号
            //$time = date("Y-m-d H:i:s",time());
            $timestate = time();
             $data=array(
                        'artcle_id'=> $proid,
                        'artcle_name'=>$protitle,
                        'wx_nid'=>$userid,
                        'order_num'=>$order_sn,
                        'order_price'=>$price,
                        'state'=>$timestate,
                        'orderstate'=>'0',
            );  
          
              $res= db('wxpay')->insert($data);

                      //①、获取用户openid
                $tools = new \JsApiPay();
                //$openId = hash(session('wx.uid')+);
                $openId = session('openids');
                /*echo $openId;
                exit();*/
                //②、统一下单
                $input = new \WxPayUnifiedOrder();
                $input->SetBody($protitle);//产品名称
                $input->SetAttach("test");//产品描述
                $input->SetOut_trade_no($order_sn);
                $input->SetTotal_fee($price1);//价格,以‘分’为单位
                $input->SetTime_start(date("YmdHis"));
                $input->SetTime_expire(date("YmdHis", time() + 600));
                $input->SetGoods_tag($protitle);
                $input->SetNotify_url("http://".$_SERVER['HTTP_HOST']."/index.php/home/index/notify");//回调地址
                $input->SetTrade_type("JSAPI");
                $input->SetProduct_id($proid);//产品id
                $input->SetOpenid($openId);
                
                $order = \WxPayApi::unifiedOrder($input);
                
                $jsApiParameters = $tools->GetJsApiParameters($order);
                $editAddress = $tools->GetEditAddressParameters();
                $this -> assign('js_api',$jsApiParameters);
                $this -> assign('edit',$editAddress);
                /*print_r($jsApiParameters) ;
                exit();*/
                    $this->assign("protitle",$protitle);
                    $this->assign("price",$price);
                    $this->assign("order_sn",$order_sn);
                    $this->assign("proid",$proid);
                    $this->assign("userid",$userid);
                    $this->assign("catid",$catid);
                return $this -> fetch('wxpay');

            }else{
     
                     echo '<div>页面加载错误,请返回!</div>';
            }
                   
         
       }else{
          //扫码支付 
          
            header('Content-Type: text/html; charset=utf-8');      
            $order_sn = date('YmdHis').rand(1000,9999);

            ini_set('date.timezone','Asia/Shanghai');
            require_once  "/public/weixin/lib/WxPay.Api.php";
            require_once "/public/weixin/WxPay.NativePay.php";
           // require_once '/public/weixin/example/log.php';
            $userid =input('nid');
            $proid = input('aid');
            $catid = input('catid');      
            if($proid){
                $rows_pay=db('article')->where('id',$proid)->find();   
                
                if($rows_pay){
                    $price = $rows_pay['price'];
                    $protitle = $rows_pay['title'];
                    
                }else{
                    $price = null;
                    exit;
                }
            }     
            if($price && $proid && $userid){
            $price1 = sprintf("%.0f",$price * 100);
            $ymurl = 'http://'.$_SERVER['HTTP_HOST'];
            $aaaa=$this->notify();
            $notify_url = "http://".$_SERVER['HTTP_HOST']."/index.php/home/index/notify";
            /*'/public/weixin/notify.php';*/
            $order_sn = date('YmdHis').rand(1000,9999);//订单编号
            //$time = date("Y-m-d H:i:s",time());
            $timestate = time();
             $data=array(
                        'artcle_id'=> $proid,
                        'artcle_name'=>$protitle,
                        'wx_nid'=>$userid,
                        'order_num'=>$order_sn,
                        'order_price'=>$price,
                        'state'=>$timestate,
                        'orderstate'=>'0',
            );  
          
              $res= db('wxpay')->insert($data);

                     $notify = new \NativePay();
                     $url1 = $notify->GetPrePayUrl("123456789");
                    
                    $input = new \WxPayUnifiedOrder();
                    $input->SetBody($protitle);//商品名称
                    $input->SetAttach("abc");//自己设置
                    $input->SetOut_trade_no($order_sn);//订单号
                    $input->SetTotal_fee($price1);//给用户展示的订单金额
                    $input->SetTime_start(date("YmdHis"));
                    $input->SetTime_expire(date("YmdHis", time() + 600));//给用户展示的订单支付的生成时间
                    $input->SetGoods_tag($protitle);
                    $input->SetNotify_url($notify_url);
                    $input->SetTrade_type("NATIVE");
                    $input->SetProduct_id($proid);//产品id
                    $result = $notify->GetPayUrl($input);
                  /* print_r($notify_url);
                     exit();*/
                    $url2 = $result["code_url"];
                    $url2=urlencode($url2);
                  /*  echo   $url2;
                    exit();*/
                    $this->assign("protitle",$protitle);
                    $this->assign("price",$price);
                    $this->assign("ymurl",$ymurl);
                    $this->assign("url2",$url2);
                    $this->assign("order_sn",$order_sn);
                    $this->assign("proid",$proid);
                    $this->assign("userid",$userid);
                    $this->assign("catid",$catid);

                    return $this -> fetch('wxpay');

            }else{
     
                     echo '<div>页面加载错误,请返回!</div>';
            }
     


       }
     
}        
  
//支付请求成功后返回
public function wxstate(){
    
    $proid = input('proid');
    $userid = input('userid');
    $order_num = input('order_num');
    $data=array('oderstate'=>'1'
    );
    //db('wxpay')->where('order_num', $order_num)->update($data);    
    $rows1 = db('wxpay')->field('oderstate')->where('order_num',$order_num)->find();
    if($rows1){
        if($rows1['oderstate'] == '1'){
            $res9 = db('wxpay')->field('id')->where('oderstate','0')->select();

        foreach($res9 as $re9){  
 
                $time = time();
                if($time >($rows9['state']+600)){
                    $orderid = $re9['id'];     
                   db('wxpay')->where('id',$orderid)->delete();
               
               }

         }
          
            echo $rows1['oderstate'];exit;
            exit("{'state':'success','info':'<span>支付成功</span>'}");
        }
    }
//微信内支付页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>微信支付:{$protitle}</title>
</head>
    <script src="<?=$ymurl;?>/public/weixin/javascript/jquery.js"></script>
    <script type="text/javascript">
    //调用微信JS api 支付
    function jsApiCall()
    {
        WeixinJSBridge.invoke(
                'getBrandWCPayRequest',
                 $.parseJSON('{$js_api}'),
        function(res){
            if(res.err_msg == "get_brand_wcpay_request:ok" ) {
               
                  pay_status();
            }else{
                //失败

            }
        }
    );
    }

    function callpay()
    {
        if (typeof WeixinJSBridge == "undefined"){
            if( document.addEventListener ){
                document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
            }else if (document.attachEvent){
                document.attachEvent('WeixinJSBridgeReady', jsApiCall);
                document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
            }
        }else{
            jsApiCall();
        }
    }
    var int=self.setInterval(function(){pay_status()},1000);
</script>
<script type="text/javascript">
    //获取共享地址
    function editAddress()
    {
        WeixinJSBridge.invoke(
                'editAddress',
               '{$edit}',
        function(res){
            var value1 = res.proviceFirstStageName;
            var value2 = res.addressCitySecondStageName;
            var value3 = res.addressCountiesThirdStageName;
            var value4 = res.addressDetailInfo;
            var tel = res.telNumber;

            //alert(value1 + value2 + value3 + value4 + ":" + tel);
        }
    );
    }

    window.onload = function(){
        if (typeof WeixinJSBridge == "undefined"){
            if( document.addEventListener ){
                document.addEventListener('WeixinJSBridgeReady', editAddress, false);
            }else if (document.attachEvent){
                document.attachEvent('WeixinJSBridgeReady', editAddress);
                document.attachEvent('onWeixinJSBridgeReady', editAddress);
            }
        }else{
            editAddress();
        }
    };

</script>






<body  style="">

<script type="text/javascript">
function pay_status(){
     var userid = $("#userid").val();
     var proid = $("#proid").val();
     var order_num = $("#order_num").val();
     $.ajax({
        url:"{:url('wxstate')}",
        dataType:'json',
        type:'post',
        data:{'order_num':order_num},
        success:function(data){            
            if(data == '1' ){
                window.clearInterval(int); //销毁定时器
                setTimeout(function(){
                    //跳转到结果页面,并传递状态
                    window.location.href="http://"+window.location.host+"{:url('home/news/info',array('id'=>$proid,'catId'=>$catid))}";
                },1000)
                
            }else if(data =='2'){
                window.clearInterval(int); //销毁定时器
                setTimeout(function(){
                    //跳转到结果页面,并传递状态
                    window.location.href="http://"+window.location.host+"/home/cart/pay_result?pay_status=fail";
                },1000)
            }
        },
        //error:function(){
            //alert("error");
            
        //},

  });
}
//启动定时器

</script>
<input type="hidden"   id="userid"  value="<?php echo $userid;?>">
<input type="hidden"   id="proid"   value="<?php echo $proid;?>">
<input type="hidden"   id="order_num"   value="<?php echo $order_sn;?>">
    <div>
        <div class="inner" style="width: 100%; height: 100px; margin: 50% auto;text-align: center;">
            <div class="middle">
                <div class="title" style="color: #333; font-size:50px; margin-top: 10%; font-weight: bold;"><?php echo $protitle;?></div>
                <div class="price" style="color: #333;margin-bottom: 10px; font-size: 40px;margin-top: 10%; font-weight: bold;">¥&nbsp;<?php echo $price;?>(元)</div>
                <button style="width:80%; height:120px; border-radius: 20px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer;  color:white;  font-size:40px; margin-top: 10%; " type="button" onclick="callpay()" >立即支付</button>
            </div>
            
           
        </div>
    </div>
    
</body>
</html> 

//扫码支付页面

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1" /> 
    <script src="<?=$ymurl;?>/public/weixin/javascript/jquery.js"></script>
    <title>微信支付:{$protitle}</title>
    <style>
        .inner{width:100%;text-align:center;margin:auto;overflow:hidden;}
        .middle{text-align:center;}
        .middle .title{font-size:24px;line-height:80px;}
        .middle .qr img{width:200px;}
        .bottom{line-height:100px;text-align:center;font-size:24px;}
        .sum{display:none;}
        .price{font-size:20px;line-height:24px;}
    </style>
</head>
<body style="background-color: rgba(51,51,51,0.8)">
<br><br><br>
<script type="text/javascript">
function pay_status(){
     var userid = $("#userid").val();
     var proid = $("#proid").val();
     var order_num = $("#order_num").val();
     $.ajax({
        url:"{:url('wxstate')}",
        dataType:'json',
        type:'post',
        data:{'order_num':order_num},
        success:function(data){            
            if(data == '1' ){
                window.clearInterval(int); //销毁定时器
                setTimeout(function(){
                    //跳转到结果页面,并传递状态
                    window.location.href="http://"+window.location.host+"{:url('home/news/info',array('id'=>$proid,'catId'=>$catid))}";
                },1000)
                
            }else if(data =='2'){
                window.clearInterval(int); //销毁定时器
                setTimeout(function(){
                    //跳转到结果页面,并传递状态
                    window.location.href="http://"+window.location.host+"/home/cart/pay_result?pay_status=fail";
                },1000)
            }
        },
        //error:function(){
            //alert("error");
            
        //},

  });
}
//启动定时器
var int=self.setInterval(function(){pay_status()},1000);
</script>
<input type="hidden"   id="userid"  value="<?php echo $userid;?>">
<input type="hidden"   id="proid"   value="<?php echo $proid;?>">
<input type="hidden"   id="order_num"   value="<?php echo $order_sn;?>">
    <div>
        <div class="inner">
            <div class="middle">
                <div class="title" style="color: #999;"><?php echo $protitle;?></div>
                <div class="price" style="color: #999;margin-bottom: 10px;">¥&nbsp;<?php echo $price;?>(元)</div>
                <div class="qr">

                    <img alt="<?php echo $protitle;?>" src="<?=$ymurl;?>/public/weixin/qrcode/index.php?data={$url2}&logo=1" />
                </div>
            </div>
            
            <div class="bottom" style="color: #999;">微信扫描二维码</div>
            <div class="sum"></div>
        </div>
    </div>
    
</body>
</html>

此处评论已关闭