<?php
/**
 *
 * example目录下为简单的支付样例，仅能用于搭建快速体验微信支付使用
 * 样例的作用仅限于指导如何使用sdk，在安全上面仅做了简单处理， 复制使用样例代码时请慎重
 * 请勿直接直接使用样例对外提供服务
 *
 **/
require_once "WxPay.Config.Interface.php";

/**
 *
 * 该类需要业务自己继承， 该类只是作为deamon使用
 * 实际部署时，请务必保管自己的商户密钥，证书等
 *
 */

use think\facade\Db;
use think\facade\Log;

class WxPayConfig extends WxPayConfigInterface
{


    private $AppId = '';
    private $MerchantId = '';
    private $Key = '';
    private $AppSecret = '';
    private $ServicePay = 0;
    private $UnionPay = 0;
    private $PayAccountPay = 0;
    private $SubAppId = '';
    private $IsTransfers = 0;
    private $SubMerchantId = '';
    private $PayType = 1;
    private $CertType = 1; // 1:微信小程序 2:公众号 3/H5 4/服务商支付 5/企业微信 6/银联支付 7/多账号支付
    private $MchId = 1;
    private $SignType = 'HMAC-SHA256';

    function __construct()
    {
        $mch_id = isset($GLOBALS['mch_id'])?$GLOBALS['mch_id']:0;
        $pay_type = isset($GLOBALS['pay_type'])?$GLOBALS['pay_type']:0;
        $platform = isset($GLOBALS['platform'])?$GLOBALS['platform']:0;
        $is_transfers = isset($GLOBALS['is_transfers']) ? $GLOBALS['is_transfers'] : 0;
        $agent_id = isset($GLOBALS['agent_id']) ? $GLOBALS['agent_id'] : 0;
        $config = Db::name('miniapp_config')->where(['mch_id' => $mch_id, 'type' => $platform])->find();
        $config_base = json_decode($config['base'], true);
        if($agent_id>0){
            $condition['mch_id'] = $mch_id;
            $condition['config_key'] = 'pay_setting'.$agent_id;
            $info = Db::name('sys_config')
                ->where($condition)
                ->find();
            if (empty($info)) {
                $config_pay = ['WxAppId'=>'', 'WxAppSecret'=>'', 'WxMerchantId'=>'', 'WxKey'=>'', 'WxAppId'=>''];
            }else{
                $pay = json_decode($info['config_value'], true);
                $config_pay = isset($pay['pay']) ? $pay['pay'] : ['WxAppId'=>'', 'WxAppSecret'=>'', 'WxMerchantId'=>'', 'WxKey'=>'', 'WxAppId'=>''];
            }
        }else{
            $config_pay = json_decode($config['pay'], true);
        }

        $moduleSwitch = new \iyibai\services\SystemService();
        $is_open = $moduleSwitch->getAddonsStatus($mch_id, 'yb_plugin_service_pay');
        if ($is_open != 0) {
            $this->ServicePay = 1;
        }
        if ($platform == 0) {
            //微信小程序银联支付
            $is_open = $moduleSwitch->getAddonsStatus($mch_id, 'yb_plugin_unionpay');
            if ($is_open != 0) {
                $this->UnionPay = 1;
            }
            //微信小程序多账户支付
            $is_open = $moduleSwitch->getAddonsStatus($mch_id, 'yb_plugin_pay_account');
            if ($is_open != 0) {
                $pay_type = 7;
                $this->PayAccountPay = 1;
            }
        }
        $this->PayType = $pay_type;
        $this->MchId = $mch_id;
        $this->IsTransfers = $is_transfers;
        if ($pay_type == 1) {
            //微信小程序
            $this->AppId = $config_base['APP_ID'];
            $this->AppSecret = $config_base['APP_SECRET'];
            $this->MerchantId = $config_pay['MerchantId'];
            $this->Key = $config_pay['Key'];
            $this->SubAppId = $config_base['APP_ID'];
        } else if ($pay_type == 2) {
            //微信公众号
            $this->AppId = $config_base['appid'];
            $this->AppSecret = $config_base['secret'];
            $this->MerchantId = $config_pay['MerchantId'];
            $this->Key = $config_pay['Key'];
            $this->SubAppId = $config_base['appid'];
        } else if ($pay_type == 3) {
            //H5支付
            $this->AppId = $config_pay['WxAppId'];
            $this->MerchantId = $config_pay['WxMerchantId'];
            $this->Key = $config_pay['WxKey'];
            $this->SubAppId = $config_pay['WxAppId'];
        } else if ($pay_type == 4) {
            //APP支付
            $this->AppId = $config_pay['WxAppId'];
            $this->MerchantId = $config_pay['WxMerchantId'];
            $this->Key = $config_pay['WxKey'];
            $this->SubAppId = $config_pay['WxAppId'];
        } else if ($pay_type == 5) {
            //pc商城支付
            $this->AppId = $config_pay['WxAppId'];
            $this->AppSecret = $config_pay['WxAppSecret'];
            $this->MerchantId = $config_pay['WxMerchantId'];
            $this->Key = $config_pay['WxKey'];
            $this->SubAppId = $config_pay['WxAppId'];
        } else if ($pay_type == 6) {
            //当面付
            $shop_config = Db::name('sys_config')->where(['mch_id' => $mch_id, 'config_key' => 'MICRO_PAY'])->find();
            $value = json_decode($shop_config['config_value'], true);
            $this->AppId = $value['WxAppId'];
            $this->AppSecret = $value['WxAppSecret'];
            $this->MerchantId = $value['WxMerchantId'];
            $this->Key = $value['WxKey'];
            $this->SubAppId = $value['WxAppId'];
        } else if ($pay_type == 7) {
            //多账户收款
            $info = Db::name('pay_account')->where(['mch_id' => $mch_id, 'type' => $this->IsTransfers == 0 ? 1 : 2, 'status' => 1, 'delete_time' => 0])->field('account_message')->find();
            $this->AppId = $config_base['APP_ID'];
            $this->AppSecret = $config_base['APP_SECRET'];
            $this->SubAppId = $config_base['APP_ID'];
            if ($info) {
                $value = json_decode($info['account_message'], true);
                $this->MerchantId = $value['WxMerchantId'];
                $this->Key = $value['WxKey'];
            } else {
                $this->MerchantId = $config_pay['MerchantId'];
                $this->Key = $config_pay['Key'];
            }
        }
        //退款证书
        $this->CertType = $pay_type;
        if ($platform == 7) {
            //企业微信退款取企业微信退款证书
            $this->CertType = 5;
        }
        if ($platform == 10) {
            //pc商城支付
            $this->CertType = 10;
        } else {
            if ($this->ServicePay == 1 && $pay_type != 6 && $pay_type != 7) {
                //服务商支付
                $shop_config = Db::name('sys_config')->where(['mch_id' => $mch_id, 'config_key' => 'SERVICE_PAY'])->find();
                $value = json_decode($shop_config['config_value'], true);
                $this->AppId = $value['AppId'];
                $this->MerchantId = $value['MerchantId'];
                $this->Key = $value['Key'];
                $this->SubMerchantId = $value['SubMerchantId'];
                $this->CertType = 4;
            }
        }

        if ($this->UnionPay == 1 && $pay_type != 6 && $pay_type != 7) {
            //银联支付
            $shop_config = Db::name('sys_config')->where(['mch_id' => $mch_id, 'config_key' => 'UNION_PAY'])->find();
            $value = json_decode($shop_config['config_value'], true);
            $this->SubAppId = $value['AppId'];
            $this->MerchantId = $value['MerchantId'];
            $this->Key = $value['Key'];
        }
    }
    //=======【基本信息设置】=====================================

    /**
     * TODO: 修改这里配置为您自己申请的商户信息
     * 微信公众号信息配置
     *
     * APPID：绑定支付的APPID（必须配置，开户邮件中可查看）
     *
     * MCHID：商户号（必须配置，开户邮件中可查看）
     *
     */
    public function GetAppId()
    {
        return $this->AppId;
    }

    public function GetMerchantId()
    {
        return $this->MerchantId;
    }

    //=======【支付相关配置：支付成功回调地址/签名方式】===================================

    /**
     * TODO:支付回调url
     * 签名和验证签名方式， 支持md5和sha256方式
     **/
    public function GetNotifyUrl()
    {
        return get_localhost_domain(false, true, true) . '/extend/Wxpay/notify_wx.php';
    }

    public function SetSignType($sign_type)
    {
        $this->SignType = $sign_type;
        return $sign_type;
    }

    public function GetSignType()
    {
        return $this->SignType;
    }

    //=======【curl代理设置】===================================

    /**
     * TODO：这里设置代理机器，只有需要代理的时候才设置，不需要代理，请设置为0.0.0.0和0
     * 本例程通过curl使用HTTP POST方法，此处可修改代理服务器，
     * 默认CURL_PROXY_HOST=0.0.0.0和CURL_PROXY_PORT=0，此时不开启代理（如有需要才设置）
     * @var unknown_type
     */
    public function GetProxy(&$proxyHost, &$proxyPort)
    {
        $proxyHost = "0.0.0.0";
        $proxyPort = 0;
    }


    //=======【上报信息配置】===================================

    /**
     * TODO：接口调用上报等级，默认紧错误上报（注意：上报超时间为【1s】，上报无论成败【永不抛出异常】，
     * 不会影响接口调用流程），开启上报之后，方便微信监控请求调用的质量，建议至少
     * 开启错误上报。
     * 上报等级，0.关闭上报; 1.仅错误出错上报; 2.全量上报
     * @var int
     */
    public function GetReportLevenl()
    {
        return 1;
    }


    //=======【商户密钥信息-需要业务方继承】===================================
    /*
     * KEY：商户支付密钥，参考开户邮件设置（必须配置，登录商户平台自行设置）, 请妥善保管， 避免密钥泄露
     * 设置地址：https://pay.weixin.qq.com/index.php/account/api_cert
     *
     * APPSECRET：公众帐号secert（仅JSAPI支付的时候需要配置， 登录公众平台，进入开发者中心可设置）， 请妥善保管， 避免密钥泄露
     * 获取地址：https://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&token=2005451881&lang=zh_CN
     * @var string
     */
    public function GetKey()
    {
        return $this->Key;
    }

    public function GetAppSecret()
    {
        return $this->AppSecret;
    }

    public function GetSubAppId()
    {
        return $this->SubAppId;
    }

    public function GetSubMerchantId()
    {
        return $this->SubMerchantId;
    }

    public function GetServicePay()
    {
        return $this->ServicePay;
    }

    //=======【证书路径设置-需要业务方继承】=====================================

    /**
     * TODO：设置商户证书路径
     * 证书路径,注意应该填写绝对路径（仅退款、撤销订单时需要，可登录商户平台下载，
     * API证书下载地址：https://pay.weixin.qq.com/index.php/account/api_cert，下载之前需要安装商户操作证书）
     * 注意:
     * 1.证书文件不能放在web服务器虚拟目录，应放在有访问权限控制的目录中，防止被他人下载；
     * 2.建议将证书文件名改为复杂且不容易猜测的文件名；
     * 3.商户服务器要做好病毒和木马防护工作，不被非法侵入者窃取证书文件。
     * @var path
     */
    public function GetSSLCertPath(&$sslCertPath, &$sslKeyPath)
    {
        if ($this->CertType == 7) {
            $sslCertPath = ROOT_PATH . 'extend/Wxpay/cert/' . $this->CertType . '/apiclient_cert_' . $this->MerchantId . '.pem';
            $sslKeyPath = ROOT_PATH . 'extend/Wxpay/cert/' . $this->CertType . '/apiclient_key_' . $this->MerchantId . '.pem';
        } else {
            $sslCertPath = ROOT_PATH . 'extend/Wxpay/cert/' . $this->CertType . '/apiclient_cert_' . $this->MchId . '.pem';
            $sslKeyPath = ROOT_PATH . 'extend/Wxpay/cert/' . $this->CertType . '/apiclient_key_' . $this->MchId . '.pem';
        }

    }
}
