<?php
!defined('IN_ONEZ') && exit('Access Denied');
class onezphp_alipay extends onezphp{
  var $vars=array();
  function __construct(){
    
  }
  function options(){
    $options=array();
    $options['alipay_partner']=array('label'=>'支付宝partner','type'=>'text','key'=>'alipay_partner','hint'=>'合作身份者id，以2088开头的16位纯数字','notempty'=>'支付宝partner不能为空');
    $options['alipay_key']=array('label'=>'支付宝安全检验码','type'=>'text','key'=>'alipay_key','hint'=>'安全检验码，以数字和字母组成的32位字符','notempty'=>'支付宝安全检验码不能为空');
    $options['alipay_seller_email']=array('label'=>'支付宝卖家账号','type'=>'text','key'=>'alipay_seller_email','hint'=>'请正确填写支付宝卖家账号','notempty'=>'支付宝卖家账号不能为空');
    return $options;
  }
  function setting($form){
    foreach(onez('call')->call('setting',array(),$this->token) as $arr){
      $form->add($arr);
    }
  }
  function bind_setting(){
    $arr=onez('call')->get('setting');
    
    #分类
    $arr[]=array('label'=>'支付宝即时到账接口整合(alipay)','type'=>'group',);
    
    $arr[]=array('label'=>'支付宝partner','type'=>'text','key'=>'alipay_partner','hint'=>'合作身份者id，以2088开头的16位纯数字','notempty'=>'支付宝partner不能为空');
    $arr[]=array('label'=>'支付宝安全检验码','type'=>'text','key'=>'alipay_key','hint'=>'安全检验码，以数字和字母组成的32位字符','notempty'=>'支付宝安全检验码不能为空');
    $arr[]=array('label'=>'支付宝卖家账号','type'=>'text','key'=>'alipay_seller_email','hint'=>'请正确填写支付宝卖家账号','notempty'=>'支付宝卖家账号不能为空');
    $arr[]=array('label'=>'支付宝证书','type'=>'form.file','local'=>'1','filetype'=>'file','key'=>'alipay_cacert','hint'=>'alipay_cacert','notempty'=>'');
    
    onez('call')->set('setting',$arr);
  }
  function error($msg){
    return 'alert('.var_export((string)$msg,1).')';
  }
  function click($has_on_click=1){
    if((float)$this->get('price')<=0){
      $this->error('支付金额设置有误');
    }
    if(!$this->get('subject')){
      $this->error('请设置商品名称');
    }
    $has_on_click && register_shutdown_function(array(&$this, '_on_click'));
    
    $eventName='_onez_alipay_'.md5($this->key);
    return $eventName.'('.var_export((string)$this->get('price'),1).','.var_export((string)$this->get('subject'),1).')';
  }
  function url(){
    $eventName='_onez_alipay_'.md5($this->key);
    $orderno=onez()->gp('_payback');
    if($orderno){
      $order=onez('order')->load($orderno);
      if($order['eventname']!=$eventName){
        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".$this->get('subject')."\t".$this->hashkey);
    
    $getorder=$this->view('getorder&jump=1&price='.urlencode($this->get('price')).'&subject='.urlencode($this->get('subject')).'&eventname='.urlencode($eventName).'&goto='.urlencode(onez()->cururl()).'&hash='.$hash);
    return $getorder;
  }
  function pay($price,$subject,$option=array()){
    $extra=array(
      'postdata'=>$option,
      'goto'=>$option['goto'],
    );
    $orderno=onez('order')->orderno($price,$subject,$extra);
    $this->paynow($orderno);
  }
  function _on_click(){
    $eventName='_onez_alipay_'.md5($this->key);
    $orderno=onez()->gp('_payback');
    if($orderno){
      $order=onez('order')->load($orderno);
      if($order['eventname']!=$eventName){
        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".$this->get('subject')."\t".$this->hashkey);
    $getorder=$this->view('getorder&price='.urlencode($this->get('price')).'&subject='.urlencode($this->get('subject')).'&hash='.$hash);
    onez('onezjs')->init();
    $data=$this->vars;
    
    $data['eventname']=$eventName;
    $data=json_encode($data);
    echo<<<ONEZ
<script type="text/javascript">
function $eventName(price,subject){
  onez.ready(function($){
    var postdata=$data;
    if(typeof postdata.goto=='undefined'){
      postdata.goto=window.location.href;
    }
    $.post('$getorder',postdata,function(data){
      if(typeof data.error!='undefined'){
        alert(data.error);
        return;
      }
      if(typeof data.url!='undefined'){
        location.href=data.url;
        return;
      }
    },'json');
  },['jquery']);
}
</script>
ONEZ;
  }
  function payback($orderno,$price,$extra=false){
    global $G;
    $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;
      }
    }
    return $order;
  }
  function getorder(){
    $A=array();
    $jump=(int)onez()->gp('jump');
    $hash=onez()->gp('hash');
    $price=onez()->gp('price');
    $subject=onez()->gp('subject');
    $myhash=md5("$price\t$subject\t".$this->hashkey);
    if($myhash!=$hash){
      onez()->error('非法请求');
    }
    $extra=$_REQUEST;
    $extra['goto']=onez()->gp('goto');
    $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'=>'paying',
    ));
    
    $payurl=$this->view('paynow&orderno='.$orderno);
    $A['url']=$payurl;
    if($jump){
      onez()->location($payurl);
    }
    
    onez()->output($A);
  }
  function paynow($orderno=false){
    !$orderno && $orderno=onez()->gp('orderno');
    $order=onez('order')->load($orderno);
    if($order['error']){
      exit('<h1>'.$order['error'].'</h1>');
    }
    require_once(dirname(__FILE__)."/lib/alipay.config.php");
    require_once(dirname(__FILE__)."/lib/alipay_submit.class.php");
    /**************************请求参数**************************/
    //支付类型
    $payment_type = "1";
    //必填，不能修改
    //服务器异步通知页面路径
    $notify_url = $this->url."/lib/notify_url.php";
    //需http://格式的完整路径，不能加?id=123这类自定义参数

    //页面跳转同步通知页面路径
    $return_url = $this->url."/lib/return_url.php";
    //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/

    //卖家支付宝帐户
    $seller_email = $alipay_config['seller_email'];
    //必填

    //商户订单号
    $out_trade_no = $orderno;
    //商户网站订单系统中唯一订单号，必填

    //订单名称
    $subject = $order['subject'];
    //必填

    //付款金额
    $total_fee = $order['price'];
    //必填

    //订单描述

    $body = $body;
    //商品展示地址
    $show_url = '';
    //需以http://开头的完整路径，例如：http://www.xxx.com/myorder.html

    //防钓鱼时间戳
    $anti_phishing_key = "";
    //若要使用请调用类文件submit中的query_timestamp函数

    //客户端的IP地址
    $exter_invoke_ip = "";
    //非局域网的外网IP地址，如：221.0.0.1
    $parameter = array(
    		"service" => "create_direct_pay_by_user",
    		"partner" => trim($alipay_config['partner']),
    		"payment_type"	=> $payment_type,
    		"notify_url"	=> $notify_url,
    		"return_url"	=> $return_url,
    		"seller_email"	=> $seller_email,
    		"out_trade_no"	=> $out_trade_no,
    		"subject"	=> $subject,
    		"total_fee"	=> $total_fee,
    		"body"	=> $body,
    		"show_url"	=> $show_url,
    		"anti_phishing_key"	=> $anti_phishing_key,
    		"exter_invoke_ip"	=> $exter_invoke_ip,
    		"_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
    );
    //建立请求
    $alipaySubmit = new AlipaySubmit($alipay_config);
    $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "正在支付...");
    echo $html_text;
    exit();
  }
  function demo(){
    global $G;
    $ui=onez('ui')->init();
    $G['title']='在线演示';
    $ui->header();
    include(dirname(__FILE__).'/demo/demo.php');
    $ui->footer();
    exit();
  }
  //以下为新版接口
  function bind_pay($data,$pay){
    global $G;
    if(defined('IS_M_API')){//是否在微信窗口内
      if($G['is_weixin']){
      }
    }
    if(!defined('IS_M_API')){//是否在电脑网页上
      if(!$G['is_weixin']){
        $this->vars=$_POST=$data;
        $this->key=uniqid();
        $event=array();
        $event['name']='支付宝支付';
        $event['click']='onez.'.$this->click(0);
        $event['btn_style']='info';
        $eventName='_onez_alipay_'.md5($this->key);
        
        $hash=md5($this->get('price')."\t".$this->get('subject')."\t".$this->hashkey);
        $getorder=$this->view('getorder&price='.urlencode($this->get('price')).'&subject='.urlencode($this->get('subject')).'&hash='.$hash);

        $data['eventname']=$eventName;
        $data=json_encode($data);
        
        $event['code']=<<<ONEZ
onez.$eventName=function(price,subject){
  onez.ready(function($){
    var postdata=$data;
    if(typeof postdata.goto=='undefined'){
      postdata.goto=window.location.href;
    }
    $.post('$getorder',postdata,function(data){
      if(typeof data.error!='undefined'){
        alert(data.error);
        return;
      }
      if(typeof data.url!='undefined'){
        location.href=data.url;
        return;
      }
    },'json');
  },['jquery']);
};
ONEZ;
        return $event;
      }
    }
  }
}