Apply the configured order lifetime to all checkout flows and close unpaid orders once their expiry is reached.
873 lines
32 KiB
PHP
873 lines
32 KiB
PHP
<?php
|
||
/**
|
||
* @package AKSRT
|
||
*/
|
||
|
||
namespace AKSRT\Payment;
|
||
|
||
defined('ABSPATH') || exit;
|
||
|
||
trait OrderRepositoryCore {
|
||
|
||
|
||
|
||
private function table(): string {
|
||
return \AKSRT\Core\DBMigrator::table('order');
|
||
}
|
||
|
||
|
||
|
||
/* ------------------------------------------------------------------
|
||
* CRUD
|
||
* ----------------------------------------------------------------*/
|
||
|
||
/**
|
||
* 创建订单(写入表)
|
||
*/
|
||
public function create(array $data): string {
|
||
global $wpdb;
|
||
|
||
$order_number = $data['order_number'] ?? $this->generate_order_number();
|
||
|
||
// Preserve JSON pay meta (VIP/content/coupon). Only strip tags for plain text notes.
|
||
$note_raw = (string) ($data['note'] ?? '');
|
||
$note_trim = trim($note_raw);
|
||
if ($note_trim !== '' && ($note_trim[0] === '{' || $note_trim[0] === '[')) {
|
||
$decoded = json_decode($note_trim, true);
|
||
$note = is_array($decoded)
|
||
? (string) wp_json_encode($decoded, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
|
||
: sanitize_textarea_field($note_raw);
|
||
} else {
|
||
$note = sanitize_textarea_field($note_raw);
|
||
}
|
||
|
||
$row = [
|
||
'order_number' => $order_number,
|
||
'user_id' => (int) ($data['user_id'] ?? 0),
|
||
'product_type' => sanitize_key((string) ($data['product_type'] ?? '')),
|
||
'product_id' => (int) ($data['product_id'] ?? 0),
|
||
'amount' => (float) ($data['amount'] ?? 0),
|
||
'currency' => sanitize_key((string) ($data['currency'] ?? 'CNY')),
|
||
'status' => \AKSRT\Core\DomainModel::normalize_order_status((string) ($data['status'] ?? \AKSRT\Core\DomainModel::ORDER_STATUS_PENDING)),
|
||
'payment_method' => sanitize_key((string) ($data['payment_method'] ?? '')),
|
||
'payment_transaction_id' => sanitize_text_field((string) ($data['payment_transaction_id'] ?? '')),
|
||
'created_at' => $data['created_at'] ?? current_time('mysql'),
|
||
'paid_at' => $data['paid_at'] ?? null,
|
||
'note' => $note,
|
||
];
|
||
$formats = ['%s', '%d', '%s', '%d', '%f', '%s', '%s', '%s', '%s', '%s', '%s', '%s'];
|
||
|
||
// Pending orders always receive an expiry. Explicit caller values remain
|
||
// supported for compatibility, while new flows use the shared runtime policy.
|
||
if (array_key_exists('expires_at', $data) && $data['expires_at'] !== null && $data['expires_at'] !== '') {
|
||
$row['expires_at'] = (string) $data['expires_at'];
|
||
$formats[] = '%s';
|
||
} elseif (in_array($row['status'], [Order::STATUS_CREATED, Order::STATUS_PENDING], true)) {
|
||
$row['expires_at'] = \AKSRT\Settings\PaymentRuntime::get_order_expiry_at();
|
||
$formats[] = '%s';
|
||
}
|
||
|
||
$wpdb->insert($this->table(), $row, $formats);
|
||
|
||
if ($wpdb->insert_id) {
|
||
return $order_number;
|
||
}
|
||
|
||
return '';
|
||
}
|
||
|
||
|
||
|
||
/**
|
||
* 获取单个订单
|
||
*/
|
||
public function get(string $order_number): ?array {
|
||
global $wpdb;
|
||
|
||
$row = $wpdb->get_row($wpdb->prepare(
|
||
"SELECT * FROM {$this->table()} WHERE order_number = %s",
|
||
$order_number
|
||
), ARRAY_A);
|
||
|
||
if ($row) {
|
||
return $this->expire_order_if_due($this->normalize_row($row));
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
|
||
|
||
/**
|
||
* 获取用户订单列表
|
||
*/
|
||
public function get_user_orders(int $user_id, array $args = []): array {
|
||
global $wpdb;
|
||
|
||
$this->expire_pending_orders($user_id);
|
||
$parts = $this->get_user_order_query_parts($user_id, $args);
|
||
$limit = max(1, min(100, (int) ($args['limit'] ?? 20)));
|
||
$offset = max(0, (int) ($args['offset'] ?? 0));
|
||
$params = $parts['params'];
|
||
$params[] = $limit;
|
||
$params[] = $offset;
|
||
|
||
$sql = "SELECT * FROM {$this->table()} {$parts['where']} ORDER BY created_at DESC LIMIT %d OFFSET %d";
|
||
$rows = $wpdb->get_results($wpdb->prepare($sql, $params), ARRAY_A);
|
||
|
||
return array_map([$this, 'normalize_row'], (array) $rows);
|
||
}
|
||
|
||
|
||
|
||
/**
|
||
* 获取单个用户订单。
|
||
*/
|
||
public function get_user_order(int $user_id, string $order_number): ?array {
|
||
$order = $this->get($order_number);
|
||
if (!$order) {
|
||
return null;
|
||
}
|
||
|
||
if ($user_id > 0 && (int) ($order['user_id'] ?? 0) !== $user_id) {
|
||
return null;
|
||
}
|
||
|
||
return $order;
|
||
}
|
||
|
||
|
||
|
||
/**
|
||
* 获取用户订单总数。
|
||
*/
|
||
public function count_user_orders(int $user_id, array $args = []): int {
|
||
global $wpdb;
|
||
|
||
if ($user_id <= 0) {
|
||
return 0;
|
||
}
|
||
|
||
$this->expire_pending_orders($user_id);
|
||
|
||
$parts = $this->get_user_order_query_parts($user_id, $args);
|
||
return (int) $wpdb->get_var($wpdb->prepare(
|
||
"SELECT COUNT(*) FROM {$this->table()} {$parts['where']}",
|
||
$parts['params']
|
||
));
|
||
}
|
||
|
||
/**
|
||
* Get the filtered list total and the user's order-center counters in one query.
|
||
*
|
||
* The filtered total mirrors the list query while the counters intentionally keep
|
||
* their existing user-wide semantics, so changing a filter does not change the
|
||
* summary cards. The subquery avoids four independent COUNT statements.
|
||
*
|
||
* @return array{total:int,stats:array{total:int,pending:int,completed:int}}
|
||
*/
|
||
public function get_user_order_center_summary(int $user_id, array $args = []): array {
|
||
global $wpdb;
|
||
|
||
if ($user_id <= 0) {
|
||
return [
|
||
'total' => 0,
|
||
'stats' => ['total' => 0, 'pending' => 0, 'completed' => 0],
|
||
];
|
||
}
|
||
|
||
$this->expire_pending_orders($user_id);
|
||
|
||
$parts = $this->get_user_order_query_parts($user_id, $args);
|
||
$pending_statuses = [Order::STATUS_CREATED, Order::STATUS_PENDING];
|
||
$paid_status = Order::STATUS_PAID;
|
||
$known_statuses = OrderCenterQuery::from_array([])->database_statuses();
|
||
$known_placeholders = implode(', ', array_fill(0, count($known_statuses), '%s'));
|
||
$sql = "SELECT
|
||
(SELECT COUNT(*) FROM {$this->table()} {$parts['where']}) AS filtered_total,
|
||
COUNT(*) AS known_total,
|
||
SUM(CASE WHEN status IN (%s, %s) THEN 1 ELSE 0 END) AS pending,
|
||
SUM(CASE WHEN status = %s THEN 1 ELSE 0 END) AS completed
|
||
FROM {$this->table()}
|
||
WHERE user_id = %d AND status IN ({$known_placeholders})";
|
||
$params = array_merge(
|
||
$parts['params'],
|
||
$pending_statuses,
|
||
[$paid_status, $user_id],
|
||
$known_statuses
|
||
);
|
||
$row = $wpdb->get_row($wpdb->prepare($sql, $params), ARRAY_A);
|
||
|
||
return [
|
||
'total' => (int) ($row['filtered_total'] ?? 0),
|
||
'stats' => [
|
||
'total' => (int) ($row['known_total'] ?? 0),
|
||
'pending' => (int) ($row['pending'] ?? 0),
|
||
'completed' => (int) ($row['completed'] ?? 0),
|
||
],
|
||
];
|
||
}
|
||
|
||
/**
|
||
* Close every expired, unpaid order for one user (or all users).
|
||
*
|
||
* The status condition makes this idempotent and prevents an expiry sweep
|
||
* from overwriting a payment completed concurrently by a gateway callback.
|
||
*/
|
||
public function expire_pending_orders(?int $user_id = null): int {
|
||
global $wpdb;
|
||
|
||
$where = "status IN ('created', 'pending') AND expires_at IS NOT NULL AND expires_at <> '' AND expires_at <= %s";
|
||
$params = [gmdate('Y-m-d H:i:s')];
|
||
if ($user_id !== null && $user_id > 0) {
|
||
$where .= ' AND user_id = %d';
|
||
$params[] = $user_id;
|
||
}
|
||
|
||
$sql = "UPDATE {$this->table()} SET status = 'expired', cancelled_at = %s WHERE {$where}";
|
||
array_unshift($params, gmdate('Y-m-d H:i:s'));
|
||
$result = $wpdb->query($wpdb->prepare($sql, $params));
|
||
|
||
return is_numeric($result) ? (int) $result : 0;
|
||
}
|
||
|
||
/** @param array<string,mixed> $order @return array<string,mixed> */
|
||
private function expire_order_if_due(array $order): array {
|
||
$status = sanitize_key((string) ($order['status'] ?? ''));
|
||
$expires_at = trim((string) ($order['expires_at'] ?? ''));
|
||
if (!in_array($status, [Order::STATUS_CREATED, Order::STATUS_PENDING], true) || $expires_at === '') {
|
||
return $order;
|
||
}
|
||
|
||
$expires = strtotime($expires_at . ' UTC');
|
||
if ($expires === false || $expires > time()) {
|
||
return $order;
|
||
}
|
||
|
||
global $wpdb;
|
||
$closed_at = gmdate('Y-m-d H:i:s');
|
||
$updated = $wpdb->update(
|
||
$this->table(),
|
||
['status' => Order::STATUS_EXPIRED, 'cancelled_at' => $closed_at],
|
||
['order_number' => (string) $order['order_number'], 'status' => $status],
|
||
['%s', '%s'],
|
||
['%s', '%s']
|
||
);
|
||
if ($updated) {
|
||
$order['status'] = Order::STATUS_EXPIRED;
|
||
$order['cancelled_at'] = $closed_at;
|
||
}
|
||
|
||
return $order;
|
||
}
|
||
|
||
|
||
|
||
public function update_status(string $order_number, string $new_status, array $extra = []): bool {
|
||
global $wpdb;
|
||
|
||
$valid = \AKSRT\Core\DomainModel::order_status_labels();
|
||
if (!isset($valid[$new_status])) return false;
|
||
|
||
$order = $this->get($order_number);
|
||
if (!$order) return false;
|
||
|
||
$current_status = $order['status'] ?? 'created';
|
||
|
||
if (empty($extra['force']) && !\AKSRT\Core\DomainModel::can_transition_order_status($current_status, $new_status)) {
|
||
return false;
|
||
}
|
||
|
||
$update_data = ['status' => $new_status];
|
||
$format = ['%s'];
|
||
|
||
// Stamp lifecycle timestamps. Some statuses share a column (e.g. expired → cancelled_at;
|
||
// pending_review still counts as a completion-like milestone for the timeline).
|
||
$time_fields = [
|
||
\AKSRT\Core\DomainModel::ORDER_STATUS_PAID => 'paid_at',
|
||
\AKSRT\Core\DomainModel::ORDER_STATUS_DELIVERED => 'delivered_at',
|
||
\AKSRT\Core\DomainModel::ORDER_STATUS_COMPLETED => 'completed_at',
|
||
\AKSRT\Core\DomainModel::ORDER_STATUS_PENDING_REVIEW => 'completed_at',
|
||
\AKSRT\Core\DomainModel::ORDER_STATUS_CANCELLED => 'cancelled_at',
|
||
\AKSRT\Core\DomainModel::ORDER_STATUS_EXPIRED => 'cancelled_at',
|
||
\AKSRT\Core\DomainModel::ORDER_STATUS_REFUNDED => 'refunded_at',
|
||
];
|
||
|
||
if (isset($time_fields[$new_status])) {
|
||
$field = $time_fields[$new_status];
|
||
// Do not overwrite an existing timestamp (idempotent callbacks / force updates).
|
||
$existing = is_string($order[$field] ?? null) ? trim((string) $order[$field]) : '';
|
||
if ($existing === '' || str_starts_with($existing, '0000-00-00')) {
|
||
$update_data[$field] = current_time('mysql');
|
||
$format[] = '%s';
|
||
}
|
||
}
|
||
|
||
// When jumping past paid (force admin transitions), backfill paid_at so the
|
||
// progress chain is never stuck on "订单创建" alone.
|
||
if (
|
||
in_array($new_status, [
|
||
\AKSRT\Core\DomainModel::ORDER_STATUS_DELIVERED,
|
||
\AKSRT\Core\DomainModel::ORDER_STATUS_COMPLETED,
|
||
\AKSRT\Core\DomainModel::ORDER_STATUS_PENDING_REVIEW,
|
||
\AKSRT\Core\DomainModel::ORDER_STATUS_REFUNDING,
|
||
\AKSRT\Core\DomainModel::ORDER_STATUS_REFUNDED,
|
||
], true)
|
||
) {
|
||
$existing_paid = is_string($order['paid_at'] ?? null) ? trim((string) $order['paid_at']) : '';
|
||
if ($existing_paid === '' || str_starts_with($existing_paid, '0000-00-00')) {
|
||
if (!isset($update_data['paid_at'])) {
|
||
$update_data['paid_at'] = current_time('mysql');
|
||
$format[] = '%s';
|
||
}
|
||
}
|
||
}
|
||
|
||
if (!empty($extra['payment_method'])) {
|
||
$update_data['payment_method'] = sanitize_key($extra['payment_method']);
|
||
$format[] = '%s';
|
||
}
|
||
|
||
if (!empty($extra['payment_transaction_id'])) {
|
||
$update_data['payment_transaction_id'] = sanitize_text_field($extra['payment_transaction_id']);
|
||
$format[] = '%s';
|
||
}
|
||
|
||
if (!empty($extra['note'])) {
|
||
// Preserve JSON pay meta (coupon/topic_pay/content_pay/…); stash human text as status_note.
|
||
$status_note = sanitize_textarea_field((string) $extra['note']);
|
||
$raw_note = isset($order['note']) && is_string($order['note']) ? $order['note'] : '';
|
||
$decoded_note = $raw_note !== '' ? json_decode($raw_note, true) : null;
|
||
if (is_array($decoded_note)) {
|
||
$decoded_note['status_note'] = $status_note;
|
||
$merged = wp_json_encode($decoded_note, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||
$update_data['note'] = is_string($merged) ? $merged : $status_note;
|
||
} else {
|
||
$update_data['note'] = $status_note;
|
||
}
|
||
$format[] = '%s';
|
||
}
|
||
|
||
// Compare-and-swap the status so concurrent callbacks cannot both win the
|
||
// first paid transition and trigger fulfillment twice.
|
||
$result = $wpdb->update(
|
||
$this->table(),
|
||
$update_data,
|
||
['order_number' => $order_number, 'status' => $current_status],
|
||
$format,
|
||
['%s', '%s']
|
||
);
|
||
|
||
if ($result === false) {
|
||
return false;
|
||
}
|
||
|
||
if ($result === 0) {
|
||
if (!empty($extra['require_transition'])) {
|
||
return false;
|
||
}
|
||
$latest = $this->get($order_number);
|
||
return is_array($latest) && ($latest['status'] ?? '') === $new_status;
|
||
}
|
||
|
||
if ($result > 0) {
|
||
do_action('aksrt_order_status_changed', $order_number, $new_status, array_merge($order, $update_data));
|
||
// 到账事件:让充值/VIP/商品履约等挂接(单一履约入口)。
|
||
// 仅在「首次」转为 paid 时触发,避免回调多次到达重复履约。
|
||
if ($new_status === \AKSRT\Core\DomainModel::ORDER_STATUS_PAID && $current_status !== \AKSRT\Core\DomainModel::ORDER_STATUS_PAID) {
|
||
$paid_order = array_merge($order, [
|
||
'status' => $new_status,
|
||
'payment_method' => $update_data['payment_method'] ?? ($order['payment_method'] ?? ''),
|
||
'payment_transaction_id' => $update_data['payment_transaction_id'] ?? ($order['payment_transaction_id'] ?? ''),
|
||
]);
|
||
if (isset($update_data['note'])) {
|
||
// Keep pre-update JSON payload for listeners (coupon burn etc.);
|
||
// only attach status_note if callers mutated note.
|
||
$pre_meta = [];
|
||
$pre_raw = isset($order['note']) && is_string($order['note']) ? $order['note'] : '';
|
||
if ($pre_raw !== '') {
|
||
$pre_decoded = json_decode($pre_raw, true);
|
||
if (is_array($pre_decoded)) {
|
||
$pre_meta = $pre_decoded;
|
||
}
|
||
}
|
||
if ($pre_meta !== []) {
|
||
$paid_order['meta_payload'] = $pre_meta;
|
||
// Prefer merged DB note (JSON + status_note) for downstream reads.
|
||
$paid_order['note'] = $update_data['note'];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 订单到账。
|
||
*
|
||
* @param string $order_number 订单号
|
||
* @param array $paid_order 订单数据(status=paid)
|
||
*/
|
||
do_action('aksrt_order_paid', $order_number, $paid_order);
|
||
}
|
||
}
|
||
|
||
return $result !== false;
|
||
}
|
||
|
||
|
||
|
||
/**
|
||
* Delete closed (cancelled/expired) orders older than $days days.
|
||
* Mirrors zibll ZibPay::clear_order(14).
|
||
*
|
||
* @return int Number of rows deleted.
|
||
*/
|
||
public function clear_closed_orders(int $days = 14): int {
|
||
global $wpdb;
|
||
|
||
$days = max(1, min(3650, $days));
|
||
$table = $this->table();
|
||
$cutoff = gmdate('Y-m-d H:i:s', time() - ($days * DAY_IN_SECONDS));
|
||
// Prefer cancelled_at when set; fall back to created_at for older rows.
|
||
$sql = "DELETE FROM {$table}
|
||
WHERE status IN ('cancelled', 'expired')
|
||
AND COALESCE(NULLIF(cancelled_at, ''), created_at) < %s";
|
||
$deleted = $wpdb->query($wpdb->prepare($sql, $cutoff));
|
||
return $deleted === false ? 0 : (int) $deleted;
|
||
}
|
||
|
||
|
||
|
||
/**
|
||
* Hard-delete a single order by order_number (admin hygiene).
|
||
*/
|
||
public function delete_order(string $order_number): bool {
|
||
global $wpdb;
|
||
$order_number = sanitize_text_field($order_number);
|
||
if ($order_number === '') {
|
||
return false;
|
||
}
|
||
$ok = $wpdb->delete($this->table(), ['order_number' => $order_number], ['%s']);
|
||
return $ok !== false && $ok > 0;
|
||
}
|
||
|
||
|
||
|
||
/**
|
||
* 获取订单统计
|
||
*/
|
||
public function get_stats(int $user_id = 0): array {
|
||
global $wpdb;
|
||
|
||
$this->expire_pending_orders($user_id > 0 ? $user_id : null);
|
||
|
||
$where = '';
|
||
$params = [];
|
||
if ($user_id > 0) {
|
||
$where = 'WHERE user_id = %d';
|
||
$params[] = $user_id;
|
||
}
|
||
|
||
$sql = "SELECT
|
||
COUNT(*) as total,
|
||
SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
|
||
SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) as paid,
|
||
SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) as delivered,
|
||
SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
|
||
SUM(CASE WHEN status = 'pending_review' THEN 1 ELSE 0 END) as pending_review,
|
||
SUM(CASE WHEN status = 'refunding' THEN 1 ELSE 0 END) as refunding,
|
||
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled,
|
||
SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) as refunded,
|
||
SUM(CASE WHEN status IN ('paid','delivered','completed','pending_review') THEN amount ELSE 0 END) as revenue
|
||
FROM {$this->table()} {$where}";
|
||
|
||
if (!empty($params)) {
|
||
$row = $wpdb->get_row($wpdb->prepare($sql, $params), ARRAY_A);
|
||
} else {
|
||
$row = $wpdb->get_row($sql, ARRAY_A);
|
||
}
|
||
|
||
return [
|
||
'total' => (int) ($row['total'] ?? 0),
|
||
'pending' => (int) ($row['pending'] ?? 0),
|
||
'paid' => (int) ($row['paid'] ?? 0),
|
||
'delivered' => (int) ($row['delivered'] ?? 0),
|
||
'completed' => (int) ($row['completed'] ?? 0),
|
||
'pending_review' => (int) ($row['pending_review'] ?? 0),
|
||
'refunding' => (int) ($row['refunding'] ?? 0),
|
||
'cancelled' => (int) ($row['cancelled'] ?? 0),
|
||
'refunded' => (int) ($row['refunded'] ?? 0),
|
||
'revenue' => (float) ($row['revenue'] ?? 0),
|
||
];
|
||
}
|
||
|
||
|
||
|
||
public function has_paid_access(int $user_id, string $product_type, int $product_id): bool {
|
||
if ($user_id <= 0 || $product_id <= 0) {
|
||
return false;
|
||
}
|
||
|
||
return null !== $this->find_latest_success_order($user_id, $product_type, $product_id);
|
||
}
|
||
|
||
|
||
|
||
public function get_valid_vip_order(int $user_id): ?array {
|
||
return $this->find_latest_success_order($user_id, \AKSRT\Core\DomainModel::ORDER_PRODUCT_VIP, 0, true);
|
||
}
|
||
|
||
|
||
|
||
/* ------------------------------------------------------------------
|
||
* Migration bridge: option → table
|
||
* ----------------------------------------------------------------*/
|
||
|
||
/**
|
||
* 一次性迁移:把 option 中的订单搬到表中。
|
||
* 幂等 — 已存在的 order_number 不会重复插入。
|
||
*/
|
||
public function migrate_from_option(): int {
|
||
global $wpdb;
|
||
|
||
$orders = get_option('aksrt_orders', []);
|
||
if (!is_array($orders) || empty($orders)) return 0;
|
||
|
||
$migrated = 0;
|
||
foreach ($orders as $order_number => $data) {
|
||
$existing = $wpdb->get_var($wpdb->prepare(
|
||
"SELECT id FROM {$this->table()} WHERE order_number = %s",
|
||
$order_number
|
||
));
|
||
if ($existing) continue;
|
||
|
||
$wpdb->insert($this->table(), [
|
||
'order_number' => $order_number,
|
||
'user_id' => (int) ($data['user_id'] ?? 0),
|
||
'product_type' => sanitize_key((string) ($data['product_type'] ?? '')),
|
||
'product_id' => (int) ($data['product_id'] ?? 0),
|
||
'amount' => (float) ($data['amount'] ?? 0),
|
||
'currency' => sanitize_key((string) ($data['currency'] ?? 'CNY')),
|
||
'status' => \AKSRT\Core\DomainModel::normalize_order_status((string) ($data['status'] ?? \AKSRT\Core\DomainModel::ORDER_STATUS_PENDING)),
|
||
'payment_method' => sanitize_key((string) ($data['payment_method'] ?? '')),
|
||
'created_at' => $data['created_at'] ?? current_time('mysql'),
|
||
'paid_at' => $data['paid_at'] ?? null,
|
||
'delivered_at' => $data['delivered_at'] ?? null,
|
||
'completed_at' => $data['completed_at'] ?? null,
|
||
'cancelled_at' => $data['cancelled_at'] ?? null,
|
||
'refunded_at' => $data['refunded_at'] ?? null,
|
||
'expires_at' => $data['expires_at'] ?? null,
|
||
'note' => '',
|
||
], ['%s', '%d', '%s', '%d', '%f', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s']);
|
||
|
||
if ($wpdb->insert_id) $migrated++;
|
||
}
|
||
|
||
update_option(\AKSRT\Core\DomainModel::ORDER_MIGRATED_OPTION, time());
|
||
|
||
return $migrated;
|
||
}
|
||
|
||
|
||
|
||
/* ------------------------------------------------------------------
|
||
* Internal helpers
|
||
* ----------------------------------------------------------------*/
|
||
|
||
/**
|
||
* Build the shared list/count predicate without changing caller semantics.
|
||
*
|
||
* @return array{where:string,params:array<int,mixed>}
|
||
*/
|
||
private function get_user_order_query_parts(int $user_id, array $args = []): array {
|
||
global $wpdb;
|
||
|
||
$where = [];
|
||
$params = [];
|
||
if ($user_id > 0) {
|
||
$where[] = 'user_id = %d';
|
||
$params[] = $user_id;
|
||
}
|
||
|
||
$statuses = array_values(array_filter(array_map('sanitize_key', (array) ($args['status_in'] ?? []))));
|
||
if ($statuses !== []) {
|
||
$where[] = 'status IN (' . implode(', ', array_fill(0, count($statuses), '%s')) . ')';
|
||
array_push($params, ...$statuses);
|
||
} else {
|
||
$status = sanitize_key((string) ($args['status'] ?? ''));
|
||
if ($status !== '') {
|
||
$where[] = 'status = %s';
|
||
$params[] = $status;
|
||
}
|
||
}
|
||
|
||
$product_type = sanitize_key((string) ($args['product_type'] ?? ''));
|
||
if ($product_type !== '') {
|
||
$where[] = 'product_type = %s';
|
||
$params[] = $product_type;
|
||
}
|
||
|
||
$order_number_prefix = strtoupper(preg_replace('/[^A-Za-z0-9_-]/', '', (string) ($args['order_number_prefix'] ?? '')) ?? '');
|
||
if ($order_number_prefix !== '') {
|
||
$where[] = 'order_number LIKE %s';
|
||
$params[] = $wpdb->esc_like($order_number_prefix) . '%';
|
||
}
|
||
|
||
return [
|
||
'where' => $where ? 'WHERE ' . implode(' AND ', $where) : '',
|
||
'params' => $params,
|
||
];
|
||
}
|
||
|
||
private function normalize_row(array $row): array {
|
||
$row['id'] = (int) $row['id'];
|
||
$row['user_id'] = (int) $row['user_id'];
|
||
$row['product_id'] = (int) $row['product_id'];
|
||
$row['amount'] = (float) $row['amount'];
|
||
$row['status'] = \AKSRT\Core\DomainModel::normalize_order_status((string) ($row['status'] ?? ''));
|
||
|
||
$row['meta_payload'] = [];
|
||
if (!empty($row['note']) && is_string($row['note'])) {
|
||
$decoded = json_decode($row['note'], true);
|
||
if (is_array($decoded)) {
|
||
$row['meta_payload'] = $decoded;
|
||
if (isset($decoded['customer_note']) && is_string($decoded['customer_note'])) {
|
||
$row['note_text'] = $decoded['customer_note'];
|
||
}
|
||
} else {
|
||
$row['note_text'] = $row['note'];
|
||
}
|
||
}
|
||
|
||
return $row;
|
||
}
|
||
|
||
|
||
|
||
private function find_latest_success_order(int $user_id, string $product_type, int $product_id = 0, bool $ignore_product_id = false): ?array {
|
||
global $wpdb;
|
||
|
||
if ($user_id <= 0 || $product_type === '') {
|
||
return null;
|
||
}
|
||
|
||
$status_placeholders = implode(', ', array_fill(0, count(\AKSRT\Core\DomainModel::paid_order_statuses()), '%s'));
|
||
$params = array_merge(
|
||
[$user_id, sanitize_key($product_type)],
|
||
$ignore_product_id ? [] : [$product_id],
|
||
\AKSRT\Core\DomainModel::paid_order_statuses()
|
||
);
|
||
|
||
$product_sql = $ignore_product_id ? '' : ' AND product_id = %d';
|
||
$sql = "SELECT * FROM {$this->table()}
|
||
WHERE user_id = %d
|
||
AND product_type = %s{$product_sql}
|
||
AND status IN ({$status_placeholders})
|
||
ORDER BY COALESCE(paid_at, created_at) DESC, id DESC
|
||
LIMIT 1";
|
||
|
||
$row = $wpdb->get_row($wpdb->prepare($sql, $params), ARRAY_A);
|
||
|
||
return is_array($row) ? $this->normalize_row($row) : null;
|
||
}
|
||
|
||
|
||
|
||
/**
|
||
* Build a unique order number using the admin-configured prefix.
|
||
*
|
||
* Column + major gateways (WeChat out_trade_no) cap at 32 chars, so the
|
||
* prefix is trimmed to leave room for {YmdHis}{4 digits} (=18).
|
||
*/
|
||
private function generate_order_number(): string {
|
||
$prefix = 'AKSRT';
|
||
if (class_exists('\AKSRT\Settings\Settings') && method_exists('\AKSRT\Settings\Settings', 'get_order_settings')) {
|
||
$settings = \AKSRT\Settings\Settings::get_order_settings();
|
||
$configured = sanitize_text_field((string) ($settings['prefix'] ?? ''));
|
||
if ($configured !== '') {
|
||
$prefix = $configured;
|
||
}
|
||
}
|
||
|
||
// Keep only gateway-safe chars (REST + WeChat/Alipay out_trade_no).
|
||
$prefix = preg_replace('/[^A-Za-z0-9_-]/', '', $prefix);
|
||
if (!is_string($prefix) || $prefix === '') {
|
||
$prefix = 'AKSRT';
|
||
}
|
||
|
||
$body = date('YmdHis') . str_pad((string) random_int(0, 9999), 4, '0', STR_PAD_LEFT);
|
||
// Reserve 18 for body; leave ≥1 char of prefix so numbers stay human-readable.
|
||
$max_prefix = max(1, 32 - strlen($body));
|
||
if (strlen($prefix) > $max_prefix) {
|
||
$prefix = substr($prefix, 0, $max_prefix);
|
||
}
|
||
|
||
return $prefix . $body;
|
||
}
|
||
|
||
/**
|
||
* Merge keys into the order note JSON payload (meta_payload).
|
||
*
|
||
* @param array<string,mixed> $patch
|
||
*/
|
||
public function merge_meta(string $order_number, array $patch): bool {
|
||
global $wpdb;
|
||
|
||
$order = $this->get($order_number);
|
||
if (!$order) {
|
||
return false;
|
||
}
|
||
|
||
$meta = is_array($order['meta_payload'] ?? null) ? $order['meta_payload'] : [];
|
||
foreach ($patch as $key => $value) {
|
||
$meta[(string) $key] = $value;
|
||
}
|
||
|
||
$encoded = wp_json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||
if (!is_string($encoded)) {
|
||
return false;
|
||
}
|
||
|
||
$updated = $wpdb->update(
|
||
$this->table(),
|
||
['note' => $encoded],
|
||
['order_number' => $order_number],
|
||
['%s'],
|
||
['%s']
|
||
);
|
||
|
||
return $updated !== false;
|
||
}
|
||
|
||
/**
|
||
* Resolve a local order from a provider out_trade_no (base or attempt-suffixed).
|
||
*
|
||
* The authoritative mapping is the order's own meta (provider_out_trade_no /
|
||
* provider_out_trade_nos); the prefix heuristic is only a fallback and must
|
||
* never be the sole resolver, otherwise a truncated attempt number would
|
||
* strand a real payment.
|
||
*/
|
||
public function resolve_by_out_trade_no(string $out_trade_no): ?array {
|
||
global $wpdb;
|
||
|
||
$out_trade_no = sanitize_text_field($out_trade_no);
|
||
if ($out_trade_no === '') {
|
||
return null;
|
||
}
|
||
|
||
$direct = $this->get($out_trade_no);
|
||
if ($direct) {
|
||
return $direct;
|
||
}
|
||
|
||
// Authoritative: the attempt number was recorded in the order note JSON.
|
||
$needle = '"provider_out_trade_no":"' . $out_trade_no . '"';
|
||
$row = $wpdb->get_row(
|
||
$wpdb->prepare(
|
||
"SELECT * FROM {$this->table()} WHERE note LIKE %s ORDER BY id DESC LIMIT 1",
|
||
'%' . $wpdb->esc_like($needle) . '%'
|
||
),
|
||
ARRAY_A
|
||
);
|
||
if (is_array($row)) {
|
||
return $this->expire_order_if_due($this->normalize_row($row));
|
||
}
|
||
|
||
// Superseded attempts stay in the history array.
|
||
$history_needle = '"' . $out_trade_no . '"';
|
||
$row = $wpdb->get_row(
|
||
$wpdb->prepare(
|
||
"SELECT * FROM {$this->table()}
|
||
WHERE note LIKE %s AND note LIKE %s
|
||
ORDER BY id DESC LIMIT 1",
|
||
'%' . $wpdb->esc_like('"provider_out_trade_nos"') . '%',
|
||
'%' . $wpdb->esc_like($history_needle) . '%'
|
||
),
|
||
ARRAY_A
|
||
);
|
||
if (is_array($row)) {
|
||
return $this->expire_order_if_due($this->normalize_row($row));
|
||
}
|
||
|
||
// Last resort: {order_number}P{n} prefix heuristic.
|
||
if (preg_match('/^(.+)P([0-9]{1,3})$/', $out_trade_no, $m)) {
|
||
$base = $this->get($m[1]);
|
||
if ($base) {
|
||
return $base;
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* Provider out_trade_no currently bound to this order (falls back to order_number).
|
||
*
|
||
* @param array<string,mixed> $order
|
||
*/
|
||
public static function provider_out_trade_no(array $order): string {
|
||
$meta = is_array($order['meta_payload'] ?? null) ? $order['meta_payload'] : [];
|
||
$out = sanitize_text_field((string) ($meta['provider_out_trade_no'] ?? ''));
|
||
if ($out !== '') {
|
||
return $out;
|
||
}
|
||
return sanitize_text_field((string) ($order['order_number'] ?? ''));
|
||
}
|
||
|
||
/**
|
||
* Allocate a new provider out_trade_no for a payment attempt.
|
||
* First attempt uses bare order_number; later attempts append Pn (WeChat limit 32).
|
||
*
|
||
* @return array{out_trade_no:string,attempt:int,previous:string}|null
|
||
*/
|
||
public function allocate_payment_attempt(string $order_number): ?array {
|
||
$order = $this->get($order_number);
|
||
if (!$order) {
|
||
return null;
|
||
}
|
||
|
||
$meta = is_array($order['meta_payload'] ?? null) ? $order['meta_payload'] : [];
|
||
$previous = sanitize_text_field((string) ($meta['provider_out_trade_no'] ?? ''));
|
||
$history = is_array($meta['provider_out_trade_nos'] ?? null) ? $meta['provider_out_trade_nos'] : [];
|
||
|
||
// First provider submission keeps the bare order number.
|
||
// Re-pay (provider_out_trade_no already set) always mints a new suffix so
|
||
// WeChat/Alipay/Epay accept the order when amount/subject/notify changed.
|
||
if ($previous === '') {
|
||
$attempt = 1;
|
||
$out = $order_number;
|
||
} else {
|
||
$attempt = max(1, (int) ($meta['pay_attempt'] ?? 1)) + 1;
|
||
$suffix = 'P' . $attempt;
|
||
$base = $order_number;
|
||
if (strlen($base) + strlen($suffix) > 32) {
|
||
$base = substr($base, 0, 32 - strlen($suffix));
|
||
}
|
||
$out = $base . $suffix;
|
||
if ($previous !== '' && !in_array($previous, $history, true)) {
|
||
$history[] = $previous;
|
||
}
|
||
}
|
||
|
||
if (!in_array($out, $history, true)) {
|
||
$history[] = $out;
|
||
}
|
||
if (count($history) > 20) {
|
||
$history = array_slice($history, -20);
|
||
}
|
||
|
||
$ok = $this->merge_meta($order_number, [
|
||
'pay_attempt' => $attempt,
|
||
'provider_out_trade_no' => $out,
|
||
'provider_out_trade_nos' => array_values($history),
|
||
]);
|
||
if (!$ok) {
|
||
return null;
|
||
}
|
||
|
||
return [
|
||
'out_trade_no' => $out,
|
||
'attempt' => $attempt,
|
||
'previous' => $previous,
|
||
];
|
||
}
|
||
|
||
}
|