425 lines
17 KiB
PHP
425 lines
17 KiB
PHP
<?php
|
|
/**
|
|
* @package AKSRT
|
|
*/
|
|
|
|
namespace AKSRT\Credits;
|
|
|
|
defined('ABSPATH') || exit;
|
|
|
|
trait BalanceServiceRest {
|
|
|
|
|
|
|
|
public function register_routes(): void {
|
|
register_rest_route('aksrt/v1', '/pay/balance/charge', [
|
|
[
|
|
'methods' => \WP_REST_Server::READABLE,
|
|
'callback' => [$this, 'rest_charge_options'],
|
|
'permission_callback' => static function () {
|
|
return is_user_logged_in();
|
|
},
|
|
],
|
|
[
|
|
'methods' => \WP_REST_Server::CREATABLE,
|
|
'callback' => [$this, 'rest_charge_create'],
|
|
'permission_callback' => static function () {
|
|
return is_user_logged_in();
|
|
},
|
|
],
|
|
]);
|
|
|
|
register_rest_route('aksrt/v1', '/pay/transfer', [
|
|
[
|
|
'methods' => \WP_REST_Server::CREATABLE,
|
|
'callback' => [$this, 'rest_transfer'],
|
|
'permission_callback' => static function () {
|
|
return is_user_logged_in();
|
|
},
|
|
],
|
|
]);
|
|
|
|
register_rest_route('aksrt/v1', '/pay/transfer/search', [
|
|
[
|
|
'methods' => \WP_REST_Server::READABLE,
|
|
'callback' => [$this, 'rest_transfer_search'],
|
|
'permission_callback' => static function () {
|
|
return is_user_logged_in();
|
|
},
|
|
],
|
|
]);
|
|
|
|
register_rest_route('aksrt/v1', '/pay/balance/points-exchange', [
|
|
[
|
|
'methods' => \WP_REST_Server::CREATABLE,
|
|
'callback' => [$this, 'rest_exchange_balance_for_points'],
|
|
'permission_callback' => static function () {
|
|
return is_user_logged_in();
|
|
},
|
|
],
|
|
]);
|
|
|
|
register_rest_route('aksrt/v1', '/pay/balance/withdraw', [
|
|
[
|
|
'methods' => \WP_REST_Server::CREATABLE,
|
|
'callback' => [$this, 'rest_balance_withdraw'],
|
|
'permission_callback' => static function () {
|
|
return is_user_logged_in();
|
|
},
|
|
],
|
|
]);
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
* GET charge options (packages + methods + limits).
|
|
*/
|
|
public function rest_charge_options(\WP_REST_Request $request) {
|
|
if (!class_exists('AKSRT\\Credits\\Balance') || !Balance::enabled()) {
|
|
return new \WP_Error('aksrt_balance_disabled', __('余额功能未启用', 'aksrt'), ['status' => 403]);
|
|
}
|
|
$user_id = get_current_user_id();
|
|
return rest_ensure_response([
|
|
'success' => true,
|
|
'data' => $this->get_charge_view($user_id),
|
|
]);
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
* POST create recharge order and initiate payment.
|
|
*/
|
|
public function rest_charge_create(\WP_REST_Request $request) {
|
|
if (!class_exists('AKSRT\\Credits\\Balance') || !Balance::enabled()) {
|
|
return new \WP_Error('aksrt_balance_disabled', __('余额功能未启用', 'aksrt'), ['status' => 403]);
|
|
}
|
|
$user_id = get_current_user_id();
|
|
$params = $request->get_json_params();
|
|
if (!is_array($params)) {
|
|
$params = $request->get_params();
|
|
}
|
|
$package_key = sanitize_text_field((string) ($params['package'] ?? 'custom'));
|
|
$custom_price = isset($params['custom_price']) ? (float) $params['custom_price'] : 0.0;
|
|
$payment_method = sanitize_key((string) ($params['payment_method'] ?? 'alipay'));
|
|
|
|
$result = $this->create_charge_order($user_id, $package_key, $custom_price, $payment_method);
|
|
if (is_wp_error($result)) {
|
|
return $result;
|
|
}
|
|
return rest_ensure_response(['success' => true, 'data' => $result]);
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
* Transfer balance or points between users.
|
|
*/
|
|
public function rest_transfer(\WP_REST_Request $request) {
|
|
$params = $request->get_json_params();
|
|
if (!is_array($params)) {
|
|
$params = $request->get_params();
|
|
}
|
|
$type = sanitize_key((string) ($params['type'] ?? 'balance'));
|
|
$recipient = (int) ($params['recipient'] ?? 0);
|
|
$amount_raw = $params['amount'] ?? $params['price'] ?? 0;
|
|
$from_id = get_current_user_id();
|
|
|
|
if (!in_array($type, ['balance', 'points'], true)) {
|
|
return new \WP_Error('aksrt_transfer_type', __('转账类型无效', 'aksrt'), ['status' => 400]);
|
|
}
|
|
if ($from_id <= 0) {
|
|
return new \WP_Error('aksrt_need_login', __('请先登录', 'aksrt'), ['status' => 401]);
|
|
}
|
|
if ($recipient <= 0 || $recipient === $from_id) {
|
|
return new \WP_Error('aksrt_transfer_user', __('请选择有效的收款用户', 'aksrt'), ['status' => 400]);
|
|
}
|
|
if (!get_userdata($recipient)) {
|
|
return new \WP_Error('aksrt_transfer_user', __('收款用户不存在', 'aksrt'), ['status' => 404]);
|
|
}
|
|
|
|
$cfg = class_exists('\AKSRT\Settings\Settings') ? \AKSRT\Settings\Settings::get_payment_recharge_settings() : [];
|
|
if ($type === 'balance') {
|
|
if (empty($cfg['enabled']) || empty($cfg['transfer']['enabled'])) {
|
|
return new \WP_Error('aksrt_transfer_closed', __('余额转账未开启', 'aksrt'), ['status' => 403]);
|
|
}
|
|
if (class_exists('\AKSRT\Settings\Capabilities') && !\AKSRT\Settings\Capabilities::user_can('balance_transfer', $from_id)) {
|
|
return new \WP_Error('aksrt_transfer_forbidden', __('当前账号无权转账余额', 'aksrt'), ['status' => 403]);
|
|
}
|
|
$amount = round((float) $amount_raw, 2);
|
|
if ($amount <= 0) {
|
|
return new \WP_Error('aksrt_transfer_amount', __('请输入有效金额', 'aksrt'), ['status' => 400]);
|
|
}
|
|
if (!class_exists('AKSRT\\Credits\\Balance')) {
|
|
return new \WP_Error('aksrt_balance_unavailable', __('余额系统不可用', 'aksrt'), ['status' => 500]);
|
|
}
|
|
$from_bal = Balance::balance($from_id);
|
|
if ($from_bal < $amount) {
|
|
return new \WP_Error('aksrt_balance_insufficient', __('余额不足', 'aksrt'), ['status' => 402]);
|
|
}
|
|
$fee_rate = max(0, min(50, (int) ($cfg['transfer']['service_charge'] ?? 0)));
|
|
$credit = $fee_rate > 0 ? round($amount * (100 - $fee_rate) / 100, 2) : $amount;
|
|
|
|
$from_user = wp_get_current_user();
|
|
$to_user = get_userdata($recipient);
|
|
$deduct = Balance::deduct(
|
|
$from_id,
|
|
$amount,
|
|
'transfer_out',
|
|
['type' => 'user', 'id' => $recipient],
|
|
sprintf(__('转账给用户[%s]', 'aksrt'), $to_user ? $to_user->display_name : (string) $recipient)
|
|
);
|
|
if (is_wp_error($deduct)) {
|
|
return $deduct;
|
|
}
|
|
Balance::add(
|
|
$recipient,
|
|
$credit,
|
|
'transfer_in',
|
|
['type' => 'user', 'id' => $from_id],
|
|
sprintf(__('来自用户[%s]的转账', 'aksrt'), $from_user->display_name ?: (string) $from_id)
|
|
);
|
|
return rest_ensure_response([
|
|
'success' => true,
|
|
'data' => [
|
|
'message' => __('转账成功', 'aksrt'),
|
|
'reload' => true,
|
|
'balance' => Balance::balance($from_id),
|
|
],
|
|
]);
|
|
}
|
|
|
|
// points transfer
|
|
if (!class_exists('\AKSRT\Settings\Settings') || !\AKSRT\Settings\Settings::credits_enabled()) {
|
|
return new \WP_Error('aksrt_transfer_closed', __('积分转账未开启', 'aksrt'), ['status' => 403]);
|
|
}
|
|
$points_settings = \AKSRT\Settings\Settings::get_all();
|
|
if (empty($points_settings['points_transfer_s'])) {
|
|
return new \WP_Error('aksrt_transfer_closed', __('积分转账未开启', 'aksrt'), ['status' => 403]);
|
|
}
|
|
if (class_exists('\AKSRT\Settings\Capabilities') && !\AKSRT\Settings\Capabilities::user_can('points_transfer', $from_id)) {
|
|
return new \WP_Error('aksrt_transfer_forbidden', __('当前账号无权转账积分', 'aksrt'), ['status' => 403]);
|
|
}
|
|
if (filter_var($amount_raw, FILTER_VALIDATE_INT) === false || (int) $amount_raw <= 0) {
|
|
return new \WP_Error('aksrt_transfer_amount', __('请输入有效积分', 'aksrt'), ['status' => 400]);
|
|
}
|
|
$amount = (int) $amount_raw;
|
|
$min_amount = max(1, (int) ($points_settings['points_transfer_min'] ?? 1));
|
|
if ($amount < $min_amount) {
|
|
return new \WP_Error('aksrt_transfer_minimum', sprintf(__('单笔转账至少需要 %d 积分', 'aksrt'), $min_amount), ['status' => 400]);
|
|
}
|
|
if (!class_exists('AKSRT\\Credits\\Credits')) {
|
|
return new \WP_Error('aksrt_credits_unavailable', __('积分系统不可用', 'aksrt'), ['status' => 500]);
|
|
}
|
|
$fee_rate = max(0, min(50, (int) ($points_settings['points_service_charge'] ?? 0)));
|
|
$credit = $fee_rate > 0 ? (int) floor($amount * (100 - $fee_rate) / 100) : $amount;
|
|
$from_user = wp_get_current_user();
|
|
$to_user = get_userdata($recipient);
|
|
$deduct = Credits::deduct(
|
|
$from_id,
|
|
$amount,
|
|
'transfer_out',
|
|
['type' => 'user', 'id' => $recipient],
|
|
sprintf(__('转账给用户[%s]', 'aksrt'), $to_user ? $to_user->display_name : (string) $recipient)
|
|
);
|
|
if (is_wp_error($deduct)) {
|
|
return $deduct;
|
|
}
|
|
$add = Credits::add(
|
|
$recipient,
|
|
$credit,
|
|
'transfer_in',
|
|
['type' => 'user', 'id' => $from_id],
|
|
sprintf(__('来自用户[%s]的转账', 'aksrt'), $from_user->display_name ?: (string) $from_id)
|
|
);
|
|
if (is_wp_error($add)) {
|
|
$refund = Credits::add(
|
|
$from_id,
|
|
$amount,
|
|
'transfer_refund',
|
|
['type' => 'user', 'id' => $recipient],
|
|
__('收款积分入账失败,已退回转账积分', 'aksrt')
|
|
);
|
|
if (is_wp_error($refund)) {
|
|
return new \WP_Error('aksrt_transfer_recovery_failed', __('收款积分入账失败,转账积分退回失败,请联系管理员', 'aksrt'), ['status' => 500]);
|
|
}
|
|
return $add;
|
|
}
|
|
return rest_ensure_response([
|
|
'success' => true,
|
|
'data' => [
|
|
'message' => __('转账成功', 'aksrt'),
|
|
'reload' => true,
|
|
'balance' => Credits::balance($from_id),
|
|
],
|
|
]);
|
|
}
|
|
|
|
|
|
|
|
public function rest_transfer_search(\WP_REST_Request $request) {
|
|
$s = sanitize_text_field((string) $request->get_param('s'));
|
|
if (mb_strlen($s) < 1) {
|
|
return rest_ensure_response(['success' => true, 'data' => ['users' => []]]);
|
|
}
|
|
$exclude = [get_current_user_id()];
|
|
$q = new \WP_User_Query([
|
|
'search' => '*' . $s . '*',
|
|
'search_columns' => ['user_login', 'user_nicename', 'display_name', 'user_email'],
|
|
'exclude' => $exclude,
|
|
'number' => 20,
|
|
'fields' => ['ID', 'display_name', 'user_login'],
|
|
]);
|
|
$users = [];
|
|
foreach ((array) $q->get_results() as $u) {
|
|
$users[] = [
|
|
'id' => (int) $u->ID,
|
|
'display_name' => (string) $u->display_name,
|
|
'user_login' => (string) $u->user_login,
|
|
'avatar' => get_avatar_url((int) $u->ID, ['size' => 48]),
|
|
];
|
|
}
|
|
return rest_ensure_response(['success' => true, 'data' => ['users' => $users]]);
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
* Exchange integer cash-wallet balance for points.
|
|
*/
|
|
public function rest_exchange_balance_for_points(\WP_REST_Request $request) {
|
|
if (!class_exists('AKSRT\\Credits\\Balance') || !Balance::enabled()) {
|
|
return new \WP_Error('aksrt_balance_disabled', __('余额功能未启用', 'aksrt'), ['status' => 403]);
|
|
}
|
|
if (!class_exists('AKSRT\\Credits\\Credits') || !class_exists('AKSRT\\Settings\\Settings') || !\AKSRT\Settings\Settings::credits_enabled()) {
|
|
return new \WP_Error('aksrt_credits_disabled', __('积分功能未启用', 'aksrt'), ['status' => 403]);
|
|
}
|
|
$cfg = \AKSRT\Settings\Settings::get_payment_recharge_settings();
|
|
$exchange = is_array($cfg['points_exchange'] ?? null) ? $cfg['points_exchange'] : [];
|
|
if (empty($exchange['enabled'])) {
|
|
return new \WP_Error('aksrt_exchange_closed', __('余额兑换积分未开启', 'aksrt'), ['status' => 403]);
|
|
}
|
|
$params = $request->get_json_params();
|
|
if (!is_array($params)) {
|
|
$params = $request->get_params();
|
|
}
|
|
$raw_amount = $params['amount'] ?? 0;
|
|
if (filter_var($raw_amount, FILTER_VALIDATE_INT) === false || (int) $raw_amount <= 0) {
|
|
return new \WP_Error('aksrt_exchange_amount', __('兑换余额必须为正整数', 'aksrt'), ['status' => 400]);
|
|
}
|
|
$amount = (int) $raw_amount;
|
|
$rate = max(1, (int) ($exchange['rate'] ?? 100));
|
|
$daily_max = max(1, (int) ($exchange['daily_max_points'] ?? 100000));
|
|
if ($amount > intdiv($daily_max, $rate)) {
|
|
return new \WP_Error('aksrt_exchange_daily_limit', sprintf(__('今日购买积分上限为 %d', 'aksrt'), $daily_max), ['status' => 400]);
|
|
}
|
|
$points = $amount * $rate;
|
|
$min_points = max(1, (int) ($exchange['min_points'] ?? 100));
|
|
if ($points < $min_points) {
|
|
return new \WP_Error('aksrt_exchange_min', sprintf(__('单笔至少购买 %d 积分', 'aksrt'), $min_points), ['status' => 400]);
|
|
}
|
|
$user_id = get_current_user_id();
|
|
$today_points = $this->today_points_exchange_total($user_id);
|
|
if ($today_points + $points > $daily_max) {
|
|
return new \WP_Error('aksrt_exchange_daily_limit', sprintf(__('今日购买积分上限为 %d,当前还可购买 %d', 'aksrt'), $daily_max, max(0, $daily_max - $today_points)), ['status' => 400]);
|
|
}
|
|
try {
|
|
$exchange_ref = random_int(1, PHP_INT_MAX);
|
|
} catch (\Throwable $e) {
|
|
$exchange_ref = (int) round(microtime(true) * 1000000);
|
|
}
|
|
$ref = ['type' => 'points_exchange', 'id' => $exchange_ref];
|
|
$deduct = Balance::deduct($user_id, (float) $amount, 'points_exchange_out', $ref, sprintf(__('余额兑换 %d 积分', 'aksrt'), $points));
|
|
if (is_wp_error($deduct)) return $deduct;
|
|
$add = Credits::add($user_id, $points, 'points_exchange_in', $ref, sprintf(__('余额兑换:扣除 %d 余额', 'aksrt'), $amount));
|
|
if (is_wp_error($add)) {
|
|
$refund = Balance::add($user_id, (float) $amount, 'points_exchange_refund', $ref, __('积分入账失败,已退回兑换余额', 'aksrt'));
|
|
if (is_wp_error($refund)) return new \WP_Error('aksrt_exchange_recovery_failed', __('积分入账失败,余额退回失败,请联系管理员', 'aksrt'), ['status' => 500]);
|
|
return $add;
|
|
}
|
|
do_action('aksrt_points_exchange_completed', $user_id, (float) $amount, $points, (string) $exchange_ref);
|
|
return rest_ensure_response(['success' => true, 'data' => [
|
|
'message' => sprintf(__('兑换成功,获得 %d 积分', 'aksrt'), $points),
|
|
'wallet_balance' => Balance::balance($user_id),
|
|
'credit_balance' => Credits::balance($user_id),
|
|
'points' => $points,
|
|
'reload' => true,
|
|
]]);
|
|
}
|
|
|
|
private function today_points_exchange_total(int $user_id): int {
|
|
if ($user_id <= 0 || !class_exists('AKSRT\\Core\\DBMigrator')) return 0;
|
|
global $wpdb;
|
|
$table = \AKSRT\Core\DBMigrator::table('credit_log');
|
|
if ($table === '') return 0;
|
|
$site_now = current_datetime();
|
|
$start = (clone $site_now)->setTime(0, 0, 0);
|
|
$end = (clone $start)->modify('+1 day');
|
|
$utc = new \DateTimeZone('UTC');
|
|
$sql = "SELECT COALESCE(SUM(delta), 0) FROM {$table} WHERE user_id = %d AND reason = %s AND created_at >= %s AND created_at < %s";
|
|
$start_gmt = $start->setTimezone($utc)->format('Y-m-d H:i:s');
|
|
$end_gmt = $end->setTimezone($utc)->format('Y-m-d H:i:s');
|
|
return max(0, (int) $wpdb->get_var($wpdb->prepare($sql, $user_id, 'points_exchange_in', $start_gmt, $end_gmt)));
|
|
}
|
|
|
|
public function rest_balance_withdraw(\WP_REST_Request $request) {
|
|
if (!class_exists('AKSRT\\Credits\\Balance') || !Balance::enabled()) {
|
|
return new \WP_Error('aksrt_balance_disabled', __('余额功能未启用', 'aksrt'), ['status' => 403]);
|
|
}
|
|
$settings = class_exists('\AKSRT\Settings\Settings') ? \AKSRT\Settings\Settings::get_all() : [];
|
|
if (empty($settings['pay_balance_withdraw_s'])) {
|
|
return new \WP_Error('aksrt_withdraw_closed', __('余额提现未开启', 'aksrt'), ['status' => 403]);
|
|
}
|
|
if (!class_exists('\AKSRT\Payment\Withdrawal')) {
|
|
return new \WP_Error('aksrt_withdraw_unavailable', __('提现系统不可用', 'aksrt'), ['status' => 500]);
|
|
}
|
|
$params = $request->get_json_params();
|
|
if (!is_array($params)) {
|
|
$params = $request->get_params();
|
|
}
|
|
$user_id = get_current_user_id();
|
|
if (class_exists('\AKSRT\Settings\Capabilities') && !\AKSRT\Settings\Capabilities::user_can('balance_withdraw', $user_id)) {
|
|
return new \WP_Error('aksrt_withdraw_forbidden', __('当前账号无权提现', 'aksrt'), ['status' => 403]);
|
|
}
|
|
$raw_amount = $params['amount'] ?? 0;
|
|
if (filter_var($raw_amount, FILTER_VALIDATE_INT) === false || (int) $raw_amount <= 0) {
|
|
return new \WP_Error('aksrt_withdraw_amount', __('提现金额必须为正整数', 'aksrt'), ['status' => 400]);
|
|
}
|
|
$amount = (int) $raw_amount;
|
|
$method = sanitize_key((string) ($params['method'] ?? 'alipay'));
|
|
$method = $method !== '' ? $method : 'alipay';
|
|
$account = sanitize_textarea_field((string) ($params['account_info'] ?? $params['account'] ?? ''));
|
|
$withdraw_settings = class_exists('\\AKSRT\\Settings\\Settings')
|
|
? \AKSRT\Settings\Settings::get_withdrawal_settings()
|
|
: ['min_amount' => 50, 'service_charge_rate' => 5, 'daily_count' => 3, 'daily_limit' => 50, 'reset_time' => '00:00'];
|
|
$lowest = (float) $withdraw_settings['min_amount'];
|
|
if ($amount < $lowest) {
|
|
return new \WP_Error('withdraw_min_amount', sprintf(__('提现金额低于最低提现门槛(%s 元)', 'aksrt'), (string) $lowest), ['status' => 400]);
|
|
}
|
|
if ($account === '') {
|
|
return new \WP_Error('aksrt_withdraw_account', __('请填写收款账号信息', 'aksrt'), ['status' => 400]);
|
|
}
|
|
if (!in_array($method, (array) ($withdraw_settings['payout_channels'] ?? []), true)) {
|
|
return new \WP_Error('aksrt_withdraw_channel', __('当前收款渠道不可用', 'aksrt'), ['status' => 400]);
|
|
}
|
|
$result = \AKSRT\Payment\Withdrawal::get_instance()->create_balance_request($user_id, $amount, $method, $account, $withdraw_settings);
|
|
if (is_wp_error($result)) {
|
|
return $result;
|
|
}
|
|
return rest_ensure_response([
|
|
'success' => true,
|
|
'data' => [
|
|
'message' => __('提现申请已提交,请等待处理', 'aksrt'),
|
|
'withdrawal_id' => $result['withdrawal_id'],
|
|
'amount' => $amount,
|
|
'net_amount' => $result['net_amount'],
|
|
'wallet_balance' => $result['wallet_balance'],
|
|
'remaining_count' => $result['usage']['remaining_count'],
|
|
'remaining_amount' => $result['usage']['remaining_amount'],
|
|
],
|
|
]);
|
|
}
|
|
|
|
}
|