<?php
// 设置编码
header("Content-Type: text/html; charset=utf-8");

// 获取路径
$requestUri = $_SERVER['REQUEST_URI'];
$pattern = '/^\/pay\/(\d+)\/([\d.]+)\/(\w+)/';

if (!preg_match($pattern, $requestUri, $matches)) {
    http_response_code(400);
    echo "Invalid URL. Format: /pay/{userId}/{amount}/{remark}";
    exit;
}

list(, $userId, $amount, $remark) = $matches;

// 构建 biz_data 参数
$bizData = json_encode([
    "s" => "money",
    "u" => $userId,
    "a" => $amount,
    "m" => $remark
], JSON_UNESCAPED_UNICODE);

$encodedBizData = urlencode($bizData);
$alipaysUrl = "alipays://platformapi/startapp?appId=20000123&actionType=scan&biz_data={$encodedBizData}";
$finalUrl = "alipayqr://platformapi/startapp?saId=20000032&url=" . urlencode($alipaysUrl);

// 判断是否为手机浏览器
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$isMobile = preg_match('/Mobile|iPhone|Android/i', $userAgent);

if ($isMobile) {
    // 手机浏览器自动跳转
    echo <<<HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>打开支付宝</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body { font-family: sans-serif; text-align: center; padding-top: 50px; }
        button {
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            background-color: #0aa;
            color: white;
            border-radius: 6px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <p>正在打开支付宝，请完成支付。</p>
    <script>
        // 自动调起支付宝
        location.href = "{$finalUrl}";
    </script>
</body>
</html>
HTML;
} else {
    // PC 端提示
    header("Content-Type: text/plain; charset=utf-8");
    echo "请使用手机浏览器打开本页面，以跳转到支付宝。\n支付链接：{$finalUrl}";
}