\\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[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_Order_Repository')) { return new WP_Error('aksrt_invalid', __('订单不存在', 'aksrt'), ['status' => 404]); } $repo = AKSRT_Order_Repository::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 content orders (user_id=0 + resource). if ($order && ((int) ($order['user_id'] ?? -1) !== 0 || (string) ($order['product_type'] ?? '') !== AKSRT_Domain_Model::ORDER_PRODUCT_RESOURCE)) { $order = null; } } if (!$order) { return new WP_Error('aksrt_invalid', __('订单不存在', 'aksrt'), ['status' => 404]); } $status = (string) ($order['status'] ?? ''); $paid = class_exists('AKSRT_Domain_Model') && AKSRT_Domain_Model::is_paid_order_status($status); if ($paid && $uid <= 0 && function_exists('aksrt_set_guest_content_pay_cookies')) { // Ensure cookie set even if notify raced ahead of browser cookie. aksrt_set_guest_content_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); } /** * 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_Domain_Model::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_Domain_Model::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_Order_Repository')) { $full = AKSRT_Order_Repository::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); } /** * 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. $coupon = is_array($meta['coupon'] ?? null) ? $meta['coupon'] : []; $coupon_code = sanitize_text_field((string) ($coupon['code'] ?? $meta['coupon_code'] ?? '')); $coupon_discount = (float) ($meta['coupon_discount'] ?? $meta['discount'] ?? ($coupon['discount'] ?? 0)); if ($coupon_code !== '' && class_exists('AKSRT_Coupon') && !$this->coupon_usage_exists($order_number)) { $coupon_api = AKSRT_Coupon::get_instance(); $coupon_api->use_coupon($coupon_code); $validated = $coupon_api->validate($coupon_code, max(0.01, $coupon_discount), ['user_id' => $buyer_id]); $coupon_id = (int) ($validated['coupon']['id'] ?? $coupon['id'] ?? 0); if ($coupon_id <= 0 && !empty($coupon['id'])) { $coupon_id = (int) $coupon['id']; } if ($coupon_id > 0) { $coupon_api->log_usage($coupon_id, max(0, $buyer_id), $order_number, max(0.0, $coupon_discount)); } } // 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_Rebate')) { return; } if ($this->rebate_log_exists($order_number, $referrer_id)) { return; } AKSRT_Rebate::get_instance()->create([ 'user_id' => $referrer_id, 'order_number' => $order_number, 'source_user_id' => $buyer_id, 'amount' => $rebate_price, 'type' => AKSRT_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 $order * @return array */ 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 coupon_usage_exists(string $order_number): bool { global $wpdb; $table = AKSRT_DB_Migrator::table('coupon_usage'); if ($table === '' || $order_number === '') { return false; } $found = $wpdb->get_var($wpdb->prepare( "SELECT id FROM {$table} WHERE order_number = %s LIMIT 1", $order_number )); return !empty($found); } private function rebate_log_exists(string $order_number, int $referrer_id): bool { global $wpdb; $table = AKSRT_DB_Migrator::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); } /** * @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); } /** * 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_Domain_Model::normalize_pay_type((string) ($meta['pay_type'] ?? AKSRT_Domain_Model::PAY_TYPE_NO)); if ($pay_type === AKSRT_Domain_Model::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') && method_exists('AKSRT_Settings', 'get_content_coupon_settings')) { $coupon_desc = (string) (AKSRT_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_Order')) { $has_paid = AKSRT_Order::get_instance()->has_paid_access( $uid, AKSRT_Domain_Model::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_Order_Repository')) { $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') ? AKSRT_Settings::get_currency_name() : __('积分', 'aksrt')) : '¥')); $balance = ($uid > 0 && class_exists('AKSRT_Credits')) ? AKSRT_Credits::balance($uid) : 0; $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; return [ 'post_id' => $post_id, 'title' => get_the_title($post), 'permalink' => get_permalink($post), 'pay_type' => $pay_type, 'pay_type_label' => AKSRT_Domain_Model::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' => $pay_modo === 'points' ? (int) ceil($payable) : round($payable, 2), '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, 'balance_enough' => $pay_modo !== 'points' || $balance >= (int) ceil($amount), '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, ]; } /** * 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_Order') || !class_exists('AKSRT_Credits')) { return new WP_Error('aksrt_pay_unavailable', __('支付系统不可用。', 'aksrt'), ['status' => 500]); } $balance = AKSRT_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_Order_Repository::get_instance()->create([ 'user_id' => $user_id, 'product_type' => AKSRT_Domain_Model::ORDER_PRODUCT_RESOURCE, 'product_id' => $post_id, 'amount' => (float) $amount, 'currency' => 'points', 'status' => AKSRT_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]); } $deducted = AKSRT_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_Order::get_instance()->update_status($order_number, AKSRT_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_Order::get_instance()->update_status($order_number, AKSRT_Order::STATUS_PAID, [ 'payment_method' => 'points', 'payment_transaction_id' => 'points_' . $order_number, 'note' => sprintf(__('积分支付 %d 积分。', 'aksrt'), $amount), ]); if (!$paid) { AKSRT_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]); } return [ 'success' => true, 'data' => [ 'order_number' => $order_number, 'amount' => $amount, 'pay_modo' => 'points', 'balance' => AKSRT_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_Order') || !class_exists('AKSRT_Order_Repository')) { 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_Order_Repository::get_instance()->create([ 'user_id' => max(0, $user_id), 'product_type' => AKSRT_Domain_Model::ORDER_PRODUCT_RESOURCE, 'product_id' => $post_id, 'amount' => 0.0, 'currency' => 'CNY', 'status' => AKSRT_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_Order::get_instance()->update_status($order_number, AKSRT_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_Order') || !class_exists('AKSRT_Order_Repository')) { 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_Order_Repository::get_instance()->create([ 'user_id' => max(0, $user_id), 'product_type' => AKSRT_Domain_Model::ORDER_PRODUCT_RESOURCE, 'product_id' => $post_id, 'amount' => $amount, 'currency' => 'CNY', 'status' => AKSRT_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_Order_Repository::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]); } $gateway_manager = AKSRT_Payment_Gateway::get_instance(); $gateway = $gateway_manager->get_gateway($payment_method); if (!$gateway) { return new WP_Error('aksrt_gateway_unavailable', __('当前支付方式不可用。', 'aksrt'), [ 'status' => 400, 'order_number' => $order_number, ]); } if (method_exists($gateway, 'is_configured') && !$gateway->is_configured()) { return new WP_Error('aksrt_gateway_unconfigured', __('该支付方式尚未配置,请联系站长。', 'aksrt'), [ 'status' => 400, 'order_number' => $order_number, ]); } $payment_result = $gateway->create_payment($order); if (empty($payment_result['success'])) { $msg = (string) ($payment_result['message'] ?? __('支付失败。', 'aksrt')); $code = ($payment_method === 'balance' && (str_contains($msg, '余额') || str_contains($msg, '不足'))) ? 'aksrt_balance_insufficient' : 'aksrt_pay_failed'; return new WP_Error($code, $msg, [ 'status' => 402, 'order_number' => $order_number, ]); } $code_url = (string) ($payment_result['payment_data']['code_url'] ?? ''); $payment_url = (string) ($payment_result['payment_url'] ?? ''); if ($payment_url !== '' || $code_url !== '') { return [ 'success' => true, 'data' => [ 'redirect' => true, 'payment_url' => $payment_url, 'qr_content' => $code_url, 'order_number' => $order_number, 'amount' => $amount, 'pay_modo' => '0', 'message' => $payment_result['message'] ?? __('请在新页面完成支付。', 'aksrt'), 'reload' => false, 'poll' => true, ], ]; } // Sync gateway (balance): mark paid. $paid = AKSRT_Order::get_instance()->update_status($order_number, AKSRT_Order::STATUS_PAID, [ 'payment_method' => $payment_method, 'payment_transaction_id' => sanitize_text_field((string) ($payment_result['transaction_id'] ?? '')), 'note' => __('用户完成内容购买支付。', 'aksrt'), ]); if (!$paid) { return new WP_Error('aksrt_order_confirm_failed', __('订单确认失败。', 'aksrt'), ['status' => 500]); } return [ 'success' => true, 'data' => [ 'order_number' => $order_number, 'amount' => $amount, 'pay_modo' => '0', 'message' => $payment_result['message'] ?? __('支付成功', 'aksrt'), 'reload' => true, ], ]; } /** * @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_Domain_Model::normalize_pay_type((string) ($meta['pay_type'] ?? AKSRT_Domain_Model::PAY_TYPE_NO)); if ($pay_type === AKSRT_Domain_Model::PAY_TYPE_NO && $price_type !== 'download_limit_over') { return new WP_Error('aksrt_not_paid', __('该内容无需购买', 'aksrt'), ['status' => 400]); } if ($pay_type === AKSRT_Domain_Model::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_Order') && AKSRT_Order::get_instance()->has_paid_access( $user_id, AKSRT_Domain_Model::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|null */ private function find_pending_content_order(int $user_id, int $post_id): ?array { if ($user_id <= 0 || $post_id <= 0 || !class_exists('AKSRT_Order_Repository')) { return null; } $orders = AKSRT_Order_Repository::get_instance()->get_user_orders($user_id, [ 'product_type' => AKSRT_Domain_Model::ORDER_PRODUCT_RESOURCE, 'status' => AKSRT_Domain_Model::ORDER_STATUS_PENDING, 'limit' => 20, 'offset' => 0, ]); foreach ($orders as $order) { if ((int) ($order['product_id'] ?? 0) === $post_id) { return $order; } } return null; } /** * @return array */ 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') && method_exists('AKSRT_Settings', 'get_content_coupon_settings')) { return !empty(AKSRT_Settings::get_content_coupon_settings()['enabled']); } if (class_exists('AKSRT_Settings') && method_exists('AKSRT_Settings', 'get_paid_content_settings')) { return !empty(AKSRT_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') || !method_exists('AKSRT_Settings', 'get_payment_affiliate_settings')) { return $empty; } $aff = AKSRT_Settings::get_payment_affiliate_settings(); if (empty($aff['enabled'])) { return $empty; } $referrer_id = 0; if (class_exists('AKSRT_Invite') && method_exists(AKSRT_Invite::get_instance(), 'get_referrer')) { $referrer_id = (int) AKSRT_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 $priced * @param array $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_Coupon')) { $err = new WP_Error('aksrt_coupon_unavailable', __('优惠券系统不可用。', 'aksrt'), ['status' => 500]); if (!$soft_coupon) { return $err; } } else { $result = AKSRT_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; } }