<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;

use think\Model;
use think\Db;
use alipay\v2\aop\Alipay as Apay;

/**
*
* 开发文档：https://open.alipay.com/api/solution?code=SP000001000000007155&index=1
*/

class Alipay extends Model
{
    protected static $config = [];
    
    public static function getSet($platform='H5',$level=-1){
        
        if(!empty(self::$config)){
            return self::$config;
        }
        
        $set = Db::name("platform")->where("id",UNIACID)->find();
        $payroute_id = 0;
        $result = \app\common\model\bbfxshop\Payroute::getPayData($level);

        addFileLog("alpay_err1",json_encode($result));

        if($result['code'] == 1){
            $pay = $result['data'];

            $set['zfb_appid'] = $pay['zfb_appid'];
            $set['zfb_privateKey'] = $pay['zfb_privateKey'];
            $set['zfb_publickey_cert'] = $pay['zfb_publickey_cert'];

            $payroute_id = $pay['id'];
        }
        
        $config = [
            "zfb_appid"=>$set['zfb_appid'],// 支付宝应用ID（支付、退款必须）
            "zfb_publickey_cert"=>ROOT_PATH."public".$set['zfb_publickey_cert'],// 支付宝公钥证书（支付、退款必须）
            "zfb_app_cert"=>ROOT_PATH."public".$set['zfb_app_cert'],// 应用证书
            "zfb_root_cert"=>ROOT_PATH."public".$set['zfb_root_cert'],//支付宝根证书
            "zfb_privateKey"=>$set['zfb_privateKey'],// 应用私钥（支付、退款必须）
            "return_url"=>request()->domain()."/mobile/#/pages/user/index?i=".UNIACID,// 支付成功返回的页面
            "notify_url"=>request()->domain()."/api/pay/alipayNotify/i/".UNIACID,
            "sign_type"=>"RSA2",
            "payroute_id"=>$payroute_id,
        ];
        
        self::$config = $config;
        
        return self::$config;
    }
    
    public static function checkParams($platform='H5',$level=-1){
        $config = self::getSet($platform,$level);
        if(empty($config['zfb_appid'])){
            return __json(0,"缺少支付宝应用ID");
        }
        if(!file_exists($config['zfb_publickey_cert'])){
            return __json(0,"缺少支付宝公钥证书");
        }
        if(!file_exists($config['zfb_app_cert'])){
            // return __json(0,"缺少支付宝应用证书");
        }
        if(!file_exists($config['zfb_root_cert'])){
            // return __json(0,"缺少支付宝根证书");
        }
        if(empty($config['zfb_privateKey'])){
            return __json(0,"缺少支付宝应用私钥");
        }
        return __json(1,"检测成功",$config);
    }
    
    // 支付
    public static function pay($params){
        if($params['platform'] == 'wxapp' || $params['platform'] == 'APP'){
            return __json(0,"暂无支持该支付方式");
        }
        else{
            return self::wapPay($params);
        }
    }
    
    // 手机网站支付
    public static function wapPay($params){
        $res = self::checkParams($params['platform'],$params['level']);
        if($res['code'] != 1){
            return $res;
        }
        $config = $res['data'];
        $payroute_id = $config['payroute_id'];
        
        $data = array(
            "out_trade_no"=>$params['order_trade_no'],// 商户订单号
            "total_amount"=>$params['fee'],// 订单总金额。 单位为元，精确到小数点后两位
            "subject"=>$params['title'],// 订单标题
            "product_code"=>"QUICK_WAP_WAY",// 产品码。 商家和支付宝签约的产品码。
            // "auth_token"=>"",// （可选）针对用户授权接口，获取用户相关数据时，用于标识用户授权关系
            // "body"=>"",// （可选）订单附加信息。 如果请求时传递了该参数，将在异步通知、对账单中原样返回，同时会在商户和用户的pc账单详情中作为交易描述展示
            "quit_url"=>request()->domain()."/mobile/#/pages/user/index?i=".UNIACID,// 用户付款中途退出返回商户网站的地址
        );
        
        if($params['platform'] == 'APP'){
            $config['return_url'] = request()->domain()."/mobile/#/pages/public/paycheck?i=".UNIACID."&order_no=".$params['order_trade_no'];
            $data['quit_url'] = request()->domain()."/mobile/#/pages/public/paycheck?i=".UNIACID."&order_no=".$params['order_trade_no'];
        }
        
        $Apay = new Apay($config);
        
        $result = $Apay->wapPay($data);

        $payroute_level = -1;
        if($payroute_id > 0){
            $payroute_level = Db::name("bbfx_payroute_pay")->where(['id'=>$payroute_id])->value("level");
        }
        
        Db::name("bbfx_pay_order")->where(['order_trade_no'=>$params['order_trade_no']])->update(['payroute_id'=>$payroute_id,'payroute_level'=>$payroute_level]);
        
        // H5支付返回支付链接
        
        return $result;
    } 
    
    // 付款码支付
    public static function micropay($params){
        $res = self::checkParams();
        if($res['code'] != 1){
            return $res;
        }
        $config = $res['data'];
        
        $data = array(
            "out_trade_no"=>$params['order_trade_no'],
            "total_amount"=>$params['fee'],
            "subject"=>$params['title'],
            "auth_code"=>$params['auth_code'],
            "scene"=>"bar_code"
        );
        
        $Apay = new Apay($config);
        
        $result = $Apay->unifiedConnect("AlipayTradePayRequest",$data);
        
        if($result['code'] == 1){
            
        }
        
        return $result;
    }
    
    // 退款
    public static function refund($params){
        $pay_order = Db::name("bbfx_pay_order")->where(['uniacid'=>UNIACID,'order_trade_no'=>$params['order_trade_no']])->find();
        $payroute_level = -1;
        if(!empty($pay_order)){
            $payroute_level = $pay_order['payroute_level'];
        }
        $res = self::checkParams($params['platform'],$payroute_level);
        if($res['code'] != 1){
            return $res;
        }
        $config = $res['data'];
        
        $data = array(
            "out_trade_no"=>$params['order_trade_no'],
            "refund_amount"=>$params['refund_fee'],
            "refund_reason"=>$params['refund_reason'],
            "out_request_no"=>$params['out_refund_no']
        );
        
        $Apay = new Apay($config);
        
        $result = $Apay->unifiedConnect("AlipayTradeRefundRequest",$data);
        
        if($result['code'] == 1){
            
        }
        
        return $result;
    }
    
    // 订单查询
    public static function orderQuery($params){
        $res = self::checkParams($params['platform'],$params['level']);
        if($res['code'] != 1){
            return $res;
        }
        $config = $res['data'];
        
        $data = array(
            "out_trade_no"=>$params['out_trade_no']
        );
        
        $Apay = new Apay($config);
        
        $result = $Apay->unifiedConnect("AlipayTradeQueryRequest",$data);
        
        return $result;
    }
    
    // 验证签名
    public static function payVerify($params){

        $pay_order = Db::name("bbfx_pay_order")->where(['uniacid'=>UNIACID,'order_trade_no'=>$params['out_trade_no']])->find();
        $payroute_level = -1;
        if(!empty($pay_order)){
            $payroute_level = $pay_order['payroute_level'];
        }
        
        $res = self::checkParams('H5',$payroute_level);
        if($res['code'] != 1){
            return $res;
        }
        $config = $res['data'];
        
        $Apay = new Apay($config);
        
        $Aop = $Apay->AopCertClient();
        $result = $Aop->rsaCheckV1($params, $config['zfb_publickey_cert'], $params['sign_type']);
        
        if(!$result){
            $res = self::orderQuery(['out_trade_no'=>$params['out_trade_no'],'platform'=>'H5','level'=>$payroute_level]);
            // echo "<pre>";
            // print_r($res);die;
            if($res['code'] == 1){
                if($res['data']['trade_status'] == 'TRADE_SUCCESS'){
                    $result = true;
                }
            }
        }
        
        if($result){
            return __json(1,"签名验证成功",$params);
        }
        else{
            return __json(0,"签名验证失败");
        }
    }
}