post_type !== 'post') { return true; } 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). $side_effects = $this->finalize_content_order_side_effects($order_number, $paid_order); if (is_wp_error($side_effects)) { return $side_effects; } if (class_exists('\AKSRT\Payment\CreatorRevenue')) { $revenue_order = array_merge($paid_order, [ 'order_number' => $order_number, 'status' => \AKSRT\Payment\Order::STATUS_PAID, ]); $revenue_id = \AKSRT\Payment\CreatorRevenue::get_instance()->create_from_paid_order($revenue_order); if ($revenue_id < 0) { return new \WP_Error('aksrt_creator_revenue_conflict', __('同一订单的收益载荷不一致。', 'aksrt'), ['status' => 409]); } } return true; } /** * On paid: burn coupon (if any) and create affiliate rebate log. */ private function finalize_content_order_side_effects(string $order_number, array $order) { $meta = $this->decode_order_note_meta($order); if (empty($meta['content_pay'])) { return true; } // Points: no coupon burn / no cash commission. if (($meta['pay_modo'] ?? '') === 'points') { return true; } $buyer_id = (int) ($order['user_id'] ?? 0); // Coupon burn (shared helper; idempotent via coupon_usage.order_number). if (function_exists('aksrt_burn_order_coupon')) { $coupon = is_array($meta['coupon'] ?? null) ? $meta['coupon'] : []; $coupon_code = (string) ($coupon['code'] ?? $meta['coupon_code'] ?? ''); if ($coupon_code !== '' && !aksrt_burn_order_coupon($order_number, $meta, $buyer_id)) { return new \WP_Error('aksrt_coupon_consume_failed', __('优惠券核销失败。', 'aksrt'), ['status' => 409]); } } // Affiliate commission is written by the order transition transaction. return true; } /** * @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 : []; } /** * 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 = '', string $operation_key = '') { $assert = $this->assert_purchasable($post_id, $user_id, $price_type); if (is_wp_error($assert)) { return $assert; } $priced = $assert['priced']; $content_type = \AKSRT\Core\DomainModel::resolve_order_product_type(\AKSRT\Core\DomainModel::ORDER_PRODUCT_RESOURCE, ['pay_type' => $assert['meta']['pay_type'] ?? '']); if ((($priced['modo'] ?? '0') !== 'points')) { return new \WP_Error('aksrt_wrong_modo', __('该内容不支持积分支付。', 'aksrt'), ['status' => 400]); } $amount = $this->parse_asset_minor($priced['amount'] ?? 0, 'points'); if ($amount <= 0) { return [ 'success' => true, 'data' => [ 'free' => true, 'message' => __('无需支付,已可访问。', 'aksrt'), 'reload' => true, ], ]; } if (!class_exists('\AKSRT\Payment\Order')) { return new \WP_Error('aksrt_pay_unavailable', __('支付系统不可用。', 'aksrt'), ['status' => 500]); } $ledger = \AKSRT\Ledger\LedgerService::get_instance(); $balance = $ledger->balance($user_id, \AKSRT\Ledger\AssetType::POINTS); if ($balance < $amount) { return new \WP_Error('aksrt_points_insufficient', __('积分不足,暂时无法支付。', 'aksrt'), [ 'status' => 402, 'balance' => $balance, 'cost' => $amount, ]); } $note = wp_json_encode([ 'content_pay' => 1, 'pay_type' => (string) ($assert['meta']['pay_type'] ?? ''), 'pay_modo' => 'points', 'post_id' => $post_id, 'price_type' => $price_type, 'vip_level' => (int) ($priced['vip_level'] ?? 0), 'base' => $this->parse_asset_minor($priced['base'] ?? $amount, 'points'), 'amount' => $amount, ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); $repo = \AKSRT\Payment\OrderRepository::get_instance(); $existing = $operation_key !== '' ? $repo->get_by_request_key($operation_key) : null; $is_new_order = !is_array($existing); if (is_array($existing)) { $existing_meta = $this->decode_order_note_meta($existing); if ((int) ($existing['user_id'] ?? 0) !== $user_id || sanitize_key((string) ($existing['product_type'] ?? '')) !== $content_type || (int) ($existing['product_id'] ?? 0) !== $post_id || (string) ($existing['currency'] ?? '') !== 'points' || (int) ($existing['amount'] ?? 0) !== $amount || sanitize_key((string) ($existing['payment_method'] ?? '')) !== 'points' || (string) ($existing_meta['price_type'] ?? '') !== $price_type ) { return new \WP_Error('aksrt_ledger_idempotency_conflict', __('相同操作标识已用于其他购买请求。', 'aksrt'), ['status' => 409]); } $order_number = (string) $existing['order_number']; } else { $order_number = $repo->allocate_order_number(); } if ($order_number === '') { return new \WP_Error('aksrt_order_create_failed', __('创建订单失败。', 'aksrt'), ['status' => 500]); } $guard = static function () use ($is_new_order, $order_number, $user_id, $post_id, $amount) { if ($is_new_order) { return true; } global $wpdb; $table = \AKSRT\Core\DBMigrator::table('order'); $current = $wpdb->get_row($wpdb->prepare("SELECT user_id, product_id, amount, currency, status FROM {$table} WHERE order_number = %s FOR UPDATE", $order_number), ARRAY_A); if (!is_array($current) || (int) ($current['user_id'] ?? 0) !== $user_id || (int) ($current['product_id'] ?? 0) !== $post_id || (int) ($current['amount'] ?? 0) !== $amount || (string) ($current['currency'] ?? '') !== 'points' || (string) ($current['status'] ?? '') !== \AKSRT\Payment\Order::STATUS_PENDING ) { return new \WP_Error('aksrt_order_confirm_failed', __('订单状态或金额已变化。', 'aksrt'), ['status' => 409]); } return true; }; $deducted = $ledger->debit( $user_id, \AKSRT\Ledger\AssetType::POINTS, $amount, $operation_key, 'content_points_pay', ['type' => 'order', 'key' => $order_number], sprintf(__('积分购买《%s》', 'aksrt'), get_the_title($post_id)), $user_id, ['post_id' => $post_id], static function () use ($is_new_order, $repo, $order_number, $operation_key, $user_id, $post_id, $amount, $note, $content_type) { if ($is_new_order) { $created = $repo->create([ 'order_number' => $order_number, 'user_id' => $user_id, 'product_type' => $content_type, 'product_id' => $post_id, 'amount' => $amount, 'currency' => 'points', 'status' => \AKSRT\Payment\Order::STATUS_PENDING, 'payment_method' => 'points', 'note' => is_string($note) ? $note : '', 'expires_at' => \AKSRT\Settings\PaymentRuntime::get_order_expiry_at(), 'request_key' => $operation_key, ]); if ($created !== $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' => 'points', 'note' => sprintf(__('积分支付 %d 积分。', 'aksrt'), $amount), 'require_transition' => true, ]); return $paid ? true : new \WP_Error('aksrt_order_confirm_failed', __('订单确认失败。', 'aksrt'), ['status' => 500]); }, $guard ); if (is_wp_error($deducted)) { return $deducted; } return [ 'success' => true, 'data' => [ 'order_number' => $order_number, 'amount' => $amount, 'pay_modo' => 'points', 'balance' => $ledger->balance($user_id, \AKSRT\Ledger\AssetType::POINTS), 'replayed' => $deducted->replayed, '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 = '', string $operation_key = '') { $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']; $content_type = \AKSRT\Core\DomainModel::resolve_order_product_type(\AKSRT\Core\DomainModel::ORDER_PRODUCT_RESOURCE, ['pay_type' => $meta['pay_type'] ?? '']); if ((($priced['modo'] ?? '0') === 'points')) { return new \WP_Error('aksrt_wrong_modo', __('该内容仅支持积分支付。', 'aksrt'), ['status' => 400]); } // Card pass cannot stack coupon (legacy). 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_minor = max(0, (int) ($discounted['payable_minor'] ?? 0)); $list_minor = max(0, (int) ($discounted['list_minor'] ?? $amount_minor)); $rebate_discount_minor = max(0, (int) ($discounted['rebate_discount_minor'] ?? 0)); $coupon_discount_minor = max(0, (int) ($discounted['coupon_discount_minor'] ?? 0)); $amount = \AKSRT\Ledger\AssetAmount::decimal_from_minor($amount_minor); $list_amount = \AKSRT\Ledger\AssetAmount::decimal_from_minor($list_minor); $rebate_discount = \AKSRT\Ledger\AssetAmount::decimal_from_minor($rebate_discount_minor); $coupon_discount = \AKSRT\Ledger\AssetAmount::decimal_from_minor($coupon_discount_minor); $coupon_meta = is_array($discounted['coupon'] ?? null) ? $discounted['coupon'] : []; $referrer_id = (int) ($discounted['referrer_id'] ?? 0); $rebate_price_minor = max(0, (int) ($discounted['rebate_price_minor'] ?? 0)); $rebate_price = \AKSRT\Ledger\AssetAmount::decimal_from_minor($rebate_price_minor); if ($amount_minor <= 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_type' => (string) ($meta['pay_type'] ?? ''), 'pay_modo' => '0', 'post_id' => $post_id, 'price_type' => $price_type, 'vip_level' => (int) ($priced['vip_level'] ?? 0), 'base' => $this->asset_value($this->parse_asset_minor($priced['base'] ?? $list_amount, '0'), '0'), '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.00', 'payable' => '0.00', 'referrer_id' => $referrer_id, 'rebate_price' => '0.00', '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); $repo = \AKSRT\Payment\OrderRepository::get_instance(); $existing = $operation_key !== '' ? $repo->get_by_request_key($operation_key) : null; $replayed = is_array($existing); if (is_array($existing)) { if ((int) ($existing['user_id'] ?? 0) !== max(0, $user_id) || sanitize_key((string) ($existing['product_type'] ?? '')) !== $content_type || (int) ($existing['product_id'] ?? 0) !== $post_id || sanitize_key((string) ($existing['payment_method'] ?? '')) !== 'free' || (string) ($existing['amount'] ?? '') !== '0.00' ) { return new \WP_Error('aksrt_ledger_idempotency_conflict', __('相同操作标识已用于其他内容请求。', 'aksrt'), ['status' => 409]); } $order_number = (string) $existing['order_number']; } else { $order_number = $repo->create([ 'user_id' => max(0, $user_id), 'product_type' => $content_type, 'product_id' => $post_id, 'amount' => '0.00', 'currency' => 'CNY', 'status' => \AKSRT\Payment\Order::STATUS_PENDING, 'payment_method' => 'free', 'note' => is_string($note) ? $note : '', 'expires_at' => \AKSRT\Settings\PaymentRuntime::get_order_expiry_at(), 'request_key' => $operation_key, ]); } if ($order_number === '') { return new \WP_Error('aksrt_order_create_failed', __('创建订单失败。', 'aksrt'), ['status' => 500]); } $status = is_array($existing) ? (string) ($existing['status'] ?? '') : ''; if ($status !== \AKSRT\Payment\Order::STATUS_PAID) { $paid = \AKSRT\Payment\Order::get_instance()->update_status($order_number, \AKSRT\Payment\Order::STATUS_PAID, [ 'payment_method' => 'free', 'payment_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' => '0.00', 'pay_modo' => '0', 'free' => true, 'transaction_id' => '', 'replayed' => $replayed, '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'; } $amount_decimal = $amount; $coupon_code_norm = (string) ($coupon_meta['code'] ?? $coupon_code); // A retry resolves only through its request key; a new operation never reuses another pending order. $pending = $operation_key !== '' ? \AKSRT\Payment\OrderRepository::get_instance()->get_by_request_key($operation_key) : null; $can_resume = false; if (is_array($pending)) { $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); } $can_resume = (int) ($pending['user_id'] ?? 0) === max(0, $user_id) && sanitize_key((string) ($pending['product_type'] ?? '')) === $content_type && (int) ($pending['product_id'] ?? 0) === $post_id && (string) ($pending['amount'] ?? '') === $amount_decimal && strtoupper((string) ($pending['currency'] ?? '')) === 'CNY' && sanitize_key((string) ($pending['payment_method'] ?? '')) === $payment_method && (string) ($pending_meta['price_type'] ?? '') === $price_type && (int) ($pending_meta['post_id'] ?? 0) === $post_id && $pending_coupon === $coupon_code_norm; if (!$can_resume) { return new \WP_Error('aksrt_ledger_idempotency_conflict', __('相同操作标识已用于其他内容购买请求。', 'aksrt'), ['status' => 409]); } } if ($can_resume) { $order_number = (string) ($pending['order_number'] ?? ''); $order = $pending; } else { $note = wp_json_encode([ 'content_pay' => 1, 'pay_type' => (string) ($meta['pay_type'] ?? ''), 'pay_modo' => '0', 'post_id' => $post_id, 'price_type' => $price_type, 'vip_level' => (int) ($priced['vip_level'] ?? 0), 'base' => $this->asset_value($this->parse_asset_minor($priced['base'] ?? $list_amount, '0'), '0'), '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_decimal, 'payable' => $amount_decimal, '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' => $content_type, 'product_id' => $post_id, 'amount' => $amount_decimal, 'currency' => 'CNY', 'status' => \AKSRT\Payment\Order::STATUS_PENDING, 'payment_method' => $payment_method, 'note' => is_string($note) ? $note : '', 'expires_at' => \AKSRT\Settings\PaymentRuntime::get_order_expiry_at(), 'request_key' => $operation_key, ]); 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'; } if ($can_resume && (string) ($order['status'] ?? '') === \AKSRT\Payment\Order::STATUS_PAID) { return [ 'success' => true, 'data' => [ 'order_number' => $order_number, 'amount' => $amount_decimal, 'pay_modo' => '0', 'replayed' => true, 'balance' => \AKSRT\Ledger\LedgerService::get_instance()->balance_decimal($user_id), 'message' => __('支付成功', 'aksrt'), 'reload' => true, ], ]; } $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_decimal; 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' => (int) ($payment_result['status'] ?? 400), '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_decimal, 'pay_modo' => '0', 'message' => $payment_result['message'], 'reload' => false, 'poll' => true, 'replayed' => false, ], ]; } return [ 'success' => true, 'data' => [ 'order_number' => $order_number, 'amount' => $amount_decimal, 'pay_modo' => '0', 'replayed' => !empty($payment_result['replayed']), 'balance' => $user_id > 0 ? \AKSRT\Ledger\LedgerService::get_instance()->balance_decimal($user_id) : '0.00', 'message' => $payment_result['message'], 'reload' => true, ], ]; } /** * @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\Payment\OrderRepository')) { return null; } $orders = \AKSRT\Payment\OrderRepository::get_instance()->get_user_orders($user_id, [ 'status' => \AKSRT\Core\DomainModel::ORDER_STATUS_PENDING, 'limit' => 20, 'offset' => 0, ]); foreach ($orders as $order) { if ((int) ($order['product_id'] ?? 0) === $post_id && \AKSRT\Core\DomainModel::is_resource_product_type((string) ($order['product_type'] ?? ''))) { return $order; } } return null; } }