refactor: flatten src/AKSRT → src (drop theme-identifier dir)

Move all domain folders from src/AKSRT/{Domain} to src/{Domain}; remap
Composer PSR-4 "AKSRT\\": "src/"; update audit script + README + ADR
paths; remove dead tools/build-psr4-map.php (scanned deleted inc/classes).
This commit is contained in:
2026-08-02 22:06:06 +08:00
parent 56f1a8175f
commit 8c5b1555c9
285 changed files with 26 additions and 3600 deletions
+457
View File
@@ -0,0 +1,457 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Content;
defined('ABSPATH') || exit;
class Download {
const TOKEN_TTL = 600; // 10 minutes
const TOKEN_LEN = 48;
const QUERY_VAR = 'aksrt_dl_token';
const ENDPOINT = 'aksrt-dl';
private static $instance = null;
private function __construct() {}
public static function get_instance(): self {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function init(): void {
add_action('init', [$this, 'register_rewrite']);
add_filter('query_vars', [$this, 'add_query_var']);
add_action('template_redirect', [$this, 'maybe_serve_download'], 0);
add_action('rest_api_init', [$this, 'register_routes']);
add_action('wp', [$this, 'maybe_schedule_cleanup']);
add_action('aksrt_dl_token_cleanup', [$this, 'cleanup_expired_tokens']);
}
public function maybe_schedule_cleanup(): void {
if (!wp_next_scheduled('aksrt_dl_token_cleanup')) {
$next = (new \DateTimeImmutable('tomorrow 03:30', wp_timezone()))->getTimestamp();
wp_schedule_event($next, 'daily', 'aksrt_dl_token_cleanup');
}
}
public function cleanup_expired_tokens(): void {
global $wpdb;
if (!class_exists('\AKSRT\Core\DBMigrator')) return;
$table = \AKSRT\Core\DBMigrator::table('dl_token');
if (!$table) return;
$now_utc = (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format('Y-m-d H:i:s');
$audit_cutoff = (new \DateTimeImmutable('-7 days', new \DateTimeZone('UTC')))->format('Y-m-d H:i:s');
$wpdb->query($wpdb->prepare(
"DELETE FROM {$table} WHERE expires_at < %s",
$now_utc
));
$wpdb->query($wpdb->prepare(
"DELETE FROM {$table} WHERE used_count >= max_uses AND created_at < %s",
$audit_cutoff
));
}
public function register_rewrite(): void {
add_rewrite_rule(
'^' . self::ENDPOINT . '/([A-Za-z0-9]{1,64})/?$',
'index.php?' . self::QUERY_VAR . '=$matches[1]',
'top'
);
}
public function add_query_var(array $vars): array {
$vars[] = self::QUERY_VAR;
return $vars;
}
public function register_routes(): void {
register_rest_route('aksrt/v1', '/download/request', [
'methods' => 'POST',
'callback' => [$this, 'rest_request'],
'permission_callback' => [$this, 'check_rest_nonce'],
]);
register_rest_route('aksrt/v1', '/download/policy/(?P<id>\d+)', [
'methods' => 'GET',
'callback' => [$this, 'rest_policy'],
'permission_callback' => '__return_true',
]);
}
public function check_rest_nonce(\WP_REST_Request $request) {
$nonce = $request->get_header('x-wp-nonce');
if (!$nonce) {
return new \WP_Error('aksrt_rest_no_nonce', __('缺少安全令牌', 'aksrt'), ['status' => 403]);
}
if (!wp_verify_nonce($nonce, 'wp_rest')) {
return new \WP_Error('aksrt_rest_bad_nonce', __('安全令牌已过期,请刷新页面', 'aksrt'), ['status' => 403]);
}
return true;
}
public function rest_policy(\WP_REST_Request $request) {
$post_id = (int) $request['id'];
$post = get_post($post_id);
if (!$post || !function_exists('aksrt_is_downloadable_content') || !aksrt_is_downloadable_content($post)) {
return new \WP_Error('aksrt_invalid', __('内容不存在或未启用下载能力', 'aksrt'), ['status' => 404]);
}
$meta = function_exists('aksrt_get_download_box_meta') ? aksrt_get_download_box_meta($post) : [];
$paid_settings = \AKSRT\Settings\Settings::get_paid_content_settings();
$cost = aksrt_resource_download_cost($post);
$uid = get_current_user_id();
$priced = function_exists('aksrt_get_user_pay_price') ? aksrt_get_user_pay_price($post, $uid) : null;
$pay_modo = is_array($priced)
? ((($priced['modo'] ?? '0') === 'points') ? 'points' : '0')
: ((($meta['pay_modo'] ?? '0') === 'points') ? 'points' : '0');
$display_price = is_array($priced) ? (float) ($priced['amount'] ?? 0) : (float) ($meta['price'] ?? 0);
$access = class_exists('AKSRT\\Content\\Visibility')
? Visibility::get_post_access_state($post, $uid)
: [];
$need_captcha = !empty($paid_settings['download_captcha']) || !empty($meta['require_captcha']);
if ($need_captcha && function_exists('aksrt_is_captcha_enabled_for') && !aksrt_is_captcha_enabled_for('download')) {
$need_captcha = false;
}
return new \WP_REST_Response([
'post_id' => $post_id,
'price' => $display_price,
'base_price' => is_array($priced) ? (float) ($priced['base'] ?? $display_price) : (float) ($meta['price'] ?? 0),
'pay_modo' => $pay_modo,
'pay_limit' => (int) ($meta['pay_limit'] ?? 0),
'cost' => $cost,
'require_login' => !empty($paid_settings['download_login']) || !empty($meta['require_login']) || (!empty($paid_settings['free_logged_show']) && $cost <= 0 && $display_price <= 0),
'require_captcha' => $need_captcha,
'logged_in' => $uid > 0,
'balance' => $uid > 0 && class_exists('\AKSRT\Credits\Credits') ? \AKSRT\Credits\Credits::balance($uid) : 0,
'has_paid_access' => !empty($access['has_paid_access']),
'need_purchase' => !empty($access['need_purchase']),
'need_vip' => !empty($access['need_vip']),
'need_login' => !empty($access['need_login']) && $uid <= 0,
'can_download' => !empty($access['can_download']),
'login_url' => wp_login_url(get_permalink($post)),
'vip_level' => (int) ($access['user_vip_level'] ?? 0),
'free_limit' => $uid > 0 && function_exists('aksrt_get_user_free_download_limit') ? aksrt_get_user_free_download_limit($uid) : 0,
'free_used' => $uid > 0 && function_exists('aksrt_get_user_free_downloaded_number') ? aksrt_get_user_free_downloaded_number($uid) : 0,
'free_surplus' => $uid > 0 && function_exists('aksrt_get_free_download_surplus') ? aksrt_get_free_download_surplus($uid) : null,
'sources' => array_map(function ($row, $idx) {
$extract_code = trim((string) ($row['extract_code'] ?? ''));
return [
'index' => $idx,
'label' => $row['label'] ?? '',
'type' => $row['type'] ?? 'direct',
'has_extract' => $extract_code !== '',
];
}, $meta['downloads'] ?? [], array_keys($meta['downloads'] ?? [])),
], 200);
}
public function rest_request(\WP_REST_Request $request) {
$params = $request->get_json_params();
if (!is_array($params)) $params = $request->get_params();
$post_id = isset($params['post_id']) ? (int) $params['post_id'] : 0;
$source_index = isset($params['source_index']) ? (int) $params['source_index'] : 0;
$post = get_post($post_id);
if (!$post || !function_exists('aksrt_is_downloadable_content') || !aksrt_is_downloadable_content($post)) {
return new \WP_Error('aksrt_invalid', __('内容不存在或未启用下载能力', 'aksrt'), ['status' => 404]);
}
$meta = function_exists('aksrt_get_download_box_meta') ? aksrt_get_download_box_meta($post) : [];
if (empty($meta['downloads'][$source_index])) {
return new \WP_Error('aksrt_no_source', __('下载源不存在', 'aksrt'), ['status' => 404]);
}
$source = $meta['downloads'][$source_index];
$gate = aksrt_can_download($post);
if (is_wp_error($gate)) return $gate;
$paid_settings = \AKSRT\Settings\Settings::get_paid_content_settings();
$uid = get_current_user_id();
$cost = aksrt_resource_download_cost($post);
// Daily free-download quota (Zibll).
if ($cost <= 0 && $uid > 0 && function_exists('aksrt_check_free_download_quota')) {
$quota = aksrt_check_free_download_quota($uid, $cost);
if (is_wp_error($quota)) {
return $quota;
}
}
$need_captcha = !empty($paid_settings['download_captcha']) || !empty($meta['require_captcha']);
// 下载双开关:cms_features.download_captcha(或单资源强制)且场景未停用。
if ($need_captcha && function_exists('aksrt_require_captcha')) {
$cap_payload = isset($params['captcha']) && is_array($params['captcha']) ? $params['captcha'] : [];
// 场景未启用时 require 直接放行;启用时强制校验 token。
if (function_exists('aksrt_is_captcha_enabled_for') && aksrt_is_captcha_enabled_for('download')) {
$verify = aksrt_require_captcha('download', $cap_payload);
if ($verify !== true) {
$msg = is_string($verify) ? $verify : __('人机验证失败', 'aksrt');
return new \WP_Error('aksrt_captcha_failed', $msg, ['status' => 400]);
}
}
}
// Purchase is one-shot via cashier (resource order). Token issue does not re-deduct.
$token = $this->issue_token($uid, $post_id, $source_index, 0);
if (is_wp_error($token)) {
return $token;
}
// Record free download against daily quota after token issued.
if ($cost <= 0 && $uid > 0 && function_exists('aksrt_record_user_free_download')) {
aksrt_record_user_free_download($uid, $post_id);
}
$dl_url = home_url('/' . self::ENDPOINT . '/' . $token);
if ($uid > 0 && function_exists('aksrt_add_user_notification')) {
aksrt_add_user_notification($uid, [
'type' => 'download_ready',
'title' => __('资源下载已就绪', 'aksrt'),
'desc' => sprintf(__('《%s》下载链接已生成,可立即开始下载。', 'aksrt'), get_the_title($post)),
'url' => $dl_url,
]);
}
$extract_code = trim((string) ($source['extract_code'] ?? ''));
return new \WP_REST_Response([
'success' => true,
'token' => $token,
'dl_url' => $dl_url,
'expires_in' => self::TOKEN_TTL,
'source_label' => $source['label'] ?? '',
'source_type' => $source['type'] ?? 'direct',
'has_extract' => $extract_code !== '',
'extract_code' => $extract_code,
'balance' => $uid > 0 && class_exists('\AKSRT\Credits\Credits') ? \AKSRT\Credits\Credits::balance($uid) : 0,
], 200);
}
public function maybe_serve_download(): void {
$token = get_query_var(self::QUERY_VAR);
if (!$token) return;
$token = (string) $token;
if (strlen($token) > 64 || !preg_match('/^[A-Za-z0-9]+$/', $token)) {
$this->fail_410();
}
global $wpdb;
$table = \AKSRT\Core\DBMigrator::table('dl_token');
if (!$table) $this->fail_410();
$row = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM {$table} WHERE token = %s LIMIT 1",
$token
), ARRAY_A);
if (!$row) $this->fail_410();
$expires_at = strtotime($row['expires_at'] . ' UTC');
if ($expires_at !== false && time() > $expires_at) $this->fail_410();
if ((int) $row['used_count'] >= (int) $row['max_uses']) $this->fail_410();
$ip = function_exists('aksrt_get_client_ip') ? (string) aksrt_get_client_ip() : (string) ($_SERVER['REMOTE_ADDR'] ?? '');
$ua_hash = sha1((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''));
if (!empty($row['ip_bind']) && $row['ip_bind'] !== $ip) $this->fail_410();
if (!empty($row['ua_hash']) && $row['ua_hash'] !== $ua_hash) $this->fail_410();
$post = get_post((int) $row['post_id']);
if (!$post || !function_exists('aksrt_is_downloadable_content') || !aksrt_is_downloadable_content($post)) $this->fail_410();
$meta = function_exists('aksrt_get_download_box_meta') ? aksrt_get_download_box_meta($post) : [];
$idx = (int) $row['source_index'];
if (empty($meta['downloads'][$idx]['url'])) $this->fail_410();
$wpdb->update(
$table,
['used_count' => (int) $row['used_count'] + 1],
['token' => $token],
['%d'],
['%s']
);
// Count on actual token consumption.
if (function_exists('aksrt_update_post_counter')) {
aksrt_update_post_counter((int) $row['post_id'], '_aksrt_res_download_count', 1);
} else {
$count = (int) get_post_meta((int) $row['post_id'], '_aksrt_res_download_count', true);
update_post_meta((int) $row['post_id'], '_aksrt_res_download_count', $count + 1);
}
$target_url = esc_url_raw((string) $meta['downloads'][$idx]['url']);
$speed_kb = 0;
$uid_speed = (int) ($row['user_id'] ?? 0);
if ($uid_speed > 0 && function_exists('aksrt_get_user_download_speed')) {
$speed_kb = aksrt_get_user_download_speed($uid_speed);
}
// Local attachment / uploads file: optional throttled stream (Zibll speed limit).
$local_path = $this->resolve_local_download_path($target_url);
if ($local_path !== '' && is_readable($local_path)) {
$this->stream_local_file($local_path, $speed_kb);
exit;
}
nocache_headers();
wp_redirect($target_url, 302);
exit;
}
/**
* Map a site-local URL to a filesystem path under uploads (or ABSPATH).
*/
private function resolve_local_download_path(string $url): string {
if ($url === '') {
return '';
}
$uploads = wp_upload_dir();
$baseurl = trailingslashit((string) ($uploads['baseurl'] ?? ''));
$basedir = trailingslashit((string) ($uploads['basedir'] ?? ''));
if ($baseurl !== '' && str_starts_with($url, $baseurl)) {
$rel = substr($url, strlen($baseurl));
$path = $basedir . ltrim(rawurldecode($rel), '/\\');
$real = realpath($path);
$root = realpath($basedir);
if ($real && $root && str_starts_with($real, $root) && is_file($real)) {
return $real;
}
}
// Same-host path under ABSPATH.
$home = trailingslashit(home_url('/'));
if (str_starts_with($url, $home)) {
$rel = substr($url, strlen($home));
$path = ABSPATH . ltrim(rawurldecode($rel), '/\\');
$real = realpath($path);
$root = realpath(ABSPATH);
if ($real && $root && str_starts_with($real, $root) && is_file($real)) {
return $real;
}
}
return '';
}
/**
* Stream a local file with optional KB/s throttle.
*/
private function stream_local_file(string $path, int $speed_kb = 0): void {
$filename = basename($path);
$size = filesize($path);
if ($size === false) {
$this->fail_410();
}
nocache_headers();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . (string) $size);
$chunk = 1024 * 64; // 64KB
$sleep_us = 0;
if ($speed_kb > 0) {
// Emit ~speed_kb KB per second using fixed 64KB chunks when possible.
$bytes_per_sec = max(1024, $speed_kb * 1024);
$chunk = min(1024 * 64, $bytes_per_sec);
$chunk = max(1024, $chunk);
// Sleep so chunk_bytes / second ≈ bytes_per_sec.
$sleep_us = (int) max(0, (int) round(($chunk / $bytes_per_sec) * 1000000) - 1000);
}
$fh = fopen($path, 'rb');
if (!$fh) {
$this->fail_410();
}
// Disable output compression for accurate Content-Length / throttle.
if (function_exists('apache_setenv')) {
@apache_setenv('no-gzip', '1');
}
@ini_set('zlib.output_compression', 'Off');
while (!feof($fh)) {
$buf = fread($fh, $chunk);
if ($buf === false) {
break;
}
echo $buf;
if (function_exists('flush')) {
flush();
}
if ($sleep_us > 0) {
usleep($sleep_us);
}
}
fclose($fh);
}
private function fail_410(): void {
status_header(410);
nocache_headers();
wp_die(esc_html__('下载链接已过期或无效,请回到资源页重新获取。', 'aksrt'), 410);
}
private function issue_token(int $user_id, int $post_id, int $source_index, int $cost) {
global $wpdb;
$table = \AKSRT\Core\DBMigrator::table('dl_token');
if (!$table) {
return new \WP_Error('aksrt_no_table', __('下载令牌表未初始化', 'aksrt'), ['status' => 500]);
}
$token = $this->random_token(self::TOKEN_LEN);
$ip = function_exists('aksrt_get_client_ip') ? (string) aksrt_get_client_ip() : (string) ($_SERVER['REMOTE_ADDR'] ?? '');
$ua_hash = sha1((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''));
$now_utc = (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format('Y-m-d H:i:s');
$expires_utc = (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->modify('+' . self::TOKEN_TTL . ' seconds')->format('Y-m-d H:i:s');
$ok = $wpdb->insert(
$table,
[
'token' => $token,
'user_id' => $user_id,
'post_id' => $post_id,
'source_index' => $source_index,
'cost' => $cost,
'ip_bind' => $ip,
'ua_hash' => $ua_hash,
'used_count' => 0,
'max_uses' => 1,
'expires_at' => $expires_utc,
'created_at' => $now_utc,
],
['%s', '%d', '%d', '%d', '%d', '%s', '%s', '%d', '%d', '%s', '%s']
);
if ($ok === false) {
return new \WP_Error('aksrt_token_insert', __('生成下载令牌失败', 'aksrt'), ['status' => 500]);
}
return $token;
}
private function random_token(int $len): string {
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$max = strlen($alphabet) - 1;
$out = '';
for ($i = 0; $i < $len; $i++) {
$out .= $alphabet[random_int(0, $max)];
}
return $out;
}
}
+250
View File
@@ -0,0 +1,250 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Content;
defined('ABSPATH') || exit;
class DownloadState {
private static $instance = null;
const STATE_NOT_LOGGED_IN = 'not_logged_in';
const STATE_NO_PERMISSION = 'no_permission';
const STATE_NEED_PURCHASE = 'need_purchase';
const STATE_NEED_VIP = 'need_vip';
const STATE_OWNED = 'owned';
const STATE_AVAILABLE = 'available';
const STATE_PENDING_DELIVERY = 'pending_delivery';
/** @deprecated use STATE_NEED_PURCHASE — kept for old templates */
const STATE_INSUFFICIENT_CREDITS = 'need_purchase';
private function __construct() {}
public static function get_instance(): self {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Resolve the current user's download state for a given resource post.
*
* @param int $post_id Resource post ID.
* @return array{
* state:string,can_download:bool,message:string,action_label:string,
* action_url:string,cost:int,balance:int,login_url:string,pay_modo:string,
* amount:float,need_purchase:bool,need_vip:bool,has_paid_access:bool
* }
*/
public function resolve(int $post_id): array {
$login_url = wp_login_url(get_permalink($post_id));
$is_logged_in = is_user_logged_in();
$user_id = $is_logged_in ? get_current_user_id() : 0;
$meta = function_exists('aksrt_get_download_box_meta')
? aksrt_get_download_box_meta($post_id)
: (function_exists('aksrt_get_resource_meta') ? aksrt_get_resource_meta($post_id) : []);
$downloads = is_array($meta['downloads'] ?? null) ? $meta['downloads'] : [];
if ($downloads === []) {
return $this->build_result(
self::STATE_NO_PERMISSION,
false,
__('该资源暂未提供下载链接。', 'aksrt'),
__('暂无下载', 'aksrt'),
'',
0,
0,
$login_url
);
}
$access = class_exists('AKSRT\\Content\\Visibility')
? Visibility::get_post_access_state($post_id, $user_id)
: [];
$priced = function_exists('aksrt_get_user_pay_price')
? aksrt_get_user_pay_price($post_id, $user_id)
: null;
$pay_modo = is_array($priced)
? ((($priced['modo'] ?? '0') === 'points') ? 'points' : '0')
: '0';
$amount = is_array($priced) ? (float) ($priced['amount'] ?? 0) : 0.0;
$cost = function_exists('aksrt_resource_download_cost')
? (int) aksrt_resource_download_cost($post_id)
: 0;
$balance = ($user_id > 0 && class_exists('\AKSRT\Credits\Credits'))
? \AKSRT\Credits\Credits::balance($user_id)
: 0;
$gate = function_exists('aksrt_can_download') ? aksrt_can_download($post_id, $user_id) : true;
if (is_wp_error($gate)) {
$code = $gate->get_error_code();
$data = (array) $gate->get_error_data();
$msg = $gate->get_error_message() ?: __('无下载权限。', 'aksrt');
if ($code === 'aksrt_need_login') {
return $this->build_result(
self::STATE_NOT_LOGGED_IN,
false,
__('登录后可下载此资源。', 'aksrt'),
__('登录下载', 'aksrt'),
(string) ($data['login_url'] ?? $login_url),
$cost,
$balance,
(string) ($data['login_url'] ?? $login_url),
[
'pay_modo' => $pay_modo,
'amount' => $amount,
'need_purchase' => false,
'need_vip' => false,
'has_paid_access' => !empty($access['has_paid_access']),
]
);
}
if ($code === 'aksrt_need_vip') {
$vip_url = function_exists('aksrt_get_user_center_tab_url')
? aksrt_get_user_center_tab_url('credits')
: $login_url;
return $this->build_result(
self::STATE_NEED_VIP,
false,
$msg,
__('开通会员', 'aksrt'),
$vip_url,
$cost,
$balance,
$login_url,
[
'pay_modo' => $pay_modo,
'amount' => $amount,
'need_purchase' => false,
'need_vip' => true,
'has_paid_access' => false,
]
);
}
// need_purchase / legacy insufficient credits → cashier.
if (in_array($code, ['aksrt_need_purchase', 'aksrt_credits_insufficient'], true)) {
$label = $pay_modo === 'points'
? sprintf(__('购买(%s 积分)', 'aksrt'), (string) (int) ceil($amount > 0 ? $amount : $cost))
: __('去购买', 'aksrt');
return $this->build_result(
self::STATE_NEED_PURCHASE,
false,
$msg ?: __('请先购买后再下载。', 'aksrt'),
$label,
'',
$cost,
$balance,
$login_url,
[
'pay_modo' => $pay_modo,
'amount' => $amount > 0 ? $amount : (float) $cost,
'need_purchase' => true,
'need_vip' => false,
'has_paid_access' => false,
]
);
}
return $this->build_result(
self::STATE_NO_PERMISSION,
false,
$msg,
__('无权限', 'aksrt'),
'',
$cost,
$balance,
$login_url,
[
'pay_modo' => $pay_modo,
'amount' => $amount,
'need_purchase' => !empty($access['need_purchase']),
'need_vip' => !empty($access['need_vip']),
'has_paid_access' => !empty($access['has_paid_access']),
]
);
}
// Paid / free unlock.
$has_paid = !empty($access['has_paid_access']);
if ($has_paid || $amount <= 0) {
$owned = $has_paid && $amount > 0;
return $this->build_result(
$owned ? self::STATE_OWNED : self::STATE_AVAILABLE,
true,
$owned
? __('已购买,可下载。', 'aksrt')
: __('此资源可免费下载。', 'aksrt'),
$owned ? __('立即下载', 'aksrt') : __('立即下载', 'aksrt'),
'',
0,
$balance,
$login_url,
[
'pay_modo' => $pay_modo,
'amount' => 0.0,
'need_purchase' => false,
'need_vip' => false,
'has_paid_access' => true,
]
);
}
// Gate true but still priced unpaid (should be rare).
return $this->build_result(
self::STATE_NEED_PURCHASE,
false,
__('请先购买后再下载。', 'aksrt'),
__('去购买', 'aksrt'),
'',
$cost,
$balance,
$login_url,
[
'pay_modo' => $pay_modo,
'amount' => $amount,
'need_purchase' => true,
'need_vip' => false,
'has_paid_access' => false,
]
);
}
/**
* @param array<string,mixed> $extra
*/
private function build_result(
string $state,
bool $can_download,
string $message,
string $action_label,
string $action_url,
int $cost,
int $balance,
string $login_url,
array $extra = []
): array {
return array_merge([
'state' => $state,
'can_download' => $can_download,
'message' => $message,
'action_label' => $action_label,
'action_url' => $action_url,
'cost' => $cost,
'balance' => $balance,
'login_url' => $login_url,
'pay_modo' => '0',
'amount' => 0.0,
'need_purchase' => false,
'need_vip' => false,
'has_paid_access' => false,
], $extra);
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Content;
defined('ABSPATH') || exit;
class Pay {
use PayRest;
use PayOrders;
use PayHelpers;
private static $instance = null;
public static function get_instance(): self {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function init(): void {
add_action('rest_api_init', [$this, 'register_routes']);
add_action('aksrt_order_paid', [$this, 'on_order_paid'], 15, 2);
}
}
+511
View File
@@ -0,0 +1,511 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Content;
defined('ABSPATH') || exit;
trait PayHelpers {
/**
* Cashier preview payload.
*
* @return array|\WP_Error
*/
public function preview(int $post_id, int $user_id = 0, string $coupon_code = '', string $price_type = '') {
$post = get_post($post_id);
if (!($post instanceof \WP_Post) || $post->post_status !== 'publish') {
return new \WP_Error('aksrt_invalid', __('内容不存在', 'aksrt'), ['status' => 404]);
}
$meta = function_exists('aksrt_get_pay_meta') ? aksrt_get_pay_meta($post) : [];
$pay_type = \AKSRT\Core\DomainModel::normalize_pay_type((string) ($meta['pay_type'] ?? \AKSRT\Core\DomainModel::PAY_TYPE_NO));
if ($pay_type === \AKSRT\Core\DomainModel::PAY_TYPE_NO) {
return new \WP_Error('aksrt_not_paid', __('该内容无需购买', 'aksrt'), ['status' => 400]);
}
$uid = $user_id > 0 ? $user_id : get_current_user_id();
$priced = function_exists('aksrt_get_user_pay_price')
? aksrt_get_user_pay_price($post, $uid)
: ['amount' => 0.0, 'base' => 0.0, 'modo' => '0', 'currency' => '¥', 'is_free' => true, 'pay_limit' => 0, 'vip_level' => 0, 'original' => 0.0, 'vip1' => 0.0, 'vip2' => 0.0];
// Optional overbuy override for preview display.
if ($price_type === 'download_limit_over') {
$over = max(0.0, (float) ($meta['download_limit_over_price'] ?? 0));
if ($over > 0) {
$priced['amount'] = $over;
$priced['base'] = $over;
$priced['is_free'] = false;
}
}
$pay_modo = (($priced['modo'] ?? '0') === 'points') ? 'points' : '0';
$pay_limit = (int) ($priced['pay_limit'] ?? 0);
$vip_level = (int) ($priced['vip_level'] ?? 0);
$amount = (float) ($priced['amount'] ?? 0);
$base = (float) ($priced['base'] ?? $amount);
$over_price = max(0.0, (float) ($meta['download_limit_over_price'] ?? 0));
$list_amount = $amount;
$rebate_discount = 0.0;
$coupon_discount = 0.0;
$coupon_payload = null;
$coupon_error = '';
$referrer_active = false;
$referrer_id = 0;
$rebate_price = 0.0;
$payable = $amount;
$coupon_allowed = $pay_modo !== 'points' && $this->is_coupon_allowed($post_id, $meta);
$coupon_desc = '';
if ($coupon_allowed) {
$coupon_desc = trim((string) ($meta['coupon_desc'] ?? ''));
if ($coupon_desc === '' && class_exists('\AKSRT\Settings\Settings') && method_exists('\AKSRT\Settings\Settings', 'get_content_coupon_settings')) {
$coupon_desc = (string) (\AKSRT\Settings\Settings::get_content_coupon_settings()['desc'] ?? '');
}
}
if ($pay_modo !== 'points') {
$discounted = $this->apply_cash_discounts($priced, $post, $meta, $uid, $coupon_code, true);
if (is_wp_error($discounted)) {
// Preview: soft-fail coupon (show error, keep base payable without coupon).
$coupon_error = $discounted->get_error_message();
$discounted = $this->apply_cash_discounts($priced, $post, $meta, $uid, '', true);
}
if (!is_wp_error($discounted)) {
$list_amount = (float) ($discounted['list_amount'] ?? $amount);
$rebate_discount = (float) ($discounted['rebate_discount'] ?? 0);
$coupon_discount = (float) ($discounted['coupon_discount'] ?? 0);
$coupon_payload = $discounted['coupon'] ?? null;
$payable = (float) ($discounted['payable'] ?? $amount);
$referrer_id = (int) ($discounted['referrer_id'] ?? 0);
$referrer_active = $referrer_id > 0;
$rebate_price = (float) ($discounted['rebate_price'] ?? 0);
$amount = $payable;
}
}
$has_paid = false;
$paid_order = null;
if ($uid > 0 && class_exists('\AKSRT\Payment\Order')) {
$has_paid = \AKSRT\Payment\Order::get_instance()->has_paid_access(
$uid,
\AKSRT\Core\DomainModel::ORDER_PRODUCT_RESOURCE,
$post_id
);
if ($has_paid && function_exists('aksrt_get_user_content_paid_order')) {
$paid_order = aksrt_get_user_content_paid_order($post_id, $uid);
}
}
if (!$has_paid && $uid <= 0 && function_exists('aksrt_get_guest_content_paid_order')) {
$guest_order = aksrt_get_guest_content_paid_order($post_id);
if ($guest_order) {
$has_paid = true;
$paid_order = $guest_order;
}
}
$pending_order = null;
if ($uid > 0 && !$has_paid && class_exists('\AKSRT\Payment\OrderRepository')) {
$pending_order = $this->find_pending_content_order($uid, $post_id);
}
$need_vip = $pay_limit > 0 && $vip_level < $pay_limit;
$allow_guest = function_exists('aksrt_allow_guest_content_pay') && aksrt_allow_guest_content_pay($post);
$currency = (string) ($priced['currency'] ?? ($pay_modo === 'points'
? (class_exists('\AKSRT\Settings\Settings') ? \AKSRT\Settings\Settings::get_currency_name() : __('积分', 'aksrt'))
: '¥'));
// Points cashier uses Credits; cash cashier uses wallet (元). Keep both for UI.
$points_balance = ($uid > 0 && class_exists('\AKSRT\Credits\Credits'))
? (int) \AKSRT\Credits\Credits::balance($uid)
: 0;
$wallet_balance = ($uid > 0 && class_exists('\AKSRT\Credits\Balance') && \AKSRT\Credits\Balance::enabled())
? (float) \AKSRT\Credits\Balance::balance($uid)
: 0.0;
$balance = $pay_modo === 'points' ? $points_balance : $wallet_balance;
$methods = $this->available_payment_methods($pay_modo, $uid > 0);
$amount_label = $this->format_amount_label($amount, $pay_modo, $currency);
$base_label = $this->format_amount_label($base, $pay_modo, $currency);
$list_label = $this->format_amount_label($list_amount, $pay_modo, $currency);
$over_label = $over_price > 0 ? $this->format_amount_label($over_price, $pay_modo, $currency) : '';
$vip_page = function_exists('aksrt_get_user_center_tab_url')
? aksrt_get_user_center_tab_url('credits')
: (function_exists('aksrt_get_user_center_url')
? aksrt_get_user_center_url()
: home_url('/'));
$free_limit = $uid > 0 && function_exists('aksrt_get_user_free_download_limit')
? aksrt_get_user_free_download_limit($uid) : 0;
$free_used = $uid > 0 && function_exists('aksrt_get_user_free_downloaded_number')
? aksrt_get_user_free_downloaded_number($uid) : 0;
$quota_over = $free_limit > 0 && $free_used >= $free_limit;
$payable_amount = $pay_modo === 'points' ? (int) ceil($payable) : round($payable, 2);
$balance_enough = $pay_modo === 'points'
? ($points_balance >= (int) ceil($amount))
: ($wallet_balance + 0.0001 >= (float) $payable_amount);
return [
'post_id' => $post_id,
'title' => get_the_title($post),
'permalink' => get_permalink($post),
'pay_type' => $pay_type,
'pay_type_label' => \AKSRT\Core\DomainModel::pay_type_labels()[$pay_type] ?? $pay_type,
'pay_modo' => $pay_modo,
'pay_limit' => $pay_limit,
'vip_level' => $vip_level,
'amount' => $pay_modo === 'points' ? (int) ceil($amount) : round($amount, 2),
'base' => $pay_modo === 'points' ? (int) ceil($base) : round($base, 2),
'list_amount' => $pay_modo === 'points' ? (int) ceil($list_amount) : round($list_amount, 2),
'list_amount_label' => $list_label,
'payable' => $payable_amount,
'original' => (float) ($priced['original'] ?? 0),
'vip1' => (float) ($priced['vip1'] ?? 0),
'vip2' => (float) ($priced['vip2'] ?? 0),
'currency' => $currency,
'amount_label' => $amount_label,
'base_label' => $base_label,
'is_free' => !empty($priced['is_free']) || $amount <= 0,
'has_paid_access' => $has_paid,
'paid_order' => $paid_order ? [
'order_number' => (string) ($paid_order['order_number'] ?? ''),
'paid_at' => (string) ($paid_order['paid_at'] ?? $paid_order['created_at'] ?? ''),
'amount' => (float) ($paid_order['amount'] ?? 0),
'currency' => (string) ($paid_order['currency'] ?? ''),
'payment_method' => (string) ($paid_order['payment_method'] ?? ''),
] : null,
'pending_order' => $pending_order ? [
'order_number' => (string) ($pending_order['order_number'] ?? ''),
'amount' => (float) ($pending_order['amount'] ?? 0),
'payment_method' => (string) ($pending_order['payment_method'] ?? ''),
'created_at' => (string) ($pending_order['created_at'] ?? ''),
] : null,
'need_login' => $uid <= 0 && !$allow_guest,
'allow_guest' => $allow_guest,
'need_vip' => $need_vip,
'need_purchase' => !$has_paid && !$need_vip && $amount > 0,
'logged_in' => $uid > 0,
'balance' => $balance,
'wallet_balance' => $wallet_balance,
'points_balance' => $points_balance,
'balance_enough' => $balance_enough,
'payment_methods' => $methods,
'login_url' => wp_login_url(get_permalink($post)),
'vip_url' => $vip_page,
'credits_url' => $vip_page,
'download_limit_over_price' => $pay_modo === 'points' ? (int) ceil($over_price) : round($over_price, 2),
'download_limit_over_label' => $over_label,
'allow_limit_over' => $over_price > 0,
'quota_over' => $quota_over,
'free_limit' => $free_limit,
'free_used' => $free_used,
'coupon_allowed' => $coupon_allowed,
'coupon_desc' => $coupon_desc,
'coupon_code' => $coupon_code,
'coupon' => $coupon_payload,
'coupon_error' => $coupon_error,
'rebate_discount' => round($rebate_discount, 2),
'rebate_discount_label' => $rebate_discount > 0 ? ('-' . $this->format_amount_label($rebate_discount, $pay_modo, $currency)) : '',
'coupon_discount' => round($coupon_discount, 2),
'coupon_discount_label' => $coupon_discount > 0 ? ('-' . $this->format_amount_label($coupon_discount, $pay_modo, $currency)) : '',
'referrer_active' => $referrer_active,
'discounts' => [
'list_amount' => round($list_amount, 2),
'rebate_discount' => round($rebate_discount, 2),
'coupon_discount' => round($coupon_discount, 2),
'total_discount' => round(max(0, $list_amount - $payable), 2),
'payable' => round($payable, 2),
'rebate_price' => round($rebate_price, 2),
],
// zibll: points_deduction runtime hard-off; card_pass not a content payment method.
'points_deduction_allowed' => function_exists('aksrt_is_allow_points_deduction')
? (bool) aksrt_is_allow_points_deduction('content')
: false,
'card_pass_allowed' => function_exists('aksrt_is_content_card_pass_pay_allowed')
? (bool) aksrt_is_content_card_pass_pay_allowed($post)
: false,
'price_type' => $price_type,
];
}
/**
* @return array{post:\WP_Post,meta:array,priced:array}|\WP_Error
*/
private function assert_purchasable(int $post_id, int $user_id, string $price_type = '') {
$post = get_post($post_id);
if (!($post instanceof \WP_Post) || $post->post_status !== 'publish') {
return new \WP_Error('aksrt_invalid', __('内容不存在', 'aksrt'), ['status' => 404]);
}
$meta = function_exists('aksrt_get_pay_meta') ? aksrt_get_pay_meta($post) : [];
$pay_type = \AKSRT\Core\DomainModel::normalize_pay_type((string) ($meta['pay_type'] ?? \AKSRT\Core\DomainModel::PAY_TYPE_NO));
if ($pay_type === \AKSRT\Core\DomainModel::PAY_TYPE_NO && $price_type !== 'download_limit_over') {
return new \WP_Error('aksrt_not_paid', __('该内容无需购买', 'aksrt'), ['status' => 400]);
}
if ($pay_type === \AKSRT\Core\DomainModel::PAY_TYPE_VIP) {
return new \WP_Error('aksrt_need_vip', __('该内容为 VIP 专属,请开通会员。', 'aksrt'), ['status' => 403]);
}
$pay_modo_meta = (($meta['pay_modo'] ?? '0') === 'points') ? 'points' : '0';
$allow_guest = function_exists('aksrt_allow_guest_content_pay') && aksrt_allow_guest_content_pay($post);
if ($user_id <= 0) {
if ($pay_modo_meta === 'points' || !$allow_guest) {
return new \WP_Error('aksrt_need_login', __('请先登录后再购买。', 'aksrt'), [
'status' => 401,
'login_url' => wp_login_url(get_permalink($post)),
]);
}
}
$priced = function_exists('aksrt_get_user_pay_price')
? aksrt_get_user_pay_price($post, $user_id)
: ['amount' => 0.0, 'modo' => '0', 'pay_limit' => 0, 'vip_level' => 0, 'is_free' => true, 'base' => 0.0];
// Free daily quota overbuy: override amount, ignore VIP discount (zibll).
if ($price_type === 'download_limit_over') {
$over = max(0.0, (float) ($meta['download_limit_over_price'] ?? 0));
if ($over <= 0) {
return new \WP_Error('aksrt_no_overbuy', __('未开放超额下载购买。', 'aksrt'), ['status' => 400]);
}
$priced['amount'] = $over;
$priced['base'] = $over;
$priced['is_free'] = false;
$priced['vip_amount'] = -1.0;
}
$pay_limit = (int) ($priced['pay_limit'] ?? 0);
$vip_level = (int) ($priced['vip_level'] ?? 0);
if ($pay_limit > 0 && $vip_level < $pay_limit && $price_type !== 'download_limit_over') {
return new \WP_Error('aksrt_need_vip', sprintf(
/* translators: %d: required VIP level */
__('该资源仅限 VIP%s 及以上会员购买/下载。', 'aksrt'),
max(1, $pay_limit)
), [
'status' => 403,
'pay_limit' => $pay_limit,
]);
}
if ($user_id > 0 && class_exists('\AKSRT\Payment\Order') && \AKSRT\Payment\Order::get_instance()->has_paid_access(
$user_id,
\AKSRT\Core\DomainModel::ORDER_PRODUCT_RESOURCE,
$post_id
)) {
return new \WP_Error('aksrt_already_paid', __('您已购买该内容。', 'aksrt'), [
'status' => 200,
'has_paid_access' => true,
'reload' => true,
]);
}
if ($user_id <= 0 && function_exists('aksrt_guest_has_paid_access') && aksrt_guest_has_paid_access($post_id)) {
return new \WP_Error('aksrt_already_paid', __('您已购买该内容。', 'aksrt'), [
'status' => 200,
'has_paid_access' => true,
'reload' => true,
]);
}
return [
'post' => $post,
'meta' => $meta,
'priced' => $priced,
];
}
/**
* @return array<int, array{id:string,name:string}>
*/
private function available_payment_methods(string $pay_modo, bool $logged_in = true): array {
if ($pay_modo === 'points') {
return [
['id' => 'points', 'name' => __('积分支付', 'aksrt')],
];
}
if (function_exists('aksrt_list_cash_payment_methods')) {
return aksrt_list_cash_payment_methods($logged_in);
}
return $logged_in
? [['id' => 'balance', 'name' => __('站内余额', 'aksrt')]]
: [['id' => 'alipay', 'name' => __('支付宝', 'aksrt')]];
}
private function is_coupon_allowed(int $post_id, array $meta): bool {
if (!empty($meta['coupon_s'])) {
return true;
}
if (function_exists('aksrt_is_content_coupon_allowed')) {
return aksrt_is_content_coupon_allowed($post_id);
}
if (class_exists('\AKSRT\Settings\Settings') && method_exists('\AKSRT\Settings\Settings', 'get_content_coupon_settings')) {
return !empty(\AKSRT\Settings\Settings::get_content_coupon_settings()['enabled']);
}
if (class_exists('\AKSRT\Settings\Settings') && method_exists('\AKSRT\Settings\Settings', 'get_paid_content_settings')) {
return !empty(\AKSRT\Settings\Settings::get_paid_content_settings()['coupon_post_s']);
}
return false;
}
/**
* @return array{id:int,ratio:float}
*/
private function resolve_referrer_context(int $user_id): array {
$empty = ['id' => 0, 'ratio' => 0.0];
if (!class_exists('\AKSRT\Settings\Settings') || !method_exists('\AKSRT\Settings\Settings', 'get_payment_affiliate_settings')) {
return $empty;
}
$aff = \AKSRT\Settings\Settings::get_payment_affiliate_settings();
if (empty($aff['enabled'])) {
return $empty;
}
$referrer_id = 0;
if (class_exists('\AKSRT\Credits\Invite') && method_exists(\AKSRT\Credits\Invite::get_instance(), 'get_referrer')) {
$referrer_id = (int) \AKSRT\Credits\Invite::get_instance()->get_referrer($user_id);
}
if ($referrer_id <= 0) {
return $empty;
}
$ratio = (float) ($aff['ratio'] ?? 0);
$user_ratio = is_array($aff['user_ratio'] ?? null) ? $aff['user_ratio'] : [];
$ref_vip = 0;
if (function_exists('aksrt_get_user_vip_level')) {
$ref_vip = (int) aksrt_get_user_vip_level($referrer_id);
}
if ($ref_vip >= 2 && isset($user_ratio['vip2']) && (float) $user_ratio['vip2'] > 0) {
$ratio = (float) $user_ratio['vip2'];
} elseif ($ref_vip >= 1 && isset($user_ratio['vip1']) && (float) $user_ratio['vip1'] > 0) {
$ratio = (float) $user_ratio['vip1'];
} elseif (isset($user_ratio['user'])) {
$ratio = (float) $user_ratio['user'];
}
$ratio = max(0.0, min(100.0, $ratio));
if ($ratio <= 0) {
return $empty;
}
return ['id' => $referrer_id, 'ratio' => $ratio];
}
/**
* Cash discount chain: VIP-priced list → 推广折扣 → coupon → payable + commission snapshot.
*
* @param array<string,mixed> $priced
* @param array<string,mixed> $meta
* @return array|\WP_Error
*/
private function apply_cash_discounts(array $priced, \WP_Post $post, array $meta, int $user_id, string $coupon_code = '', bool $soft_coupon = false) {
$list_amount = round(max(0.0, (float) ($priced['amount'] ?? 0)), 2);
$pay = $list_amount;
$rebate_discount = 0.0;
$coupon_discount = 0.0;
$coupon_meta = [];
$ref = $this->resolve_referrer_context($user_id);
$referrer_id = (int) ($ref['id'] ?? 0);
$ratio = (float) ($ref['ratio'] ?? 0);
// 1) Buyer-facing 推广折扣 (fixed).
$fixed = max(0.0, (float) ($meta['pay_rebate_discount'] ?? 0));
if ($referrer_id > 0 && $ratio > 0 && $fixed > 0 && $pay > 0) {
$rebate_discount = round(min($pay, $fixed), 2);
$pay = round(max(0.0, $pay - $rebate_discount), 2);
}
// 2) Coupon after rebate discount.
$coupon_code = sanitize_text_field($coupon_code);
if ($coupon_code !== '') {
if (!$this->is_coupon_allowed((int) $post->ID, $meta)) {
$err = new \WP_Error('aksrt_coupon_not_allowed', __('当前内容不支持优惠码。', 'aksrt'), ['status' => 400]);
if (!$soft_coupon) {
return $err;
}
} elseif (!class_exists('\AKSRT\Payment\Coupon')) {
$err = new \WP_Error('aksrt_coupon_unavailable', __('优惠券系统不可用。', 'aksrt'), ['status' => 500]);
if (!$soft_coupon) {
return $err;
}
} else {
$result = \AKSRT\Payment\Coupon::get_instance()->validate($coupon_code, $pay, [
'user_id' => max(0, $user_id),
'product_ids' => [(int) $post->ID],
'context' => 'content',
]);
if (empty($result['valid'])) {
$err = new \WP_Error(
'aksrt_coupon_error',
(string) ($result['message'] ?? __('优惠码不可用。', 'aksrt')),
['status' => 400]
);
if (!$soft_coupon) {
return $err;
}
} else {
$coupon_discount = round(max(0.0, (float) ($result['discount'] ?? 0)), 2);
if ($coupon_discount > $pay) {
$coupon_discount = $pay;
}
$pay = round(max(0.0, $pay - $coupon_discount), 2);
$c = is_array($result['coupon'] ?? null) ? $result['coupon'] : [];
$coupon_meta = [
'id' => (int) ($c['id'] ?? 0),
'code' => (string) ($c['code'] ?? $coupon_code),
'type' => (string) ($c['type'] ?? ''),
'value' => (float) ($c['value'] ?? 0),
'discount' => $coupon_discount,
];
}
}
}
$payable = round(max(0.0, $pay), 2);
$rebate_price = 0.0;
if ($referrer_id > 0 && $ratio > 0 && $payable > 0) {
$rebate_price = round($payable * $ratio / 100, 2);
}
return [
'list_amount' => $list_amount,
'rebate_discount' => $rebate_discount,
'coupon_discount' => $coupon_discount,
'coupon' => $coupon_meta,
'payable' => $payable,
'referrer_id' => $referrer_id,
'rebate_price' => $rebate_price,
'ratio' => $ratio,
];
}
private function format_amount_label(float $amount, string $pay_modo, string $currency): string {
if ($amount <= 0) {
return (string) __('免费', 'aksrt');
}
$n = function_exists('aksrt_format_price') ? aksrt_format_price($amount) : (string) $amount;
if ($pay_modo === 'points') {
return $n . ' ' . $currency;
}
return $currency . $n;
}
}
+547
View File
@@ -0,0 +1,547 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Content;
defined('ABSPATH') || exit;
trait PayOrders {
/**
* Bump content sales when a resource order is paid.
*
* @param string $order_number
* @param array $paid_order
*/
public function on_order_paid(string $order_number, array $paid_order): void {
$product_type = sanitize_key((string) ($paid_order['product_type'] ?? ''));
if ($product_type !== \AKSRT\Core\DomainModel::ORDER_PRODUCT_RESOURCE) {
return;
}
$post_id = (int) ($paid_order['product_id'] ?? 0);
if ($post_id <= 0) {
return;
}
// Only count normal posts (content pay), not necessarily forum topics.
$post = get_post($post_id);
if (!($post instanceof \WP_Post) || $post->post_type !== 'post') {
return;
}
if (function_exists('aksrt_bump_content_sales_volume')) {
aksrt_bump_content_sales_volume($post_id, 1);
} else {
$key = \AKSRT\Core\DomainModel::RESOURCE_SALES_VOLUME_KEY;
$cur = (int) get_post_meta($post_id, $key, true);
update_post_meta($post_id, $key, $cur + 1);
}
// Guest cookie unlock (user_id=0).
$uid = (int) ($paid_order['user_id'] ?? 0);
if ($uid <= 0 && function_exists('aksrt_set_guest_content_pay_cookies')) {
// Ensure full order row for token material.
if (class_exists('\AKSRT\Payment\OrderRepository')) {
$full = \AKSRT\Payment\OrderRepository::get_instance()->get($order_number);
if (is_array($full)) {
$paid_order = array_merge($full, $paid_order);
}
}
aksrt_set_guest_content_pay_cookies($paid_order);
}
// Consume coupon + write affiliate commission (cash content only; idempotent).
$this->finalize_content_order_side_effects($order_number, $paid_order);
if (class_exists('\AKSRT\Payment\OrderRepository')) {
\AKSRT\Payment\OrderRepository::get_instance()->update_status(
$order_number,
\AKSRT\Payment\Order::STATUS_COMPLETED,
['note' => __('内容权益已发放。', 'aksrt')]
);
}
}
/**
* On paid: burn coupon (if any) and create affiliate rebate log.
*/
private function finalize_content_order_side_effects(string $order_number, array $order): void {
$meta = $this->decode_order_note_meta($order);
if (empty($meta['content_pay'])) {
return;
}
// Points: no coupon burn / no cash commission.
if (($meta['pay_modo'] ?? '') === 'points') {
return;
}
$buyer_id = (int) ($order['user_id'] ?? 0);
// Coupon burn (shared helper; idempotent via coupon_usage.order_number).
if (function_exists('aksrt_burn_order_coupon')) {
aksrt_burn_order_coupon($order_number, $meta, $buyer_id);
}
// Affiliate commission (does not reduce buyer pay).
$referrer_id = (int) ($meta['referrer_id'] ?? 0);
$rebate_price = round((float) ($meta['rebate_price'] ?? 0), 2);
$pay_amount = round((float) ($order['amount'] ?? $meta['payable'] ?? 0), 2);
if ($referrer_id <= 0 || $rebate_price <= 0 || $pay_amount <= 0) {
return;
}
if (!class_exists('\AKSRT\Payment\Rebate')) {
return;
}
if ($this->rebate_log_exists($order_number, $referrer_id)) {
return;
}
\AKSRT\Payment\Rebate::get_instance()->create([
'user_id' => $referrer_id,
'order_number' => $order_number,
'source_user_id' => $buyer_id,
'amount' => $rebate_price,
'type' => \AKSRT\Payment\Rebate::TYPE_ORDER,
'note' => sprintf(
/* translators: 1: order number 2: post id */
__('内容推广返佣 订单 %1$s 内容 #%2$d', 'aksrt'),
$order_number,
(int) ($order['product_id'] ?? $meta['post_id'] ?? 0)
),
]);
}
/**
* @param array<string,mixed> $order
* @return array<string,mixed>
*/
private function decode_order_note_meta(array $order): array {
if (is_array($order['meta_payload'] ?? null) && $order['meta_payload'] !== []) {
return $order['meta_payload'];
}
$note = (string) ($order['note'] ?? '');
if ($note === '') {
return [];
}
$decoded = json_decode($note, true);
return is_array($decoded) ? $decoded : [];
}
private function rebate_log_exists(string $order_number, int $referrer_id): bool {
global $wpdb;
$table = \AKSRT\Core\DBMigrator::table('rebate_log');
if ($table === '' || $order_number === '') {
return false;
}
$found = $wpdb->get_var($wpdb->prepare(
"SELECT id FROM {$table} WHERE order_number = %s AND user_id = %d LIMIT 1",
$order_number,
$referrer_id
));
return !empty($found);
}
/**
* Points one-shot purchase → permanent resource order.
*
* @return array|\WP_Error
*/
public function create_and_pay_points(int $post_id, int $user_id, string $price_type = '') {
$assert = $this->assert_purchasable($post_id, $user_id, $price_type);
if (is_wp_error($assert)) {
return $assert;
}
$priced = $assert['priced'];
if ((($priced['modo'] ?? '0') !== 'points')) {
return new \WP_Error('aksrt_wrong_modo', __('该内容不支持积分支付。', 'aksrt'), ['status' => 400]);
}
$amount = (int) ceil((float) ($priced['amount'] ?? 0));
if ($amount <= 0) {
return [
'success' => true,
'data' => [
'free' => true,
'message' => __('无需支付,已可访问。', 'aksrt'),
'reload' => true,
],
];
}
if (!class_exists('\AKSRT\Payment\Order') || !class_exists('\AKSRT\Credits\Credits')) {
return new \WP_Error('aksrt_pay_unavailable', __('支付系统不可用。', 'aksrt'), ['status' => 500]);
}
$balance = \AKSRT\Credits\Credits::balance($user_id);
if ($balance < $amount) {
return new \WP_Error('aksrt_credits_insufficient', __('积分不足,暂时无法支付。', 'aksrt'), [
'status' => 402,
'balance' => $balance,
'cost' => $amount,
]);
}
$note = wp_json_encode([
'content_pay' => 1,
'pay_modo' => 'points',
'post_id' => $post_id,
'price_type' => $price_type,
'vip_level' => (int) ($priced['vip_level'] ?? 0),
'base' => (float) ($priced['base'] ?? $amount),
'amount' => $amount,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$order_number = \AKSRT\Payment\OrderRepository::get_instance()->create([
'user_id' => $user_id,
'product_type' => \AKSRT\Core\DomainModel::ORDER_PRODUCT_RESOURCE,
'product_id' => $post_id,
'amount' => (float) $amount,
'currency' => 'points',
'status' => \AKSRT\Payment\Order::STATUS_PENDING,
'payment_method' => 'points',
'note' => is_string($note) ? $note : '',
'expires_at' => gmdate('Y-m-d H:i:s', time() + 30 * MINUTE_IN_SECONDS),
]);
if ($order_number === '') {
return new \WP_Error('aksrt_order_create_failed', __('创建订单失败。', 'aksrt'), ['status' => 500]);
}
$lock = class_exists('\AKSRT\Payment\PaymentAttemptLock')
? \AKSRT\Payment\PaymentAttemptLock::acquire($order_number)
: false;
if ($lock === false) {
return new \WP_Error('aksrt_pay_locked', __('该订单正在发起支付,请稍后重试。', 'aksrt'), ['status' => 409]);
}
try {
$deducted = \AKSRT\Credits\Credits::deduct(
$user_id,
$amount,
'content_points_pay',
['type' => 'post', 'id' => $post_id, 'order' => $order_number],
sprintf(__('积分购买《%s》', 'aksrt'), get_the_title($post_id))
);
if (is_wp_error($deducted) || $deducted === false) {
\AKSRT\Payment\Order::get_instance()->update_status($order_number, \AKSRT\Payment\Order::STATUS_CANCELLED, [
'note' => __('积分扣除失败,自动取消', 'aksrt'),
]);
$msg = is_wp_error($deducted) ? $deducted->get_error_message() : __('积分扣除失败。', 'aksrt');
return new \WP_Error('aksrt_credits_deduct_failed', $msg ?: __('积分扣除失败。', 'aksrt'), ['status' => 400]);
}
$paid = \AKSRT\Payment\Order::get_instance()->update_status($order_number, \AKSRT\Payment\Order::STATUS_PAID, [
'payment_method' => 'points',
'payment_transaction_id' => 'points_' . $order_number,
'note' => sprintf(__('积分支付 %d 积分。', 'aksrt'), $amount),
'require_transition' => true,
]);
if (!$paid) {
\AKSRT\Credits\Credits::add(
$user_id,
$amount,
'content_points_pay_refund',
['type' => 'post', 'id' => $post_id, 'order' => $order_number],
sprintf(__('购买失败退款:%s', 'aksrt'), get_the_title($post_id))
);
return new \WP_Error('aksrt_order_confirm_failed', __('订单确认失败,已尝试退回积分。', 'aksrt'), ['status' => 500]);
}
} finally {
\AKSRT\Payment\PaymentAttemptLock::release($order_number, $lock);
}
return [
'success' => true,
'data' => [
'order_number' => $order_number,
'amount' => $amount,
'pay_modo' => 'points',
'balance' => \AKSRT\Credits\Credits::balance($user_id),
'message' => __('支付成功', 'aksrt'),
'reload' => true,
],
];
}
/**
* Cash order create + balance/gateway pay.
*
* @return array|\WP_Error
*/
public function create_cash_order(int $post_id, int $user_id, string $payment_method = 'balance', string $price_type = '', string $coupon_code = '') {
$assert = $this->assert_purchasable($post_id, $user_id, $price_type);
if (is_wp_error($assert)) {
return $assert;
}
$post = $assert['post'];
$meta = $assert['meta'];
$priced = $assert['priced'];
if ((($priced['modo'] ?? '0') === 'points')) {
return new \WP_Error('aksrt_wrong_modo', __('该内容仅支持积分支付。', 'aksrt'), ['status' => 400]);
}
// Card pass cannot stack coupon (zibll). Content cashier does not sell via card_pass.
$payment_method = sanitize_key($payment_method);
if ($payment_method === 'card_pass') {
if (!function_exists('aksrt_is_content_card_pass_pay_allowed') || !aksrt_is_content_card_pass_pay_allowed($post)) {
return new \WP_Error(
'aksrt_card_pass_not_allowed',
__('内容购买不支持卡密支付,请在用户中心使用卡密兑换余额/会员/积分。', 'aksrt'),
['status' => 400]
);
}
$coupon_code = '';
}
$discounted = $this->apply_cash_discounts($priced, $post, $meta, $user_id, $coupon_code, false);
if (is_wp_error($discounted)) {
return $discounted;
}
$amount = round((float) ($discounted['payable'] ?? 0), 2);
$list_amount = round((float) ($discounted['list_amount'] ?? $amount), 2);
$rebate_discount = round((float) ($discounted['rebate_discount'] ?? 0), 2);
$coupon_discount = round((float) ($discounted['coupon_discount'] ?? 0), 2);
$coupon_meta = is_array($discounted['coupon'] ?? null) ? $discounted['coupon'] : [];
$referrer_id = (int) ($discounted['referrer_id'] ?? 0);
$rebate_price = round((float) ($discounted['rebate_price'] ?? 0), 2);
if ($amount <= 0) {
// Free after discount (or free content): create 0-paid order for access + burn coupon.
if (!class_exists('\AKSRT\Payment\Order') || !class_exists('\AKSRT\Payment\OrderRepository')) {
return new \WP_Error('aksrt_pay_unavailable', __('支付系统不可用。', 'aksrt'), ['status' => 500]);
}
$note = wp_json_encode([
'content_pay' => 1,
'pay_modo' => '0',
'post_id' => $post_id,
'price_type' => $price_type,
'vip_level' => (int) ($priced['vip_level'] ?? 0),
'base' => (float) ($priced['base'] ?? $list_amount),
'list_amount' => $list_amount,
'rebate_discount' => $rebate_discount,
'coupon_discount' => $coupon_discount,
'discount' => $coupon_discount,
'coupon' => $coupon_meta,
'coupon_code' => (string) ($coupon_meta['code'] ?? $coupon_code),
'amount' => 0,
'payable' => 0,
'referrer_id' => $referrer_id,
'rebate_price' => 0,
'ip_address' => function_exists('aksrt_pay_client_ip') ? aksrt_pay_client_ip() : (string) ($_SERVER['REMOTE_ADDR'] ?? ''),
'guest' => $user_id <= 0 ? 1 : 0,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$order_number = \AKSRT\Payment\OrderRepository::get_instance()->create([
'user_id' => max(0, $user_id),
'product_type' => \AKSRT\Core\DomainModel::ORDER_PRODUCT_RESOURCE,
'product_id' => $post_id,
'amount' => 0.0,
'currency' => 'CNY',
'status' => \AKSRT\Payment\Order::STATUS_PENDING,
'payment_method' => 'free',
'note' => is_string($note) ? $note : '',
'expires_at' => gmdate('Y-m-d H:i:s', time() + 30 * MINUTE_IN_SECONDS),
]);
if ($order_number === '') {
return new \WP_Error('aksrt_order_create_failed', __('创建订单失败。', 'aksrt'), ['status' => 500]);
}
$paid = \AKSRT\Payment\Order::get_instance()->update_status($order_number, \AKSRT\Payment\Order::STATUS_PAID, [
'payment_method' => 'free',
'payment_transaction_id' => 'free_' . $order_number,
'note' => __('优惠后无需支付。', 'aksrt'),
]);
if (!$paid) {
return new \WP_Error('aksrt_order_confirm_failed', __('订单确认失败。', 'aksrt'), ['status' => 500]);
}
return [
'success' => true,
'data' => [
'order_number' => $order_number,
'amount' => 0,
'pay_modo' => '0',
'free' => true,
'message' => __('无需支付,已可访问。', 'aksrt'),
'reload' => true,
],
];
}
if (!class_exists('\AKSRT\Payment\Order') || !class_exists('\AKSRT\Payment\OrderRepository')) {
return new \WP_Error('aksrt_pay_unavailable', __('支付系统不可用。', 'aksrt'), ['status' => 500]);
}
if ($payment_method === '') {
$payment_method = $user_id > 0 ? 'balance' : 'alipay';
}
if ($user_id <= 0 && in_array($payment_method, ['balance', 'points'], true)) {
$payment_method = 'alipay';
}
$coupon_code_norm = (string) ($coupon_meta['code'] ?? $coupon_code);
// Resume existing pending content order for this post when amount + coupon match (logged-in only).
$pending = $user_id > 0 ? $this->find_pending_content_order($user_id, $post_id) : null;
$can_resume = false;
if ($pending && abs((float) ($pending['amount'] ?? 0) - $amount) < 0.001) {
$pending_meta = $this->decode_order_note_meta($pending);
$pending_coupon = (string) ($pending_meta['coupon_code'] ?? '');
if (is_array($pending_meta['coupon'] ?? null)) {
$pending_coupon = (string) ($pending_meta['coupon']['code'] ?? $pending_coupon);
}
if ($pending_coupon === $coupon_code_norm) {
$can_resume = true;
}
}
if ($can_resume) {
$order_number = (string) ($pending['order_number'] ?? '');
$order = $pending;
} else {
$note = wp_json_encode([
'content_pay' => 1,
'pay_modo' => '0',
'post_id' => $post_id,
'price_type' => $price_type,
'vip_level' => (int) ($priced['vip_level'] ?? 0),
'base' => (float) ($priced['base'] ?? $list_amount),
'list_amount' => $list_amount,
'rebate_discount' => $rebate_discount,
'coupon_discount' => $coupon_discount,
'discount' => $coupon_discount,
'coupon' => $coupon_meta,
'coupon_code' => $coupon_code_norm,
'amount' => $amount,
'payable' => $amount,
'referrer_id' => $referrer_id,
'rebate_price' => $rebate_price,
'ip_address' => function_exists('aksrt_pay_client_ip') ? aksrt_pay_client_ip() : (string) ($_SERVER['REMOTE_ADDR'] ?? ''),
'guest' => $user_id <= 0 ? 1 : 0,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$order_number = \AKSRT\Payment\OrderRepository::get_instance()->create([
'user_id' => max(0, $user_id),
'product_type' => \AKSRT\Core\DomainModel::ORDER_PRODUCT_RESOURCE,
'product_id' => $post_id,
'amount' => $amount,
'currency' => 'CNY',
'status' => \AKSRT\Payment\Order::STATUS_PENDING,
'payment_method' => $payment_method,
'note' => is_string($note) ? $note : '',
'expires_at' => gmdate('Y-m-d H:i:s', time() + 30 * MINUTE_IN_SECONDS),
]);
if ($order_number === '') {
return new \WP_Error('aksrt_order_create_failed', __('创建订单失败。', 'aksrt'), ['status' => 500]);
}
$order = \AKSRT\Payment\OrderRepository::get_instance()->get($order_number);
if (!$order) {
return new \WP_Error('aksrt_order_create_failed', __('创建订单失败。', 'aksrt'), ['status' => 500]);
}
}
$payment_method = sanitize_key($payment_method ?: (string) ($order['payment_method'] ?? 'balance'));
if ($payment_method === '') {
$payment_method = $user_id > 0 ? 'balance' : 'alipay';
}
$order['subject'] = sprintf(
/* translators: %s: post title */
__('购买《%s》', 'aksrt'),
get_the_title($post_id)
);
$order['payment_method'] = $payment_method;
// Ensure gateway uses discounted amount.
$order['amount'] = $amount;
if (!class_exists('\AKSRT\Payment\Gateway')) {
return new \WP_Error('aksrt_pay_unavailable', __('支付网关不可用。', 'aksrt'), ['status' => 500]);
}
$resolved = \AKSRT\Payment\PaymentOrchestrator::resolve_gateway($payment_method);
if (empty($resolved['gateway'])) {
return new \WP_Error(
(string) ($resolved['error_code'] ?? 'aksrt_gateway_unavailable'),
(string) ($resolved['message'] ?? __('当前支付方式不可用。', 'aksrt')),
['status' => 400, 'order_number' => $order_number]
);
}
$payment_result = \AKSRT\Payment\PaymentOrchestrator::pay($resolved['gateway'], $order, [
'paid_note' => __('用户完成内容购买支付。', 'aksrt'),
]);
if (empty($payment_result['success'])) {
return new \WP_Error(
(string) ($payment_result['code'] ?? 'aksrt_pay_failed'),
(string) ($payment_result['message'] ?? __('支付失败。', 'aksrt')),
['status' => 402, 'order_number' => $order_number]
);
}
if (!empty($payment_result['redirect'])) {
return [
'success' => true,
'data' => [
'redirect' => true,
'payment_url' => (string) ($payment_result['payment_url'] ?? ''),
'qr_content' => (string) ($payment_result['qr_content'] ?? ''),
'order_number' => $order_number,
'amount' => $amount,
'pay_modo' => '0',
'message' => $payment_result['message'],
'reload' => false,
'poll' => true,
],
];
}
return [
'success' => true,
'data' => [
'order_number' => $order_number,
'amount' => $amount,
'pay_modo' => '0',
'message' => $payment_result['message'],
'reload' => true,
],
];
}
/**
* @return array<string,mixed>|null
*/
private function find_pending_content_order(int $user_id, int $post_id): ?array {
if ($user_id <= 0 || $post_id <= 0 || !class_exists('\AKSRT\Payment\OrderRepository')) {
return null;
}
$orders = \AKSRT\Payment\OrderRepository::get_instance()->get_user_orders($user_id, [
'product_type' => \AKSRT\Core\DomainModel::ORDER_PRODUCT_RESOURCE,
'status' => \AKSRT\Core\DomainModel::ORDER_STATUS_PENDING,
'limit' => 20,
'offset' => 0,
]);
foreach ($orders as $order) {
if ((int) ($order['product_id'] ?? 0) === $post_id) {
return $order;
}
}
return null;
}
}
+209
View File
@@ -0,0 +1,209 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Content;
defined('ABSPATH') || exit;
trait PayRest {
public function register_routes(): void {
register_rest_route('aksrt/v1', '/pay/content/(?P<id>\d+)', [
[
'methods' => 'GET',
'callback' => [$this, 'rest_preview'],
'permission_callback' => [$this, 'check_rest_nonce'],
],
[
'methods' => 'POST',
'callback' => [$this, 'rest_purchase'],
'permission_callback' => [$this, 'check_rest_nonce'],
],
]);
register_rest_route('aksrt/v1', '/pay/content/order/(?P<order_number>[A-Za-z0-9_-]+)', [
'methods' => 'GET',
'callback' => [$this, 'rest_order_status'],
'permission_callback' => [$this, 'check_rest_nonce'],
]);
}
/**
* REST nonce for logged-in users (wp_rest). Guests get 401 on purchase paths.
*
* @param \WP_REST_Request $request
* @return true|\WP_Error
*/
public function check_rest_nonce(\WP_REST_Request $request) {
$nonce = $request->get_header('x-wp-nonce');
if (!$nonce) {
return new \WP_Error('aksrt_rest_no_nonce', __('缺少安全令牌', 'aksrt'), ['status' => 403]);
}
if (!wp_verify_nonce($nonce, 'wp_rest')) {
return new \WP_Error('aksrt_rest_bad_nonce', __('安全令牌已过期,请刷新页面', 'aksrt'), ['status' => 403]);
}
return true;
}
/**
* GET /pay/content/{id}
* query: coupon_code?, price_type?
*/
public function rest_preview(\WP_REST_Request $request) {
$post_id = (int) $request['id'];
$uid = get_current_user_id();
$coupon_code = sanitize_text_field((string) ($request->get_param('coupon_code') ?? $request->get_param('coupon') ?? ''));
$price_type = sanitize_key((string) ($request->get_param('price_type') ?? ''));
if ($price_type !== 'download_limit_over') {
$price_type = '';
}
$preview = $this->preview($post_id, $uid, $coupon_code, $price_type);
if (is_wp_error($preview)) {
return $preview;
}
return new \WP_REST_Response($preview, 200);
}
/**
* POST /pay/content/{id}
* body: { mode?: points|cash, payment_method?: balance|alipay|..., price_type?: ''|download_limit_over, coupon_code?: string }
*/
public function rest_purchase(\WP_REST_Request $request) {
$post_id = (int) $request['id'];
$uid = get_current_user_id();
$params = $request->get_json_params();
if (!is_array($params)) {
$params = $request->get_params();
}
$price_type = sanitize_key((string) ($params['price_type'] ?? ''));
if ($price_type !== 'download_limit_over') {
$price_type = '';
}
$coupon_code = sanitize_text_field((string) ($params['coupon_code'] ?? $params['coupon'] ?? ''));
// Guest allowed only for cash + pay_limit=0 + setting on.
if ($uid <= 0) {
$post = get_post($post_id);
$allow_guest = function_exists('aksrt_allow_guest_content_pay') && aksrt_allow_guest_content_pay($post);
if (!$allow_guest) {
return new \WP_Error('aksrt_need_login', __('请先登录后再购买。', 'aksrt'), [
'status' => 401,
'login_url' => wp_login_url($post ? get_permalink($post) : home_url('/')),
]);
}
}
$gate = $this->assert_purchasable($post_id, $uid, $price_type);
if (is_wp_error($gate)) {
return $gate;
}
$priced = $gate['priced'];
$pay_modo = (($priced['modo'] ?? '0') === 'points') ? 'points' : '0';
$mode = sanitize_key((string) ($params['mode'] ?? ''));
if ($mode === '') {
$mode = $pay_modo === 'points' ? 'points' : 'cash';
}
if ($mode === 'points' || $pay_modo === 'points') {
if ($uid <= 0) {
return new \WP_Error('aksrt_need_login', __('积分支付请先登录。', 'aksrt'), ['status' => 401]);
}
// Points path: ignore coupon (zibll parity).
return $this->rest_wrap_result($this->create_and_pay_points($post_id, $uid, $price_type));
}
$payment_method = sanitize_key((string) ($params['payment_method'] ?? 'balance'));
if ($payment_method === '' || $payment_method === 'cash') {
$payment_method = 'balance';
}
// Guests cannot use balance/points gateways.
if ($uid <= 0 && in_array($payment_method, ['balance', 'points'], true)) {
$payment_method = 'alipay';
}
return $this->rest_wrap_result($this->create_cash_order($post_id, $uid, $payment_method, $price_type, $coupon_code));
}
/**
* GET /pay/content/order/{order_number}
*/
public function rest_order_status(\WP_REST_Request $request) {
$uid = get_current_user_id();
$order_number = sanitize_text_field((string) $request['order_number']);
if ($order_number === '' || !class_exists('\AKSRT\Payment\OrderRepository')) {
return new \WP_Error('aksrt_invalid', __('订单不存在', 'aksrt'), ['status' => 404]);
}
$repo = \AKSRT\Payment\OrderRepository::get_instance();
if ($uid > 0) {
$order = $repo->get_user_order($uid, $order_number);
} else {
$order = $repo->get($order_number);
// Guest may only poll own guest cash orders (user_id=0): content resource.
$ptype = sanitize_key((string) ($order['product_type'] ?? ''));
$guest_types = [
\AKSRT\Core\DomainModel::ORDER_PRODUCT_RESOURCE,
];
if ($order && ((int) ($order['user_id'] ?? -1) !== 0 || !in_array($ptype, $guest_types, true))) {
$order = null;
}
}
if (!$order) {
return new \WP_Error('aksrt_invalid', __('订单不存在', 'aksrt'), ['status' => 404]);
}
if (class_exists('\AKSRT\Payment\Gateway')) {
$order = \AKSRT\Payment\Gateway::get_instance()->reconcile_order($order_number, $order) ?: $order;
}
$status = (string) ($order['status'] ?? '');
$paid = class_exists('\AKSRT\Core\DomainModel') && \AKSRT\Core\DomainModel::is_paid_order_status($status);
if ($paid && $uid <= 0 && function_exists('aksrt_set_guest_pay_cookies')) {
// Ensure cookie set even if notify raced ahead of browser cookie.
aksrt_set_guest_pay_cookies($order);
}
return new \WP_REST_Response([
'order_number' => $order_number,
'status' => $status,
'paid' => $paid,
'amount' => (float) ($order['amount'] ?? 0),
'currency' => (string) ($order['currency'] ?? ''),
'product_id' => (int) ($order['product_id'] ?? 0),
'product_type' => (string) ($order['product_type'] ?? ''),
'reload' => $paid,
], 200);
}
/**
* @param array|\WP_Error $result
* @return \WP_REST_Response|\WP_Error
*/
private function rest_wrap_result($result) {
if (is_wp_error($result)) {
return $result;
}
if (empty($result['success'])) {
$code = sanitize_key((string) ($result['code'] ?? 'aksrt_pay_failed'));
$status = (int) ($result['status'] ?? 400);
return new \WP_Error($code !== '' ? $code : 'aksrt_pay_failed', (string) ($result['message'] ?? __('支付失败', 'aksrt')), array_merge(
['status' => $status > 0 ? $status : 400],
is_array($result['data'] ?? null) ? $result['data'] : []
));
}
return new \WP_REST_Response($result, 200);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Content;
defined('ABSPATH') || exit;
class VipService {
use VipServiceRest;
use VipServicePurchase;
use VipServicePackages;
use VipServiceModal;
private static $instance = null;
public static function get_instance(): self {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function init(): void {
add_action('rest_api_init', [$this, 'register_routes']);
add_action('aksrt_order_paid', [$this, 'on_order_paid'], 20, 2);
}
}
+318
View File
@@ -0,0 +1,318 @@
<?php
/**
* VIP modal + card HTML (zibll pay-vip modal / vip-card parity).
*
* @package AKSRT
*/
namespace AKSRT\Content;
defined('ABSPATH') || exit;
trait VipServiceModal {
/**
* Build pay / renew / upgrade modal HTML for a user.
*/
public function render_modal_html(int $user_id, int $prefer_level = 1): string {
if ($user_id <= 0) {
return '<div class="box-body payvip-modal text-center padding-20">'
. esc_html__('请先登录后再开通会员。', 'aksrt')
. '</div>';
}
$vip = class_exists('\AKSRT\Settings\Settings')
? \AKSRT\Settings\Settings::get_payment_vip_settings()
: ['enabled' => false];
if (empty($vip['enabled'])) {
return '<div class="box-body payvip-modal text-center padding-20">'
. esc_html__('会员功能未启用。', 'aksrt')
. '</div>';
}
$catalog = $this->get_catalog($user_id);
$user_level = (int) ($catalog['user_level'] ?? 0);
$prefer_level = max(1, min(2, $prefer_level));
if ($user_level > 0) {
return $this->render_modal_viped($user_id, $catalog, $vip, $prefer_level);
}
return $this->render_modal_pay($user_id, $catalog, $vip, $prefer_level);
}
/**
* Mini hover card for header (zibll zibpay_get_vip_card).
*/
public function render_vip_card(int $level, int $user_id = 0): string {
$level = max(1, min(2, $level));
$vip = class_exists('\AKSRT\Settings\Settings')
? \AKSRT\Settings\Settings::get_payment_vip_settings()
: [];
$levels = is_array($vip['levels'] ?? null) ? $vip['levels'] : [];
if (empty($levels[$level]['enabled'])) {
return '';
}
$name = (string) ($levels[$level]['name'] ?? ('VIP' . $level));
$desc = (string) ($levels[$level]['desc'] ?? '');
$equity = (string) ($levels[$level]['equity'] ?? '');
$cls = $user_id > 0 ? ' pay-vip' : ' signin-loader';
// Preserve admin equity HTML as-is (sanitize/wrap only; never re-split).
$equity_html = function_exists('aksrt_format_vip_equity_html')
? aksrt_format_vip_equity_html($equity, 'mb10 relative')
: '';
$icon = '<i class="fas fa-gem" aria-hidden="true"></i>';
$html = '<div class="vip-card pointer level-' . $level . ' vip-theme' . $level . $cls . '" vip-level="' . $level . '">';
$html .= '<div class="vip-baicon" aria-hidden="true">' . $icon . '</div>';
$html .= '<div class="vip-img abs-right">' . $icon . '</div>';
$html .= '<div class="relative">';
$html .= '<div class="vip-name mb10"><span class="mr6">' . $icon . '</span>' . esc_html($name) . '</div>';
if ($desc !== '') {
$html .= '<div class="mb6 font-bold em09">' . esc_html($desc) . '</div>';
}
$html .= $equity_html;
$html .= '<a class="but jb-blue radius payvip-button" href="javascript:;">'
. esc_html(sprintf(__('开通%s', 'aksrt'), $name))
. '<span class="ml6"><i class="fas fa-chevron-circle-right" aria-hidden="true"></i></span></a>';
$html .= '</div></div>';
return $html;
}
private function render_modal_pay(int $user_id, array $catalog, array $vip, int $prefer_level): string {
$user = get_userdata($user_id);
$name = $user ? $user->display_name : '';
$avatar = get_avatar($user_id, 42);
$desc = (string) ($vip['desc'] ?? $catalog['desc'] ?? '');
$more = (string) ($vip['more'] ?? '');
$groups = is_array($catalog['level_packages'] ?? null) ? $catalog['level_packages'] : [];
$methods = is_array($catalog['payment_methods'] ?? null) ? $catalog['payment_methods'] : [];
$levels = is_array($vip['levels'] ?? null) ? $vip['levels'] : [];
$active_lv = !empty($levels[$prefer_level]['enabled']) ? $prefer_level : 0;
if ($active_lv <= 0) {
foreach ([1, 2] as $lv) {
if (!empty($levels[$lv]['enabled'])) {
$active_lv = $lv;
break;
}
}
}
$tabs = '';
$panes = '';
foreach ([1, 2] as $lv) {
if (empty($levels[$lv]['enabled'])) {
continue;
}
$is_active = ($lv === $active_lv);
$lv_name = (string) ($levels[$lv]['name'] ?? ('VIP' . $lv));
$tabs .= '<li class="relative' . ($is_active ? ' active' : '') . '">'
. '<a class="aksrt-vip-tab" href="javascript:;" data-vip-tab="tab-payvip-' . $lv . '">'
. esc_html($lv_name)
. '</a></li>';
$group_items = [];
foreach ($groups as $g) {
if ((int) ($g['level'] ?? 0) === $lv) {
$group_items = is_array($g['items'] ?? null) ? $g['items'] : [];
break;
}
}
$products = $this->render_product_radios($group_items);
$equity = (string) ($levels[$lv]['equity'] ?? '');
$lv_desc = (string) ($levels[$lv]['desc'] ?? '');
$panes .= '<div class="tab-pane aksrt-vip-pane' . ($is_active ? ' active' : '') . '" id="tab-payvip-' . $lv . '"' . ($is_active ? '' : ' hidden') . '>';
$panes .= '<div class="pay-vip-form-row">';
$panes .= '<div class="pay-vip-info level-' . $lv . '">';
$panes .= '<div class="v-name font-bold">' . esc_html($lv_name) . '</div>';
if ($lv_desc !== '') {
$panes .= '<div class="muted-2-color em09 mb6">' . esc_html($lv_desc) . '</div>';
}
if ($equity !== '') {
$panes .= function_exists('aksrt_format_vip_equity_html')
? aksrt_format_vip_equity_html($equity)
: '<div class="v-equity">' . wp_kses_post($equity) . '</div>';
}
$panes .= '</div><div class="pay-vip-products">';
$panes .= $products;
$panes .= $this->render_pay_methods($methods);
$panes .= '<button type="button" class="but jb-red btn-block padding-lg radius aksrt-vip-submit" data-vip-submit>'
. esc_html__('立即开通', 'aksrt') . '</button>';
$panes .= '<p class="aksrt-vip-modal-tip muted-2-color em09 mt10" data-aksrt-vip-tip></p>';
$panes .= '</div></div></div>';
}
$points = '';
if (!empty($catalog['points_exchange']['enabled']) && !empty($catalog['points_exchange']['packages'])) {
$points = '<div class="mt10"><a class="but c-green btn-block" href="'
. esc_url(function_exists('aksrt_get_user_center_url') ? aksrt_get_user_center_url('vip') : '#')
. '">' . esc_html__('积分兑换会员', 'aksrt') . '</a></div>';
}
$html = '<div class="box-body payvip-modal" data-aksrt-vip-modal>';
$html .= '<button type="button" class="close aksrt-vip-modal-close" aria-label="Close">&times;</button>';
$html .= '<ul class="list-inline user-box flex ac mb10"><li class="avatar-img">' . $avatar . '</li>';
$html .= '<li><b class="em12">' . esc_html($name) . '</b>';
if ($desc !== '') {
$html .= '<div class="muted-2-color em09">' . esc_html($desc) . '</div>';
}
$html .= '</li></ul>';
$html .= '<ul class="flex jsb mt10 mb20 vip-cardminis gutters-5 nav">' . $tabs . '</ul>';
$html .= '<div class="tab-content mt10">' . $panes . '</div>';
if ($more !== '') {
$html .= '<div class="muted-2-color mb10 em09 muted-box padding-10 mini-radius">' . $more . '</div>';
}
$html .= $points;
$html .= '</div>';
return $html;
}
/**
* @param array<string,mixed> $catalog
* @param array<string,mixed> $vip
*/
private function render_modal_viped(int $user_id, array $catalog, array $vip, int $prefer_level): string {
$user = get_userdata($user_id);
$name = $user ? $user->display_name : '';
$avatar = get_avatar($user_id, 42);
$exp_label = (string) ($catalog['user_expires_label'] ?? '');
$groups = is_array($catalog['level_packages'] ?? null) ? $catalog['level_packages'] : [];
$methods = is_array($catalog['payment_methods'] ?? null) ? $catalog['payment_methods'] : [];
$levels = is_array($vip['levels'] ?? null) ? $vip['levels'] : [];
$more = (string) ($vip['more'] ?? '');
$tabs = '';
$panes = '';
$active_set = false;
foreach ($groups as $g) {
$lv = (int) ($g['level'] ?? 0);
$action = (string) ($g['action'] ?? 'renew');
$items = is_array($g['items'] ?? null) ? $g['items'] : [];
if ($lv <= 0 || $items === []) {
continue;
}
$is_active = !$active_set;
if ($is_active) {
$active_set = true;
}
$lv_name = (string) ($g['name'] ?? ($levels[$lv]['name'] ?? ('VIP' . $lv)));
$badge = $action === 'upgrade' ? __('升级', 'aksrt') : __('续费', 'aksrt');
$tab_id = 'tab-payvip-' . $lv . '-' . $action;
$tabs .= '<li class="relative' . ($is_active ? ' active' : '') . '">'
. '<a class="aksrt-vip-tab" href="javascript:;" data-vip-tab="' . esc_attr($tab_id) . '">'
. esc_html($badge . $lv_name)
. '</a></li>';
$products = $this->render_product_radios($items);
$equity = (string) ($levels[$lv]['equity'] ?? '');
$panes .= '<div class="tab-pane aksrt-vip-pane' . ($is_active ? ' active' : '') . '" id="' . esc_attr($tab_id) . '"' . ($is_active ? '' : ' hidden') . '>';
$panes .= '<div class="pay-vip-form-row">';
$panes .= '<div class="pay-vip-info level-' . $lv . '">';
$panes .= '<div class="v-name font-bold">' . esc_html($lv_name) . '</div>';
if ($equity !== '') {
$panes .= function_exists('aksrt_format_vip_equity_html')
? aksrt_format_vip_equity_html($equity)
: '<div class="v-equity">' . wp_kses_post($equity) . '</div>';
}
$panes .= '</div><div class="pay-vip-products">';
$panes .= $products;
$panes .= $this->render_pay_methods($methods);
$cta = $action === 'upgrade' ? __('立即升级', 'aksrt') : __('立即续费', 'aksrt');
$panes .= '<button type="button" class="but jb-red btn-block padding-lg radius aksrt-vip-submit" data-vip-submit>'
. esc_html($cta) . '</button>';
$panes .= '<p class="aksrt-vip-modal-tip muted-2-color em09 mt10" data-aksrt-vip-tip></p>';
$panes .= '</div></div></div>';
}
if ($tabs === '') {
return '<div class="box-body payvip-modal text-center padding-20">'
. esc_html__('当前没有可续费或升级的套餐。', 'aksrt')
. '</div>';
}
$html = '<div class="box-body payvip-modal" data-aksrt-vip-modal>';
$html .= '<button type="button" class="close aksrt-vip-modal-close" aria-label="Close">&times;</button>';
$html .= '<ul class="list-inline user-box flex ac mb10"><li class="avatar-img">' . $avatar . '</li>';
$html .= '<li><b class="em12">' . esc_html($name) . '</b>';
$html .= '<div class="muted-2-color em09"><span class="badg c-yellow vip-expdate-tag">'
. esc_html($exp_label) . '</span></div></li></ul>';
$html .= '<ul class="flex jsb mt10 mb20 vip-cardminis gutters-5 nav">' . $tabs . '</ul>';
$html .= '<div class="tab-content mt10">' . $panes . '</div>';
if ($more !== '') {
$html .= '<div class="muted-2-color mb10 em09 muted-box padding-10 mini-radius">' . $more . '</div>';
}
$html .= '</div>';
return $html;
}
/**
* @param array<int,array<string,mixed>> $items
*/
private function render_product_radios(array $items): string {
if ($items === []) {
return '<div class="muted-2-color text-center padding-10">'
. esc_html__('暂无可用套餐', 'aksrt') . '</div>';
}
$html = '<div class="mb10 label-box charge-box aksrt-vip-products">';
$i = 0;
foreach ($items as $item) {
$pid = (int) ($item['package_id'] ?? 0);
if ($pid <= 0) {
continue;
}
$i++;
$price = (string) ($item['price_label'] ?? '');
$show = (string) ($item['show_price_label'] ?? '');
$tag = (string) ($item['discount_tag'] ?? '');
$time = (string) ($item['days_label'] ?? '');
$title = (string) ($item['title'] ?? '');
$checked = $i === 1 ? ' checked' : '';
$html .= '<label class="aksrt-vip-product-label">';
$html .= '<input class="hide vip-product-input" type="radio" name="vip_product_id" value="'
. esc_attr((string) $pid) . '"' . $checked . '>';
$html .= '<div class="zib-widget vip-product relative text-center product-box">';
if ($tag !== '') {
$html .= '<div class="abs-right vip-tag badg jb-yellow">' . esc_html($tag) . '</div>';
}
if ($title !== '') {
$html .= '<div class="em09 mb3">' . esc_html($title) . '</div>';
}
$html .= '<div class="flex abl gap6 jc"><div class="product-price c-red">' . esc_html($price) . '</div>';
if ($show !== '') {
$html .= '<div class="original-price relative muted-2-color"><s>' . esc_html($show) . '</s></div>';
}
$html .= '</div>';
if ($time !== '') {
$html .= '<div class="muted-2-color c-blue em09 p2-10 badg radius">' . esc_html($time) . '</div>';
}
$html .= '</div></label>';
}
$html .= '</div>';
return $html;
}
/**
* @param array<int,array{id?:string,name?:string}> $methods
*/
private function render_pay_methods(array $methods): string {
if ($methods === []) {
return '<input type="hidden" name="aksrt_vip_pay_method" value="balance" data-aksrt-vip-method-fixed>';
}
if (count($methods) === 1) {
$id = (string) ($methods[0]['id'] ?? 'balance');
return '<input type="hidden" name="aksrt_vip_pay_method" value="' . esc_attr($id) . '" data-aksrt-vip-method-fixed>';
}
$html = '<div class="uc-vip-shop__methods mb10" data-aksrt-vip-methods>';
$html .= '<span class="uc-vip-shop__methods-label">' . esc_html__('支付方式', 'aksrt') . '</span>';
foreach ($methods as $i => $m) {
$mid = (string) ($m['id'] ?? '');
$mname = (string) ($m['name'] ?? $mid);
$html .= '<label class="uc-vip-shop__method"><input type="radio" name="aksrt_vip_pay_method" value="'
. esc_attr($mid) . '"' . ($i === 0 ? ' checked' : '') . '> <span>'
. esc_html($mname) . '</span></label>';
}
$html .= '</div>';
return $html;
}
}
+564
View File
@@ -0,0 +1,564 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Content;
defined('ABSPATH') || exit;
trait VipServicePackages {
/**
* Parse per-level product lines (zibll vip_product).
*
* Preferred: price|show_price|time|unit|tag|title
* Legacy: price|days|title
*
* @return array<int, array{price:float,show_price:float,time:int,unit:string,tag:string,tag_class:string,title:string,days:int}>
*/
public function parse_level_products(string $raw): array {
$lines = preg_split('/\r\n|\r|\n/', $raw) ?: [];
$out = [];
foreach ($lines as $line) {
$line = trim((string) $line);
if ($line === '') {
continue;
}
$parts = array_map('trim', explode('|', $line));
$price = isset($parts[0]) ? (float) $parts[0] : 0.0;
if ($price <= 0) {
continue;
}
$n = count($parts);
// New format: price|show_price|time|unit|tag|title (6+)
// Or: price|show_price|time|unit|title (5)
if ($n >= 4 && (in_array(strtolower((string) ($parts[3] ?? '')), ['day', 'month', 'd', 'm'], true)
|| (isset($parts[3]) && $parts[3] !== '' && !is_numeric($parts[3])))) {
$show_price = isset($parts[1]) ? (float) $parts[1] : 0.0;
$time = isset($parts[2]) ? (int) $parts[2] : 0;
$unit_raw = strtolower((string) ($parts[3] ?? 'month'));
$unit = ($unit_raw === 'day' || $unit_raw === 'd') ? 'day' : 'month';
$tag = '';
$title = '';
if ($n >= 6) {
$tag = sanitize_text_field((string) ($parts[4] ?? ''));
$title = sanitize_text_field((string) ($parts[5] ?? ''));
} elseif ($n === 5) {
// price|show|time|unit|title
$title = sanitize_text_field((string) ($parts[4] ?? ''));
}
} else {
// Legacy: price|days|title
$show_price = 0.0;
$days_legacy = isset($parts[1]) ? (int) $parts[1] : 0;
$time = $days_legacy;
$unit = 'day';
$tag = '';
$title = isset($parts[2]) ? sanitize_text_field($parts[2]) : '';
}
$time = max(0, $time);
$days = $this->duration_to_days($time, $unit);
if ($title === '') {
if ($time <= 0) {
$title = __('永久会员', 'aksrt');
} elseif ($unit === 'day') {
$title = sprintf(__('%d天会员', 'aksrt'), $time);
} else {
$title = sprintf(__('%d个月会员', 'aksrt'), $time);
}
}
$out[] = [
'price' => round($price, 2),
'show_price' => max(0.0, round($show_price, 2)),
'time' => $time,
'unit' => $unit,
'tag' => $tag,
'tag_class' => '',
'title' => $title,
'days' => $days,
];
}
return $out;
}
/**
* Approximate days for catalog labels / order meta; activate prefers time+unit calendar math.
*/
public function duration_to_days(int $time, string $unit = 'day'): int {
if ($time <= 0) {
return 0;
}
if ($unit === 'month') {
return $time * 30;
}
return $time;
}
/**
* @deprecated Use parse_level_products — kept as thin adapter for upgrade fixed lines.
*
* @return array<int, array{price:float,days:int,title:string}>
*/
public function parse_packages(string $raw): array {
$parsed = $this->parse_level_products($raw);
$out = [];
foreach ($parsed as $p) {
$out[] = [
'price' => (float) $p['price'],
'days' => (int) $p['days'],
'title' => (string) $p['title'],
];
}
return $out;
}
/**
* Build upgrade package items (zibll vip_upgrade_product parity).
*
* upgrade.product multi-line formats:
* - permanent VIP1: permanent|price|title[|show_price]
* - fixed (alias): price|days|title
* - timed unit: unit|daily_price|title
* - timed jump permanent: jump|price|title[|show_price]
*
* Rules:
* - permanent user: only permanent/fixed (days=0 preferred)
* - timed user: unit (keep expiry) + optional jump (to permanent)
*
* package index: 901 permanent/fixed, 902 unit, 903 jump
*
* @return array<int, array<string,mixed>>
*/
private function build_upgrade_items(int $user_id, int $expires, bool $is_permanent, string $raw): array {
$raw = trim($raw);
if ($raw === '') {
return [];
}
$items = [];
$lines = preg_split('/\r\n|\r|\n/', $raw) ?: [];
$has_permanent = false;
$has_unit = false;
$has_jump = false;
foreach ($lines as $line) {
$line = trim((string) $line);
if ($line === '') {
continue;
}
$parts = array_map('trim', explode('|', $line));
$mode = strtolower((string) ($parts[0] ?? ''));
// unit|daily|title — timed VIP1 only.
if ($mode === 'unit') {
if ($is_permanent || $expires <= time() || $has_unit) {
continue;
}
$daily = isset($parts[1]) ? (float) $parts[1] : 0.0;
if ($daily <= 0) {
continue;
}
$remaining = (int) ceil(max(1, ($expires - time()) / DAY_IN_SECONDS));
$price = round(max(0.01, $remaining * $daily), 2);
$title = sanitize_text_field((string) ($parts[2] ?? ''));
if ($title === '') {
$title = sprintf(__('按剩余 %d 天升级', 'aksrt'), $remaining);
}
$items[] = [
'package_id' => $this->encode_package_id(2, 902),
'level' => 2,
'index' => 902,
'action' => 'upgrade',
'price' => $price,
'base_price' => $price,
'show_price' => 0.0,
'discount_tag' => __('剩余天数', 'aksrt'),
'days' => $remaining,
'title' => $title,
'price_label' => $this->format_cash_label($price),
'show_price_label' => '',
'days_label' => sprintf(__('%d 天', 'aksrt'), $remaining),
'cta_label' => __('立即升级', 'aksrt'),
'is_upgrade_product' => true,
'upgrade_mode' => 'unit',
];
$has_unit = true;
continue;
}
// jump|price|title[|show_price] — timed VIP1 only → permanent VIP2.
if ($mode === 'jump') {
if ($is_permanent || $has_jump) {
continue;
}
$price = isset($parts[1]) ? (float) $parts[1] : 0.0;
if ($price <= 0) {
continue;
}
$title = sanitize_text_field((string) ($parts[2] ?? ''));
if ($title === '') {
$title = __('升级为永久会员', 'aksrt');
}
$show = isset($parts[3]) ? (float) $parts[3] : 0.0;
$items[] = [
'package_id' => $this->encode_package_id(2, 903),
'level' => 2,
'index' => 903,
'action' => 'upgrade',
'price' => round($price, 2),
'base_price' => round($price, 2),
'show_price' => max(0.0, $show),
'discount_tag' => __('永久升级', 'aksrt'),
'days' => 0,
'title' => $title,
'price_label' => $this->format_cash_label($price),
'show_price_label' => $show > 0 ? $this->format_cash_label($show) : '',
'days_label' => __('永久', 'aksrt'),
'cta_label' => __('立即升级', 'aksrt'),
'is_upgrade_product' => true,
'upgrade_mode' => 'jump',
];
$has_jump = true;
continue;
}
// permanent|price|title[|show_price]
if ($mode === 'permanent') {
if ($has_permanent) {
continue;
}
$price = isset($parts[1]) ? (float) $parts[1] : 0.0;
if ($price <= 0) {
continue;
}
$title = sanitize_text_field((string) ($parts[2] ?? ''));
if ($title === '') {
$title = __('永久会员升级', 'aksrt');
}
$show = isset($parts[3]) ? (float) $parts[3] : 0.0;
$items[] = [
'package_id' => $this->encode_package_id(2, 901),
'level' => 2,
'index' => 901,
'action' => 'upgrade',
'price' => round($price, 2),
'base_price' => round($price, 2),
'show_price' => max(0.0, $show),
'discount_tag' => __('升级专享', 'aksrt'),
'days' => 0,
'title' => $title,
'price_label' => $this->format_cash_label($price),
'show_price_label' => $show > 0 ? $this->format_cash_label($show) : '',
'days_label' => __('永久', 'aksrt'),
'cta_label' => __('立即升级', 'aksrt'),
'is_upgrade_product' => true,
'upgrade_mode' => 'permanent',
];
$has_permanent = true;
continue;
}
// fixed: price|days|title
$parsed = $this->parse_packages($line);
if (empty($parsed[0]) || $has_permanent) {
continue;
}
// For permanent VIP1, only accept days=0 fixed lines as permanent upgrade.
if ($is_permanent && (int) $parsed[0]['days'] > 0) {
continue;
}
$pkg = $parsed[0];
$items[] = [
'package_id' => $this->encode_package_id(2, 901),
'level' => 2,
'index' => 901,
'action' => 'upgrade',
'price' => (float) $pkg['price'],
'base_price' => (float) $pkg['price'],
'show_price' => 0.0,
'discount_tag' => __('升级专享', 'aksrt'),
'days' => (int) $pkg['days'],
'title' => (string) $pkg['title'],
'price_label' => $this->format_cash_label((float) $pkg['price']),
'show_price_label' => '',
'days_label' => ((int) $pkg['days'] <= 0)
? __('永久', 'aksrt')
: sprintf(__('%d 天', 'aksrt'), (int) $pkg['days']),
'cta_label' => __('立即升级', 'aksrt'),
'is_upgrade_product' => true,
'upgrade_mode' => ((int) $pkg['days'] <= 0) ? 'permanent' : 'fixed',
];
$has_permanent = true;
}
// Permanent VIP1 should not see unit/jump.
if ($is_permanent) {
$items = array_values(array_filter($items, static function ($it) {
$m = (string) ($it['upgrade_mode'] ?? '');
return in_array($m, ['permanent', 'fixed'], true);
}));
}
return $items;
}
/**
* Points exchange packages: level|points|days|title
*
* @param array<string,mixed> $vip
* @param array<int,mixed> $levels
* @return array<int, array<string,mixed>>
*/
public function get_points_exchange_packages(array $vip, array $levels): array {
$points_ex = is_array($vip['points_exchange'] ?? null) ? $vip['points_exchange'] : [];
$raw = (string) ($points_ex['packages_raw'] ?? '');
$currency = class_exists('\AKSRT\Settings\Settings') ? \AKSRT\Settings\Settings::get_currency_name() : __('积分', 'aksrt');
$out = [];
$lines = preg_split('/\r\n|\r|\n/', $raw) ?: [];
$i = 0;
foreach ($lines as $line) {
$line = trim((string) $line);
if ($line === '') {
continue;
}
$parts = array_map('trim', explode('|', $line));
if (count($parts) < 3) {
continue;
}
$lv = (int) ($parts[0] ?? 0);
$pts = (int) ($parts[1] ?? 0);
$days = (int) ($parts[2] ?? 0);
$title = sanitize_text_field((string) ($parts[3] ?? ''));
if ($lv < 1 || $lv > 2 || $pts <= 0) {
continue;
}
if (empty($levels[$lv]['enabled'])) {
continue;
}
$i++;
if ($title === '') {
$lv_name = (string) ($levels[$lv]['name'] ?? ('VIP' . $lv));
$title = $days > 0
? sprintf(__('%1$s · %2$d天', 'aksrt'), $lv_name, $days)
: sprintf(__('%s · 永久', 'aksrt'), $lv_name);
}
$out[] = [
'package_id' => 5000 + $i,
'level' => $lv,
'index' => $i,
'points' => $pts,
'days' => max(0, $days),
'title' => $title,
'price_label' => $pts . ' ' . $currency,
'days_label' => $days > 0 ? sprintf(__('%d 天', 'aksrt'), $days) : __('永久', 'aksrt'),
'cta_label' => __('立即兑换', 'aksrt'),
];
}
return $out;
}
/**
* Single upgrade product line: price|days|title
*
* @return array{price:float,days:int,title:string}|null
*/
public function parse_upgrade_product_line(string $raw): ?array {
$raw = trim($raw);
if ($raw === '') {
return null;
}
$lines = preg_split('/\r\n|\r|\n/', $raw) ?: [];
foreach ($lines as $line) {
$line = trim((string) $line);
if ($line === '' || str_starts_with(strtolower($line), 'unit|')) {
continue;
}
$parsed = $this->parse_packages($line);
if (!empty($parsed[0])) {
return $parsed[0];
}
}
return null;
}
/**
* Apply renew discount/reduce to same-level packages.
*
* @param array<string,mixed> $renew
* @param array<string,mixed> $upgrade
* @return array{price:float,show_price:float,tag:string}|null
*/
private function apply_action_price(
float $base_price,
string $action,
array $renew,
array $upgrade,
int $target_level,
int $user_level,
int $expires,
bool $is_permanent,
int $days
): ?array {
if ($base_price <= 0) {
return null;
}
if ($action === 'renew' && $is_permanent) {
return null;
}
if ($action !== 'renew') {
return [
'price' => round($base_price, 2),
'show_price' => 0.0,
'tag' => '',
];
}
$type = sanitize_key((string) ($renew['price_type'] ?? 'discount'));
$price = $base_price;
$show = $base_price;
$tag = '';
if ($type === 'discount') {
$discount = (float) ($renew['discount'] ?? 8);
if ($discount <= 0) {
$discount = 8;
}
if ($discount <= 10) {
$price = round($base_price * ($discount / 10), 2);
$tag = sprintf(
/* translators: %s: discount like 8 */
__('%s折续费', 'aksrt'),
rtrim(rtrim(number_format($discount, 1, '.', ''), '0'), '.')
);
} else {
$price = round($base_price * (min(100, $discount) / 100), 2);
$tag = sprintf(__('%s%% 续费价', 'aksrt'), (string) (int) $discount);
}
} elseif ($type === 'reduce') {
$reduce = max(0, (float) ($renew['reduce'] ?? 20));
$price = round(max(0.01, $base_price - $reduce), 2);
$tag = sprintf(
/* translators: %s: amount */
__('续费立减%s', 'aksrt'),
$this->format_cash_label($reduce)
);
} else {
$show = 0.0;
$tag = __('续费同价', 'aksrt');
}
if ($price < 0.01) {
$price = 0.01;
}
if ($show > 0 && $price >= $show) {
$show = 0.0;
$tag = __('续费', 'aksrt');
}
return [
'price' => $price,
'show_price' => $show > $price ? $show : 0.0,
'tag' => $tag,
];
}
public function encode_package_id(int $level, int $index): int {
return (max(1, min(2, $level)) * 1000) + max(1, $index);
}
/**
* @return array{level:int,index:int}|null
*/
public function decode_package_id(int $package_id): ?array {
if ($package_id < 1001) {
return null;
}
$level = intdiv($package_id, 1000);
$index = $package_id % 1000;
if ($level < 1 || $level > 2 || $index < 1) {
return null;
}
return ['level' => $level, 'index' => $index];
}
/**
* @return array<int, array{id:string,name:string}>
*/
private function available_payment_methods(): array {
if (function_exists('aksrt_list_cash_payment_methods')) {
return aksrt_list_cash_payment_methods(true);
}
$methods = [];
if (!class_exists('\AKSRT\Payment\Gateway')) {
return $methods;
}
$gw = \AKSRT\Payment\Gateway::get_instance();
foreach (['balance', 'alipay', 'wechatpay', 'paypal', 'stripe', 'epay_alipay', 'epay_wxpay'] as $id) {
$g = $gw->get_gateway($id);
if (!$g) {
continue;
}
if (method_exists($g, 'is_configured') && !$g->is_configured()) {
continue;
}
$methods[] = [
'id' => $id,
'name' => method_exists($g, 'get_name') ? (string) $g->get_name() : $id,
];
}
return $methods;
}
private function format_cash_label(float $amount): string {
$symbol = '¥';
if (class_exists('\AKSRT\Settings\Settings')) {
$paid = \AKSRT\Settings\Settings::get_paid_content_settings();
$symbol = (string) ($paid['display']['currency_symbol'] ?? '¥');
}
$n = function_exists('aksrt_format_price') ? aksrt_format_price($amount) : (string) $amount;
return $symbol . $n;
}
private function format_expires_label(int $expires, int $level): string {
if ($level <= 0) {
return __('未开通', 'aksrt');
}
if ($expires <= 0) {
return __('永久有效', 'aksrt');
}
if ($expires < time()) {
return __('已过期', 'aksrt');
}
return sprintf(
/* translators: %s: date */
__('到期时间:%s', 'aksrt'),
wp_date('Y-m-d H:i', $expires)
);
}
}
+704
View File
@@ -0,0 +1,704 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Content;
defined('ABSPATH') || exit;
trait VipServicePurchase {
/**
* @return array<string,mixed>
*/
public function get_catalog(int $user_id = 0): array {
$vip = class_exists('\AKSRT\Settings\Settings')
? \AKSRT\Settings\Settings::get_payment_vip_settings()
: ['enabled' => false, 'levels' => [], 'renew' => [], 'upgrade' => [], 'points_exchange' => []];
$level = function_exists('aksrt_get_user_vip_level') ? aksrt_get_user_vip_level($user_id) : 0;
$expires = $user_id > 0 ? (int) get_user_meta($user_id, 'aksrt_vip_expires', true) : 0;
$is_permanent = ($level > 0 && $expires <= 0);
$levels = is_array($vip['levels'] ?? null) ? $vip['levels'] : [];
$renew = is_array($vip['renew'] ?? null) ? $vip['renew'] : [];
$upgrade = is_array($vip['upgrade'] ?? null) ? $vip['upgrade'] : [];
$points_ex = is_array($vip['points_exchange'] ?? null) ? $vip['points_exchange'] : [];
$renew_enabled = !isset($renew['enabled']) || !empty($renew['enabled']);
$upgrade_enabled = !isset($upgrade['enabled']) || !empty($upgrade['enabled']);
$points_enabled = !empty($points_ex['enabled'])
&& (!class_exists('\AKSRT\Settings\Settings') || \AKSRT\Settings\Settings::credits_enabled());
$level_packages = [];
foreach ([1, 2] as $lv) {
if (empty($levels[$lv]['enabled'])) {
continue;
}
// Cash products can be disabled per level.
$product_s = !isset($levels[$lv]['product_s']) || !empty($levels[$lv]['product_s']);
if ($is_permanent && $lv <= $level) {
continue;
}
if ($level > 0 && $lv === $level && !$renew_enabled) {
continue;
}
if ($level > 0 && $lv > $level && !$upgrade_enabled) {
continue;
}
$name = (string) ($levels[$lv]['name'] ?? ('VIP' . $lv));
$items = [];
$packages = $product_s
? $this->parse_level_products((string) ($levels[$lv]['products_raw'] ?? ''))
: [];
foreach ($packages as $idx => $pkg) {
$base_price = (float) $pkg['price'];
$days = (int) $pkg['days'];
$action = 'pay';
if ($level > 0 && $lv === $level) {
$action = 'renew';
} elseif ($level > 0 && $lv > $level) {
$action = 'upgrade';
}
$priced = $this->apply_action_price($base_price, $action, $renew, $upgrade, $lv, $level, $expires, $is_permanent, $days);
if ($priced === null) {
continue;
}
$show_price = (float) ($priced['show_price'] ?? 0);
if ($show_price <= 0 && !empty($pkg['show_price']) && $action === 'pay') {
$show_price = (float) $pkg['show_price'];
}
$discount_tag = (string) ($priced['tag'] ?? '');
if ($discount_tag === '' && $action === 'pay' && !empty($pkg['tag'])) {
$discount_tag = (string) $pkg['tag'];
}
$days_label = __('永久', 'aksrt');
if ((int) $pkg['time'] > 0) {
$days_label = ((string) ($pkg['unit'] ?? 'day') === 'month')
? sprintf(__('%d 个月', 'aksrt'), (int) $pkg['time'])
: sprintf(__('%d 天', 'aksrt'), (int) $pkg['time']);
}
$items[] = [
'package_id' => $this->encode_package_id($lv, $idx + 1),
'level' => $lv,
'index' => $idx + 1,
'action' => $action,
'price' => (float) $priced['price'],
'base_price' => $base_price,
'show_price' => $show_price,
'discount_tag' => $discount_tag,
'days' => $days,
'time' => (int) ($pkg['time'] ?? 0),
'unit' => (string) ($pkg['unit'] ?? 'day'),
'title' => (string) $pkg['title'],
'price_label' => $this->format_cash_label((float) $priced['price']),
'show_price_label' => $show_price > 0
? $this->format_cash_label($show_price)
: '',
'days_label' => $days_label,
'cta_label' => $action === 'renew'
? __('立即续费', 'aksrt')
: ($action === 'upgrade' ? __('立即升级', 'aksrt') : __('立即开通', 'aksrt')),
];
}
// Dedicated upgrade product: fixed or remaining-days unit price.
if ($level === 1 && $lv === 2 && $upgrade_enabled) {
$upgrade_items = $this->build_upgrade_items($user_id, $expires, $is_permanent, (string) ($upgrade['product'] ?? ''));
foreach ($upgrade_items as $ui) {
$items[] = $ui;
}
}
if ($items === []) {
continue;
}
$level_packages[] = [
'level' => $lv,
'name' => $name,
'action' => ($level > 0 && $lv === $level) ? 'renew' : (($level > 0 && $lv > $level) ? 'upgrade' : 'pay'),
'items' => $items,
];
}
$points_packages = [];
if ($points_enabled && $level <= 0) {
$points_packages = $this->get_points_exchange_packages($vip, $levels);
}
$points_balance = ($user_id > 0 && class_exists('\AKSRT\Credits\Credits'))
? (int) \AKSRT\Credits\Credits::balance($user_id)
: 0;
$wallet_balance = ($user_id > 0 && class_exists('\AKSRT\Credits\Balance') && \AKSRT\Credits\Balance::enabled())
? (float) \AKSRT\Credits\Balance::balance($user_id)
: 0.0;
$methods = $this->available_payment_methods();
$currency_name = class_exists('\AKSRT\Settings\Settings') ? \AKSRT\Settings\Settings::get_currency_name() : __('积分', 'aksrt');
return [
'enabled' => !empty($vip['enabled']),
'desc' => (string) ($vip['desc'] ?? ''),
'help_text' => (string) ($vip['help_text'] ?? ''),
'user_level' => $level,
'user_expires' => $expires,
'user_is_permanent' => $is_permanent,
'user_expires_label' => $this->format_expires_label($expires, $level),
'user_points' => $points_balance,
'wallet_balance' => $wallet_balance,
'currency_name' => $currency_name,
'renew_enabled' => $renew_enabled,
'upgrade_enabled' => $upgrade_enabled,
'renew_desc' => (string) ($renew['desc'] ?? ''),
'upgrade_desc' => (string) ($upgrade['desc'] ?? ''),
'level_packages' => $level_packages,
'points_exchange' => [
'enabled' => $points_enabled && $level <= 0,
'desc' => (string) ($points_ex['desc'] ?? ''),
'packages' => $points_packages,
],
'payment_methods' => $methods,
'vip_url' => function_exists('aksrt_get_user_center_tab_url')
? aksrt_get_user_center_tab_url('credits')
: (function_exists('aksrt_get_user_center_url') ? aksrt_get_user_center_url() : home_url('/')),
'logged_in' => $user_id > 0,
];
}
/**
* @return array|\WP_Error
*/
public function purchase(int $user_id, int $package_id, string $payment_method = 'balance') {
if ($user_id <= 0) {
return new \WP_Error('aksrt_need_login', __('请先登录后再开通会员。', 'aksrt'), ['status' => 401]);
}
$decoded = $this->decode_package_id($package_id);
if (!$decoded) {
return new \WP_Error('aksrt_invalid_package', __('套餐无效', 'aksrt'), ['status' => 400]);
}
$level = (int) $decoded['level'];
$index = (int) $decoded['index'];
$vip = class_exists('\AKSRT\Settings\Settings')
? \AKSRT\Settings\Settings::get_payment_vip_settings()
: ['enabled' => false, 'levels' => [], 'renew' => [], 'upgrade' => []];
if (empty($vip['enabled'])) {
return new \WP_Error('aksrt_vip_disabled', __('会员功能未启用', 'aksrt'), ['status' => 400]);
}
$levels = is_array($vip['levels'] ?? null) ? $vip['levels'] : [];
if (empty($levels[$level]['enabled'])) {
return new \WP_Error('aksrt_vip_level_disabled', __('该会员等级未启用', 'aksrt'), ['status' => 400]);
}
$user_level = function_exists('aksrt_get_user_vip_level') ? aksrt_get_user_vip_level($user_id) : 0;
$expires = (int) get_user_meta($user_id, 'aksrt_vip_expires', true);
$is_permanent = ($user_level > 0 && $expires <= 0);
$renew = is_array($vip['renew'] ?? null) ? $vip['renew'] : [];
$upgrade = is_array($vip['upgrade'] ?? null) ? $vip['upgrade'] : [];
$renew_enabled = !isset($renew['enabled']) || !empty($renew['enabled']);
$upgrade_enabled = !isset($upgrade['enabled']) || !empty($upgrade['enabled']);
if ($is_permanent && $level <= $user_level) {
return new \WP_Error('aksrt_vip_permanent', __('您已是永久会员,无需续费。', 'aksrt'), ['status' => 400]);
}
if ($user_level > 0 && $level === $user_level && !$renew_enabled) {
return new \WP_Error('aksrt_vip_renew_disabled', __('续费功能未开启。', 'aksrt'), ['status' => 400]);
}
if ($user_level > 0 && $level > $user_level && !$upgrade_enabled) {
return new \WP_Error('aksrt_vip_upgrade_disabled', __('升级功能未开启。', 'aksrt'), ['status' => 400]);
}
if ($user_level > 0 && $level < $user_level) {
return new \WP_Error('aksrt_vip_downgrade', __('不支持降级购买。', 'aksrt'), ['status' => 400]);
}
$action = 'pay';
if ($user_level > 0 && $level === $user_level) {
$action = 'renew';
} elseif ($user_level > 0 && $level > $user_level) {
$action = 'upgrade';
}
// Dedicated upgrade product:
// 901 permanent/fixed, 902 unit remaining days, 903 jump permanent.
$upgrade_mode = '';
$pkg_time = 0;
$pkg_unit = 'day';
if (in_array($index, [901, 902, 903], true)) {
$upgrade_items = $this->build_upgrade_items($user_id, $expires, $is_permanent, (string) ($upgrade['product'] ?? ''));
$match = null;
foreach ($upgrade_items as $ui) {
if ((int) ($ui['package_id'] ?? 0) === $package_id) {
$match = $ui;
break;
}
}
if (!$match || $level !== 2) {
return new \WP_Error('aksrt_invalid_package', __('升级套餐不存在', 'aksrt'), ['status' => 400]);
}
$pkg = [
'price' => (float) $match['price'],
'days' => (int) $match['days'],
'title' => (string) $match['title'],
];
$amount = round((float) $match['price'], 2);
$days = (int) $match['days'];
$pkg_time = $days; // unit upgrade keeps days as remaining; jump/permanent use 0
$pkg_unit = 'day';
$base_price = (float) ($match['base_price'] ?? $amount);
$discount_tag = (string) ($match['discount_tag'] ?? __('升级专享', 'aksrt'));
$upgrade_mode = sanitize_key((string) ($match['upgrade_mode'] ?? ''));
$action = 'upgrade';
if ($upgrade_mode === 'jump' || $upgrade_mode === 'permanent') {
$pkg_time = 0;
$days = 0;
}
} else {
$level_cfg = is_array($levels[$level] ?? null) ? $levels[$level] : [];
if (isset($level_cfg['product_s']) && empty($level_cfg['product_s'])) {
return new \WP_Error('aksrt_vip_product_disabled', __('该等级暂不支持购买', 'aksrt'), ['status' => 400]);
}
$packages = $this->parse_level_products((string) ($level_cfg['products_raw'] ?? ''));
$pkg = $packages[$index - 1] ?? null;
if (!$pkg) {
return new \WP_Error('aksrt_invalid_package', __('套餐不存在', 'aksrt'), ['status' => 400]);
}
$base_price = (float) $pkg['price'];
$days = (int) $pkg['days'];
$pkg_time = (int) ($pkg['time'] ?? 0);
$pkg_unit = (string) ($pkg['unit'] ?? 'day');
$priced = $this->apply_action_price($base_price, $action, $renew, $upgrade, $level, $user_level, $expires, $is_permanent, $days);
if ($priced === null) {
return new \WP_Error('aksrt_invalid_package', __('当前无法购买该套餐', 'aksrt'), ['status' => 400]);
}
$amount = round((float) $priced['price'], 2);
$discount_tag = (string) ($priced['tag'] ?? '');
}
if ($amount <= 0) {
return new \WP_Error('aksrt_invalid_price', __('套餐价格无效', 'aksrt'), ['status' => 400]);
}
if (!class_exists('\AKSRT\Payment\Order') || !class_exists('\AKSRT\Payment\OrderRepository')) {
return new \WP_Error('aksrt_pay_unavailable', __('支付系统不可用', 'aksrt'), ['status' => 500]);
}
$payment_method = sanitize_key($payment_method);
if ($payment_method === '') {
$payment_method = 'balance';
}
$note = wp_json_encode([
'vip_pay' => 1,
'level' => $level,
'days' => $days,
'time' => $pkg_time,
'unit' => $pkg_unit,
'package_index' => $index,
'package_title' => (string) ($pkg['title'] ?? ''),
'package_id' => $package_id,
'action' => $action,
'upgrade_mode' => $upgrade_mode,
'base_price' => $base_price,
'discount_tag' => $discount_tag,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$order_number = \AKSRT\Payment\OrderRepository::get_instance()->create([
'user_id' => $user_id,
'product_type' => \AKSRT\Core\DomainModel::ORDER_PRODUCT_VIP,
'product_id' => $package_id,
'amount' => $amount,
'currency' => 'CNY',
'status' => \AKSRT\Payment\Order::STATUS_PENDING,
'payment_method' => $payment_method,
'note' => is_string($note) ? $note : '',
'expires_at' => gmdate('Y-m-d H:i:s', time() + 30 * MINUTE_IN_SECONDS),
]);
if ($order_number === '') {
return new \WP_Error('aksrt_order_create_failed', __('创建订单失败', 'aksrt'), ['status' => 500]);
}
$order = \AKSRT\Payment\OrderRepository::get_instance()->get($order_number);
if (!$order) {
return new \WP_Error('aksrt_order_create_failed', __('创建订单失败', 'aksrt'), ['status' => 500]);
}
$level_name = (string) ($levels[$level]['name'] ?? ('VIP' . $level));
$action_label = $action === 'renew' ? __('续费', 'aksrt') : ($action === 'upgrade' ? __('升级', 'aksrt') : __('开通', 'aksrt'));
$order['subject'] = sprintf(
/* translators: 1: action 2: vip name 3: package title */
__('%1$s%2$s · %3$s', 'aksrt'),
$action_label,
$level_name,
(string) ($pkg['title'] ?? '')
);
$order['payment_method'] = $payment_method;
if (!class_exists('\AKSRT\Payment\Gateway')) {
return new \WP_Error('aksrt_pay_unavailable', __('支付网关不可用', 'aksrt'), ['status' => 500]);
}
$resolved = \AKSRT\Payment\PaymentOrchestrator::resolve_gateway($payment_method);
if (empty($resolved['gateway'])) {
return new \WP_Error(
(string) ($resolved['error_code'] ?? 'aksrt_gateway_unavailable'),
(string) ($resolved['message'] ?? __('当前支付方式不可用', 'aksrt')),
['status' => 400, 'order_number' => $order_number]
);
}
$payment_result = \AKSRT\Payment\PaymentOrchestrator::pay($resolved['gateway'], $order, [
'paid_note' => __('用户完成会员开通支付。', 'aksrt'),
]);
if (empty($payment_result['success'])) {
return new \WP_Error(
(string) ($payment_result['code'] ?? 'aksrt_pay_failed'),
(string) ($payment_result['message'] ?? __('支付失败', 'aksrt')),
['status' => 402, 'order_number' => $order_number]
);
}
if (!empty($payment_result['redirect'])) {
return [
'success' => true,
'data' => [
'redirect' => true,
'payment_url' => (string) ($payment_result['payment_url'] ?? ''),
'qr_content' => (string) ($payment_result['qr_content'] ?? ''),
'order_number' => $order_number,
'amount' => $amount,
'message' => $payment_result['message'],
'reload' => false,
'poll' => true,
],
];
}
return [
'success' => true,
'data' => [
'order_number' => $order_number,
'amount' => $amount,
'level' => $level,
'days' => $days,
'action' => $action,
'message' => $action === 'renew'
? __('会员续费成功', 'aksrt')
: ($action === 'upgrade' ? __('会员升级成功', 'aksrt') : __('会员开通成功', 'aksrt')),
'reload' => true,
],
];
}
/**
* Activate VIP on paid order.
*
* @param string $order_number
* @param array $paid_order
*/
public function on_order_paid(string $order_number, array $paid_order): void {
if (sanitize_key((string) ($paid_order['product_type'] ?? '')) !== \AKSRT\Core\DomainModel::ORDER_PRODUCT_VIP) {
return;
}
$user_id = (int) ($paid_order['user_id'] ?? 0);
if ($user_id <= 0) {
return;
}
$meta = [];
if (!empty($paid_order['note']) && is_string($paid_order['note'])) {
$decoded = json_decode($paid_order['note'], true);
if (is_array($decoded)) {
$meta = $decoded;
}
}
if (empty($meta) && is_array($paid_order['meta_payload'] ?? null)) {
$meta = $paid_order['meta_payload'];
}
$level = (int) ($meta['level'] ?? 0);
$days = (int) ($meta['days'] ?? 0);
$time = (int) ($meta['time'] ?? 0);
$unit = sanitize_key((string) ($meta['unit'] ?? 'day'));
if (!in_array($unit, ['day', 'month'], true)) {
$unit = 'day';
}
$upgrade_mode = sanitize_key((string) ($meta['upgrade_mode'] ?? ''));
if ($level <= 0) {
$decoded = $this->decode_package_id((int) ($paid_order['product_id'] ?? 0));
if ($decoded) {
$level = (int) $decoded['level'];
}
}
if ($level < 1) {
$level = 1;
}
if ($level > 2) {
$level = 2;
}
$previous_level = (int) get_user_meta($user_id, 'aksrt_vip_level', true);
$previous_expiry = (int) get_user_meta($user_id, 'aksrt_vip_expires', true);
$fulfilled = false;
// unit upgrade: raise level only, keep current expiry (zibll).
if ($upgrade_mode === 'unit') {
$this->activate_vip($user_id, $level, 0, true);
$fulfilled = (int) get_user_meta($user_id, 'aksrt_vip_level', true) >= $level;
} elseif ($time > 0 || (isset($meta['time']) && (int) $meta['time'] === 0 && $days === 0)) {
// Prefer calendar time+unit when present (including permanent time=0).
$this->activate_vip_duration($user_id, $level, $time, $unit);
$new_expiry = (int) get_user_meta($user_id, 'aksrt_vip_expires', true);
$expected_base = max($previous_expiry, time());
$expected_expiry = $time <= 0
? 0
: strtotime('+' . $time . ' ' . ($unit === 'month' ? 'months' : 'days'), $expected_base);
if ($expected_expiry === false) {
$expected_expiry = $expected_base + ($this->duration_to_days($time, $unit) * DAY_IN_SECONDS);
}
$fulfilled = (int) get_user_meta($user_id, 'aksrt_vip_level', true) >= max($previous_level, $level)
&& ($new_expiry === 0 || ($time <= 0 ? $new_expiry === 0 : $new_expiry >= $expected_expiry));
} else {
$this->activate_vip($user_id, $level, $days, false);
$new_expiry = (int) get_user_meta($user_id, 'aksrt_vip_expires', true);
$fulfilled = (int) get_user_meta($user_id, 'aksrt_vip_level', true) >= max($previous_level, $level)
&& ($new_expiry === 0 || $days <= 0 || $new_expiry >= max($previous_expiry, time()) + ($days * DAY_IN_SECONDS));
}
if ($fulfilled && class_exists('\AKSRT\Payment\OrderRepository')) {
\AKSRT\Payment\OrderRepository::get_instance()->update_status(
$order_number,
\AKSRT\Payment\Order::STATUS_COMPLETED,
['note' => __('会员权益已发放。', 'aksrt')]
);
}
}
/**
* Apply membership meta.
*
* @param bool $keep_expiry When true (unit upgrade), only raise level and do not change expiry.
* When days<=0 and keep_expiry=false, set permanent (expires=0).
*/
public function activate_vip(int $user_id, int $level, int $days = 0, bool $keep_expiry = false): void {
if ($user_id <= 0) {
return;
}
$level = max(1, min(2, $level));
$current_level = (int) get_user_meta($user_id, 'aksrt_vip_level', true);
$new_level = max($current_level, $level);
update_user_meta($user_id, 'aksrt_vip_level', $new_level);
// Clear expired memory when re-granting.
delete_user_meta($user_id, 'aksrt_vip_level_expired');
// Unit upgrade (zibll): keep vip_exp_date, only raise level.
if ($keep_expiry) {
return;
}
if ($days <= 0) {
// Permanent.
update_user_meta($user_id, 'aksrt_vip_expires', 0);
return;
}
$current_exp = (int) get_user_meta($user_id, 'aksrt_vip_expires', true);
if ($current_exp === 0 && $current_level > 0) {
// Already permanent — keep permanent.
return;
}
$base = max($current_exp, time());
update_user_meta($user_id, 'aksrt_vip_expires', $base + ($days * DAY_IN_SECONDS));
}
/**
* Activate VIP using calendar duration (zibll month/day).
* time=0 → permanent. Extends from max(now, current_exp).
*/
public function activate_vip_duration(int $user_id, int $level, int $time, string $unit = 'day'): void {
if ($user_id <= 0) {
return;
}
$level = max(1, min(2, $level));
$unit = $unit === 'month' ? 'month' : 'day';
$current_level = (int) get_user_meta($user_id, 'aksrt_vip_level', true);
$new_level = max($current_level, $level);
update_user_meta($user_id, 'aksrt_vip_level', $new_level);
delete_user_meta($user_id, 'aksrt_vip_level_expired');
if ($time <= 0) {
update_user_meta($user_id, 'aksrt_vip_expires', 0);
return;
}
$current_exp = (int) get_user_meta($user_id, 'aksrt_vip_expires', true);
if ($current_exp === 0 && $current_level > 0) {
return; // keep permanent
}
$base = max($current_exp, time());
$modifier = $unit === 'month'
? ('+' . $time . ' months')
: ('+' . $time . ' days');
$new_exp = strtotime($modifier, $base);
if ($new_exp === false) {
$new_exp = $base + ($this->duration_to_days($time, $unit) * DAY_IN_SECONDS);
}
update_user_meta($user_id, 'aksrt_vip_expires', (int) $new_exp);
}
/**
* Points exchange (non-VIP only, zibll pay_vip_points_exchange).
*
* @return array|\WP_Error
*/
public function exchange_with_points(int $user_id, int $package_id) {
if ($user_id <= 0) {
return new \WP_Error('aksrt_need_login', __('请先登录后再兑换。', 'aksrt'), ['status' => 401]);
}
if (!class_exists('\AKSRT\Credits\Credits')) {
return new \WP_Error('aksrt_credits_unavailable', __('积分系统不可用', 'aksrt'), ['status' => 500]);
}
if (class_exists('\AKSRT\Settings\Settings') && !\AKSRT\Settings\Settings::credits_enabled()) {
return new \WP_Error('aksrt_credits_disabled', __('积分功能未启用', 'aksrt'), ['status' => 400]);
}
$vip = class_exists('\AKSRT\Settings\Settings')
? \AKSRT\Settings\Settings::get_payment_vip_settings()
: [];
$points_ex = is_array($vip['points_exchange'] ?? null) ? $vip['points_exchange'] : [];
if (empty($points_ex['enabled'])) {
return new \WP_Error('aksrt_points_exchange_disabled', __('积分兑换会员未启用', 'aksrt'), ['status' => 400]);
}
$user_level = function_exists('aksrt_get_user_vip_level') ? aksrt_get_user_vip_level($user_id) : 0;
if ($user_level > 0) {
return new \WP_Error('aksrt_already_vip', __('您已是会员,无法使用积分兑换。', 'aksrt'), ['status' => 400]);
}
$levels = is_array($vip['levels'] ?? null) ? $vip['levels'] : [];
$packages = $this->get_points_exchange_packages($vip, $levels);
$match = null;
foreach ($packages as $pkg) {
if ((int) ($pkg['package_id'] ?? 0) === $package_id) {
$match = $pkg;
break;
}
}
if (!$match) {
return new \WP_Error('aksrt_invalid_package', __('兑换套餐不存在', 'aksrt'), ['status' => 400]);
}
$cost = (int) ($match['points'] ?? 0);
$level = (int) ($match['level'] ?? 1);
$days = (int) ($match['days'] ?? 0);
if ($cost <= 0) {
return new \WP_Error('aksrt_invalid_price', __('兑换积分无效', 'aksrt'), ['status' => 400]);
}
$balance = \AKSRT\Credits\Credits::balance($user_id);
if ($balance < $cost) {
return new \WP_Error('aksrt_credits_insufficient', __('积分不足,暂时无法兑换', 'aksrt'), [
'status' => 402,
'balance' => $balance,
'cost' => $cost,
]);
}
if (!class_exists('\AKSRT\Payment\Order') || !class_exists('\AKSRT\Payment\OrderRepository')) {
return new \WP_Error('aksrt_pay_unavailable', __('订单系统不可用', 'aksrt'), ['status' => 500]);
}
$note = wp_json_encode([
'vip_pay' => 1,
'vip_pay_type' => 'points_exchange',
'level' => $level,
'days' => $days,
'points' => $cost,
'package_id' => $package_id,
'package_title' => (string) ($match['title'] ?? ''),
'action' => 'points_exchange',
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$order_number = \AKSRT\Payment\OrderRepository::get_instance()->create([
'user_id' => $user_id,
'product_type' => \AKSRT\Core\DomainModel::ORDER_PRODUCT_VIP,
'product_id' => $package_id,
'amount' => (float) $cost,
'currency' => 'points',
'status' => \AKSRT\Payment\Order::STATUS_PENDING,
'payment_method' => 'points',
'note' => is_string($note) ? $note : '',
'expires_at' => gmdate('Y-m-d H:i:s', time() + 30 * MINUTE_IN_SECONDS),
]);
if ($order_number === '') {
return new \WP_Error('aksrt_order_create_failed', __('创建订单失败', 'aksrt'), ['status' => 500]);
}
$lock = class_exists('\AKSRT\Payment\PaymentAttemptLock')
? \AKSRT\Payment\PaymentAttemptLock::acquire($order_number)
: false;
if ($lock === false) {
return new \WP_Error('aksrt_pay_locked', __('该订单正在发起支付,请稍后重试。', 'aksrt'), ['status' => 409]);
}
try {
$deducted = \AKSRT\Credits\Credits::deduct(
$user_id,
$cost,
'vip_points_exchange',
['order' => $order_number, 'level' => $level, 'days' => $days],
sprintf(__('积分兑换会员 · %s', 'aksrt'), (string) ($match['title'] ?? ''))
);
if (is_wp_error($deducted) || $deducted === false) {
\AKSRT\Payment\Order::get_instance()->update_status($order_number, \AKSRT\Payment\Order::STATUS_CANCELLED, [
'note' => __('积分扣除失败,自动取消', 'aksrt'),
]);
$msg = is_wp_error($deducted) ? $deducted->get_error_message() : __('积分扣除失败', 'aksrt');
return new \WP_Error('aksrt_credits_deduct_failed', $msg ?: __('积分扣除失败', 'aksrt'), ['status' => 400]);
}
$paid = \AKSRT\Payment\Order::get_instance()->update_status($order_number, \AKSRT\Payment\Order::STATUS_PAID, [
'payment_method' => 'points',
'payment_transaction_id' => 'points_' . $order_number,
'note' => sprintf(__('积分兑换会员 %d 积分。', 'aksrt'), $cost),
'require_transition' => true,
]);
if (!$paid) {
\AKSRT\Credits\Credits::add(
$user_id,
$cost,
'vip_points_exchange_refund',
['order' => $order_number],
__('会员兑换失败退款', 'aksrt')
);
return new \WP_Error('aksrt_order_confirm_failed', __('兑换确认失败,已尝试退回积分', 'aksrt'), ['status' => 500]);
}
} finally {
\AKSRT\Payment\PaymentAttemptLock::release($order_number, $lock);
}
return [
'success' => true,
'data' => [
'order_number' => $order_number,
'points' => $cost,
'level' => $level,
'days' => $days,
'balance' => \AKSRT\Credits\Credits::balance($user_id),
'message' => __('兑换成功', 'aksrt'),
'reload' => true,
],
];
}
}
+158
View File
@@ -0,0 +1,158 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Content;
defined('ABSPATH') || exit;
trait VipServiceRest {
public function register_routes(): void {
register_rest_route('aksrt/v1', '/pay/vip', [
[
'methods' => 'GET',
'callback' => [$this, 'rest_catalog'],
'permission_callback' => [$this, 'check_rest_nonce'],
],
[
'methods' => 'POST',
'callback' => [$this, 'rest_purchase'],
'permission_callback' => [$this, 'check_rest_nonce'],
],
]);
register_rest_route('aksrt/v1', '/pay/vip/points-exchange', [
'methods' => 'POST',
'callback' => [$this, 'rest_points_exchange'],
'permission_callback' => [$this, 'check_rest_nonce'],
]);
register_rest_route('aksrt/v1', '/pay/vip/modal', [
'methods' => 'GET',
'callback' => [$this, 'rest_modal'],
'permission_callback' => [$this, 'check_rest_nonce'],
'args' => [
'vip_level' => [
'type' => 'integer',
'default' => 1,
],
],
]);
}
/**
* GET /pay/vip/modal?vip_level=1
*/
public function rest_modal(\WP_REST_Request $request) {
$uid = get_current_user_id();
if ($uid <= 0) {
return new \WP_Error('aksrt_need_login', __('请先登录后再开通会员。', 'aksrt'), [
'status' => 401,
'login_url' => function_exists('aksrt_get_login_url') ? aksrt_get_login_url() : wp_login_url(),
]);
}
$level = (int) $request->get_param('vip_level');
if ($level < 1 || $level > 2) {
$level = 1;
}
$html = $this->render_modal_html($uid, $level);
return new \WP_REST_Response([
'html' => $html,
'user_level' => function_exists('aksrt_get_user_vip_level') ? aksrt_get_user_vip_level($uid) : 0,
], 200);
}
/**
* @param \WP_REST_Request $request
* @return true|\WP_Error
*/
public function check_rest_nonce(\WP_REST_Request $request) {
$nonce = $request->get_header('x-wp-nonce');
if (!$nonce) {
return new \WP_Error('aksrt_rest_no_nonce', __('缺少安全令牌', 'aksrt'), ['status' => 403]);
}
if (!wp_verify_nonce($nonce, 'wp_rest')) {
return new \WP_Error('aksrt_rest_bad_nonce', __('安全令牌已过期,请刷新页面', 'aksrt'), ['status' => 403]);
}
return true;
}
/**
* GET /pay/vip
*/
public function rest_catalog(\WP_REST_Request $request) {
$uid = get_current_user_id();
return new \WP_REST_Response($this->get_catalog($uid), 200);
}
/**
* POST /pay/vip
* body: { package_id: int, payment_method?: string }
*/
public function rest_purchase(\WP_REST_Request $request) {
$uid = get_current_user_id();
if ($uid <= 0) {
return new \WP_Error('aksrt_need_login', __('请先登录后再开通会员。', 'aksrt'), [
'status' => 401,
'login_url' => function_exists('aksrt_get_login_url') ? aksrt_get_login_url() : wp_login_url(),
]);
}
$params = $request->get_json_params();
if (!is_array($params)) {
$params = $request->get_params();
}
$package_id = (int) ($params['package_id'] ?? 0);
$payment_method = sanitize_key((string) ($params['payment_method'] ?? 'balance'));
if ($payment_method === '' || $payment_method === 'cash') {
$payment_method = 'balance';
}
$result = $this->purchase($uid, $package_id, $payment_method);
if (is_wp_error($result)) {
return $result;
}
if (empty($result['success'])) {
return new \WP_Error(
sanitize_key((string) ($result['code'] ?? 'aksrt_vip_pay_failed')),
(string) ($result['message'] ?? __('开通失败', 'aksrt')),
['status' => (int) ($result['status'] ?? 400)]
);
}
return new \WP_REST_Response($result, 200);
}
/**
* POST /pay/vip/points-exchange
* body: { package_id: int } // points package id = 5000 + index
*/
public function rest_points_exchange(\WP_REST_Request $request) {
$uid = get_current_user_id();
if ($uid <= 0) {
return new \WP_Error('aksrt_need_login', __('请先登录后再兑换。', 'aksrt'), ['status' => 401]);
}
$params = $request->get_json_params();
if (!is_array($params)) {
$params = $request->get_params();
}
$package_id = (int) ($params['package_id'] ?? 0);
$result = $this->exchange_with_points($uid, $package_id);
if (is_wp_error($result)) {
return $result;
}
return new \WP_REST_Response($result, 200);
}
}
+409
View File
@@ -0,0 +1,409 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Content;
defined('ABSPATH') || exit;
class Visibility {
private static $instance = null;
public static function get_instance(): self {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function init(): void {
// 短代码注册统一在 \AKSRT\Core\Shortcodes(registry);本类只提供渲染实现。
add_action('wp_ajax_aksrt_check_visibility', [$this, 'ajax_check_visibility']);
add_action('wp_ajax_nopriv_aksrt_check_visibility', [$this, 'ajax_check_visibility']);
}
/**
* @param int|\WP_Post|null $post
* @return array<string, mixed>
*/
public static function get_post_access_state($post = null, int $user_id = 0): array {
$resource_post = get_post($post);
$uid = $user_id > 0 ? $user_id : get_current_user_id();
$pay_meta = function_exists('aksrt_get_pay_meta')
? aksrt_get_pay_meta($resource_post)
: \AKSRT\Core\DomainModel::default_pay_meta();
$pay_type = \AKSRT\Core\DomainModel::normalize_pay_type((string) ($pay_meta['pay_type'] ?? \AKSRT\Core\DomainModel::PAY_TYPE_NO));
$priced = function_exists('aksrt_get_user_pay_price')
? aksrt_get_user_pay_price($resource_post, $uid)
: null;
$pay_modo = is_array($priced)
? ((($priced['modo'] ?? '0') === 'points') ? 'points' : '0')
: ((($pay_meta['pay_modo'] ?? '0') === 'points') ? 'points' : '0');
$price = is_array($priced)
? (float) ($priced['amount'] ?? 0)
: (($pay_modo === 'points')
? (float) ($pay_meta['points_price'] ?? 0)
: (float) ($pay_meta['price'] ?? 0));
$paid_settings = class_exists('\AKSRT\Settings\Settings')
? \AKSRT\Settings\Settings::get_paid_content_settings()
: [
'download_login' => true,
'download_credit' => true,
'download_captcha' => false,
];
$state = [
'post_id' => $resource_post instanceof \WP_Post ? (int) $resource_post->ID : 0,
'pay_type' => $pay_type,
'pay_modo' => $pay_modo,
'price' => $price,
'need_login' => false,
'need_purchase' => false,
'need_vip' => false,
'require_captcha' => false,
'has_paid_access' => false,
'can_view' => true,
'can_download' => true,
'download_cost' => 0,
'pay_limit' => 0,
'user_vip_level' => 0,
];
if (!($resource_post instanceof \WP_Post)) {
$state['can_view'] = false;
$state['can_download'] = false;
return $state;
}
if ($pay_type === \AKSRT\Core\DomainModel::PAY_TYPE_NO) {
$state['has_paid_access'] = true;
return $state;
}
$has_free_access = $price <= 0 && $pay_type !== \AKSRT\Core\DomainModel::PAY_TYPE_VIP;
$pay_limit = (int) ($pay_meta['pay_limit'] ?? 0);
if (!in_array($pay_limit, [0, 1, 2], true)) {
$pay_limit = 0;
}
$state['pay_limit'] = $pay_limit;
$has_paid_order = false;
if ($uid > 0 && class_exists('\AKSRT\Payment\Order')) {
$has_paid_order = \AKSRT\Payment\Order::get_instance()->has_paid_access(
$uid,
\AKSRT\Core\DomainModel::ORDER_PRODUCT_RESOURCE,
(int) $resource_post->ID
);
}
// Guest cookie paid unlock (Zibll pay_no_logged_in).
if (!$has_paid_order && $uid <= 0 && function_exists('aksrt_guest_has_paid_access')) {
$has_paid_order = aksrt_guest_has_paid_access((int) $resource_post->ID);
}
$has_vip_access = false;
$user_vip_level = is_array($priced) ? (int) ($priced['vip_level'] ?? 0) : 0;
if ($uid > 0) {
if ($user_vip_level <= 0 && function_exists('aksrt_get_user_vip_level')) {
$user_vip_level = aksrt_get_user_vip_level($uid);
}
if (function_exists('aksrt_is_vip_exempt') && aksrt_is_vip_exempt($uid)) {
$has_vip_access = true;
$user_vip_level = max($user_vip_level, 2);
} elseif ($pay_type === \AKSRT\Core\DomainModel::PAY_TYPE_VIP || $pay_limit > 0) {
$has_vip_access = $user_vip_level >= max(1, $pay_limit);
} elseif ($user_vip_level > 0) {
// VIP tier pricing may zero cost; still track membership.
$has_vip_access = $pay_limit <= 0 || $user_vip_level >= $pay_limit;
}
}
$state['user_vip_level'] = $user_vip_level;
// Member-only purchase restriction (Zibll pay_limit).
if ($pay_limit > 0 && $pay_type !== \AKSRT\Core\DomainModel::PAY_TYPE_NO) {
$state['need_vip'] = $uid <= 0 || $user_vip_level < $pay_limit;
$allowed_member = $uid > 0 && $user_vip_level >= $pay_limit;
if ($pay_type === \AKSRT\Core\DomainModel::PAY_TYPE_DOWNLOAD) {
// Cash: order gate only. Points: cashier once → paid order zeros cost.
$download_cost = 0;
if ($pay_modo === 'points' && $price > 0 && !$has_paid_order) {
$download_cost = (int) ceil($price);
}
if ($allowed_member && $price <= 0) {
$download_cost = 0;
}
$state['download_cost'] = max(0, $download_cost);
$state['need_login'] = $uid <= 0;
$state['need_purchase'] = $allowed_member && $price > 0 && !$has_paid_order;
$state['has_paid_access'] = $allowed_member && ($has_paid_order || $price <= 0);
$state['can_view'] = true;
$state['can_download'] = $allowed_member && ($uid > 0) && ($has_paid_order || $price <= 0);
if (!$allowed_member) {
$state['can_download'] = false;
$state['has_paid_access'] = false;
$state['need_purchase'] = false;
$state['need_vip'] = true;
}
return $state;
}
// reading/gallery/video with pay_limit
if ($allowed_member) {
$state['has_paid_access'] = $has_paid_order || $price <= 0;
$state['need_purchase'] = !$state['has_paid_access'];
$state['need_vip'] = false;
} else {
$state['has_paid_access'] = false;
$state['need_purchase'] = false;
$state['need_vip'] = true;
}
$state['can_view'] = $state['has_paid_access'];
$state['can_download'] = false;
return $state;
}
if ($pay_type === \AKSRT\Core\DomainModel::PAY_TYPE_DOWNLOAD) {
// Zibll: cash = order unlock; points = one-shot cashier order (not per-download deduct).
$download_cost = 0;
if ($pay_modo === 'points' && $price > 0 && !$has_paid_order) {
$download_cost = (int) ceil($price);
}
$state['download_cost'] = max(0, $download_cost);
$free_logged_show = !empty($paid_settings['free_logged_show']);
$state['need_login'] = !empty($paid_settings['download_login'])
|| !empty($pay_meta['require_login'])
|| ($free_logged_show && $price <= 0);
$state['require_captcha'] = !empty($paid_settings['download_captcha']) || !empty($pay_meta['require_captcha']);
$state['need_purchase'] = !$has_paid_order && $price > 0;
$state['has_paid_access'] = $has_paid_order || $price <= 0 || $has_free_access;
$state['can_view'] = true;
$state['can_download'] = (!$state['need_login'] || $uid > 0) && ($has_paid_order || $price <= 0);
return $state;
}
if ($pay_type === \AKSRT\Core\DomainModel::PAY_TYPE_VIP) {
$state['need_vip'] = true;
$state['has_paid_access'] = $has_vip_access;
$state['can_view'] = $has_vip_access;
$state['can_download'] = false;
return $state;
}
$state['need_login'] = !empty($pay_meta['require_login']);
$state['need_purchase'] = !$has_free_access && !$has_paid_order;
$state['has_paid_access'] = $has_free_access || $has_paid_order;
// VIP free tier for reading etc. via amount.
if (!$state['has_paid_access'] && $price <= 0 && $pay_type !== \AKSRT\Core\DomainModel::PAY_TYPE_VIP) {
$state['has_paid_access'] = true;
$state['need_purchase'] = false;
}
$state['can_view'] = $state['has_paid_access'] && (!$state['need_login'] || $uid > 0);
$state['can_download'] = false;
return $state;
}
public static function can_view_paid_content($post = null, int $user_id = 0): bool {
$state = self::get_post_access_state($post, $user_id);
return !empty($state['can_view']);
}
/**
* @param int|\WP_Post|null $post
* @return true|\WP_Error
*/
public static function can_download_resource($post = null, int $user_id = 0) {
$resource_post = get_post($post);
if (!($resource_post instanceof \WP_Post) || !function_exists('aksrt_is_downloadable_content') || !aksrt_is_downloadable_content($resource_post)) {
return new \WP_Error('aksrt_not_downloadable', __('该内容未启用下载能力。', 'aksrt'));
}
$state = self::get_post_access_state($resource_post, $user_id);
$uid = $user_id > 0 ? $user_id : get_current_user_id();
if (($state['pay_type'] ?? '') !== \AKSRT\Core\DomainModel::PAY_TYPE_DOWNLOAD) {
return new \WP_Error('aksrt_not_downloadable', __('该内容未启用下载能力。', 'aksrt'));
}
if (!empty($state['need_login']) && $uid <= 0) {
return new \WP_Error('aksrt_need_login', __('请先登录后再下载。', 'aksrt'), [
'status' => 401,
'login_url' => wp_login_url(get_permalink($resource_post)),
]);
}
// Free download + pay_free_logged_show (belt-and-suspenders with state.need_login).
$cost = (int) ($state['download_cost'] ?? 0);
$paid_settings = class_exists('\AKSRT\Settings\Settings')
? \AKSRT\Settings\Settings::get_paid_content_settings()
: ['download_credit' => true, 'free_logged_show' => false];
if ($cost <= 0 && !empty($paid_settings['free_logged_show']) && $uid <= 0) {
return new \WP_Error('aksrt_need_login', __('免费资源,请登录后下载。', 'aksrt'), [
'status' => 401,
'login_url' => wp_login_url(get_permalink($resource_post)),
]);
}
// Member-only (pay_limit).
if (!empty($state['need_vip']) && empty($state['has_paid_access']) && empty($state['can_download'])) {
$need_level = (int) ($state['pay_limit'] ?? 1);
return new \WP_Error('aksrt_need_vip', sprintf(
/* translators: %d: required VIP level */
__('该资源仅限 VIP%s 及以上会员购买/下载。', 'aksrt'),
max(1, $need_level)
), [
'status' => 403,
'pay_limit' => $need_level,
]);
}
// Cash or points: require cashier purchase (resource order) before download token.
if (!empty($state['need_purchase']) && empty($state['has_paid_access'])) {
$pay_modo = (string) ($state['pay_modo'] ?? '0');
$price = (float) ($state['price'] ?? 0);
return new \WP_Error('aksrt_need_purchase', __('请先购买后再下载。', 'aksrt'), [
'status' => 402,
'pay_modo' => $pay_modo,
'amount' => $pay_modo === 'points' ? (int) ceil($price) : $price,
'post_id' => (int) ($state['post_id'] ?? 0),
]);
}
// Zibll daily free-download quota (only when free / already unlocked).
if ($cost <= 0 && function_exists('aksrt_check_free_download_quota')) {
// Provide per-post overbuy price to quota error.
$over_cb = static function ($over, $uid) use ($resource_post) {
if (!($resource_post instanceof \WP_Post) || !function_exists('aksrt_get_pay_meta')) {
return $over;
}
$m = aksrt_get_pay_meta($resource_post);
return max(0.0, (float) ($m['download_limit_over_price'] ?? 0));
};
add_filter('aksrt_download_limit_over_price', $over_cb, 10, 2);
$quota = aksrt_check_free_download_quota($uid, $cost);
remove_filter('aksrt_download_limit_over_price', $over_cb, 10);
if (is_wp_error($quota)) {
$data = (array) $quota->get_error_data();
$data['post_id'] = (int) ($state['post_id'] ?? 0);
$data['pay_modo'] = (string) ($state['pay_modo'] ?? '0');
return new \WP_Error($quota->get_error_code(), $quota->get_error_message(), $data);
}
}
return true;
}
public function render_hide_shortcode(array $atts, string $content = ''): string {
$atts = shortcode_atts([
'mode' => 'comment',
'message' => '',
'pid' => get_the_ID(),
], $atts, 'aksrt_hide');
$mode = sanitize_key((string) $atts['mode']);
$pid = (int) $atts['pid'];
$message = (string) $atts['message'];
if ($pid <= 0) {
return '';
}
if ($this->is_unlocked($mode, $pid)) {
return '<div class="aksrt-hidden-content aksrt-hidden-content--unlocked">' . do_shortcode($content) . '</div>';
}
if ($message === '') {
switch ($mode) {
case 'comment':
$message = __('评论后查看隐藏内容', 'aksrt');
break;
case 'login':
$message = __('登录后查看隐藏内容', 'aksrt');
break;
case 'password':
$message = __('输入密码后查看隐藏内容', 'aksrt');
break;
default:
$message = __('此内容已隐藏', 'aksrt');
}
}
$wrapper_class = 'aksrt-hidden-content aksrt-hidden-content--locked aksrt-hidden-content--' . esc_attr($mode);
$html = '<div class="' . $wrapper_class . '" data-aksrt-visibility-mode="' . esc_attr($mode) . '" data-aksrt-visibility-pid="' . esc_attr((string) $pid) . '">';
$html .= '<div class="aksrt-hidden-content__message">';
$html .= '<i class="fas fa-lock" aria-hidden="true"></i> ';
$html .= '<span>' . esc_html($message) . '</span>';
$html .= '</div>';
if ($mode === 'password') {
$html .= '<div class="aksrt-hidden-content__form">';
$html .= '<input type="password" class="aksrt-hidden-content__password-input" placeholder="' . esc_attr__('请输入密码', 'aksrt') . '">';
$html .= '<button type="button" class="aksrt-hidden-content__submit-btn btn-primary btn-sm">' . esc_html__('验证', 'aksrt') . '</button>';
$html .= '</div>';
}
$html .= '</div>';
return $html;
}
private function is_unlocked(string $mode, int $pid): bool {
switch ($mode) {
case 'comment':
if (!is_user_logged_in()) {
return false;
}
return get_comments([
'post_id' => $pid,
'user_id' => get_current_user_id(),
'count' => true,
'status' => 'approve',
]) > 0;
case 'login':
return is_user_logged_in();
case 'password':
return !empty($_COOKIE['aksrt_hide_pwd_' . $pid]);
default:
return false;
}
}
public function ajax_check_visibility(): void {
check_ajax_referer('aksrt_visibility', '_nonce');
$mode = sanitize_key((string) ($_POST['mode'] ?? ''));
$pid = (int) ($_POST['pid'] ?? 0);
if ($pid <= 0 || !in_array($mode, ['comment', 'login', 'password'], true)) {
wp_send_json_error(['message' => __('参数无效', 'aksrt')]);
}
if ($mode === 'password') {
$password = sanitize_text_field((string) ($_POST['password'] ?? ''));
$post_password = get_post_password($pid);
if ($post_password === '' || $password !== $post_password) {
wp_send_json_error(['message' => __('密码错误', 'aksrt')]);
}
setcookie('aksrt_hide_pwd_' . $pid, '1', time() + HOUR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
wp_send_json_success(['message' => __('验证成功', 'aksrt')]);
}
if ($this->is_unlocked($mode, $pid)) {
wp_send_json_success(['message' => __('已解锁', 'aksrt')]);
}
wp_send_json_error(['message' => __('未满足条件', 'aksrt')]);
}
}