<?php
// 确保这些常量已经定义
defined('DB_SERVER') ? null : define('DB_SERVER', 'localhost');
defined('DB_USER') ? null : define('DB_USER', 'root');
defined('DB_PASS') ? null : define('DB_PASS', 'wch123.com');
defined('DB_NAME') ? null : define('DB_NAME', 'sdk');

// 连接数据库
$connection = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);

// 检查连接
if ($connection->connect_error) {
    die("连接失败: " . $connection->connect_error);
}

$now = time();
 
// 1天的时间戳
$halfHourAgo = strtotime("-1 day", $now);
 
// 格式化时间戳为日期时间字符串
$halfHourAgoFormatted = date("Y-m-d H:i:s", $halfHourAgo);

// 查询数据库
$query = "SELECT * FROM game_order where status= 1 and token != '' and create_time >= '{$halfHourAgoFormatted}' ";
$result = $connection->query($query);

$data = [];
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
} else {
    die("查询失败: " . $connection->error);
}

// 关闭数据库连接
$connection->close();

if(empty($data)){
    die("查询为空");
}

foreach ($data as $val) {
    $apiParams = [
        'orderId' => $val['order_id'],
        'platform' => $val['platform'],
        'purchaseToken' => $val['token']
    ];

    var_dump($apiParams['orderId']);

    // 发送POST请求
    $url = 'http://sso.skystoryorigin.com:3000/callback';
    $jsonStr = json_encode($apiParams);
    list($returnCode, $returnContent) = http_post_json($url, $jsonStr);

    var_dump($returnCode, $returnContent);
}

function http_post_json($url, $jsonStr)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt(
        $ch,
        CURLOPT_HTTPHEADER,
        array(
            'Content-Type: application/json;charset=utf-8',
            'Content-Length: ' . strlen($jsonStr)
        )
    );
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 超时时间设置为10秒
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return array($httpCode, $response);
}

