<?php
/**
 * User: 呆呆
 * Agreement: 禁止使用本软件（系统）用于任何违法违规业务或项目,造成的任何法律后果允由使用者（或运营者）承担
 * Date: 2024/11/24
 * Time: 18:58
 */
namespace app\common\Usdt\controller;//跟目录路径一样

class Index
{
    /**************************核心控制器（不可修改）**************************/
    
    static public $config = [
		'name'        => 'Usdt', //插件标识【需和目录名称一致，不能有重复】
		'showname'    => 'USDT(trc20)', //插件名称
		'author'      => '呆呆', //插件作者
		'types'       => ['usdt'], //支付方式，可选的有alipay,qqpay,wxpay,bank
	];
    
    /**
	 * 检测心跳
	 */
    public function Cookie($Pay,$Json)
    {
        return Cookie_json($Pay,1,'不支持检测心跳');
    }
    
    /**
	 * 检测回调
	 */
    public function Status($Order,$Type,$Pay,$Json)
    {
        $data = [];
        $usdt = $Json['usdt'];
        $tdid = isset($Json['tdid']) ? intval($Json['tdid']) : 5;
        $list = self::transfers($usdt);
        if(is_array($list)){
            foreach ($list as $item) {
                // 检查交易时间是否在订单支付时间之前
				if(strtotime($Order['pay_time']) >= $item['time']){
					continue;
				}
				// 判断交易时间是否在付款时间内
				if (abs(strtotime($Order['pay_time']) - $item['time']) <= (60*$tdid)) {
                    $money = $Order['pay_json']['data']['money'];
					if($item['money'] == $money){
                        $data[] = $item;
                    }
				} else {
					continue;
				}
            }
        }
        if(empty($data)){
            return Status_json($Order,false,'交易失败');
        }else{
            return Status_json($Order,true,'交易成功');
        }
    }
    
    /**
	 * 异步回调
	 * 正确语法：processNotify($Order,$api_trade_no = '')
	 */
    public function Notify_url($Order,$Api,$Type,$Pay,$Json)
    {
        if(false == true){
            processNotify($Order,$api_trade_no = '');
            return 'success';
        }else{
            return 'fail';
        }
    }
    
    /**
	 * 同步回调
	 * 正确语法：success
	 */
    public function Return_url($Order,$Api,$Type,$Pay,$Json)
    {
        if(false == true){
            return 'success';
        }else{
            return 'fail';
        }
    }
    
    /**
	 * 拉起支付
	 */
	public function Exec($Order,$Api,$Type,$Pay,$Json)
    {
        if(empty($Json['pay'])){
            $header = array(
                'Host: www.528btc.com',
                'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36 Core/1.116.475.400 QQBrowser/13.5.6267.400',
                'Referer: https://www.528btc.com/coin/32675.html',
            );
            $cny = getSubstr(getSubstr(curl_get('https://www.528btc.com/coin/',$header), '泰达币</div>','<td>$'), '<td>￥','</td>');
        }else{
            $cny = $Json['cny'];
        }
        if(!is_numeric($cny)){
            return Pay_error('自动获取汇率模式失败，请切换手动填写模式!');
        }
        $Order['price'] = pay_price($Order,$Json['tdid']);
        $url = $Json['usdt'];
        $money = round($Order['price'] / $cny, 3);
        return Pay_success($Order,['type'=>'page','page'=>'usdt','data'=>['url'=>$url,'cny'=>$cny,'money'=>$money,'Json'=>$Json]]);
    }
    
    /**************************核心控制器（不可修改）**************************/
    
    /**
	 * 获取账单
	 */
	private function transfers($address,$hour = 1): array
    {
        $result = [];
        $end = time() * 1000;
        $start = strtotime("-$hour hour") * 1000;
        $params = [
            'limit' => 10,
            'start' => 0,
            'direction' => 'in',
            'relatedAddress' => $address,
            'start_timestamp' => $start,
            'end_timestamp' => $end,
        ];
        $api = "https://apilist.tronscan.org/api/token_trc20/transfers?".http_build_query($params);
        $resp = curl_get($api);
        $data = json_decode($resp, true);
        if(!is_array($data)){
            return $result;
        }else{
            foreach ($data['token_transfers'] as $transfer) {
                if ($transfer['to_address'] == $address && $transfer['finalResult'] == 'SUCCESS') {
                    $result[] = [
                        'time' => $transfer['block_ts'] / 1000,
                        'money' => $transfer['quant'] / 1000000,
                        'trade_id' => $transfer['transaction_id'],
                        'buyer' => $transfer['from_address'],
                    ];
                }
            }
        }
        return $result;
    }
}