feat: move account tools into user menu and add referral security flows
parent
c5a7ca6d35
commit
dd3dcedb8b
@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Services\AccountSecurityService;
|
||||
use App\Services\AdminCsrf;
|
||||
use App\Services\Auth;
|
||||
use App\Services\Payment\RechargeMethodsService;
|
||||
use App\Services\UserFeatureRestrictionService;
|
||||
use App\Utils\Hash;
|
||||
|
||||
/** Account drawer APIs which do not need to render a page. */
|
||||
class AccountSecurityController extends BaseController
|
||||
{
|
||||
public function passwordVerifySend($request, $response, $args)
|
||||
{
|
||||
$csrf = $this->verifyCsrf($request, $response);
|
||||
if ($csrf !== null) {
|
||||
return $csrf;
|
||||
}
|
||||
$user = Auth::getUser();
|
||||
$result = AccountSecurityService::sendPasswordEmailCode(
|
||||
$user,
|
||||
$request->getServerParam('REMOTE_ADDR', '')
|
||||
);
|
||||
return $this->json($response, [
|
||||
'ret' => $result['ok'] ? 1 : 0,
|
||||
'msg' => $result['msg'],
|
||||
'retry_after' => $result['retry_after'],
|
||||
], $result['ok'] ? 200 : 429);
|
||||
}
|
||||
|
||||
public function updatePassword($request, $response, $args)
|
||||
{
|
||||
$csrf = $this->verifyCsrf($request, $response);
|
||||
if ($csrf !== null) {
|
||||
return $csrf;
|
||||
}
|
||||
$user = Auth::getUser();
|
||||
$old = $request->getParam('oldpwd', '');
|
||||
$password = $request->getParam('pwd', '');
|
||||
$repeat = $request->getParam('repwd', '');
|
||||
if (!is_string($old) || !is_string($password) || !is_string($repeat)) {
|
||||
return $this->json($response, ['ret' => 0, 'msg' => '密码格式无效'], 422);
|
||||
}
|
||||
if (!Hash::checkPassword($user->pass, $old)) {
|
||||
return $this->json($response, ['ret' => 0, 'msg' => '旧密码错误'], 422);
|
||||
}
|
||||
$error = Hash::newPasswordError($password);
|
||||
if ($error !== null || $password !== $repeat) {
|
||||
return $this->json($response, ['ret' => 0, 'msg' => $error ?? '两次密码不一致'], 422);
|
||||
}
|
||||
|
||||
$factor = AccountSecurityService::consumePasswordFactor(
|
||||
$user,
|
||||
$request->getParam('emailcode', ''),
|
||||
$request->getParam('gacode', ''),
|
||||
$request->getServerParam('REMOTE_ADDR', '')
|
||||
);
|
||||
if ($factor === null) {
|
||||
$hasTotp = AccountSecurityService::hasTotp($user);
|
||||
return $this->json($response, [
|
||||
'ret' => 0,
|
||||
'need_security_verify' => 1,
|
||||
'need_email_verify' => 1,
|
||||
'need_ga_verify' => $hasTotp ? 1 : 0,
|
||||
'msg' => $hasTotp ? '请使用邮箱验证码或谷歌验证器完成安全验证' : '请先获取邮箱验证码完成安全验证',
|
||||
], 422);
|
||||
}
|
||||
|
||||
try {
|
||||
$user->updatePassword($password);
|
||||
Auth::logout();
|
||||
} catch (\Throwable $exception) {
|
||||
error_log('Account password update failed: ' . get_class($exception));
|
||||
return $this->json($response, ['ret' => 0, 'msg' => '密码修改失败,请稍后重试'], 500);
|
||||
}
|
||||
|
||||
return $this->json($response, [
|
||||
'ret' => 1,
|
||||
'method' => $factor,
|
||||
'msg' => '密码修改成功,请重新登录',
|
||||
]);
|
||||
}
|
||||
|
||||
public function rechargeOptions($request, $response, $args)
|
||||
{
|
||||
$user = Auth::getUser();
|
||||
if (UserFeatureRestrictionService::isRechargeRestricted($user)) {
|
||||
return $this->json($response, [
|
||||
'ret' => 0,
|
||||
'msg' => UserFeatureRestrictionService::RECHARGE_MESSAGE,
|
||||
'methods' => [],
|
||||
], 503);
|
||||
}
|
||||
|
||||
return $this->json($response, [
|
||||
'ret' => 1,
|
||||
'methods' => RechargeMethodsService::forUser($user),
|
||||
]);
|
||||
}
|
||||
|
||||
private function json($response, array $data, $status = 200)
|
||||
{
|
||||
$response = $response->withStatus((int) $status)
|
||||
->withHeader('Content-Type', 'application/json; charset=utf-8')
|
||||
->withHeader('Cache-Control', 'no-store, private');
|
||||
$response->getBody()->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
||||
return $response;
|
||||
}
|
||||
|
||||
private function verifyCsrf($request, $response)
|
||||
{
|
||||
if (AdminCsrf::verify($request)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->json($response, [
|
||||
'ret' => 0,
|
||||
'msg' => '请求已过期,请刷新页面后重试',
|
||||
], 403);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,203 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\EmailVerify;
|
||||
use App\Models\User;
|
||||
use App\Utils\Totp;
|
||||
|
||||
/** Account security helpers shared by the account drawer and password API. */
|
||||
class AccountSecurityService
|
||||
{
|
||||
private const SEND_COOLDOWN_SECONDS = 60;
|
||||
private const ACTIVE_CODE_LIMIT = 3;
|
||||
private const FACTOR_FAIL_LIMIT = 8;
|
||||
private const FACTOR_FAIL_TTL = 600;
|
||||
|
||||
public static function hasTotp(User $user): bool
|
||||
{
|
||||
return (int) $user->ga_enable === 1
|
||||
&& Totp::normalizeSecret($user->ga_token) !== '';
|
||||
}
|
||||
|
||||
/** @return array{ok:bool,msg:string,retry_after:int} */
|
||||
public static function sendPasswordEmailCode(User $user, $clientIp = ''): array
|
||||
{
|
||||
$email = strtolower(trim((string) $user->email));
|
||||
if ($email === '' || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
|
||||
return ['ok' => false, 'msg' => '账户邮箱无效', 'retry_after' => 0];
|
||||
}
|
||||
if (Mail::isRecipientBlacklisted($email)) {
|
||||
return ['ok' => false, 'msg' => '当前邮箱暂时无法接收验证邮件', 'retry_after' => 0];
|
||||
}
|
||||
|
||||
$ip = is_scalar($clientIp) ? trim((string) $clientIp) : '';
|
||||
$redis = new RedisClient();
|
||||
// Scope the send gate to the authenticated account. Binding it to a
|
||||
// client IP lets a requester evade the cooldown by rotating proxies.
|
||||
$key = self::sendCooldownKey($user);
|
||||
if (!self::acquireCooldown($redis, $key)) {
|
||||
$retryAfter = self::ttl($redis, $key);
|
||||
return ['ok' => false, 'msg' => '请求过于频繁,请稍后再试', 'retry_after' => $retryAfter];
|
||||
}
|
||||
|
||||
$now = time();
|
||||
$ttl = (int) CaptchaConfig::get('email_verify_ttl');
|
||||
$active = EmailVerify::where('email', $email)
|
||||
->where('code', 'like', 'password_change:%')
|
||||
->where('expire_in', '>', $now)
|
||||
->count();
|
||||
if ((int) $active >= self::ACTIVE_CODE_LIMIT) {
|
||||
return ['ok' => false, 'msg' => '验证码请求次数过多,请稍后再试', 'retry_after' => self::SEND_COOLDOWN_SECONDS];
|
||||
}
|
||||
|
||||
$verification = new EmailVerify();
|
||||
$verification->email = $email;
|
||||
$verification->ip = $ip === '' ? '0.0.0.0' : $ip;
|
||||
$plainCode = (string) random_int(100000, 999999);
|
||||
$verification->code = 'password_change:' . $plainCode;
|
||||
$verification->expire_in = $now + $ttl;
|
||||
if (!$verification->save()) {
|
||||
return ['ok' => false, 'msg' => '验证码发送失败,请稍后重试', 'retry_after' => 0];
|
||||
}
|
||||
|
||||
try {
|
||||
$sent = Mail::send(
|
||||
$email,
|
||||
Config::get('appName') . ' - 修改密码验证',
|
||||
'auth/verify.tpl',
|
||||
[
|
||||
'code' => $plainCode,
|
||||
'expire' => date('Y-m-d H:i:s', $verification->expire_in),
|
||||
'language' => 'false',
|
||||
'scene' => 'password_change',
|
||||
],
|
||||
[],
|
||||
'修改密码验证'
|
||||
);
|
||||
} catch (\Throwable $exception) {
|
||||
$sent = false;
|
||||
}
|
||||
if (!$sent) {
|
||||
$verification->delete();
|
||||
return ['ok' => false, 'msg' => '验证码发送失败,请稍后重试', 'retry_after' => 0];
|
||||
}
|
||||
|
||||
return ['ok' => true, 'msg' => '验证码已发送,请检查邮箱', 'retry_after' => self::SEND_COOLDOWN_SECONDS];
|
||||
}
|
||||
|
||||
/** Consume one accepted password-change factor. */
|
||||
public static function consumePasswordFactor(User $user, $emailCode = '', $totpCode = '', $clientIp = ''): ?string
|
||||
{
|
||||
$redis = new RedisClient();
|
||||
$failKey = self::factorFailKey($user);
|
||||
if (self::factorFailures($redis, $failKey) >= self::FACTOR_FAIL_LIMIT) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$emailCode = is_scalar($emailCode) ? trim((string) $emailCode) : '';
|
||||
$totpCode = is_scalar($totpCode) ? trim((string) $totpCode) : '';
|
||||
if (self::hasTotp($user)) {
|
||||
if (Totp::verify($user->ga_token, $totpCode)) {
|
||||
self::clearFactorFailures($redis, $failKey);
|
||||
return 'totp';
|
||||
}
|
||||
}
|
||||
if ($emailCode === '' || !preg_match('/^\d{6}$/D', $emailCode)
|
||||
|| Mail::isRecipientBlacklisted($user->email)) {
|
||||
self::recordFactorFailure($redis, $failKey);
|
||||
return null;
|
||||
}
|
||||
|
||||
$connection = (new EmailVerify())->getConnection();
|
||||
$consumed = false;
|
||||
$connection->transaction(function () use ($user, $emailCode, &$consumed) {
|
||||
$verification = EmailVerify::where('email', strtolower(trim((string) $user->email)))
|
||||
->where('code', 'password_change:' . $emailCode)
|
||||
->where('expire_in', '>', time())
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
if ($verification !== null) {
|
||||
$verification->delete();
|
||||
$consumed = true;
|
||||
}
|
||||
}, 3);
|
||||
|
||||
if ($consumed) {
|
||||
self::clearFactorFailures($redis, $failKey);
|
||||
return 'email';
|
||||
}
|
||||
self::recordFactorFailure($redis, $failKey);
|
||||
return null;
|
||||
}
|
||||
|
||||
private static function sendCooldownKey(User $user): string
|
||||
{
|
||||
return 'account_password_verify_send:' . (int) $user->id;
|
||||
}
|
||||
|
||||
private static function ttl(RedisClient $redis, string $key): int
|
||||
{
|
||||
try {
|
||||
$ttl = $redis->getClient()->ttl($key);
|
||||
return $ttl > 0 ? (int) $ttl : 0;
|
||||
} catch (\Throwable $exception) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static function acquireCooldown(RedisClient $redis, string $key): bool
|
||||
{
|
||||
try {
|
||||
$result = $redis->getClient()->set(
|
||||
$key,
|
||||
'1',
|
||||
'EX',
|
||||
self::SEND_COOLDOWN_SECONDS,
|
||||
'NX'
|
||||
);
|
||||
return $result === true || strtoupper((string) $result) === 'OK';
|
||||
} catch (\Throwable $exception) {
|
||||
// Redis is an abuse-control accelerator. The database active-code
|
||||
// limit still bounds outstanding codes when it is unavailable.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static function factorFailKey(User $user): string
|
||||
{
|
||||
return 'account_password_verify_fail:' . (int) $user->id;
|
||||
}
|
||||
|
||||
private static function factorFailures(RedisClient $redis, string $key): int
|
||||
{
|
||||
try {
|
||||
$value = $redis->getClient()->get($key);
|
||||
return is_numeric($value) ? (int) $value : 0;
|
||||
} catch (\Throwable $exception) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static function recordFactorFailure(RedisClient $redis, string $key): void
|
||||
{
|
||||
try {
|
||||
$client = $redis->getClient();
|
||||
$value = (int) $client->incr($key);
|
||||
if ($value === 1) {
|
||||
$client->expire($key, self::FACTOR_FAIL_TTL);
|
||||
}
|
||||
} catch (\Throwable $exception) {
|
||||
// Continue with database verification when Redis is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
private static function clearFactorFailures(RedisClient $redis, string $key): void
|
||||
{
|
||||
try {
|
||||
$redis->del($key);
|
||||
} catch (\Throwable $exception) {
|
||||
// A stale failure counter only affects abuse throttling.
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Payment;
|
||||
|
||||
use App\Models\User;
|
||||
|
||||
/** Exposes only payment methods currently usable by a user. */
|
||||
class RechargeMethodsService
|
||||
{
|
||||
public static function forUser(User $user): array
|
||||
{
|
||||
$methods = [];
|
||||
|
||||
if (PaytaroConfig::isUserVisible($user)) {
|
||||
$values = PaytaroConfig::values();
|
||||
$methods[] = self::method('paytaro', '支付宝', $values['paytaro_min_amount'], $values['paytaro_max_amount'], [
|
||||
'provider' => 'paytaro',
|
||||
]);
|
||||
}
|
||||
|
||||
$yipayValues = YipayConfig::values();
|
||||
foreach (YipayConfig::visibleMethods($user, $yipayValues) as $method) {
|
||||
// visibleMethods reflects switches; runtimeForUser additionally
|
||||
// validates credentials, callback URL and the selected method.
|
||||
try {
|
||||
YipayConfig::runtimeForUser($user, $method);
|
||||
} catch (\Throwable $exception) {
|
||||
continue;
|
||||
}
|
||||
$label = $method === 'wxpay' ? '微信支付' : '支付宝支付';
|
||||
$methods[] = self::method('yipay_' . $method, $label, $yipayValues['yipay_min_amount'], $yipayValues['yipay_max_amount'], [
|
||||
'provider' => 'yipay',
|
||||
'method' => $method,
|
||||
]);
|
||||
}
|
||||
|
||||
if (UsdtConfig::isUserVisible($user)) {
|
||||
$values = UsdtConfig::values();
|
||||
$methods[] = self::method('usdt', 'USDT', $values['usdt_min_amount'], '9999999.99', [
|
||||
'provider' => 'usdt',
|
||||
'network' => 'tron',
|
||||
]);
|
||||
}
|
||||
|
||||
return $methods;
|
||||
}
|
||||
|
||||
private static function method(string $id, string $label, $minimum, $maximum, array $extra = []): array
|
||||
{
|
||||
return array_merge([
|
||||
'id' => $id,
|
||||
'label' => $label,
|
||||
'min_amount' => PaymentAmount::normalize($minimum),
|
||||
'max_amount' => PaymentAmount::normalize($maximum),
|
||||
], $extra);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,198 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Configurations;
|
||||
|
||||
/**
|
||||
* Runtime settings for referral rewards.
|
||||
*
|
||||
* The values are kept in the administrator configuration table and cached in
|
||||
* Redis. The configured flag is intentionally retained so installations
|
||||
* upgraded from the old per-referrer `user.aff_rate` model keep their current
|
||||
* behaviour until an administrator explicitly saves the new global rate.
|
||||
*/
|
||||
class ReferralConfig
|
||||
{
|
||||
public const RATE_KEY = 'referral_reward_rate';
|
||||
public const VALID_DAYS_KEY = 'referral_reward_days';
|
||||
public const ENABLED_KEY = 'referral_reward_enabled';
|
||||
public const CACHE_KEY = 'referral:config';
|
||||
public const CACHE_TTL_MINUTES = 5;
|
||||
|
||||
public const DEFAULT_RATE = '20';
|
||||
public const DEFAULT_VALID_DAYS = '730';
|
||||
public const DEFAULT_ENABLED = 'true';
|
||||
|
||||
private const DEFAULTS = [
|
||||
self::RATE_KEY => self::DEFAULT_RATE,
|
||||
self::VALID_DAYS_KEY => self::DEFAULT_VALID_DAYS,
|
||||
self::ENABLED_KEY => self::DEFAULT_ENABLED,
|
||||
];
|
||||
|
||||
/**
|
||||
* @return array{referral_reward_rate: string, referral_reward_days: int,
|
||||
* referral_reward_enabled: bool, rate_configured: bool,
|
||||
* days_configured: bool, enabled_configured: bool}
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
$raw = null;
|
||||
|
||||
try {
|
||||
$redis = new RedisClient();
|
||||
$cached = $redis->get(self::CACHE_KEY, self::CACHE_TTL_MINUTES, static function () {
|
||||
return json_encode(self::loadRaw(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
});
|
||||
if (is_string($cached) && $cached !== '') {
|
||||
$decoded = json_decode($cached, true);
|
||||
if (is_array($decoded)) {
|
||||
$raw = $decoded;
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $exception) {
|
||||
// Redis is an optional acceleration layer. Database settings are
|
||||
// still authoritative when it is unavailable during a request.
|
||||
}
|
||||
|
||||
if (!is_array($raw)) {
|
||||
$raw = self::loadRaw();
|
||||
}
|
||||
|
||||
$rate = self::normalizeRate($raw[self::RATE_KEY] ?? self::DEFAULT_RATE);
|
||||
$days = self::normalizeDays($raw[self::VALID_DAYS_KEY] ?? self::DEFAULT_VALID_DAYS);
|
||||
$enabled = self::normalizeBoolean($raw[self::ENABLED_KEY] ?? self::DEFAULT_ENABLED);
|
||||
|
||||
return [
|
||||
self::RATE_KEY => $rate,
|
||||
self::VALID_DAYS_KEY => $days,
|
||||
self::ENABLED_KEY => $enabled,
|
||||
'rate_configured' => (bool) ($raw[self::RATE_KEY . '_configured'] ?? false),
|
||||
'days_configured' => (bool) ($raw[self::VALID_DAYS_KEY . '_configured'] ?? false),
|
||||
'enabled_configured' => (bool) ($raw[self::ENABLED_KEY . '_configured'] ?? false),
|
||||
];
|
||||
}
|
||||
|
||||
public static function clearCache(?RedisClient $redis = null): void
|
||||
{
|
||||
try {
|
||||
($redis ?? new RedisClient())->del(self::CACHE_KEY);
|
||||
} catch (\Throwable $exception) {
|
||||
// A stale Redis cache must never prevent an administrator from
|
||||
// saving a valid database configuration.
|
||||
}
|
||||
}
|
||||
|
||||
public static function normalizeRate($value): string
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
if (!preg_match('/^(?:\d{1,3})(?:\.\d{1,2})?$/D', $value)) {
|
||||
return self::DEFAULT_RATE;
|
||||
}
|
||||
|
||||
$number = (float) $value;
|
||||
if (!is_finite($number) || $number < 0 || $number > 100) {
|
||||
return self::DEFAULT_RATE;
|
||||
}
|
||||
|
||||
return number_format($number, 2, '.', '');
|
||||
}
|
||||
|
||||
public static function validateRate($value): string
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
if (!preg_match('/^(?:\d{1,3})(?:\.\d{1,2})?$/D', $value)
|
||||
|| (float) $value < 0 || (float) $value > 100) {
|
||||
throw new \InvalidArgumentException('推广返利比例必须是 0 至 100 之间的数字,最多两位小数');
|
||||
}
|
||||
|
||||
return number_format((float) $value, 2, '.', '');
|
||||
}
|
||||
|
||||
public static function normalizeDays($value): int
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
if (!preg_match('/^\d+$/D', $value)) {
|
||||
return (int) self::DEFAULT_VALID_DAYS;
|
||||
}
|
||||
|
||||
return max(1, min(3650, (int) $value));
|
||||
}
|
||||
|
||||
public static function validateDays($value): int
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
if (!preg_match('/^\d+$/D', $value) || (int) $value < 1 || (int) $value > 3650) {
|
||||
throw new \InvalidArgumentException('推广返利有效期必须是 1 至 3650 天');
|
||||
}
|
||||
|
||||
return (int) $value;
|
||||
}
|
||||
|
||||
public static function normalizeBoolean($value): bool
|
||||
{
|
||||
return in_array(strtolower(trim((string) $value)), ['1', 'true', 'yes', 'on'], true);
|
||||
}
|
||||
|
||||
public static function validateBoolean($value): string
|
||||
{
|
||||
$value = strtolower(trim((string) $value));
|
||||
if (!in_array($value, ['0', '1', 'true', 'false', 'yes', 'no', 'on', 'off'], true)) {
|
||||
throw new \InvalidArgumentException('推广返利开关值无效');
|
||||
}
|
||||
|
||||
return self::normalizeBoolean($value) ? 'true' : 'false';
|
||||
}
|
||||
|
||||
public static function isEligible($user, ?int $now = null): bool
|
||||
{
|
||||
$values = self::values();
|
||||
if (!$values[self::ENABLED_KEY] || (int) ($user->ref_by ?? 0) <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$registeredAt = strtotime((string) ($user->reg_date ?? ''));
|
||||
if ($registeredAt === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$now = $now ?? time();
|
||||
$age = $now - $registeredAt;
|
||||
return $age >= 0 && $age <= $values[self::VALID_DAYS_KEY] * 86400;
|
||||
}
|
||||
|
||||
public static function rateFor($referrer): float
|
||||
{
|
||||
$values = self::values();
|
||||
if ($values['rate_configured']) {
|
||||
return (float) $values[self::RATE_KEY];
|
||||
}
|
||||
|
||||
// Existing installations may still rely on a per-referrer rate. The
|
||||
// administrator can switch to the global rule by saving the setting.
|
||||
$legacy = (float) ($referrer->aff_rate ?? 0);
|
||||
return max(0.0, min(100.0, $legacy));
|
||||
}
|
||||
|
||||
private static function loadRaw(): array
|
||||
{
|
||||
$raw = self::DEFAULTS;
|
||||
foreach (array_keys(self::DEFAULTS) as $key) {
|
||||
$raw[$key . '_configured'] = false;
|
||||
}
|
||||
|
||||
try {
|
||||
$rows = Configurations::whereIn('name', array_keys(self::DEFAULTS))->get()->keyBy('name');
|
||||
foreach (array_keys(self::DEFAULTS) as $key) {
|
||||
if (isset($rows[$key])) {
|
||||
$raw[$key] = (string) $rows[$key]->value;
|
||||
$raw[$key . '_configured'] = true;
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $exception) {
|
||||
// Fresh bootstrap/tests may not have created the settings table.
|
||||
}
|
||||
|
||||
return $raw;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,184 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\InviteCode;
|
||||
|
||||
/**
|
||||
* Referral-code rules shared by registration and the promotion drawer.
|
||||
*/
|
||||
class ReferralService
|
||||
{
|
||||
public const CODE_LENGTH = 8;
|
||||
public const CODE_PATTERN = '/^[A-Za-z0-9]{8}$/D';
|
||||
private const CODE_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
|
||||
|
||||
public static function normalizeCode($value): string
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
return preg_match(self::CODE_PATTERN, $value) === 1 ? $value : '';
|
||||
}
|
||||
|
||||
public static function generateCode(): string
|
||||
{
|
||||
// The generation lock serializes the check-and-select sequence. A
|
||||
// caller that needs an atomic create/update should use codeForUser()
|
||||
// or rotateForUser(); this method remains available for legacy code
|
||||
// that only needs a fresh candidate value.
|
||||
return self::withGenerationLock(static function (): string {
|
||||
return self::generateCodeValue();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a user's existing eight-character code or create it atomically.
|
||||
*
|
||||
* The lock row is deliberately separate from ss_invite_code: legacy
|
||||
* installations may contain duplicate/long codes, so adding a unique
|
||||
* constraint to that table would make the migration destructive.
|
||||
*/
|
||||
public static function codeForUser($user): ?InviteCode
|
||||
{
|
||||
$userId = (int) ($user->id ?? 0);
|
||||
if ($userId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return self::withGenerationLock(static function () use ($userId): InviteCode {
|
||||
$existing = InviteCode::where('user_id', $userId)
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->first(static function ($code) {
|
||||
return self::normalizeCode($code->code) !== '';
|
||||
});
|
||||
if ($existing !== null) {
|
||||
return $existing;
|
||||
}
|
||||
|
||||
$code = new InviteCode();
|
||||
$code->code = self::generateCodeValue();
|
||||
$code->user_id = $userId;
|
||||
$code->save();
|
||||
return $code;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate and persist a replacement code while holding the same lock.
|
||||
* This is the safe replacement for legacy callers that used
|
||||
* generateCode() followed by save() in separate statements.
|
||||
*/
|
||||
public static function rotateForUser($user): ?InviteCode
|
||||
{
|
||||
$userId = (int) ($user->id ?? 0);
|
||||
if ($userId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return self::withGenerationLock(static function () use ($userId): InviteCode {
|
||||
$code = InviteCode::where('user_id', $userId)->orderBy('id')->first();
|
||||
if ($code === null) {
|
||||
$code = new InviteCode();
|
||||
$code->user_id = $userId;
|
||||
}
|
||||
$code->code = self::generateCodeValue();
|
||||
$code->save();
|
||||
|
||||
// Keep the historical one-code-per-user behaviour without
|
||||
// touching invitation rows belonging to other users.
|
||||
InviteCode::where('user_id', $userId)
|
||||
->where('id', '<>', $code->id)
|
||||
->delete();
|
||||
|
||||
return $code;
|
||||
});
|
||||
}
|
||||
|
||||
private static function generateCodeValue(): string
|
||||
{
|
||||
$alphabetLength = strlen(self::CODE_ALPHABET);
|
||||
for ($attempt = 0; $attempt < 32; $attempt++) {
|
||||
$code = '';
|
||||
for ($index = 0; $index < self::CODE_LENGTH; $index++) {
|
||||
$code .= self::CODE_ALPHABET[random_int(0, $alphabetLength - 1)];
|
||||
}
|
||||
|
||||
if (!InviteCode::where('code', $code)->exists()) {
|
||||
return $code;
|
||||
}
|
||||
}
|
||||
|
||||
throw new \RuntimeException('无法生成唯一推广码');
|
||||
}
|
||||
|
||||
private static function withGenerationLock(callable $callback)
|
||||
{
|
||||
$connection = (new InviteCode())->getConnection();
|
||||
try {
|
||||
return $connection->transaction(static function () use ($connection, $callback) {
|
||||
$lock = $connection->table('referral_code_generation_locks')
|
||||
->where('id', 1)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
if ($lock === null) {
|
||||
throw new \RuntimeException(
|
||||
'推广码生成锁未初始化,请先导入 web/sql/referral_affiliate_code.sql'
|
||||
);
|
||||
}
|
||||
|
||||
return $callback();
|
||||
});
|
||||
} catch (\Throwable $exception) {
|
||||
if ($exception instanceof \RuntimeException
|
||||
&& str_starts_with($exception->getMessage(), '推广码生成锁未初始化')) {
|
||||
throw $exception;
|
||||
}
|
||||
throw new \RuntimeException('推广码生成锁不可用,请先导入 web/sql/referral_affiliate_code.sql', 0, $exception);
|
||||
}
|
||||
}
|
||||
|
||||
public static function findInvitation($rawCode, $lock = false): ?InviteCode
|
||||
{
|
||||
$code = self::normalizeCode($rawCode);
|
||||
if ($code === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$query = InviteCode::where('code', $code);
|
||||
if ($lock) {
|
||||
$query->lockForUpdate();
|
||||
}
|
||||
|
||||
// Existing installations may still have the old case-insensitive
|
||||
// column collation until the optional SQL migration is applied. Read
|
||||
// the candidate set and compare in PHP so mixed-case codes never
|
||||
// resolve to the wrong inviter during that transition.
|
||||
foreach ($query->get() as $invitation) {
|
||||
if ((string) $invitation->code === $code) {
|
||||
return $invitation;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static function registrationCode($query, $cookie = ''): string
|
||||
{
|
||||
if (is_array($query)) {
|
||||
$queryCode = $query['aff'] ?? '';
|
||||
$normalized = self::normalizeCode($queryCode);
|
||||
if ($normalized !== '') {
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
// Keep accepting the historical `code` query parameter while all
|
||||
// newly generated links use `aff`.
|
||||
$normalized = self::normalizeCode($query['code'] ?? '');
|
||||
if ($normalized !== '') {
|
||||
return $normalized;
|
||||
}
|
||||
}
|
||||
|
||||
return self::normalizeCode($cookie);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,99 @@
|
||||
const drawer = document.getElementById('panel-account-drawer');
|
||||
const frame = document.getElementById('panel-account-drawer-frame');
|
||||
const closeButton = document.getElementById('panel-account-drawer-close');
|
||||
const drawerTitle = document.getElementById('panel-account-drawer-title');
|
||||
const drawerDescription = document.getElementById('panel-account-drawer-description');
|
||||
const drawerFrameWrap = drawer && drawer.querySelector('.panel-account-drawer-frame-wrap');
|
||||
const drawerRoutes = {
|
||||
account: '/user/edit?drawer=1',
|
||||
balance: '/user/code?drawer=1',
|
||||
promotion: '/user/invite?drawer=1'
|
||||
};
|
||||
let lastTrigger = null;
|
||||
let scrollTop = 0;
|
||||
|
||||
function setDrawerState(open) {
|
||||
if (open) {
|
||||
scrollTop = window.scrollY || document.documentElement.scrollTop || 0;
|
||||
document.documentElement.style.setProperty('--panel-account-scroll-top', `-${scrollTop}px`);
|
||||
} else {
|
||||
document.documentElement.style.removeProperty('--panel-account-scroll-top');
|
||||
}
|
||||
document.documentElement.classList.toggle('panel-account-open', open);
|
||||
if (drawerFrameWrap) drawerFrameWrap.setAttribute('aria-busy', open ? 'true' : 'false');
|
||||
if (!open && scrollTop > 0) window.scrollTo(0, scrollTop);
|
||||
}
|
||||
|
||||
function closeDrawer() {
|
||||
if (!drawer) return;
|
||||
if (drawer.open && typeof drawer.close === 'function') drawer.close();
|
||||
else drawer.removeAttribute('open');
|
||||
setDrawerState(false);
|
||||
if (frame) frame.src = 'about:blank';
|
||||
if (lastTrigger && typeof lastTrigger.focus === 'function') lastTrigger.focus();
|
||||
lastTrigger = null;
|
||||
}
|
||||
|
||||
function openDrawer(trigger) {
|
||||
if (!drawer || !frame) return;
|
||||
const kind = trigger.getAttribute('data-account-drawer-open') || '';
|
||||
const route = drawerRoutes[kind];
|
||||
if (!route) return;
|
||||
|
||||
lastTrigger = trigger;
|
||||
if (drawerTitle) drawerTitle.textContent = trigger.getAttribute('data-drawer-title') || '账户中心';
|
||||
if (drawerDescription) drawerDescription.textContent = trigger.getAttribute('data-drawer-description') || '';
|
||||
frame.setAttribute('title', drawerTitle ? drawerTitle.textContent : '账户中心');
|
||||
const menu = trigger.closest('details');
|
||||
if (menu) menu.removeAttribute('open');
|
||||
setDrawerState(true);
|
||||
if (typeof drawer.showModal === 'function') {
|
||||
if (!drawer.open) drawer.showModal();
|
||||
} else {
|
||||
drawer.setAttribute('open', 'open');
|
||||
}
|
||||
frame.src = route;
|
||||
if (closeButton) closeButton.focus();
|
||||
}
|
||||
|
||||
document.querySelectorAll('[data-account-drawer-open]').forEach((trigger) => {
|
||||
trigger.addEventListener('click', () => openDrawer(trigger));
|
||||
});
|
||||
|
||||
document.querySelectorAll('.panel-user-menu').forEach((menu) => {
|
||||
const summary = menu.querySelector('summary');
|
||||
if (summary) menu.addEventListener('toggle', () => summary.setAttribute('aria-expanded', menu.open ? 'true' : 'false'));
|
||||
});
|
||||
|
||||
document.addEventListener('click', (event) => {
|
||||
document.querySelectorAll('.panel-user-menu[open]').forEach((menu) => {
|
||||
if (!menu.contains(event.target)) {
|
||||
menu.removeAttribute('open');
|
||||
const summary = menu.querySelector('summary');
|
||||
if (summary) summary.setAttribute('aria-expanded', 'false');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (frame) {
|
||||
frame.addEventListener('load', () => {
|
||||
if (drawer && drawer.open && drawerFrameWrap) drawerFrameWrap.setAttribute('aria-busy', 'false');
|
||||
});
|
||||
}
|
||||
|
||||
if (closeButton) closeButton.addEventListener('click', closeDrawer);
|
||||
if (drawer) {
|
||||
drawer.addEventListener('close', () => {
|
||||
setDrawerState(false);
|
||||
if (frame) frame.src = 'about:blank';
|
||||
if (lastTrigger && typeof lastTrigger.focus === 'function') lastTrigger.focus();
|
||||
lastTrigger = null;
|
||||
});
|
||||
drawer.addEventListener('click', (event) => {
|
||||
if (event.target === drawer) closeDrawer();
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Escape' && drawer && drawer.open) closeDrawer();
|
||||
});
|
||||
@ -0,0 +1,380 @@
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var payTimer = null;
|
||||
var methodRequestTimer = null;
|
||||
var methodRequestId = 0;
|
||||
var payDialog = document.getElementById("vuPayDialog");
|
||||
var payTitle = document.getElementById("vuPayTitle");
|
||||
var payInfo = document.getElementById("vuPayInfo");
|
||||
var payOpen = document.getElementById("vuPayOpen");
|
||||
var payOpenLabel = document.getElementById("vuPayOpenLabel");
|
||||
var qrcodeBox = document.getElementById("qrcode");
|
||||
var chainDetails = document.getElementById("vuPayChainDetails");
|
||||
var payNetwork = document.getElementById("vuPayNetwork");
|
||||
var payAmount = document.getElementById("vuPayAmount");
|
||||
var payAddress = document.getElementById("vuPayAddress");
|
||||
var payAddressCopy = document.getElementById("vuPayAddressCopy");
|
||||
var currentBalance = document.getElementById("vuCurrentBalance");
|
||||
var priceInput = document.getElementById("price");
|
||||
var methodBox = document.getElementById("vuRechargeMethods");
|
||||
var methodHint = document.getElementById("vuRechargeHint");
|
||||
|
||||
function qs(selector) {
|
||||
return document.querySelector(selector);
|
||||
}
|
||||
|
||||
function qsa(selector) {
|
||||
return Array.prototype.slice.call(document.querySelectorAll(selector));
|
||||
}
|
||||
|
||||
function topWindow() {
|
||||
try {
|
||||
return window.top || window;
|
||||
} catch (error) {
|
||||
return window;
|
||||
}
|
||||
}
|
||||
|
||||
function alertPay(message, type, title) {
|
||||
if (window.VuModal && window.VuModal.alert) {
|
||||
return window.VuModal.alert(message, type || "success", title);
|
||||
}
|
||||
window.alert(message);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
function encoded(data) {
|
||||
return new URLSearchParams(data || {}).toString();
|
||||
}
|
||||
|
||||
function requestHeaders(headers) {
|
||||
var next = Object.assign({}, headers || {});
|
||||
next["X-Requested-With"] = "XMLHttpRequest";
|
||||
var csrfField = qs("[data-csrf-token]");
|
||||
var csrfToken = csrfField ? String(csrfField.getAttribute("data-csrf-token") || "") : "";
|
||||
if (csrfToken) next["X-Admin-CSRF-Token"] = csrfToken;
|
||||
return next;
|
||||
}
|
||||
|
||||
function parseJson(response) {
|
||||
return response.text().then(function (text) {
|
||||
var data = {};
|
||||
try {
|
||||
data = text ? JSON.parse(text) : {};
|
||||
} catch (error) {
|
||||
data = {};
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(data.msg || data.errmsg || ("HTTP " + response.status));
|
||||
}
|
||||
return data;
|
||||
});
|
||||
}
|
||||
|
||||
function postForm(url, data) {
|
||||
return fetch(url, {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: requestHeaders({
|
||||
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
|
||||
"X-Requested-With": "XMLHttpRequest"
|
||||
}),
|
||||
body: encoded(data)
|
||||
}).then(parseJson);
|
||||
}
|
||||
|
||||
function getJson(url) {
|
||||
return fetch(url, {
|
||||
credentials: "same-origin",
|
||||
headers: requestHeaders({ "X-Requested-With": "XMLHttpRequest" })
|
||||
}).then(parseJson);
|
||||
}
|
||||
|
||||
function amountInCents() {
|
||||
if (!priceInput) return 0;
|
||||
var raw = String(priceInput.value || "").trim();
|
||||
if (!/^\d+(?:\.\d{1,2})?$/.test(raw)) return 0;
|
||||
var amount = Number(raw);
|
||||
if (!Number.isFinite(amount) || amount <= 0) return 0;
|
||||
return Math.round(amount * 100);
|
||||
}
|
||||
|
||||
function amountText() {
|
||||
return (amountInCents() / 100).toFixed(2);
|
||||
}
|
||||
|
||||
function methodCents(value) {
|
||||
var amount = Number(value);
|
||||
return Number.isFinite(amount) && amount >= 0 ? Math.round(amount * 100) : 0;
|
||||
}
|
||||
|
||||
function setMethodHint(message, type) {
|
||||
if (!methodHint) return;
|
||||
methodHint.textContent = message || "";
|
||||
methodHint.className = "vu-form-message" + (type ? " is-" + type : "");
|
||||
}
|
||||
|
||||
function methodDefinition(method) {
|
||||
var id = String(method && method.id || "");
|
||||
var definitions = {
|
||||
paytaro: { type: "paytaro", createUrl: "/user/paytaro/order", statusUrl: "/user/paytaro/status", icon: "mdi-qrcode-scan" },
|
||||
yipay_alipay: { type: "yipay", method: "alipay", createUrl: "/user/yipay/order", statusUrl: "/user/yipay/status", icon: "mdi-credit-card-check-outline" },
|
||||
yipay_wxpay: { type: "yipay", method: "wxpay", createUrl: "/user/yipay/order", statusUrl: "/user/yipay/status", icon: "mdi-wechat" },
|
||||
usdt: { type: "usdt", createUrl: "/user/usdt/order", statusUrl: "/user/usdt/status", icon: "mdi-currency-usd" }
|
||||
};
|
||||
if (!Object.prototype.hasOwnProperty.call(definitions, id)) return null;
|
||||
return Object.assign({}, definitions[id], { id: id, label: String(method.label || id) });
|
||||
}
|
||||
|
||||
function renderMethods(methods) {
|
||||
if (!methodBox) return;
|
||||
methodBox.innerHTML = "";
|
||||
var amount = amountInCents();
|
||||
var available = (methods || []).filter(function (method) {
|
||||
var definition = methodDefinition(method);
|
||||
if (!definition) return false;
|
||||
var minimum = methodCents(method.min_amount);
|
||||
var maximum = methodCents(method.max_amount);
|
||||
return amount >= minimum && (maximum === 0 || amount <= maximum);
|
||||
});
|
||||
|
||||
if (!available.length) {
|
||||
methodBox.hidden = true;
|
||||
setMethodHint("当前金额没有符合条件的支付方式,请调整充值金额。", "warning");
|
||||
return;
|
||||
}
|
||||
|
||||
available.forEach(function (method) {
|
||||
var definition = methodDefinition(method);
|
||||
var button = document.createElement("button");
|
||||
var icon = document.createElement("i");
|
||||
var label = document.createElement("span");
|
||||
button.className = "vu-recharge-method";
|
||||
button.type = "button";
|
||||
button.setAttribute("data-recharge-method", definition.id);
|
||||
icon.className = "mdi " + definition.icon;
|
||||
label.textContent = definition.label;
|
||||
button.appendChild(icon);
|
||||
button.appendChild(label);
|
||||
button.addEventListener("click", function () {
|
||||
createPay(definition);
|
||||
});
|
||||
methodBox.appendChild(button);
|
||||
});
|
||||
methodBox.hidden = false;
|
||||
setMethodHint("选择支付方式继续,订单金额为 ¥ " + amountText() + "。", "success");
|
||||
}
|
||||
|
||||
function loadMethods() {
|
||||
if (!priceInput || !methodBox) return;
|
||||
if (methodRequestTimer) window.clearTimeout(methodRequestTimer);
|
||||
var amount = amountInCents();
|
||||
if (!amount) {
|
||||
methodBox.innerHTML = "";
|
||||
methodBox.hidden = true;
|
||||
setMethodHint("先填写充值金额,系统会显示可用的支付方式。", "");
|
||||
return;
|
||||
}
|
||||
methodBox.hidden = false;
|
||||
methodBox.innerHTML = "<span class=\"vu-method-loading\"><i class=\"mdi mdi-loading mdi-spin\"></i>正在查询支付方式…</span>";
|
||||
setMethodHint("正在根据金额查询可用方式…", "");
|
||||
methodRequestTimer = window.setTimeout(function () {
|
||||
var requestId = ++methodRequestId;
|
||||
getJson("/user/recharge/options?amount=" + encodeURIComponent((amount / 100).toFixed(2))).then(function (data) {
|
||||
if (requestId !== methodRequestId) return;
|
||||
if (Number(data.ret) !== 1) {
|
||||
methodBox.hidden = true;
|
||||
setMethodHint(data.msg || "充值方式暂时不可用。", "error");
|
||||
return;
|
||||
}
|
||||
renderMethods(Array.isArray(data.methods) ? data.methods : []);
|
||||
}).catch(function (error) {
|
||||
if (requestId !== methodRequestId) return;
|
||||
methodBox.hidden = true;
|
||||
setMethodHint(error.message || "支付方式查询失败,请稍后重试。", "error");
|
||||
});
|
||||
}, 220);
|
||||
}
|
||||
|
||||
function isMobileDevice() {
|
||||
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent || "");
|
||||
}
|
||||
|
||||
function isPaytaroMobileDevice() {
|
||||
if (isMobileDevice()) return true;
|
||||
if (navigator.userAgentData && navigator.userAgentData.mobile) return true;
|
||||
return Boolean(window.matchMedia && window.matchMedia("(pointer: coarse) and (hover: none)").matches);
|
||||
}
|
||||
|
||||
function alipayAppUrl(payurl) {
|
||||
return "alipays://platformapi/startapp?appId=20000067&url=" + encodeURIComponent(String(payurl || ""));
|
||||
}
|
||||
|
||||
function paytaroMobileUrl(payurl) {
|
||||
payurl = String(payurl || "");
|
||||
try {
|
||||
var url = new URL(payurl);
|
||||
var host = String(url.hostname || "").toLowerCase();
|
||||
if (host === "mclient.alipay.com" || url.searchParams.get("method") === "alipay.trade.wap.pay") return payurl;
|
||||
} catch (error) {
|
||||
return "";
|
||||
}
|
||||
return alipayAppUrl(payurl);
|
||||
}
|
||||
|
||||
function renderPaymentQr(container, content, fallbackUrl) {
|
||||
container.innerHTML = "";
|
||||
try {
|
||||
if (!window.QRCode) throw new Error("QRCode library unavailable");
|
||||
var levels = window.QRCode.CorrectLevel || { L: 1, M: 0 };
|
||||
new QRCode(container, { text: content, width: 220, height: 220, correctLevel: content.length > 1200 ? levels.L : levels.M });
|
||||
if (!container.children.length) throw new Error("QRCode output missing");
|
||||
return true;
|
||||
} catch (error) {
|
||||
container.innerHTML = "";
|
||||
if (fallbackUrl) {
|
||||
var link = document.createElement("a");
|
||||
link.className = "vu-text-link";
|
||||
link.href = fallbackUrl;
|
||||
link.target = "_blank";
|
||||
link.rel = "noopener";
|
||||
link.textContent = "打开支付页面";
|
||||
container.appendChild(link);
|
||||
} else {
|
||||
var code = document.createElement("code");
|
||||
code.textContent = content;
|
||||
container.appendChild(code);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function clearPaymentReturnParams() {
|
||||
if (!window.history || !window.history.replaceState) return;
|
||||
var url = new URL(window.location.href);
|
||||
url.searchParams.delete("payment");
|
||||
url.searchParams.delete("pid");
|
||||
window.history.replaceState(null, "", url.pathname + (url.search ? url.search : "") + url.hash);
|
||||
}
|
||||
|
||||
function closePayDialog() {
|
||||
if (payTimer) {
|
||||
window.clearInterval(payTimer);
|
||||
payTimer = null;
|
||||
}
|
||||
if (!payDialog) return;
|
||||
payDialog.classList.remove("is-open");
|
||||
payDialog.setAttribute("aria-hidden", "true");
|
||||
payDialog.setAttribute("hidden", "hidden");
|
||||
document.body.classList.remove("vu-modal-lock");
|
||||
}
|
||||
|
||||
function openPayDialog(data) {
|
||||
if (!payDialog || !qrcodeBox || !payInfo || !payOpen) return false;
|
||||
var isUsdt = data.payment_type === "usdt";
|
||||
var qrContent = isUsdt ? String(data.receive_address || "") : String(data.url || "");
|
||||
if (!qrContent) {
|
||||
alertPay(isUsdt ? "系统没有返回有效收款地址。" : "支付网关没有返回有效支付链接。", "error", "创建订单失败");
|
||||
return false;
|
||||
}
|
||||
if (payTitle) payTitle.textContent = isUsdt ? "USDT 扫码支付" : (data.payment_label || "扫码支付");
|
||||
payInfo.textContent = isUsdt ? "请按下方网络和数量完成转账,支付数量必须完全一致。" : "订单金额:¥ " + data.amount + ",请扫码完成支付。";
|
||||
var checkoutLinkEnabled = data.payment_type !== "paytaro" && (!isUsdt || (data.checkout_link_enabled === true && Boolean(data.url)));
|
||||
payOpen.hidden = !checkoutLinkEnabled;
|
||||
if (checkoutLinkEnabled) payOpen.setAttribute("href", data.url);
|
||||
else payOpen.removeAttribute("href");
|
||||
if (payOpenLabel) payOpenLabel.textContent = isUsdt ? "打开收银台" : "打开支付链接";
|
||||
if (chainDetails) chainDetails.hidden = !isUsdt;
|
||||
if (isUsdt) {
|
||||
var network = String(data.network || "").toLowerCase();
|
||||
var token = String(data.token || "USDT").toUpperCase();
|
||||
if (payNetwork) payNetwork.textContent = network === "tron" && token === "USDT" ? "TRON (TRC20)" : network.toUpperCase();
|
||||
if (payAmount) payAmount.textContent = data.actual_amount + " " + token;
|
||||
if (payAddress) payAddress.textContent = qrContent;
|
||||
if (payAddressCopy) payAddressCopy.setAttribute("data-copy", qrContent);
|
||||
} else if (payAddressCopy) payAddressCopy.removeAttribute("data-copy");
|
||||
renderPaymentQr(qrcodeBox, qrContent, isUsdt ? "" : data.url);
|
||||
payDialog.removeAttribute("hidden");
|
||||
payDialog.classList.add("is-open");
|
||||
payDialog.setAttribute("aria-hidden", "false");
|
||||
document.body.classList.add("vu-modal-lock");
|
||||
return true;
|
||||
}
|
||||
|
||||
function checkPayStatus(statusUrl) {
|
||||
if (!statusUrl) return;
|
||||
postForm(statusUrl, {}).then(function (data) {
|
||||
if (String(data.result) === "1") {
|
||||
closePayDialog();
|
||||
if (currentBalance && data.balance !== null && typeof data.balance !== "undefined") currentBalance.textContent = "¥ " + data.balance;
|
||||
alertPay("支付成功,余额已入账。", "success", "账户充值").then(function () {
|
||||
clearPaymentReturnParams();
|
||||
topWindow().location.reload();
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (data.status === "expired" || data.status === "failed") {
|
||||
closePayDialog();
|
||||
alertPay(data.status === "expired" ? "订单已过期,请重新发起充值。" : "订单处理失败,请重新发起充值。", "error", "支付未完成");
|
||||
}
|
||||
}).catch(function () {
|
||||
// A transient status request failure should not interrupt the payment poll.
|
||||
});
|
||||
}
|
||||
|
||||
function createPay(definition) {
|
||||
var cents = amountInCents();
|
||||
if (!definition || !cents) {
|
||||
alertPay("请填写正确的充值金额。", "error", "金额错误");
|
||||
return;
|
||||
}
|
||||
if (payTimer) {
|
||||
window.clearInterval(payTimer);
|
||||
payTimer = null;
|
||||
}
|
||||
qsa("[data-recharge-method]").forEach(function (button) { button.disabled = true; });
|
||||
postForm(definition.createUrl, { price: (cents / 100).toFixed(2), type: definition.type, method: definition.method || "" }).then(function (data) {
|
||||
qsa("[data-recharge-method]").forEach(function (button) { button.disabled = false; });
|
||||
if (Number(data.code) !== 0) {
|
||||
alertPay(data.errmsg || data.msg || "支付网关处理失败。", "error", "创建订单失败");
|
||||
return;
|
||||
}
|
||||
data.payment_type = definition.type;
|
||||
if (definition.type === "paytaro" && isPaytaroMobileDevice()) {
|
||||
payTimer = window.setInterval(function () { checkPayStatus(data.status_url || definition.statusUrl); }, Number(data.poll_interval) || 3000);
|
||||
var mobileUrl = paytaroMobileUrl(data.url);
|
||||
if (!mobileUrl) {
|
||||
openPayDialog(data);
|
||||
return;
|
||||
}
|
||||
topWindow().location.assign(mobileUrl);
|
||||
return;
|
||||
}
|
||||
if (definition.type !== "usdt" && isMobileDevice()) {
|
||||
topWindow().location.href = data.url;
|
||||
return;
|
||||
}
|
||||
if (!openPayDialog(data)) return;
|
||||
payTimer = window.setInterval(function () { checkPayStatus(data.status_url || definition.statusUrl); }, Number(data.poll_interval) || 3000);
|
||||
}).catch(function (error) {
|
||||
qsa("[data-recharge-method]").forEach(function (button) { button.disabled = false; });
|
||||
alertPay(error.message || "发生了错误。", "error", "请求失败");
|
||||
});
|
||||
}
|
||||
|
||||
if (priceInput) {
|
||||
priceInput.addEventListener("input", loadMethods);
|
||||
priceInput.addEventListener("change", loadMethods);
|
||||
}
|
||||
qsa("[data-pay-close]").forEach(function (item) { item.addEventListener("click", closePayDialog); });
|
||||
|
||||
var returnParams = new URLSearchParams(window.location.search);
|
||||
if (returnParams.get("payment") === "yipay") {
|
||||
checkPayStatus("/user/yipay/status");
|
||||
payTimer = window.setInterval(function () { checkPayStatus("/user/yipay/status"); }, 3000);
|
||||
} else if (returnParams.get("payment") === "paytaro") {
|
||||
checkPayStatus("/user/paytaro/status");
|
||||
payTimer = window.setInterval(function () { checkPayStatus("/user/paytaro/status"); }, 3000);
|
||||
}
|
||||
})();
|
||||
@ -1,2 +1,2 @@
|
||||
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
|
||||
{assign var=venix_asset_version value='2026093011' scope='global'}
|
||||
{assign var=venix_asset_version value='2026093013' scope='global'}
|
||||
|
||||
@ -0,0 +1,14 @@
|
||||
<dialog class="panel-account-drawer" id="panel-account-drawer" aria-labelledby="panel-account-drawer-title" aria-describedby="panel-account-drawer-description">
|
||||
<header class="panel-account-drawer-header">
|
||||
<div>
|
||||
<p class="panel-account-drawer-kicker">账户中心</p>
|
||||
<h2 id="panel-account-drawer-title">账户设置</h2>
|
||||
<p id="panel-account-drawer-description">管理双重认证和登录密码。</p>
|
||||
</div>
|
||||
<button class="button button-ghost panel-account-drawer-close" id="panel-account-drawer-close" type="button" aria-label="关闭账户抽屉"><i class="mdi mdi-close" aria-hidden="true"></i></button>
|
||||
</header>
|
||||
<div class="panel-account-drawer-frame-wrap" aria-busy="false">
|
||||
<iframe id="panel-account-drawer-frame" title="账户设置" src="about:blank" loading="lazy"></iframe>
|
||||
</div>
|
||||
</dialog>
|
||||
<script type="module" src="/cloud/account-drawer.js?v={$venix_asset_version|escape:'html'}"></script>
|
||||
@ -1,483 +1,60 @@
|
||||
{include file='user/layout_header.tpl' vu_title='账户充值' vu_active='code'}
|
||||
<header class="vu-topbar">
|
||||
<div>
|
||||
<p class="vu-kicker">钱包</p>
|
||||
<h1>账户充值</h1>
|
||||
</div>
|
||||
<div class="vu-top-actions">
|
||||
<a class="vu-btn vu-btn-ghost" href="/user/cloud/deploy"><i class="mdi mdi-cart-outline"></i><span>购买套餐</span></a>
|
||||
<a class="vu-btn" href="/user/cloud/instances"><i class="mdi mdi-arrow-left"></i><span>返回实例</span></a>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="vu-pay-hero">
|
||||
<article class="vu-pay-hero-main">
|
||||
<span class="vu-status is-live">余额充值</span>
|
||||
<h2>账户余额充值</h2>
|
||||
<p>请选择充值金额并完成扫码支付。支付成功后余额通常会自动入账,若长时间未到账请联系站内客服。</p>
|
||||
</article>
|
||||
<aside class="vu-pay-balance">
|
||||
<span>当前余额</span>
|
||||
<strong id="vuCurrentBalance">¥ {$user->money}</strong>
|
||||
<a class="vu-btn vu-btn-soft" href="/user/cloud/deploy"><i class="mdi mdi-package-variant-closed"></i><span>去选套餐</span></a>
|
||||
</aside>
|
||||
<section class="vu-recharge-workspace" aria-labelledby="vuRechargeTitle">
|
||||
<header class="vu-recharge-banner">
|
||||
<div class="vu-recharge-banner-copy"><span class="vu-account-eyebrow">WALLET</span><h1 id="vuRechargeTitle">账户充值</h1><p>输入充值金额后,系统会自动筛选当前可用的支付方式。支付成功后余额将自动入账。</p></div>
|
||||
<div class="vu-recharge-balance"><span>当前余额</span><strong id="vuCurrentBalance">¥ {$user->money}</strong><a href="/user/cloud/deploy" target="_top" class="vu-btn vu-btn-soft"><i class="mdi mdi-package-variant-closed"></i><span>去选套餐</span></a></div>
|
||||
</header>
|
||||
|
||||
<div class="vu-recharge-stack">
|
||||
<section class="vu-recharge-card" aria-labelledby="vuRechargeFormTitle">
|
||||
<div class="vu-recharge-card-head"><div><span class="vu-account-eyebrow">RECHARGE</span><h2 id="vuRechargeFormTitle">选择充值方式</h2></div><span class="vu-recharge-card-icon"><i class="mdi mdi-credit-card-plus-outline"></i></span></div>
|
||||
{if $recharge_restricted}
|
||||
<div class="vu-empty-state vu-recharge-empty"><i class="mdi mdi-clock-alert-outline"></i><strong>充值服务暂时无法使用</strong><span>当前账户暂不满足充值条件,请稍后再试。</span></div>
|
||||
{else}
|
||||
<form class="vu-form vu-recharge-form" id="vuPayForm" data-csrf-token="{$account_csrf_token|default:''|escape:'html'}" autocomplete="off">
|
||||
<label class="vu-field" for="price"><span>充值金额</span><div class="vu-amount-field"><span>¥</span><input class="vu-input" id="price" name="price" type="number" min="0.01" step="0.01" inputmode="decimal" placeholder="请输入充值金额" aria-describedby="vuRechargeHint"></div></label>
|
||||
<p class="vu-form-message" id="vuRechargeHint">先填写充值金额,系统会显示可用的支付方式。</p>
|
||||
<div class="vu-pay-methods vu-recharge-methods" id="vuRechargeMethods" hidden aria-live="polite"></div>
|
||||
</form>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<section class="vu-pay-layout">
|
||||
<div class="vu-pay-main">
|
||||
<article class="vu-card vu-pay-card">
|
||||
<div class="vu-card-head">
|
||||
<div>
|
||||
<p class="vu-kicker">Recharge</p>
|
||||
<h2>在线充值</h2>
|
||||
</div>
|
||||
<i class="mdi mdi-credit-card-plus-outline vu-card-icon"></i>
|
||||
</div>
|
||||
|
||||
<form class="vu-form" id="vuPayForm">
|
||||
{if $recharge_restricted}
|
||||
<div class="vu-empty-state">
|
||||
<i class="mdi mdi-clock-alert-outline"></i>
|
||||
<strong>充值服务暂时无法使用</strong>
|
||||
<span>请稍后再试。</span>
|
||||
</div>
|
||||
{else}
|
||||
<label class="vu-field" for="price">
|
||||
<span>充值金额</span>
|
||||
<input class="vu-input" id="price" name="price" type="number" min="0.01" step="0.01" inputmode="decimal" placeholder="请输入充值金额">
|
||||
</label>
|
||||
{if $paytaro_enabled || $usdt_enabled || $yipay_alipay_enabled || $yipay_wxpay_enabled}
|
||||
<div class="vu-pay-methods">
|
||||
{if $paytaro_enabled}
|
||||
<button class="vu-btn" id="pay-paytaro" type="button" data-pay-type="paytaro" data-create-url="/user/paytaro/order" data-status-url="/user/paytaro/status"><i class="mdi mdi-qrcode-scan"></i><span>支付宝</span></button>
|
||||
{/if}
|
||||
{if $yipay_alipay_enabled}
|
||||
<button class="vu-btn" id="pay-yipay-alipay" type="button" data-pay-type="yipay" data-pay-method="alipay" data-create-url="/user/yipay/order" data-status-url="/user/yipay/status"><i class="mdi mdi-credit-card-check"></i><span>支付宝充值</span></button>
|
||||
{/if}
|
||||
{if $yipay_wxpay_enabled}
|
||||
<button class="vu-btn vu-btn-soft" id="pay-yipay-wxpay" type="button" data-pay-type="yipay" data-pay-method="wxpay" data-create-url="/user/yipay/order" data-status-url="/user/yipay/status"><i class="mdi mdi-wechat"></i><span>微信支付</span></button>
|
||||
{/if}
|
||||
{if $usdt_enabled}
|
||||
<button class="vu-btn vu-btn-soft" id="pay-usdt" type="button" data-pay-type="usdt" data-create-url="/user/usdt/order" data-status-url="/user/usdt/status"><i class="mdi mdi-currency-usd"></i><span>USDT 充值</span></button>
|
||||
{/if}
|
||||
</div>
|
||||
{else}
|
||||
<p class="vu-form-message">当前暂无可用在线充值方式。</p>
|
||||
{/if}
|
||||
{/if}
|
||||
</form>
|
||||
</article>
|
||||
|
||||
{if !$transaction_records_restricted}
|
||||
<article class="vu-card vu-pay-card">
|
||||
<div class="vu-card-head">
|
||||
<div>
|
||||
<p class="vu-kicker">History</p>
|
||||
<h2>充值记录</h2>
|
||||
</div>
|
||||
<i class="mdi mdi-receipt-text-clock-outline vu-card-icon"></i>
|
||||
</div>
|
||||
<div class="vu-table-wrap">
|
||||
<table class="vu-data-table vu-pay-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>充值代码</th>
|
||||
<th>类型</th>
|
||||
<th>内容</th>
|
||||
<th>状态</th>
|
||||
<th>时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{if $codes->isEmpty()}
|
||||
<tr>
|
||||
<td colspan="5">
|
||||
<div class="vu-empty-state">
|
||||
<i class="mdi mdi-receipt-text-remove-outline"></i>
|
||||
<strong>暂无充值记录</strong>
|
||||
<span>完成第一笔充值后,记录会显示在这里。</span>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{else}
|
||||
{foreach $codes as $code}
|
||||
{if $code->type!=-2}
|
||||
<tr>
|
||||
<td>
|
||||
<div class="vu-pay-code">
|
||||
<code>{$code->display_code|default:'--'|escape:'html'}</code>
|
||||
{if $code->display_code != ''}
|
||||
<button class="vu-icon-btn" type="button" data-copy="{$code->display_code|escape:'html'}" aria-label="复制充值代码">
|
||||
<i class="mdi mdi-content-copy"></i>
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
{if $code->type==-1}余额充值{/if}
|
||||
{if $code->type==10003}账户充值{/if}
|
||||
{if $code->type==10004}金额充值{/if}
|
||||
{if $code->type==10005}余额充值{/if}
|
||||
{if $code->type==10006}USDT 充值{/if}
|
||||
{if $code->type==10007}在线充值{/if}
|
||||
</td>
|
||||
<td>
|
||||
<strong>
|
||||
{if $code->type==-1 || $code->type==10003 || $code->type==10004 || $code->type==10005 || $code->type==10006 || $code->type==10007}
|
||||
¥ {$code->number}
|
||||
{/if}
|
||||
</strong>
|
||||
</td>
|
||||
<td><span class="vu-pill">成功</span></td>
|
||||
<td>{$code->usedatetime}</td>
|
||||
</tr>
|
||||
{/if}
|
||||
{/foreach}
|
||||
{/if}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="vu-table-footer">
|
||||
<span>共 {$codes->total()} 条充值记录</span>
|
||||
<div class="vu-pagination-wrap">{$codes->links()}</div>
|
||||
</div>
|
||||
</article>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<aside class="vu-pay-side">
|
||||
<article class="vu-card vu-pay-card">
|
||||
<div class="vu-card-head">
|
||||
<div>
|
||||
<p class="vu-kicker">Tips</p>
|
||||
<h2>充值说明</h2>
|
||||
</div>
|
||||
<i class="mdi mdi-information-outline vu-card-icon"></i>
|
||||
</div>
|
||||
<div class="vu-profile-tips">
|
||||
<div><i class="mdi mdi-timer-sand"></i><span>扫码支付后请等待页面自动确认,避免重复发起订单。</span></div>
|
||||
<div><i class="mdi mdi-shield-check-outline"></i><span>请核对支付金额,付款完成后余额会按订单金额入账。</span></div>
|
||||
<div><i class="mdi mdi-lifebuoy"></i><span>{if !empty($ticket_navigation_enabled)}如遇到账延迟,请保留支付记录并提交工单。{else}如遇到账延迟,请保留支付记录并稍后重试。{/if}</span></div>
|
||||
</div>
|
||||
</article>
|
||||
</aside>
|
||||
<section class="vu-recharge-card vu-recharge-notes" aria-labelledby="vuRechargeNotesTitle">
|
||||
<div class="vu-recharge-card-head"><div><span class="vu-account-eyebrow">HOW IT WORKS</span><h2 id="vuRechargeNotesTitle">充值说明</h2></div><span class="vu-recharge-card-icon is-soft"><i class="mdi mdi-information-outline"></i></span></div>
|
||||
<div class="vu-recharge-tip-list"><div><i class="mdi mdi-timer-sand"></i><span>扫码或打开支付链接后请等待系统确认,避免重复创建订单。</span></div><div><i class="mdi mdi-shield-check-outline"></i><span>请核对支付金额和收款网络,付款完成后余额会按订单金额入账。</span></div><div><i class="mdi mdi-lifebuoy"></i><span>{if !empty($ticket_navigation_enabled)}如遇到账延迟,请保留支付记录并提交工单。{else}如遇到账延迟,请保留支付记录并稍后重试。{/if}</span></div></div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{if !$transaction_records_restricted}
|
||||
<section class="vu-recharge-card vu-recharge-history" aria-labelledby="vuRechargeHistoryTitle">
|
||||
<div class="vu-recharge-card-head"><div><span class="vu-account-eyebrow">HISTORY</span><h2 id="vuRechargeHistoryTitle">充值记录</h2></div><span class="vu-recharge-card-icon is-soft"><i class="mdi mdi-receipt-text-clock-outline"></i></span></div>
|
||||
<div class="vu-table-wrap"><table class="vu-data-table vu-pay-table"><thead><tr><th>充值代码</th><th>类型</th><th>金额</th><th>状态</th><th>时间</th></tr></thead><tbody>
|
||||
{if $codes->isEmpty()}
|
||||
<tr><td colspan="5"><div class="vu-empty-state"><i class="mdi mdi-receipt-text-remove-outline"></i><strong>暂无充值记录</strong><span>完成第一笔充值后,记录会显示在这里。</span></div></td></tr>
|
||||
{else}
|
||||
{foreach $codes as $code}
|
||||
{if $code->type!=-2}
|
||||
<tr><td><div class="vu-pay-code"><code>{$code->display_code|default:'--'|escape:'html'}</code>{if $code->display_code != ''}<button class="vu-icon-btn" type="button" data-copy="{$code->display_code|escape:'html'}" aria-label="复制充值代码"><i class="mdi mdi-content-copy"></i></button>{/if}</div></td><td>{if $code->type==-1 || $code->type==10003 || $code->type==10004 || $code->type==10005}余额充值{elseif $code->type==10006}USDT 充值{elseif $code->type==10007}在线充值{else}充值{/if}</td><td><strong>¥ {$code->number}</strong></td><td><span class="vu-pill">成功</span></td><td>{$code->usedatetime}</td></tr>
|
||||
{/if}
|
||||
{/foreach}
|
||||
{/if}
|
||||
</tbody></table></div><div class="vu-table-footer"><span>共 {$codes->total()} 条充值记录</span><div class="vu-pagination-wrap">{$codes->links()}</div></div>
|
||||
</section>
|
||||
{/if}
|
||||
</section>
|
||||
{include file='user/layout_footer.tpl'}
|
||||
|
||||
<div class="vu-pay-dialog" id="vuPayDialog" aria-hidden="true" hidden>
|
||||
<div class="vu-pay-dialog-backdrop" data-pay-close></div>
|
||||
<div class="vu-pay-dialog-panel" role="dialog" aria-modal="true" aria-labelledby="vuPayTitle">
|
||||
<button class="vu-modal-close" type="button" data-pay-close aria-label="关闭"><i class="mdi mdi-close"></i></button>
|
||||
<div class="vu-modal-mark"><i class="mdi mdi-qrcode-scan"></i></div>
|
||||
<h2 id="vuPayTitle">扫码支付</h2>
|
||||
<p id="vuPayInfo">请使用对应客户端完成支付。</p>
|
||||
<div class="vu-pay-qrcode" id="qrcode"></div>
|
||||
<div class="vu-pay-chain-details" id="vuPayChainDetails" hidden>
|
||||
<div class="vu-pay-chain-summary">
|
||||
<span><small>支付网络</small><strong id="vuPayNetwork">--</strong></span>
|
||||
<span><small>应付数量</small><strong id="vuPayAmount">--</strong></span>
|
||||
</div>
|
||||
<div class="vu-pay-address">
|
||||
<small>USDT 收款地址</small>
|
||||
<div>
|
||||
<code id="vuPayAddress">--</code>
|
||||
<button class="vu-icon-btn" id="vuPayAddressCopy" type="button" aria-label="复制 USDT 收款地址"><i class="mdi mdi-content-copy"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="vu-modal-mark"><i class="mdi mdi-qrcode-scan"></i></div><h2 id="vuPayTitle">扫码支付</h2><p id="vuPayInfo">请使用对应客户端完成支付。</p><div class="vu-pay-qrcode" id="qrcode"></div>
|
||||
<div class="vu-pay-chain-details" id="vuPayChainDetails" hidden><div class="vu-pay-chain-summary"><span><small>支付网络</small><strong id="vuPayNetwork">--</strong></span><span><small>应付数量</small><strong id="vuPayAmount">--</strong></span></div><div class="vu-pay-address"><small>USDT 收款地址</small><div><code id="vuPayAddress">--</code><button class="vu-icon-btn" id="vuPayAddressCopy" type="button" aria-label="复制 USDT 收款地址"><i class="mdi mdi-content-copy"></i></button></div></div></div>
|
||||
<a class="vu-btn vu-btn-soft" id="vuPayOpen" href="#" target="_blank" rel="noopener"><i class="mdi mdi-open-in-new"></i><span id="vuPayOpenLabel">打开支付链接</span></a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{include file='user/layout_modal.tpl'}
|
||||
|
||||
{include file='user/layout_scripts.tpl' vu_qrcode=1}
|
||||
<script>
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var payTimer = null;
|
||||
var payDialog = document.getElementById("vuPayDialog");
|
||||
var payTitle = document.getElementById("vuPayTitle");
|
||||
var payInfo = document.getElementById("vuPayInfo");
|
||||
var payOpen = document.getElementById("vuPayOpen");
|
||||
var payOpenLabel = document.getElementById("vuPayOpenLabel");
|
||||
var qrcodeBox = document.getElementById("qrcode");
|
||||
var chainDetails = document.getElementById("vuPayChainDetails");
|
||||
var payNetwork = document.getElementById("vuPayNetwork");
|
||||
var payAmount = document.getElementById("vuPayAmount");
|
||||
var payAddress = document.getElementById("vuPayAddress");
|
||||
var payAddressCopy = document.getElementById("vuPayAddressCopy");
|
||||
var currentBalance = document.getElementById("vuCurrentBalance");
|
||||
|
||||
function qs(selector) {
|
||||
return document.querySelector(selector);
|
||||
}
|
||||
|
||||
function qsa(selector) {
|
||||
return Array.prototype.slice.call(document.querySelectorAll(selector));
|
||||
}
|
||||
|
||||
function alertPay(message, type, title) {
|
||||
if (window.VuModal && window.VuModal.alert) {
|
||||
return window.VuModal.alert(message, type || "success", title);
|
||||
}
|
||||
window.alert(message);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
function clearPaymentReturnParams() {
|
||||
if (!window.history || !window.history.replaceState) return;
|
||||
var url = new URL(window.location.href);
|
||||
url.searchParams.delete("payment");
|
||||
url.searchParams.delete("pid");
|
||||
window.history.replaceState(null, "", url.pathname + (url.search ? url.search : "") + url.hash);
|
||||
}
|
||||
|
||||
function encoded(data) {
|
||||
return new URLSearchParams(data || {}).toString();
|
||||
}
|
||||
|
||||
function postForm(url, data) {
|
||||
return fetch(url, {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
|
||||
"X-Requested-With": "XMLHttpRequest"
|
||||
},
|
||||
body: encoded(data)
|
||||
}).then(function (response) {
|
||||
return response.json().then(function (data) {
|
||||
if (!response.ok) throw new Error(data.msg || ("HTTP " + response.status));
|
||||
return data;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function isMobileDevice() {
|
||||
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent || "");
|
||||
}
|
||||
|
||||
function isPaytaroMobileDevice() {
|
||||
if (isMobileDevice()) return true;
|
||||
if (navigator.userAgentData && navigator.userAgentData.mobile) return true;
|
||||
return Boolean(window.matchMedia && window.matchMedia("(pointer: coarse) and (hover: none)").matches);
|
||||
}
|
||||
|
||||
function alipayAppUrl(payurl) {
|
||||
return "alipays://platformapi/startapp?appId=20000067&url=" + encodeURIComponent(String(payurl || ""));
|
||||
}
|
||||
|
||||
function paytaroMobileUrl(payurl) {
|
||||
payurl = String(payurl || "");
|
||||
try {
|
||||
var url = new URL(payurl);
|
||||
var host = String(url.hostname || "").toLowerCase();
|
||||
if (host === "mclient.alipay.com" || url.searchParams.get("method") === "alipay.trade.wap.pay") {
|
||||
return payurl;
|
||||
}
|
||||
} catch (error) {
|
||||
return "";
|
||||
}
|
||||
return alipayAppUrl(payurl);
|
||||
}
|
||||
|
||||
function renderPaymentQr(container, content, fallbackUrl) {
|
||||
container.innerHTML = "";
|
||||
try {
|
||||
if (!window.QRCode) throw new Error("QRCode library unavailable");
|
||||
var levels = window.QRCode.CorrectLevel || { L: 1, M: 0 };
|
||||
new QRCode(container, {
|
||||
text: content,
|
||||
width: 220,
|
||||
height: 220,
|
||||
correctLevel: content.length > 1200 ? levels.L : levels.M
|
||||
});
|
||||
if (!container.children.length) throw new Error("QRCode output missing");
|
||||
return true;
|
||||
} catch (error) {
|
||||
container.innerHTML = "";
|
||||
if (fallbackUrl) {
|
||||
var link = document.createElement("a");
|
||||
link.className = "vu-text-link";
|
||||
link.href = fallbackUrl;
|
||||
link.target = "_blank";
|
||||
link.rel = "noopener";
|
||||
link.textContent = "打开支付宝支付";
|
||||
container.appendChild(link);
|
||||
} else {
|
||||
var code = document.createElement("code");
|
||||
code.textContent = content;
|
||||
container.appendChild(code);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function closePayDialog() {
|
||||
if (payTimer) {
|
||||
clearInterval(payTimer);
|
||||
payTimer = null;
|
||||
}
|
||||
if (!payDialog) return;
|
||||
payDialog.classList.remove("is-open");
|
||||
payDialog.setAttribute("aria-hidden", "true");
|
||||
payDialog.setAttribute("hidden", "hidden");
|
||||
document.body.classList.remove("vu-modal-lock");
|
||||
}
|
||||
|
||||
function openPayDialog(data) {
|
||||
if (!payDialog || !qrcodeBox || !payInfo || !payOpen) return false;
|
||||
var isUsdt = data.payment_type === "usdt";
|
||||
var qrContent = isUsdt ? String(data.receive_address || "") : String(data.url || "");
|
||||
if (!qrContent) {
|
||||
alertPay(isUsdt ? "系统没有返回有效收款地址。" : "支付网关没有返回有效支付链接。", "error", "创建订单失败");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (payTitle) payTitle.textContent = isUsdt ? "USDT 扫码支付" : (data.payment_label || "扫码支付");
|
||||
payInfo.textContent = isUsdt
|
||||
? "请按下方网络和数量完成转账,支付数量必须完全一致。"
|
||||
: "订单金额:¥ " + data.amount + ",请扫码完成支付。";
|
||||
var checkoutLinkEnabled = data.payment_type !== "paytaro"
|
||||
&& (!isUsdt || (data.checkout_link_enabled === true && Boolean(data.url)));
|
||||
payOpen.hidden = !checkoutLinkEnabled;
|
||||
if (checkoutLinkEnabled) {
|
||||
payOpen.setAttribute("href", data.url);
|
||||
} else {
|
||||
payOpen.removeAttribute("href");
|
||||
}
|
||||
if (payOpenLabel) payOpenLabel.textContent = isUsdt ? "打开收银台" : "打开支付链接";
|
||||
|
||||
if (chainDetails) chainDetails.hidden = !isUsdt;
|
||||
if (isUsdt) {
|
||||
var network = String(data.network || "").toLowerCase();
|
||||
var token = String(data.token || "USDT").toUpperCase();
|
||||
if (payNetwork) payNetwork.textContent = network === "tron" && token === "USDT" ? "TRON (TRC20)" : network.toUpperCase();
|
||||
if (payAmount) payAmount.textContent = data.actual_amount + " " + String(data.token || "USDT").toUpperCase();
|
||||
if (payAddress) payAddress.textContent = qrContent;
|
||||
if (payAddressCopy) payAddressCopy.setAttribute("data-copy", qrContent);
|
||||
} else if (payAddressCopy) {
|
||||
payAddressCopy.removeAttribute("data-copy");
|
||||
}
|
||||
|
||||
renderPaymentQr(qrcodeBox, qrContent, isUsdt ? "" : data.url);
|
||||
|
||||
payDialog.removeAttribute("hidden");
|
||||
payDialog.classList.add("is-open");
|
||||
payDialog.setAttribute("aria-hidden", "false");
|
||||
document.body.classList.add("vu-modal-lock");
|
||||
return true;
|
||||
}
|
||||
|
||||
function checkPayStatus(statusUrl) {
|
||||
postForm(statusUrl, {}).then(function (data) {
|
||||
if (String(data.result) === "1") {
|
||||
closePayDialog();
|
||||
if (currentBalance && data.balance !== null && typeof data.balance !== "undefined") {
|
||||
currentBalance.textContent = "¥ " + data.balance;
|
||||
}
|
||||
alertPay("支付成功,余额已入账。", "success", "账户充值").then(function () {
|
||||
clearPaymentReturnParams();
|
||||
window.location.reload();
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (data.status === "expired" || data.status === "failed") {
|
||||
closePayDialog();
|
||||
alertPay(data.status === "expired" ? "订单已过期,请重新发起充值。" : "订单处理失败,请重新发起充值。", "error", "支付未完成");
|
||||
}
|
||||
}).catch(function () {
|
||||
return;
|
||||
});
|
||||
}
|
||||
|
||||
function createPay(button) {
|
||||
var input = qs("#price");
|
||||
var price = input ? parseFloat(input.value) : 0;
|
||||
var type = button.getAttribute("data-pay-type");
|
||||
var method = button.getAttribute("data-pay-method") || "";
|
||||
var createUrl = button.getAttribute("data-create-url");
|
||||
var statusUrl = button.getAttribute("data-status-url");
|
||||
|
||||
if (payTimer) {
|
||||
clearInterval(payTimer);
|
||||
payTimer = null;
|
||||
}
|
||||
|
||||
if (Number.isNaN(price) || price <= 0) {
|
||||
alertPay("请填写正确的充值金额。", "error", "金额错误");
|
||||
return;
|
||||
}
|
||||
|
||||
qsa("[data-pay-type]").forEach(function (button) {
|
||||
button.disabled = true;
|
||||
});
|
||||
|
||||
postForm(createUrl, { price: price, type: type, method: method }).then(function (data) {
|
||||
qsa("[data-pay-type]").forEach(function (button) {
|
||||
button.disabled = false;
|
||||
});
|
||||
|
||||
if (Number(data.code) !== 0) {
|
||||
alertPay(data.errmsg || data.msg || "支付网关处理失败。", "error", "创建订单失败");
|
||||
return;
|
||||
}
|
||||
|
||||
data.payment_type = type;
|
||||
if (type === "paytaro" && isPaytaroMobileDevice()) {
|
||||
payTimer = window.setInterval(function () {
|
||||
checkPayStatus(data.status_url || statusUrl);
|
||||
}, Number(data.poll_interval) || 1000);
|
||||
var mobileUrl = paytaroMobileUrl(data.url);
|
||||
if (!mobileUrl) {
|
||||
openPayDialog(data);
|
||||
return;
|
||||
}
|
||||
window.location.assign(mobileUrl);
|
||||
return;
|
||||
}
|
||||
if (type !== "usdt" && isMobileDevice()) {
|
||||
window.location.href = data.url;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!openPayDialog(data)) return;
|
||||
payTimer = window.setInterval(function () {
|
||||
checkPayStatus(data.status_url || statusUrl);
|
||||
}, Number(data.poll_interval) || 1000);
|
||||
}).catch(function (error) {
|
||||
qsa("[data-pay-type]").forEach(function (button) {
|
||||
button.disabled = false;
|
||||
});
|
||||
alertPay(error.message || "发生了错误。", "error", "请求失败");
|
||||
});
|
||||
}
|
||||
|
||||
qsa("[data-pay-type]").forEach(function (button) {
|
||||
button.addEventListener("click", function () {
|
||||
createPay(button);
|
||||
});
|
||||
});
|
||||
|
||||
qsa("[data-pay-close]").forEach(function (item) {
|
||||
item.addEventListener("click", closePayDialog);
|
||||
});
|
||||
|
||||
var returnParams = new URLSearchParams(window.location.search);
|
||||
if (returnParams.get("payment") === "yipay") {
|
||||
checkPayStatus("/user/yipay/status");
|
||||
payTimer = window.setInterval(function () {
|
||||
checkPayStatus("/user/yipay/status");
|
||||
}, 3000);
|
||||
} else if (returnParams.get("payment") === "paytaro") {
|
||||
checkPayStatus("/user/paytaro/status");
|
||||
payTimer = window.setInterval(function () {
|
||||
checkPayStatus("/user/paytaro/status");
|
||||
}, 3000);
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
<script src="/theme/venix/js/recharge.js?v={$vu_asset_version}"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@ -0,0 +1,13 @@
|
||||
-- Import once for existing installations before enabling promotion links.
|
||||
-- New promotion links use an eight-character case-sensitive code in
|
||||
-- ss_invite_code.code; the index keeps registration lookups bounded.
|
||||
CREATE TABLE IF NOT EXISTS `referral_code_generation_locks` (
|
||||
`id` tinyint unsigned NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
|
||||
|
||||
INSERT IGNORE INTO `referral_code_generation_locks` (`id`) VALUES (1);
|
||||
|
||||
ALTER TABLE `ss_invite_code`
|
||||
MODIFY `code` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
|
||||
ADD KEY IF NOT EXISTS `idx_ss_invite_code_code` (`code`);
|
||||
@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
$System_Config = [];
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\AccountSecurityService;
|
||||
use App\Services\Payment\RechargeMethodsService;
|
||||
use App\Utils\Totp;
|
||||
|
||||
$assert = static function ($condition, $message) {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
$user = new User();
|
||||
$user->ga_enable = 1;
|
||||
$user->ga_token = Totp::generateSecret();
|
||||
$assert(AccountSecurityService::hasTotp($user), 'Enabled TOTP was not detected.');
|
||||
$user->ga_enable = 0;
|
||||
$assert(!AccountSecurityService::hasTotp($user), 'Disabled TOTP was reported as enabled.');
|
||||
$assert(AccountSecurityService::consumePasswordFactor($user, '', '') === null,
|
||||
'An empty password factor was accepted.');
|
||||
|
||||
$routes = file_get_contents(dirname(__DIR__) . '/config/routes.php');
|
||||
foreach ([
|
||||
"'/password/verify/send'",
|
||||
"'/password'",
|
||||
"'/recharge/options'",
|
||||
'AccountSecurityController:passwordVerifySend',
|
||||
'AccountSecurityController:updatePassword',
|
||||
'AccountSecurityController:rechargeOptions',
|
||||
] as $needle) {
|
||||
$assert(strpos($routes, $needle) !== false, 'Missing account API route: ' . $needle);
|
||||
}
|
||||
|
||||
$controller = file_get_contents(dirname(__DIR__) . '/app/Controllers/AccountSecurityController.php');
|
||||
foreach (['oldpwd', 'emailcode', 'gacode', 'need_security_verify', 'AdminCsrf::verify'] as $needle) {
|
||||
$assert(strpos($controller, $needle) !== false, 'Password API dropped security field: ' . $needle);
|
||||
}
|
||||
|
||||
$security = file_get_contents(dirname(__DIR__) . '/app/Services/AccountSecurityService.php');
|
||||
foreach ([
|
||||
"'password_change:' . $plainCode",
|
||||
"'password_change:' . $emailCode",
|
||||
"->where('code', 'like', 'password_change:%')",
|
||||
'is_scalar($emailCode)',
|
||||
'is_scalar($totpCode)',
|
||||
'->incr($key)',
|
||||
'->getClient()->set(',
|
||||
] as $needle) {
|
||||
$assert(strpos($security, $needle) !== false, 'Password factor hardening is missing: ' . $needle);
|
||||
}
|
||||
|
||||
$methods = RechargeMethodsService::class;
|
||||
$assert(method_exists($methods, 'forUser'), 'Recharge method discovery service is missing.');
|
||||
|
||||
echo "Account security and recharge API contract checks passed.\n";
|
||||
@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\ReferralConfig;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
// Force Redis connection attempts to fail fast; the service must fall back to
|
||||
// the authoritative configuration table when Redis is unavailable.
|
||||
$System_Config = ['redis_host' => '127.0.0.1', 'redis_port' => 1];
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
$schema = $capsule->schema('default');
|
||||
$schema->create('configurations', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('name');
|
||||
$table->text('value')->nullable();
|
||||
});
|
||||
|
||||
ReferralConfig::clearCache();
|
||||
$defaults = ReferralConfig::values();
|
||||
$assert($defaults[ReferralConfig::RATE_KEY] === '20.00', 'Default referral rate changed unexpectedly.');
|
||||
$assert($defaults[ReferralConfig::VALID_DAYS_KEY] === 730, 'Default referral validity changed unexpectedly.');
|
||||
$assert($defaults[ReferralConfig::ENABLED_KEY] === true, 'Default referral switch should be enabled.');
|
||||
$assert($defaults['rate_configured'] === false, 'Missing rate row was marked configured.');
|
||||
|
||||
Capsule::table('configurations')->insert([
|
||||
['name' => ReferralConfig::RATE_KEY, 'value' => '12.5'],
|
||||
['name' => ReferralConfig::VALID_DAYS_KEY, 'value' => '30'],
|
||||
['name' => ReferralConfig::ENABLED_KEY, 'value' => 'false'],
|
||||
]);
|
||||
ReferralConfig::clearCache();
|
||||
$configured = ReferralConfig::values();
|
||||
$assert($configured[ReferralConfig::RATE_KEY] === '12.50' && $configured['rate_configured'], 'Configured rate was not loaded.');
|
||||
$assert($configured[ReferralConfig::VALID_DAYS_KEY] === 30 && $configured['days_configured'], 'Configured validity was not loaded.');
|
||||
$assert($configured[ReferralConfig::ENABLED_KEY] === false && $configured['enabled_configured'], 'Configured switch was not loaded.');
|
||||
|
||||
$now = 1700000000;
|
||||
$eligible = (object) ['ref_by' => 9, 'reg_date' => date('Y-m-d H:i:s', $now - 29 * 86400)];
|
||||
$expired = (object) ['ref_by' => 9, 'reg_date' => date('Y-m-d H:i:s', $now - 31 * 86400)];
|
||||
$assert(!ReferralConfig::isEligible($eligible, $now), 'Disabled referral configuration still paid rewards.');
|
||||
$assert(ReferralConfig::rateFor((object) ['aff_rate' => 7.5]) === 12.5, 'Configured global rate did not override legacy per-user rate.');
|
||||
|
||||
Capsule::table('configurations')->where('name', ReferralConfig::ENABLED_KEY)->update(['value' => 'true']);
|
||||
ReferralConfig::clearCache();
|
||||
$assert(ReferralConfig::isEligible($eligible, $now), 'An in-window referred user was rejected.');
|
||||
$assert(!ReferralConfig::isEligible($expired, $now), 'An expired referral remained eligible.');
|
||||
$assert(!ReferralConfig::isEligible((object) ['ref_by' => 0, 'reg_date' => date('Y-m-d H:i:s', $now)], $now), 'A user without an inviter was eligible.');
|
||||
|
||||
Capsule::table('configurations')->where('name', ReferralConfig::RATE_KEY)->delete();
|
||||
ReferralConfig::clearCache();
|
||||
$assert(ReferralConfig::rateFor((object) ['aff_rate' => 7.5]) === 7.5, 'Legacy per-referrer rate was not preserved before global configuration.');
|
||||
|
||||
foreach ([['0', '0.00'], ['100', '100.00'], ['12.5', '12.50']] as [$input, $expected]) {
|
||||
$assert(ReferralConfig::validateRate($input) === $expected, 'Valid referral rate was rejected.');
|
||||
}
|
||||
foreach (['-1', '100.01', '1.234', 'abc'] as $invalid) {
|
||||
try {
|
||||
ReferralConfig::validateRate($invalid);
|
||||
throw new RuntimeException('Invalid referral rate was accepted: ' . $invalid);
|
||||
} catch (InvalidArgumentException $exception) {
|
||||
// Expected.
|
||||
}
|
||||
}
|
||||
|
||||
// Regression guard for ConfigController's first-save/default-row path.
|
||||
$controller = file_get_contents(dirname(__DIR__) . '/app/Controllers/Admin/ConfigController.php');
|
||||
$assert(str_contains($controller, '$isReferralKey')
|
||||
&& str_contains($controller, '!($isReferralKey && !isset($configurations[$key]))'),
|
||||
'ConfigController does not persist an explicitly saved referral default.');
|
||||
|
||||
echo "Referral config checks passed.\n";
|
||||
@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\ReferralService;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
|
||||
// Keep this regression test self-contained: no Redis or production database
|
||||
// is needed to exercise the code/lock invariants.
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
$schema = $capsule->schema('default');
|
||||
$schema->create('ss_invite_code', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('code', 128);
|
||||
$table->integer('user_id');
|
||||
});
|
||||
$schema->create('referral_code_generation_locks', static function (Blueprint $table): void {
|
||||
$table->unsignedTinyInteger('id')->primary();
|
||||
});
|
||||
Capsule::table('referral_code_generation_locks')->insert(['id' => 1]);
|
||||
|
||||
Capsule::table('ss_invite_code')->insert([
|
||||
['id' => 1, 'code' => 'Ab3dE9x0', 'user_id' => 1],
|
||||
['id' => 2, 'code' => 'aB3dE9x0', 'user_id' => 2],
|
||||
['id' => 3, 'code' => 'legacy-long-code', 'user_id' => 3],
|
||||
]);
|
||||
|
||||
$assert(ReferralService::normalizeCode('Ab3dE9x0') === 'Ab3dE9x0', 'Valid mixed-case code was rejected.');
|
||||
$assert(ReferralService::normalizeCode(' Ab3dE9x0 ') === 'Ab3dE9x0', 'Whitespace was not trimmed.');
|
||||
$assert(ReferralService::normalizeCode('Ab3dE9x') === '', 'Short code was accepted.');
|
||||
$assert(ReferralService::normalizeCode('Ab3dE9x!') === '', 'Non-alphanumeric code was accepted.');
|
||||
$assert(ReferralService::findInvitation('Ab3dE9x0')->user_id === 1, 'Exact mixed-case lookup chose the wrong inviter.');
|
||||
$assert(ReferralService::findInvitation('aB3dE9x0')->user_id === 2, 'Case-sensitive lookup did not preserve the code owner.');
|
||||
$assert(ReferralService::findInvitation('AB3DE9X0') === null, 'A differently cased code resolved unexpectedly.');
|
||||
$assert(ReferralService::findInvitation('legacy-long-code') === null, 'Legacy long code was accepted by the new lookup.');
|
||||
|
||||
// Query-string links win over a stale cookie; `code` remains a compatibility
|
||||
// alias, and a valid cookie is used only when neither query key is valid.
|
||||
$assert(ReferralService::registrationCode(['aff' => 'Ab3dE9x0'], 'aB3dE9x0') === 'Ab3dE9x0', 'aff did not win over cookie.');
|
||||
$assert(ReferralService::registrationCode(['aff' => 'invalid', 'code' => 'aB3dE9x0'], 'Ab3dE9x0') === 'aB3dE9x0', 'Legacy code query alias was not accepted.');
|
||||
$assert(ReferralService::registrationCode([], 'aB3dE9x0') === 'aB3dE9x0', 'Valid cookie was not used as fallback.');
|
||||
$assert(ReferralService::registrationCode(['aff' => 'invalid', 'code' => 'invalid'], 'invalid') === '', 'Invalid referral values were accepted.');
|
||||
|
||||
$first = ReferralService::codeForUser((object) ['id' => 4]);
|
||||
$again = ReferralService::codeForUser((object) ['id' => 4]);
|
||||
$other = ReferralService::codeForUser((object) ['id' => 5]);
|
||||
$assert($first !== null && $again !== null && $other !== null, 'Code generation returned no model.');
|
||||
$assert($first->code === $again->code, 'Repeated codeForUser calls generated duplicate rows.');
|
||||
$assert($first->code !== $other->code, 'Different users received the same generated code.');
|
||||
$assert(ReferralService::normalizeCode($first->code) === $first->code, 'Generated code does not match the eight-character contract.');
|
||||
$assert(Capsule::table('ss_invite_code')->where('code', $first->code)->count() === 1, 'Generated code was not persisted once.');
|
||||
$candidate = ReferralService::generateCode();
|
||||
$assert(ReferralService::normalizeCode($candidate) === $candidate
|
||||
&& Capsule::table('ss_invite_code')->where('code', $candidate)->count() === 0,
|
||||
'The locked candidate generator returned an invalid or already-used code.');
|
||||
|
||||
Capsule::table('referral_code_generation_locks')->delete();
|
||||
try {
|
||||
ReferralService::codeForUser((object) ['id' => 6]);
|
||||
throw new RuntimeException('Missing referral generation lock was not rejected.');
|
||||
} catch (RuntimeException $exception) {
|
||||
$assert(str_contains($exception->getMessage(), 'referral_affiliate_code.sql'), 'Missing lock error was not actionable.');
|
||||
}
|
||||
Capsule::table('referral_code_generation_locks')->insert(['id' => 1]);
|
||||
|
||||
$rotated = ReferralService::rotateForUser((object) ['id' => 4]);
|
||||
$assert($rotated !== null && $rotated->code !== $first->code, 'Code rotation did not issue a replacement.');
|
||||
$assert(Capsule::table('ss_invite_code')->where('user_id', 4)->count() === 1, 'Code rotation left multiple rows for one user.');
|
||||
$assert(Capsule::table('ss_invite_code')->where('code', $first->code)->count() === 0, 'Rotated code remained active.');
|
||||
|
||||
echo "Referral service checks passed.\n";
|
||||
Loading…
Reference in New Issue