<?php
!defined('IN_ONEZ') && exit('Access Denied');
class onezphp_wxpay extends onezphp{
  
  var $hashkey='hashkey';
  function __construct(){
    
  }
  function options(){
    $options=array();
    $options['wx_AppId']=array('label'=>'微信AppId','type'=>'text','key'=>'wx_AppId','hint'=>'请正确填写微信AppId','notempty'=>'微信AppId不能为空');
    $options['wx_AppSecret']=array('label'=>'微信AppSecret','type'=>'text','key'=>'wx_AppSecret','hint'=>'请正确填写微信AppSecret','notempty'=>'微信AppSecret不能为空');
    $options['wx_MCHID']=array('label'=>'微信支付MCHID','type'=>'text','key'=>'wx_MCHID','hint'=>'请正确填写微信支付MCHID','notempty'=>'微信支付MCHID不能为空');
    $options['wx_KEY']=array('label'=>'微信支付密钥','type'=>'text','key'=>'wx_KEY','hint'=>'请正确填写支付密钥','notempty'=>'支付密钥不能为空');
    return $options;
  }
  function bind_setting(){
    $arr=onez('call')->get('setting');
    
    #分类
    $arr[]=array('label'=>'微信支付(wxpay)','type'=>'group',);
    $arr[]=array('label'=>'微信AppId','type'=>'text','key'=>'wx_AppId','hint'=>'请正确填写微信AppId','notempty'=>'微信AppId不能为空');
    $arr[]=array('label'=>'微信AppSecret','type'=>'text','key'=>'wx_AppSecret','hint'=>'请正确填写微信AppSecret','notempty'=>'微信AppSecret不能为空');
    $arr[]=array('label'=>'微信支付MCHID','type'=>'text','key'=>'wx_MCHID','hint'=>'请正确填写微信支付MCHID','notempty'=>'微信支付MCHID不能为空');
    $arr[]=array('label'=>'微信支付密钥','type'=>'text','key'=>'wx_KEY','hint'=>'请正确填写支付密钥','notempty'=>'支付密钥不能为空');
    onez('call')->set('setting',$arr);
  }
  function error($msg){
    return 'alert('.var_export((string)$msg,1).')';
  }
  function bind_weixin_apiList(){
    if(onez()->exists('site.weixin')){
      onez('site.weixin')->add('chooseWXPay');
    }
  }
  function qrcode($url){
    if(onez()->exists('qrcode')){
      return onez('qrcode')->set('width',256)->set('size',10)->pic($url);
    }
    return 'http://qrcode.onez.cn/api.php?size=256&text='.urlencode($url);
  }
  function click($has_on_click=1){
    global $G;
    $has_on_click && register_shutdown_function(array(&$this, '_on_click'));
    
    
    $get=array(
      'price'=>$this->get('price'),
      'subject'=>$this->get('subject'),
    );
    $info=$this->get('info');
    if($info && is_array($info)){
      $get=array_merge($get,$info);
      unset($this->vars['info']);
    }
    if((float)$get['price']<=0){
      return $this->error('支付金额设置有误');
    }
    if(!$get['subject']){
      return $this->error('请设置商品名称');
    }
    $hash=md5($get['price']."\t\t".$this->hashkey);
    $get['hash']=$hash;
    foreach($this->vars as $k=>$v){
      $get[$k]=$v;
    }
    $get['key']=$this->key;
    $_POST && $get=array_merge($get,$_POST);
    #$getorder=$this->view('getorder&'.http_build_query($get));
    $getorder='index.php?_p='.$this->token.'&_m=getorder&'.http_build_query(array(
      'subject'=>$get['subject'],
      'price'=>$get['price'],
      'hash'=>$get['hash'],
    ));
    return 'onez.wxpay.pay('.var_export($getorder,1).','.var_export(urlencode(json_encode($get)),1).')';
  }
  function payback($orderno,$price,$extra=false){
    $order=onez('order')->payback($orderno,$price,$extra);
    if($order['postdata']['plugintoken'] && onez()->exists($order['postdata']['plugintoken'])){
      $myorder=onez($order['postdata']['plugintoken'])->data()->open('order')->one("token='$orderno'");
      if($myorder){
        return $order;
      }
      $myorder=$order;
      $myorder['token']=$orderno;
      $myorder['userid']=$order['postdata']['userid'];
      onez($order['postdata']['plugintoken'])->data()->open('order')->insert($myorder);
      
      
      if(method_exists(onez($order['postdata']['plugintoken']),'payback')){
        onez($order['postdata']['plugintoken'])->payback($order);
        return $order;
      }
    }
    /*
    if($order['goto']){
      onez()->location($order['goto']);
    }
    if($order['postdata']['goto']){
      onez()->location($order['postdata']['goto']);
    }
    */
    return $order;
  }
  function getorder(){
    global $G;
    $A=array();
    $hash=onez()->gp('hash');
    $price=onez()->gp('price');
    $subject=onez()->gp('subject');
    $myhash=md5("$price\t\t".$this->hashkey);
    if($myhash!=$hash){
      onez()->error('非法请求');
    }
    $extra=$_POST;
    $extra['goto']=onez()->gp('goto');
    $extra['key']=onez()->gp('key');
    $extra['postdata']=$_POST;
    
    $orderno=onez('order')->orderno($price,$subject,$extra);
    
    if(strpos($extra['goto'],'?')!=-1){
      list($a,$b)=explode('?',$extra['goto']);
      parse_str($b,$info);
      $info['_payback']=$orderno;
      $extra['goto']=$a.'?'.http_build_query($info);
    }else{
      $info['_payback']=$orderno;
      $extra['goto'].='?'.http_build_query($info);
    }
    onez('order')->update($orderno,array(
      'goto'=>$extra['goto'],
      'status'=>'qrcode',
    ));
    
    $payurl='?_p='.$this->token.'&_m=paynow&orderno='.$orderno;
    $proxy=$_POST['proxy'];
    if($proxy){
      $payurl=$proxy.$payurl;
    }else{
      $payurl=onez()->homepage().$payurl;
    }
    $A['qrcode']=$this->qrcode($payurl);
    $A['orderno']=$orderno;
    //$A['payurl']=$payurl;
    
    
    onez()->output($A);
  }
  function jsApiParameters($orderno){
    global $G;
    $order=onez('order')->load($orderno);
    if($order['error']){
      exit('<h1>'.$order['error'].'</h1>');
    }
    
    include_once(dirname(__FILE__)."/lib/WxPayPubHelper.php");
    
    $jsApi = new JsApi_pub();
    $unifiedOrder = new UnifiedOrder_pub();
    
    if(!$order['openid']){
      $order['openid']=$this->get('openid');
    }
    if(!$order['openid']){
      $order['openid']=onez('wxauth')->openid();
    }
    
    $arr=array(
      'openid'=>$order['openid'],
      'status'=>'paying',
    );
    if($G['this']){
      $arr['sitetoken']=$G['this']->token;
    }
    onez('order')->update($orderno,$arr);
    $unifiedOrder->setParameter("openid",$order['openid']);//商品描述
    $unifiedOrder->setParameter("body",$order['subject']);//商品描述
    //自定义订单号，此处仅作举例
    $total_fee=$order['price']*100;
    $timeStamp = time();
    $unifiedOrder->setParameter("out_trade_no","$orderno");//商户订单号 
    $unifiedOrder->setParameter("total_fee","$total_fee");//总金额
    $unifiedOrder->setParameter("notify_url",$this->url.'/lib/wxpay_notify.php');//通知地址 
    $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
    //$unifiedOrder->setParameter("product_id","$gid");//商品ID
    $prepay_id = $unifiedOrder->getPrepayId();
    //=========步骤3：使用jsapi调起支付============
    $jsApi->setPrepayId($prepay_id);

    $jsApiParameters = $jsApi->getParameters();
    
    return $jsApiParameters;
  }
  function pay($subject,$price,$data=array()){
    global $G;
    $extra=array();
    $extra['userid']=(int)$data['userid'];
    $extra['price']=$price;
    $extra['postdata']=$data;
    $orderno=onez('order')->orderno($price,$subject,$extra);  
    
    $jsApiParameters=$this->jsApiParameters($orderno);
    
    $goto=onez()->homepage().'?_p='.$this->token.'&_m=pay_back&orderno='.$orderno;
    
    if(onez()->exists('site.weixin')){
      onez('site.weixin')->add('chooseWXPay');
    }
    $ui=onez('ui')->init();
    $G['title']='微信支付';
    $ui->header();
    include(dirname(__FILE__).'/php/paynow.php');
    //$ui->footer();
  }
  function pay_back(){
    global $G;
    $orderno=onez()->gp('orderno');
    $message=onez()->gp('message');
    $order=onez('order')->load($orderno);
    if($order['postdata']['plugintoken'] && onez()->exists($order['postdata']['plugintoken'])){
      if($order['postdata']['sitetoken'] && onez()->exists($order['postdata']['sitetoken'])){
        $G['this']=onez($order['postdata']['sitetoken']);
      }
      $myorder=onez($order['postdata']['plugintoken'])->data()->open('order')->one("token='$orderno'");
      if(!$myorder){
        $ui=onez('ui')->init();
        $status='fail';
        $G['title']='支付失败';
        $ui->header();
        include(dirname(__FILE__).'/php/payok.php');
        $ui->footer();
        exit();
      }
      if($order['postdata']['goto']){
        onez()->location($order['postdata']['goto']);
      }
    }
    $ui=onez('ui')->init();
    $G['title']='支付成功';
    $ui->header();
    $status='ok';
    include(dirname(__FILE__).'/php/payok.php');
    $ui->footer();
    exit();
  }
  function paynow(){
    global $G;
    
    
    $orderno=onez()->gp('orderno');
    
    $jsApiParameters=$this->jsApiParameters($orderno);
    
    $goto=$this->view('payok');
    
    global $G;
    $ui=onez('ui')->init();
    $G['title']='微信支付';
    $ui->header();
    include(dirname(__FILE__).'/php/paynow.php');
    $ui->footer();
  }
  function update(){
    $orderno=onez()->gp('orderno');
    $order=onez('order')->load($orderno);
    $A=array();
    $A['status']='wait';
    if($order['status']=='payok'){
      $A['status']='ok';
      $A['goto']=$order['goto'];
      $A['return_code']=(string)$order['return_code'];
    }
    onez()->output($A);
  }
  function _on_click(){
    global $G;
    $orderno=onez()->gp('_payback');
    if($orderno){
      $order=onez('order')->load($orderno);
      if($order['key']!=$this->key){
        return;
      }
      ob_clean();
      
      $callback=$this->get('callback');
      $ifok=$order['error']?false:true;
      if(is_string($callback) && function_exists($callback)){
        $callback($ifok,$order);
      }else{
        exit("<pre>支付成功\n".var_export($order,1).'</pre>');
      }
      exit();
    }
    $hash=md5($this->get('price')."\t\t".$this->hashkey);
    
    $getorder=$this->view('getorder&price='.$this->get('price').'&subject='.$this->get('subject').'&hash='.$hash);
    $updateurl=$this->view('update');
    onez('onezjs')->init();
    $data=$this->vars;
    $data=json_encode($data);
    $jsurl=$this->url.'/js/wxpay.js';
    echo<<<ONEZ
<script type="text/javascript">
onez.ready(function($){
  onez.wxpay.init({
    updateurl:'$updateurl'
  });
},['jquery',{name:'wxpay',url:'$jsurl'}]);
</script>
ONEZ;
  }
  function demo(){
    global $G;
    $ui=onez('ui')->init();
    $G['title']='在线演示';
    $ui->header();
    include(dirname(__FILE__).'/demo/demo.php');
    $ui->footer();
    exit();
  }
  function payok(){
    global $G;
    $ui=onez('ui')->init();
    $G['title']='支付成功';
    $ui->header();
    include(dirname(__FILE__).'/php/payok.php');
    $ui->footer();
    exit();
  }
  function bind_payname($data){
    global $G;
    if($G['is_weixin']){
      return array(
        'name'=>'微信支付',
        'token'=>onez('m2')->event(array(
          'token'=>'pay_weixin',
          'data'=>$data,
        )),
      );
    }
  }
  //以下为新版接口
  function bind_pay($data){
    global $G;
    
    
    if(defined('IS_M_API')){//是否在微信窗口内
      if($G['is_weixin']){
        $data['name']='微信支付';
        $data['token']=$this->cname.'_pay';
        return $data;
      }
    }
    if(!defined('IS_M_API')){//是否在电脑网页上
      if(!$G['is_weixin']){
        $this->vars=$_POST=$data;
        $event=array();
        $event['name']='微信支付';
        $event['click']=onez('wxpay')->set('info',array(
          'plugintoken'=>$data['plugintoken'],
          'paytype'=>'wxpay',
          'payname'=>'微信支付',
          'userid'=>$G['userid'],
          'type'=>$data['type'],
          'price'=>$data['price'],
          'goto'=>$data['goto'],
          'subject'=>$data['subject'],
          'proxy'=>'http://www.onez.cn',
        ))->click(0);
        $event['btn_style']='success';
        
        $jsurl=$this->url.'/js/wxpay.js?t='.filemtime($this->path.'/js/wxpay.js');
        $updateurl=$this->view('update');
        $event['code'].=<<<ONEZ
onez.ready(function($){
  onez.wxpay.init({
    updateurl:'$updateurl'
  });
  onez.wxpay.payok=function(){
    location.href='$data[goto]';
  };
},['jquery',{name:'wxpay',url:'$jsurl'}]);
ONEZ;
        return $event;
      }
    }
  }
  function bind_weixin_onload($data,$weixin_onload){
    return array(
      'ptoken'=>$this->token,
      'jsFile'=>$this->path.'/js/event.weixin.js',
    );
  }
  
}