<?php
//https://ciyon.local.ciy.cn/ajax/ambap/wxpay.pay_pnt
//https://ciyon.local.ciy.cn/ajax/ambap/wxpay.transfer
namespace web\ambap;

class wxpay {
    public static function json_charge() {
        global $db;
        $msg = file_get_contents('php://input');
        savelogfile('wxpay_charge', '', true);
        if (empty($msg))
            $msg = '{"id":"601ce864-430c-5dc6-bb14-99ba0e75092a","create_time":"2025-06-18T00:55:47+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"tWglulTGTqVaw5FkYXOoAlksz62KOC3726nN0EFkCHXV4mWARk+k5sVhmnglBUG5RO+JLRcADO+xY1fX2kP2wrk7YOAGstM2SQfnoxzlur1HmnWtIamBQ+38UnsH+mi0a4WGMsMDIgqa1YmvklXrlsiS5DXVxYF13tvlXGDeM8atLFprGPs50lSYz6x0XfobMMaiM3S37BE574QDFMTuEaKQkA9P0AkQIQ4LvHTAzg1qZuaJ5uly7Zs+ViMEF9bG7l808cG2/jNtrG8Nu9VD3GyjRTUPX+OnHjWnwuBF+XRpDSLUioophdK0fGvC5Z7wJg1PpJYkTm5m4Fk93i9ao3d8uY7oV8ekQ3GpD+JlJzCoPk30cPC9+UyxiupvvJJK50AzsyXwZ7BU4YIvXEjBUJstcntb5gTFgaICKQCqpIgSKgcrVkDdb8i3IuA17Z1wAJqJQdknx6eLVuelwxbISEtL8v+a9moCjsRPqzJ7HTOkxcujh+SWSftx2f9MEKOxIem1HLr0t4zhVDqwx2Hgnk+YoLdXQ3CdJNXk4435H403gUeNwuAOpemy","associated_data":"transaction","nonce":"Vw6lMyykEja3"}}';

        $json = json_decode($msg, true);
        if ($json === null)
            return self::errlog('回调JSON出错:' . $msg);
        if (@$json['event_type'] != 'TRANSACTION.SUCCESS')
            return self::errlog('支付失败:' . $msg);
        $wxcfg = gettoken($db, 1);
        $aesKey         = $wxcfg['v3key']; //v3秘钥
        $associatedData = $json['resource']['associated_data'];
        $nonceStr       = $json['resource']['nonce'];
        $ciphertext     = $json['resource']['ciphertext'];
        $dat = \sodium_crypto_aead_aes256gcm_decrypt(base64_decode($ciphertext), $associatedData, $nonceStr, $aesKey);
        //clog($dat);
        //{"mchid":"1521600371","appid":"wx04060908b8fb3341","out_trade_no":"E2049007187","transaction_id":"4200002494202412238883646214","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"87,1,oUlwX5Tv9jYjlENyvCFQtMrmT3Ok","success_time":"2024-12-23T06:44:43+08:00","payer":{"openid":"oUlwX5Tv9jYjlENyvCFQtMrmT3Ok"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}
        if ($dat === false)
            return self::errlog('解析密文出错:' . $msg);
        $json = json_decode($dat, true);
        if ($json === null)
            return self::errlog('解析密文JSON出错:' . $dat);
        if (@$json['trade_state'] != 'SUCCESS')
            return self::errlog('支付失败:' . $dat);
        $noid = toint(substr($json['out_trade_no'], 9));
        $csql = new \ciy\sql('ap_cash_in');
        $csql->where('id', $noid);
        $orderrow = $db->getone($csql);
        if (!is_array($orderrow))
            return self::errlog('订单不存在:' . $noid);
        $userid = $orderrow['vuser'];
        $inmoney = toint($orderrow['inmoney']);
        if ($inmoney != $json['amount']['total'])
            return self::errlog('订单金额错误[' . $inmoney . '!=' . $json['amount']['total'] . ']:' . $noid, $userid);
        if ($orderrow['paytimes'] > 0) {
            savelogfile('wxpay_charge', '已充值[' . $noid . ']');
            return succjson();
        }

        try {
            $db->begin();
            $updata = array();
            $updata['name'] = $json['transaction_id'];
            $updata['paytimes'] = tostamp();
            $csql = new \ciy\sql('ap_cash_in');
            $csql->where('id', $noid);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新ap_cash_in失败:' . $db->error);
            //sendusermsg($db, $orderrow['userid'], '集市通知', '买家已付款，请及时处理', '/work/ec/order_detail?id=' . $noid);

            $updata = array();
            $updata['cashietype'] = 10;
            $updata['iemoney'] = $inmoney;
            $updata['vuser'] = $userid;
            $updata['name'] = '在线充值';
            $updata['addtimes'] = tostamp();
            $csql = new \ciy\sql('ap_cash_ie');
            if ($db->insert($csql, $updata) === false)
                throw new \Exception('新建消费收支失败:' . $db->error);
            $updata = array();
            $updata['mymoney'] = array('mymoney+' . $inmoney);
            $updata['myinvmoney'] = array('myinvmoney+' . $inmoney);
            $csql = new \ciy\sql('ap_user');
            $csql->where('id', $userid);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新ap_user失败:' . $db->error);
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return self::errlog($ex->getMessage(), $userid);
        }
        savelogfile('wxpay_charge', '成功充值[' . $noid . ']');
        return succjson();
    }
    public static function json_transfer() {
        global $db;
        $msg = file_get_contents('php://input');
        savelogfile('wxpay_pnt_transfer', '', true);
        if (empty($msg))
            $msg = '{"id":"0f99407d-4233-55af-800d-4903053961de","create_time":"2025-03-25T03:23:33+08:00","resource_type":"encrypt-resource","event_type":"MCHTRANSFER.BILL.FINISHED","summary":"商家转账单据终态通知","resource":{"original_type":"mch_payment","algorithm":"AEAD_AES_256_GCM","ciphertext":"34JXsWOjxPjMBoW8xugqnZTslV/DrcLp7IebMmnlt/kezwvr7m+ifyn/spXAMCFQhODJ0pZvklcyGuY+vL7T17pY15mjnqbx3A82n0m2e0NTgd0R/kU8FO2C0tKGVDZZ+fJiFDcpmbjX8DZqvIzku6aTMbAZxnL6V+0dd5jrOV70BsmfjIDPpKGbOuVmjl/9PWe8k14IGUP/JWdcTWnceiRyPH4Heym2EcsxeVoRLcoQsFxyfqUq8238GnvxnxTEZPnRVLPdOa5PTry48U+A0cS8rrwU4kDpRbZTVP1KcdtLRLCiNtJahD4kRmQLkHN4Aju2mlS5d9ZwJ47QSiS8XntCJpaFE7dJIEWlTq68vwLfPi6ylAoprSzr/SAUbCxAsvBaTE3KeXGnsHozNBC+R6a8","associated_data":"mch_payment","nonce":"TrFY18YTTNfj"}}';

        $json = json_decode($msg, true);
        if ($json === null)
            return self::errlog('回调JSON出错:' . $msg);
        if (@$json['event_type'] != 'MCHTRANSFER.BILL.FINISHED')
            return self::errlog('付款失败:' . $msg);
        $wxcfg = gettoken($db, 1);
        $aesKey         = $wxcfg['v3key']; //v3秘钥
        $associatedData = $json['resource']['associated_data'];
        $nonceStr       = $json['resource']['nonce'];
        $ciphertext     = $json['resource']['ciphertext'];
        $dat = \sodium_crypto_aead_aes256gcm_decrypt(base64_decode($ciphertext), $associatedData, $nonceStr, $aesKey);
        //clog($dat);
        //{"mchid":"1521600371","appid":"wx04060908b8fb3341","out_trade_no":"E2049007187","transaction_id":"4200002494202412238883646214","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"87,1,oUlwX5Tv9jYjlENyvCFQtMrmT3Ok","success_time":"2024-12-23T06:44:43+08:00","payer":{"openid":"oUlwX5Tv9jYjlENyvCFQtMrmT3Ok"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}
        if ($dat === false)
            return self::errlog('解析密文出错:' . $msg);
        $json = json_decode($dat, true);
        if ($json === null)
            return self::errlog('解析密文JSON出错:' . $dat);

        if (@$json['state'] != 'SUCCESS')
            return self::errlog('付款失败:' . $dat);
        $noid = (int)substr($json['out_bill_no'], 9);

        $csql = new \ciy\sql('ap_cash_out');
        $csql->where('id', $noid);
        $orderrow = $db->getone($csql);
        if (!is_array($orderrow))
            return self::errlog('订单不存在:' . $noid);
        $userid = $orderrow['vuser'];
        $cashmoney = toint($orderrow['cashmoney']/100);
        if ($cashmoney != $json['transfer_amount'])
            return self::errlog('订单金额错误[' . $cashmoney . '!=' . $json['transfer_amount'] . ']:' . $noid, $userid);
        if ($orderrow['cashstatus'] == 100) {
            savelogfile('wxpay_pnt', '已付款[' . $noid . ']');
            return succjson();
        }

        try {
            $db->begin();
            $updata = array();
            $updata['cashtimes'] = tostamp();
            $updata['cashno'] = $json['transfer_bill_no'];
            $updata['cashstatus'] = 100;
            $csql = new \ciy\sql('ap_cash_out');
            $csql->where('id', $noid);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新ap_cash_out失败:' . $db->error);
            //sendusermsg($db, $orderrow['userid'], '集市通知', '买家已付款，请及时处理', '/work/ec/order_detail?id=' . $noid);

            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            return self::errlog($ex->getMessage(), $userid);
        }
        savelogfile('wxpay_pnt', '成功提现[' . $noid . ']');
        return succjson();
    }
    public static function json_pay_pnt() {
        global $db;
        $msg = file_get_contents('php://input');
        savelogfile('wxpay_pnt', '', true);
        if (empty($msg))
            $msg = '{"id":"07d610d5-ca44-58a1-a18a-430c6a91360d","create_time":"2025-01-27T07:25:29+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"JHppfFEjJ9MApZ14on/BuyHuGbuVaGzCjQJR38DL/yQ55Ksg4e6JtWCCm6mvqShMMnwri+SyG9XFE/0WzeXcktK6gPQ/tb5uMxq9L3Q5Hgw9YMyrwP3ZW7y0QmiHSXESNQs9203Az8h1NkWLtIgNzLMFnJirNuUaQ4nhtyLp0aBmh2k6IEpmmE4kZ60OVeuFAeOjkYFez4P5IB8KKQ/2eevq/OCiPmlwWb4OpMIvzK5b+Weji1RnL2C1eL8nrUbowy0y0jdySh9jg2qJ/ey1wc3EpbeasROOTRkIcyV7bCFqc0ET/0THdjfxUS+yI352MTXdhDyEQkG9D7Q+fkA/Z/6ukWqp36vtFX5MZMA5bBj0p3TTcc7Pt2eQXFj572CWJybAU7xBKqDjoOlvJZVJaRXhMPJbQf7DbGXmQvNeV+geJIOkbaF6loyxQIYjyWJSJfa1qbnNpXZXkTFus8VEqtZ1G5cXCLxqra25eijv9WRpGrO+GImByTJzCUHMwa579xB7eyPdG0YxoEF2+BITgZnu9MmtCq8GxrOUrXcCsiN+tX9cbxGuLIA=","associated_data":"transaction","nonce":"pitvzETSu49Y"}}';

        $json = json_decode($msg, true);
        if ($json === null)
            return self::errlog('回调JSON出错:' . $msg);
        if (@$json['event_type'] != 'TRANSACTION.SUCCESS')
            return self::errlog('支付失败:' . $msg);
        $wxcfg = gettoken($db, 1);
        $aesKey         = $wxcfg['v3key']; //v3秘钥
        $associatedData = $json['resource']['associated_data'];
        $nonceStr       = $json['resource']['nonce'];
        $ciphertext     = $json['resource']['ciphertext'];
        $dat = \sodium_crypto_aead_aes256gcm_decrypt(base64_decode($ciphertext), $associatedData, $nonceStr, $aesKey);
        //clog($dat);
        //{"mchid":"1521600371","appid":"wx04060908b8fb3341","out_trade_no":"E2049007187","transaction_id":"4200002494202412238883646214","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"87,1,oUlwX5Tv9jYjlENyvCFQtMrmT3Ok","success_time":"2024-12-23T06:44:43+08:00","payer":{"openid":"oUlwX5Tv9jYjlENyvCFQtMrmT3Ok"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}
        if ($dat === false)
            return self::errlog('解析密文出错:' . $msg);
        $json = json_decode($dat, true);
        if ($json === null)
            return self::errlog('解析密文JSON出错:' . $dat);
        if (@$json['trade_state'] != 'SUCCESS')
            return self::errlog('支付失败:' . $dat);
        $noid = (int)substr($json['out_trade_no'], 9);

        $csql = new \ciy\sql('ap_pnt_buy');
        $csql->where('id', $noid);
        $orderrow = $db->getone($csql);
        if (!is_array($orderrow))
            return self::errlog('订单不存在:' . $noid);
        $userid = $orderrow['vuser'];
        $buypntmoney = (int)$orderrow['buypntmoney'];
        if ($buypntmoney != $json['amount']['total'])
            return self::errlog('订单金额错误[' . $buypntmoney . '!=' . $json['amount']['total'] . ']:' . $noid, $userid);
        if ($orderrow['paytimes'] > 0) {
            savelogfile('wxpay_pnt', '已支付[' . $noid . ']');
            return succjson();
        }

        try {
            $db->begin();
            $updata = array();
            $updata['name'] = $json['transaction_id'];
            $updata['paytimes'] = tostamp();
            $csql = new \ciy\sql('ap_pnt_buy');
            $csql->where('id', $noid);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新ap_pnt_buy失败:' . $db->error);
            //sendusermsg($db, $orderrow['userid'], '集市通知', '买家已付款，请及时处理', '/work/ec/order_detail?id=' . $noid);

            $pnt = (int)$orderrow['pnt'];
            $updata = array();
            $updata['mypnt'] = array('mypnt+' . $pnt);
            $updata['myinvmoney'] = array('myinvmoney+' . $buypntmoney);
            $csql = new \ciy\sql('ap_user');
            $csql->where('id', $userid);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新ap_user失败:' . $db->error);
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return self::errlog($ex->getMessage(), $userid);
        }
        savelogfile('wxpay_pnt', '成功支付[' . $noid . ']');
        return succjson();
    }
    public static function json_pay() {
        global $db;
        $msg = file_get_contents('php://input');
        savelogfile('wxpay_user', '', true);
        if (empty($msg))
            $msg = '{"id":"07d610d5-ca44-58a1-a18a-430c6a91360d","create_time":"2025-01-27T07:25:29+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"JHppfFEjJ9MApZ14on/BuyHuGbuVaGzCjQJR38DL/yQ55Ksg4e6JtWCCm6mvqShMMnwri+SyG9XFE/0WzeXcktK6gPQ/tb5uMxq9L3Q5Hgw9YMyrwP3ZW7y0QmiHSXESNQs9203Az8h1NkWLtIgNzLMFnJirNuUaQ4nhtyLp0aBmh2k6IEpmmE4kZ60OVeuFAeOjkYFez4P5IB8KKQ/2eevq/OCiPmlwWb4OpMIvzK5b+Weji1RnL2C1eL8nrUbowy0y0jdySh9jg2qJ/ey1wc3EpbeasROOTRkIcyV7bCFqc0ET/0THdjfxUS+yI352MTXdhDyEQkG9D7Q+fkA/Z/6ukWqp36vtFX5MZMA5bBj0p3TTcc7Pt2eQXFj572CWJybAU7xBKqDjoOlvJZVJaRXhMPJbQf7DbGXmQvNeV+geJIOkbaF6loyxQIYjyWJSJfa1qbnNpXZXkTFus8VEqtZ1G5cXCLxqra25eijv9WRpGrO+GImByTJzCUHMwa579xB7eyPdG0YxoEF2+BITgZnu9MmtCq8GxrOUrXcCsiN+tX9cbxGuLIA=","associated_data":"transaction","nonce":"pitvzETSu49Y"}}';

        $json = json_decode($msg, true);
        if ($json === null)
            return self::errlog('回调JSON出错:' . $msg);
        if (@$json['event_type'] != 'TRANSACTION.SUCCESS')
            return self::errlog('支付失败:' . $msg);
        $wxcfg = gettoken($db, 1);
        $aesKey         = $wxcfg['v3key']; //v3秘钥
        $associatedData = $json['resource']['associated_data'];
        $nonceStr       = $json['resource']['nonce'];
        $ciphertext     = $json['resource']['ciphertext'];
        $dat = \sodium_crypto_aead_aes256gcm_decrypt(base64_decode($ciphertext), $associatedData, $nonceStr, $aesKey);
        //clog($dat);
        //{"mchid":"1521600371","appid":"wx04060908b8fb3341","out_trade_no":"E2049007187","transaction_id":"4200002494202412238883646214","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"87,1,oUlwX5Tv9jYjlENyvCFQtMrmT3Ok","success_time":"2024-12-23T06:44:43+08:00","payer":{"openid":"oUlwX5Tv9jYjlENyvCFQtMrmT3Ok"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}
        if ($dat === false)
            return self::errlog('解析密文出错:' . $msg);
        $json = json_decode($dat, true);
        if ($json === null)
            return self::errlog('解析密文JSON出错:' . $dat);
        if (@$json['trade_state'] != 'SUCCESS')
            return self::errlog('支付失败:' . $dat);
        $noid = toint(substr($json['out_trade_no'], 9));

        $csql = new \ciy\sql('ap_usr_buy_user');
        $csql->where('id', $noid);
        $orderrow = $db->getone($csql);
        if (!is_array($orderrow))
            return self::errlog('订单不存在:' . $noid);
        $userid = $orderrow['vuser'];
        $csql = new \ciy\sql('ap_user');
        $csql->where('id', $userid);
        $userrow = $db->getone($csql);
        if (!is_array($userrow))
            return self::errlog('用户不存在:' . $userid);
        $money = toint($orderrow['buydaymoney']);
        if ($money != $json['amount']['total'])
            return self::errlog('订单金额错误[' . $money . '!=' . $json['amount']['total'] . ']:' . $noid, $userid);
        if ($orderrow['paytimes'] > 0) {
            savelogfile('wxpay_user', '已支付[' . $noid . ']');
            return succjson();
        }

        try {
            $db->begin();
            $updata = array();
            $updata['paytimes'] = tostamp();
            $csql = new \ciy\sql('ap_usr_buy_user');
            $csql->where('id', $noid);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新ap_usr_buy_user失败:' . $db->error);

            $days = toint($orderrow['days']);
            if($userrow['accounttimes'] < tostamp())
                $userrow['accounttimes'] = tostamp();
            $updata = array();
            $updata['userlevel'] = $orderrow['userlevel'];
            $updata['myinvmoney'] = array('myinvmoney+' . $money);
            $updata['accounttimes'] = $userrow['accounttimes'] + $days * 86400;
            $csql = new \ciy\sql('ap_user');
            $csql->where('id', $userid);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新ap_user失败:' . $db->error);
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return self::errlog($ex->getMessage(), $userid);
        }
        savelogfile('wxpay_user', '成功支付[' . $noid . ']');
        return succjson();
    }
    static function errlog($errmsg, $user = 0) {
        global $db;
        savelog($db, $user, 'PAY_PNT', $errmsg);
        $ret = array();
        $ret['code'] = 0;
        $ret['errmsg'] = $errmsg;
        return $ret;
    }
}
