<?php

/* ========================================================================
 * $Id: bs.pay.php 10555 2020-07-08 17:33:03Z onez $
 * 
 * Email: www@onez.cn
 * QQ: 6200103
 * HomePage: http://www.onez.cn
 * ========================================================================
 * Copyright 2016-2017 佳蓝科技.
 * 
 * ======================================================================== */

!defined('IN_ONEZ') && exit('Access Denied');
#名称：支付能力
#标识：bs.pay

class onezphp_bs_pay extends onezphp{
  function __construct(){
    
  }
  function res(){
    return array(
      onez('ui')->resurl($this->url.'/js/api.js'),
    );
  }
  //当前网址
  function cururl(){
    global $G;
    $_purl=$_REQUEST['_purl']?$_REQUEST['_purl']:$_GET['_purl'];
    if($_purl){
      return onez()->homepage('?_purl='.$_purl);
    }
    return onez()->cururl();
  }
  function payOK($orderno,$status){
    global $G;
    $temp_order=$G['this']->data()->open('temp.orders')->one("token='$orderno'");
    if(!$temp_order){
      return;
    }
    $item=$temp_order['data'];
    $item['key1']=$item['orderType']=$item['token'];
    $item['key2']=$item['paytype'];
    $item['key3']=$item['subject'];
    $item['key4']=$item['type'];
    $item['key5']=$item['status']=$status;
    $item['key6']=$item['up_orderno']=$up_orderno=$item['orderno'];
    $item['key7']=$item['qq'];
    $item['key8']=$item['email'];
    $item['key9']=$item['user'];
    $item['key10']=$item['ip']=onez()->ip();
    $item['money1']=$item['price'];
    $item['money2']=$item['totalPrice'];
    $item['money3']=$item['zhekou'];
    $item['token']=$item['orderno'];
    $item['upid']=$item['proId'];
    if($item['carts']){
      $carts=$item['carts'];
      unset($item['carts']);
      $index=0;
      foreach($carts as $cart){
        $index++;
        $item['token']=$item['orderno']=$item['up_orderno'].str_pad($index,2,'0',STR_PAD_LEFT);
        if(intval($item['couponProId'])==intval($cart['id'])){
          $item['money1']=$cart['price'];
          $item['money2']=$item['totalPrice']=$cart['totalprice'];
          $item['money3']=$item['zhekou']=0;
        }else{
          $item['money1']=$cart['price']-$item['couponPrice'];
          $item['money2']=$item['totalPrice']=$cart['totalprice'];
          $item['money3']=$item['zhekou']=$item['couponPrice'];
        }
        $item['image']=$cart['image'];
        $item['upid']=$cart['id'];
        $item['key3']=$item['subject']=$cart['title'];
        $G['this']->data()->open('orders')->insert($item);
      }
    }else{
      $item['ip']=onez()->ip();
      $G['this']->data()->open('orders')->insert($item);
    }
    $G['this']->data()->open('temp.orders')->delete("id='$temp_order[id]'");
    if($item['paytype']=='user' && $item['price']>0){#人工转账订单由人工触发后续操作
      return;
    }
    $T=$G['this']->data()->open('orders')->record("key6='$up_orderno'");
    $MODE='$pay';
    foreach($T as $order){
      $BS_PAY_OK=$order;
      if($item['borrow']){#借权支付
        $postdata=array();
        $postdata['action']='$borrow.payback';
        $postdata['time']=$item['time'];
        $postdata['hash']=$item['hash'];
        $postdata['order']=$item['hash'];
        $postdata['orderno']=$item['orderno'];
        onez()->post($item['borrow'],$postdata);
        //onez()->location($item['borrow'].'/index.php?action=$payend&orderno='.$item['orderno']);
      }else{
        include($item['$file']);
      }
    }
  }
  function init(){
    
    $action=onez()->gp('action');
    if($action=='$payback'){
      onez('bs.pay')->notify();
    }elseif($action=='$borrow'){
      onez('bs.pay')->borrow();
    }elseif($action=='$payend'){
      onez('bs.pay')->payend();
    }elseif($action=='$pay.auto'){
      onez('bs.pay')->payauto();
    }elseif($action=='$borrow.payback'){
      onez('bs.pay')->borrow_payback();
    }
  }
  function payend(){
    global $G;
    $orderno=onez()->gp('orderno');
    $T=$G['this']->data()->open('orders')->one("(token='$orderno' or key6='$orderno')");
    if($T){#支付完成
      if($T['goto']){
        onez()->location(onez()->homepage().'#'.$T['goto']);
      }
    }else{#支付未完成
      $T=$G['this']->data()->open('temp.orders')->one("(token='$orderno' or key6='$orderno')");
      if($T['data']['goto']){
        onez()->location(onez()->homepage().'#'.$T['data']['goto']);
      }
    }
    onez()->location(onez()->homepage());
  }
  function borrow_payback(){
    global $G;
    $orderno=onez()->gp('orderno');
    $hash=onez()->gp('hash');
    $time=onez()->gp('time');
    if($hash==md5(__FILE__.$time)){
      $this->payOK($orderno,'ok');
    }else{
      onez('log')->write('bs.pay','校验失败'.var_export($_REQUEST,1));
    }
  }
  #借权支付
  function borrow(){
    global $G;
    $orderno=onez()->gp('orderno');
    $subject=onez()->gp('subject');
    $price=onez()->gp('price');
    $paytype=onez()->gp('paytype');
    $myurl=onez()->gp('myurl');
    $time=time();
    $_REQUEST['data']=array(
      'paytype'=>$paytype,
      'orderno'=>$orderno,
      'subject'=>$subject,
      'price'=>$price,
      'borrow'=>$myurl,
      'time'=>$time,
      'hash'=>md5(__FILE__.$time),
      'token'=>'borrow',
      'type'=>'borrow',
    );
    $G['this']->data()->open('temp.orders')->delete("addtime<".(time()-86400));
    $ip=onez()->ip();
    $hash=md5("$G[userid]\t$ip\t".serialize($_REQUEST['data']));
    $T=$G['this']->data()->open('temp.orders')->one("key1='$hash'");
    if($T){
      $A['orderno']=$T['token'];
    }else{
      $item=array();
      $item['key1']=$hash;
      $item['userid']=$G['userid'];
      $A['orderno']=$item['orderno']=$item['token']=$orderno;
      $item['data']=$_REQUEST['data'];
      $G['this']->data()->open('temp.orders')->insert($item);
    }
    $PT=$G['this']->data()->open('bs.pay.setting')->one("token='$paytype'");
    list($Token,$_token)=explode('.',$paytype);
    $payFile=onez('bs.pay')->path.'/paytypes/'.$Token.'/'.$_token.'/pay.php';
    if(!file_exists($payFile)){
      exit('支付接口集成错误，请与管理员联系');
      return $A;
    }
    $orderno=$A['orderno'];
    $order=$G['this']->data()->open('temp.orders')->one("token='$orderno'");
    $payPath=substr(dirname($payFile),strlen($this->path));
    $FORCEURL=1;
    $A=include($payFile);
    if(!$A['url']){
      print_r($A);exit();
    }
    onez()->location($A['url']);
  }
  function notify(){
    global $G;
    $action=onez()->gp('action');
    if($action=='$payback'){
      $method=onez()->gp('method');
      $orderno=onez()->gp('orderno');
      if($method=='success'){
        if(!$orderno){
          $ip=onez()->ip();
          $order=$G['this']->data()->open('orders')->one("key10='$ip' order by id desc");
          if($order && $order['updatetime']>time()-1800){
            if($order['borrow']){
              $A['location']=$order['borrow'].'/index.php?action=$payend&orderno='.$order['orderno'];
            }else{
              $A['location']=onez()->homepage().'/index.php?action=$payend&orderno='.$order['orderno'];
            }
            onez()->output($A);
          }
        }
      }elseif($method=='checkout'){
        if(!$orderno){
          $ip=onez()->ip();
          $order=$G['this']->data()->open('orders')->one("key10='$ip' order by id desc");
          if($order && $order['updatetime']>time()-1800){
            if($order['borrow']){
              $A['location']=$order['borrow'].'/index.php?action=$payend&orderno='.$order['orderno'];
            }else{
              $A['location']=onez()->homepage().'/index.php?action=$payend&orderno='.$order['orderno'];
            }
            onez()->output($A);
          }
        }
      }
      $order=$G['this']->data()->open('temp.orders')->one("token='$orderno'");
      $paytype=$order['data']['paytype'];
      $PT=$G['this']->data()->open('bs.pay.setting')->one("token='$paytype'");
      list($Token,$_token)=explode('.',$paytype);
      $payFile=onez('bs.pay')->path.'/paytypes/'.$Token.'/'.$_token.'/notify.php';
      if(file_exists($payFile)){
        include($payFile);
      }
      exit();
    }
  }
  //构造支付结构
  function pay($req){
    global $G;
    $A=array();
    !$req['subject'] && onez()->error('请填写支付标题');
    $req['price']*=1;
    if($req['price']<=0){//免费
      $req['price']=0;
      $this->payOK($req['orderno'],'ok');
      $A['result']='ok';
      $A['paytypeName']='免费';
      return $A;
    }else{
      $PT=$G['this']->data()->open('bs.pay.setting')->one("token='$req[paytype]'");
      if($PT['borrow']){#需借权
        $get=array();
        $get['action']='$borrow';
        $get['orderno']=$req['orderno'];
        $get['subject']=$req['subject'];
        $get['price']=$req['price'];
        $get['paytype']=$req['paytype'];
        $get['myurl']=onez()->homepage();
        $A['url']=$PT['borrow'].'/index.php?'.http_build_query($get);
        $A['method']='location';
        $A['result']='next';
        return $A;
      }
      list($Token,$_token)=explode('.',$req['paytype']);
      $payFile=onez('bs.pay')->path.'/paytypes/'.$Token.'/'.$_token.'/pay.php';
      if(!file_exists($payFile)){
        $A['error']='支付接口集成错误，请与管理员联系';
        return $A;
      }
      $orderno=$req['orderno'];
      $order=$G['this']->data()->open('temp.orders')->one("token='$req[orderno]'");
      $payPath=substr(dirname($payFile),strlen($this->path));
      $A=include($payFile);
      if($A['status']=='end'){
        $this->payOK($req['orderno'],'ok');
      }
      !$A['result'] && $A['result']='ok';
      $A['paytypeName']=$PT['name'];
      return $A;
    }
    return $A;
  }
  function paytypes($type){
    global $G;
    $categorys=array();
    $Glob=glob(dirname(__FILE__).'/paytypes/*');
    if($Glob){
      foreach($Glob as $V){
        if(!is_dir($V)){
          continue;
        }
        $Token=basename($V);
        $Con=include($V.'/config.php');
        if($Con){
          $paytypes=array();
          $glob=glob($V.'/*');
          if($glob){
            foreach($glob as $v){
              if(!is_dir($V)){
                continue;
              }
              $con=include($v.'/config.php');
              if($con){
                $token=basename($v);
                $con['token']=$token;
                $T=$G['this']->data()->open('bs.pay.setting')->one("token='$Token.$token'");
                if($T['enabled']){
                  $con['status']='ok';
                  $con['statusName']='已开通';
                }else{
                  $con['status']='none';
                  $con['statusName']='未开通';
                }
                $paytypes[]=$con;
              }
            }
          }
          $Con['token']=$Token;
          $Con['paytypes']=$paytypes;
          $categorys[]=$Con;
        }
      }
    }
    return $categorys;
  }
}