<?php
namespace app\common\controller;
use think\facade\Db;
class Results extends Base
{

    /**
     * [__construct 构造函数]
     * @return [type] [description]
     */
    public function __construct(){
        parent::__construct();
    }
    /**
     * 微信支付回调
     */
    public function appWxpayRedirect()
    {
        //接收参数
        $post = file_get_contents("php://input");
        if(!$post){echo "<xml> <return_code><![CDATA[FAIL]]></return_code> <return_msg><![CDATA[非法请求]]></return_msg> </xml>";die;}
        $postObj = simplexml_load_string($post, 'SimpleXMLElement', LIBXML_NOCDATA);
        $data = json_decode(json_encode($postObj),true);
        $path=CUSTOM_LOG.'/appWxpayRedirects/';
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        $paths=CUSTOM_LOG.'/appWxpayServices/';
        if (!file_exists($paths)) {
            mkdir($paths, 0777, true);
        }
        file_put_contents($path.date('Ymd').'.log',json_encode($data,JSON_UNESCAPED_UNICODE)."\r\n",FILE_APPEND);
        $xmlObj=$data;
        if(Db::name('wxpayNotify')->where('out_trade_no',$data['out_trade_no'])->count()){
            echo "<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg> </xml>";
            file_put_contents($paths.$data['out_trade_no'].'.log',"重复推送，已拦截\n",FILE_APPEND);
            die;
        }
        //判断是否成功
        if (is_array($data) && $data['return_code'] == 'SUCCESS')
        {
            foreach( $xmlObj as $k=>$v) {
                if($k == 'sign') {
                    $xmlSign = $xmlObj[$k];
                    unset($xmlObj[$k]);
                };
            }
 
            $sign = http_build_query($xmlObj);
            //md5处理
            $sign = md5($sign.'&key='.config('wxpay.key'));
            //转大写
            $sign = strtoupper($sign);
 
            //验签名。默认支持MD5
            if ( $sign === $xmlSign) {
                //参数实例
                $ordersn = $data['out_trade_no'];
                $insertData=[
                    'appid'             =>  $data['appid'],
                    'bank_type'         =>  $data['bank_type'],
                    'cash_fee'          =>  $data['cash_fee'],
                    'fee_type'          =>  $data['fee_type'],
                    'is_subscribe'      =>  $data['is_subscribe'],
                    'mch_id'            =>  $data['mch_id'],
                    'nonce_str'         =>  $data['nonce_str'],
                    'openid'            =>  $data['openid'],
                    'out_trade_no'      =>  $data['out_trade_no'],
                    'result_code'       =>  $data['result_code'],
                    'return_code'       =>  $data['return_code'],
                    'sign'              =>  $data['sign'],
                    'time_end'          =>  $data['time_end'],
                    'total_fee'         =>  $data['total_fee'],
                    'trade_type'        =>  $data['trade_type'],
                    'transaction_id'    =>  $data['transaction_id'],
                    'status'    		=>  $ordersn=='20191204164729239418'?1:0,
                    'create_time'       =>  time()
                ];
                //启动事务
                Db::startTrans();
                try {
                    Db::name('wxpayNotify')->insert($insertData);
                    Db::name('orders')->where(['otrade'=>$ordersn])->update(['status'=>1,'pay_type'=>2,'pay_time'=>time()]);
                    // 提交事务
                    Db::commit();
                    echo "<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg> </xml>";
                } catch (Exception $e) {
                    //回滚事务
                    Db::rollback();
                    echo "<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[ERROR]]></return_msg> </xml>";
                }
            }else{
                file_put_contents($path.date('Ymd').'.log',"验证签名失败\r\n",FILE_APPEND);
            }
        }else{
            file_put_contents($path.date('Ymd').'.log',"支付失败\r\n",FILE_APPEND);
            echo "<xml> <return_code><![CDATA[FAIL]]></return_code> <return_msg><![CDATA[数据解析出错]]></return_msg> </xml>";die;
        }
        file_put_contents($path.date('Ymd').'.log',json_encode($data,JSON_UNESCAPED_UNICODE)."\r\n",FILE_APPEND);
    }
    /**
     * 支付宝回调
     */
    public function appAlipayRedirect()
    {
        $D=request()->post();
        if(!request()->isPost()){echo "error";die;}
        if(empty($D['sign'])){echo "error";die;}
        require_once(EXTEND_PATH.'alipay/AopSdk.php');
        /**
         * [$aop 验证支付宝订单信息]
         * @var [type]
         */
        $aop = new \AopClient;
        $alipayConfig=config('alipay.');
        $aop->alipayrsaPublicKey=$alipayConfig['alipayrsaPublicKey'];
        $flag=$aop->rsaCheckV1($D,NULL,"RSA2");
        /**
         * End;
         */
        $path=CUSTOM_LOG.'/appAlipayRedirects/';
        $paths=CUSTOM_LOG.'/appAlipayServices/';
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        if (!file_exists($paths)) {
            mkdir($paths, 0777, true);
        }
        $D['create_time']=time();
        file_put_contents($path.date('Ymd').'.log',json_encode($D,JSON_UNESCAPED_UNICODE)."\r\n",FILE_APPEND);
        file_put_contents($paths.$D['out_trade_no'].'.log',json_encode($D,JSON_UNESCAPED_UNICODE)."\r\n",FILE_APPEND);
        if(Db::name('alipayNotify')->where('out_trade_no',$D['out_trade_no'])->count()){
            echo "success";
            file_put_contents($paths.$D['out_trade_no'].'.log',"重复推送，已拦截\n",FILE_APPEND);
            die;
        }
        $insertData=[
            'gmt_create'        =>  $D['gmt_create'],
            'charset'           =>  $D['charset'],
            'seller_email'      =>  $D['seller_email'],
            'subject'           =>  $D['subject'],
            'sign'              =>  $D['sign'],
            'body'              =>  $D['body'],
            'buyer_id'          =>  $D['buyer_id'],
            'invoice_amount'    =>  $D['invoice_amount'],
            'notify_id'         =>  $D['notify_id'],
            'fund_bill_list'    =>  $D['fund_bill_list'],
            'notify_type'       =>  $D['notify_type'],
            'trade_status'      =>  $D['trade_status'],
            'receipt_amount'    =>  $D['receipt_amount'],
            'app_id'            =>  $D['app_id'],
            'buyer_pay_amount'  =>  $D['buyer_pay_amount'],
            'sign_type'         =>  $D['sign_type'],
            'seller_id'         =>  $D['seller_id'],
            'gmt_payment'       =>  $D['gmt_payment'],
            'notify_time'       =>  $D['notify_time'],
            'version'           =>  $D['version'],
            'out_trade_no'      =>  $D['out_trade_no'],
            'total_amount'      =>  $D['total_amount'],
            'trade_no'          =>  $D['trade_no'],
            'auth_app_id'       =>  $D['auth_app_id'],
            'buyer_logon_id'    =>  $D['buyer_logon_id'],
            'point_amount'      =>  $D['point_amount'],
            'create_time'       =>  time()
        ];
        //启动事务
        Db::startTrans();
        try {
            file_put_contents($paths.$D['out_trade_no'].'.log',"订单信息入库\n",FILE_APPEND);
            Db::name('alipayNotify')->insert($insertData);
            Db::name('orders')->where(['otrade'=>$D['out_trade_no']])->update(['status'=>1,'pay_type'=>1,'pay_time'=>time()]);
            // 提交事务
            Db::commit();
            echo "success";
        } catch (Exception $e) {
            //回滚事务
            Db::rollback();
            file_put_contents($path.date('Ymd').'.log',"插入数据库失败\n",FILE_APPEND);
            echo "error";
        }
    }
}
