feat(pay): content cashier coupon and rebate discount chain

Wire zibll-style cash content discounts: VIP list price → buyer 推广折扣 → coupon, then commission on final pay. Reuse AKSRT_Coupon, add Invite::get_referrer, cashier UI, and paid-time coupon burn + rebate_log.
This commit is contained in:
2026-07-14 19:38:05 +08:00
parent 9eaddce457
commit 5d7b138c2c
11 changed files with 724 additions and 22 deletions
@@ -23,6 +23,8 @@ export const paidSchema = {
payment_download_post_log: 50,
payment_download_remote_size: 2048,
payment_download_remote_ext: 'zip,rar,7z',
coupon_post_s: false,
coupon_desc: '',
},
groups: [
{
@@ -72,5 +74,14 @@ export const paidSchema = {
{ key: 'payment_download_remote_ext', label: '远程文件格式限制', type: 'input', default: 'zip,rar,7z', help: '逗号分隔扩展名', dependsOn: { key: 'payment_download_remote_s', value: true } },
],
},
{
key: 'coupon',
title: '内容优惠码',
icon: 'fas fa-ticket-alt',
fields: [
{ key: 'coupon_post_s', label: '全站内容允许优惠码', type: 'switch', default: false, help: '开启后所有付费内容收银台可用优惠码;关闭时仅单篇勾选「允许优惠码」的文章可用。' },
{ key: 'coupon_desc', label: '优惠码说明', type: 'textarea', default: '', dependsOn: { key: 'coupon_post_s', value: true }, help: '展示在内容收银台优惠码输入框下方。' },
],
},
],
}
+97 -13
View File
@@ -366,23 +366,36 @@
};
}
function openCashier(postId, returnFocusEl, priceType) {
function buildPreviewUrl(postId, priceType, couponCode) {
var previewUrl = REST_BASE + '/pay/content/' + postId;
var qs = [];
if (priceType) qs.push('price_type=' + encodeURIComponent(priceType));
if (couponCode) qs.push('coupon_code=' + encodeURIComponent(couponCode));
if (qs.length) previewUrl += '?' + qs.join('&');
return previewUrl;
}
function fetchPreview(postId, priceType, couponCode) {
return fetch(buildPreviewUrl(postId, priceType, couponCode), {
method: 'GET',
credentials: 'same-origin',
headers: restHeaders(),
}).then(function (resp) {
return resp.json().then(function (j) { return { ok: resp.ok, status: resp.status, json: j }; });
});
}
function openCashier(postId, returnFocusEl, priceType, couponCode) {
if (!postId) return;
priceType = priceType || '';
couponCode = couponCode || '';
open(
'<h3 class="aksrt-dl-modal__title">' + tt('cashier_loading', '确认购买') + '</h3>' +
'<p class="aksrt-dl-modal__msg">' + tt('loading', '加载中…') + '</p>',
returnFocusEl
);
var previewUrl = REST_BASE + '/pay/content/' + postId;
if (priceType) previewUrl += (previewUrl.indexOf('?') >= 0 ? '&' : '?') + 'price_type=' + encodeURIComponent(priceType);
fetch(previewUrl, {
method: 'GET',
credentials: 'same-origin',
headers: restHeaders(),
})
.then(function (resp) { return resp.json().then(function (j) { return { ok: resp.ok, status: resp.status, json: j }; }); })
fetchPreview(postId, priceType, couponCode)
.then(function (r) {
if (!r.ok || (r.json && r.json.code)) {
const code = r.json && r.json.code ? r.json.code : '';
@@ -404,6 +417,7 @@
}
var prev = r.json || {};
if (priceType) prev._price_type = priceType;
if (couponCode) prev._coupon_code = couponCode;
renderCashier(prev, returnFocusEl);
})
.catch(function () {
@@ -430,7 +444,8 @@
const priceType = (preview._price_type || preview.price_type || '');
let amountLabel = escapeHtml(preview.amount_label || '');
let baseLabel = escapeHtml(preview.base_label || '');
if (priceType === 'download_limit_over' && preview.download_limit_over_label) {
const listLabel = escapeHtml(preview.list_amount_label || preview.amount_label || amountLabel);
if (priceType === 'download_limit_over' && preview.download_limit_over_label && !preview.discounts) {
amountLabel = escapeHtml(preview.download_limit_over_label);
baseLabel = amountLabel;
preview.amount = preview.download_limit_over_price;
@@ -440,14 +455,25 @@
const typeLabel = escapeHtml(preview.pay_type_label || '');
const balance = typeof preview.balance === 'number' ? preview.balance : 0;
const methods = Array.isArray(preview.payment_methods) ? preview.payment_methods : [];
const couponAllowed = !isPoints && !!preview.coupon_allowed;
const couponCodeVal = escapeAttr(preview.coupon_code || preview._coupon_code || '');
let priceRows = '';
if (!preview.pay_limit) {
priceRows += '<div class="aksrt-cashier__row"><span>' + tt('price', '价格') + '</span><b>' + baseLabel + '</b></div>';
}
if (preview.amount !== preview.base) {
// VIP list price row when VIP reduced list amount.
if (typeof preview.list_amount === 'number' && typeof preview.base === 'number' && preview.list_amount !== preview.base) {
priceRows += '<div class="aksrt-cashier__row"><span>' + tt('vip_price', '会员价') + '</span><b class="is-sale">' + listLabel + '</b></div>';
} else if (preview.amount !== preview.base && !preview.rebate_discount && !preview.coupon_discount) {
priceRows += '<div class="aksrt-cashier__row"><span>' + tt('vip_price', '会员价') + '</span><b class="is-sale">' + amountLabel + '</b></div>';
}
if (preview.rebate_discount > 0) {
priceRows += '<div class="aksrt-cashier__row"><span>' + tt('rebate_discount', '推广折扣') + '</span><b class="is-sale">' + escapeHtml(preview.rebate_discount_label || ('-' + preview.rebate_discount)) + '</b></div>';
}
if (preview.coupon_discount > 0) {
priceRows += '<div class="aksrt-cashier__row"><span>' + tt('coupon_discount', '优惠码') + '</span><b class="is-sale">' + escapeHtml(preview.coupon_discount_label || ('-' + preview.coupon_discount)) + '</b></div>';
}
priceRows += '<div class="aksrt-cashier__row"><span>' + tt('pay_amount', '支付金额') + '</span><b class="is-sale">' + amountLabel + '</b></div>';
let body = '';
@@ -470,6 +496,23 @@
body += '<button type="button" class="btn-primary aksrt-dl-modal__download" data-aksrt-pay-submit data-mode="points" data-price-type="' + escapeAttr(priceType) + '">' + tt('pay_now', '立即支付') + ' ' + amountLabel + '</button>';
body += '</div>';
} else {
if (couponAllowed) {
body += '<div class="aksrt-cashier__coupon">';
body += '<div class="aksrt-cashier__methods-title">' + tt('use_coupon', '使用优惠码') + '</div>';
body += '<div class="aksrt-cashier__coupon-row">';
body += '<input type="text" class="aksrt-cashier__coupon-input" name="aksrt_coupon_code" value="' + couponCodeVal + '" placeholder="' + escapeAttr(tt('enter_coupon', '请输入优惠码')) + '" autocomplete="off">';
body += '<button type="button" class="btn-sm" data-aksrt-check-coupon>' + tt('check_coupon', '检查优惠码') + '</button>';
body += '</div>';
if (preview.coupon_desc) {
body += '<div class="aksrt-cashier__coupon-desc">' + escapeHtml(preview.coupon_desc) + '</div>';
}
if (preview.coupon_error) {
body += '<div class="aksrt-cashier__warn">' + escapeHtml(preview.coupon_error) + '</div>';
} else if (preview.coupon_discount > 0) {
body += '<div class="aksrt-cashier__coupon-ok">' + tt('coupon_ok', '优惠码可用') + '</div>';
}
body += '</div>';
}
let methodHtml = '';
methods.forEach(function (m, idx) {
const id = escapeAttr(m.id || '');
@@ -486,6 +529,39 @@
open('<h3 class="aksrt-dl-modal__title">' + tt('confirm_buy', '确认购买') + '</h3>' + body, returnFocusEl);
const checkBtn = document.querySelector('[data-aksrt-check-coupon]');
if (checkBtn) {
checkBtn.addEventListener('click', function () {
const input = document.querySelector('input[name="aksrt_coupon_code"]');
const code = input ? String(input.value || '').trim() : '';
if (!code) {
if (input) input.focus();
return;
}
checkBtn.disabled = true;
const old = checkBtn.innerHTML;
checkBtn.innerHTML = tt('checking', '检查中…');
fetchPreview(preview.post_id, priceType, code)
.then(function (r) {
checkBtn.disabled = false;
checkBtn.innerHTML = old;
if (!r.ok || (r.json && r.json.code && !r.json.amount && r.json.amount !== 0)) {
renderError((r.json && r.json.message) || tt('default_err', '请稍后重试'), (r.json && r.json.data) || {}, returnFocusEl, (r.json && r.json.code) || '');
return;
}
var prev = r.json || {};
if (priceType) prev._price_type = priceType;
prev._coupon_code = code;
renderCashier(prev, returnFocusEl);
})
.catch(function () {
checkBtn.disabled = false;
checkBtn.innerHTML = old;
renderError(tt('network_err', '网络错误,请稍后重试'), {}, returnFocusEl);
});
});
}
const submitBtn = document.querySelector('[data-aksrt-pay-submit]');
if (submitBtn) {
submitBtn.addEventListener('click', function () {
@@ -493,12 +569,14 @@
let paymentMethod = 'balance';
const checked = document.querySelector('input[name="aksrt_pay_method"]:checked');
if (checked) paymentMethod = checked.value;
submitPurchase(preview.post_id, mode, paymentMethod, submitBtn, returnFocusEl);
const input = document.querySelector('input[name="aksrt_coupon_code"]');
const code = input ? String(input.value || '').trim() : (preview.coupon_code || preview._coupon_code || '');
submitPurchase(preview.post_id, mode, paymentMethod, submitBtn, returnFocusEl, code);
});
}
}
function submitPurchase(postId, mode, paymentMethod, button, returnFocusEl) {
function submitPurchase(postId, mode, paymentMethod, button, returnFocusEl, couponCode) {
if (!postId) return;
const original = button.innerHTML;
button.disabled = true;
@@ -508,6 +586,7 @@
if (mode === 'cash') payload.payment_method = paymentMethod || 'balance';
const pt = button.getAttribute('data-price-type') || '';
if (pt) payload.price_type = pt;
if (mode === 'cash' && couponCode) payload.coupon_code = couponCode;
fetch(REST_BASE + '/pay/content/' + postId, {
method: 'POST',
@@ -627,6 +706,11 @@
'.aksrt-cashier__methods{margin:0 0 14px;}' +
'.aksrt-cashier__methods-title{font-size:13px;font-weight:600;color:#374151;margin:0 0 8px;}' +
'.aksrt-cashier__method{display:flex;align-items:center;gap:8px;padding:8px 10px;border:1px solid #e5e7eb;border-radius:8px;margin:0 0 6px;cursor:pointer;font-size:13px;}' +
'.aksrt-cashier__coupon{margin:0 0 14px;}' +
'.aksrt-cashier__coupon-row{display:flex;gap:8px;align-items:center;}' +
'.aksrt-cashier__coupon-input{flex:1;min-width:0;padding:8px 10px;border:1px solid #e5e7eb;border-radius:8px;font-size:13px;}' +
'.aksrt-cashier__coupon-desc{margin-top:6px;font-size:12px;color:#9ca3af;line-height:1.5;}' +
'.aksrt-cashier__coupon-ok{margin-top:6px;font-size:12px;color:#059669;}' +
'.resource-download-box__attrs{list-style:none;margin:10px 0 0;padding:0;display:grid;gap:6px;}' +
'.resource-download-box__attrs-item{display:flex;justify-content:space-between;gap:12px;font-size:12px;color:#6b7280;}' +
'.resource-download-box__attrs-name{flex:0 0 auto;}' +
@@ -52,6 +52,10 @@ class AKSRT_Admin_Schema_Payment {
['key' => 'payment_download_remote_size', 'label' => '远程文件大小限制(KB)', 'type' => 'number', 'default' => 2048, 'min' => 1, 'max' => 999999],
['key' => 'payment_download_remote_ext', 'label' => '远程文件格式限制', 'type' => 'input', 'default' => 'zip,rar,7z'],
]],
['key' => 'coupon', 'title' => '内容优惠码', 'fields' => [
['key' => 'coupon_post_s', 'label' => '全站内容允许优惠码', 'type' => 'switch', 'default' => false],
['key' => 'coupon_desc', 'label' => '优惠码说明', 'type' => 'textarea', 'default' => '', 'dependsOn' => ['key' => 'coupon_post_s', 'value' => true]],
]],
],
],
'recharge' => [
+434 -9
View File
@@ -66,11 +66,17 @@ class AKSRT_Content_Pay {
/**
* 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();
$preview = $this->preview($post_id, $uid);
$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;
}
@@ -79,7 +85,7 @@ class AKSRT_Content_Pay {
/**
* POST /pay/content/{id}
* body: { mode?: points|cash, payment_method?: balance|alipay|..., price_type?: ''|download_limit_over }
* 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'];
@@ -94,6 +100,7 @@ class AKSRT_Content_Pay {
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) {
@@ -123,6 +130,7 @@ class AKSRT_Content_Pay {
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));
}
@@ -134,7 +142,7 @@ class AKSRT_Content_Pay {
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));
return $this->rest_wrap_result($this->create_cash_order($post_id, $uid, $payment_method, $price_type, $coupon_code));
}
/**
@@ -218,6 +226,112 @@ class AKSRT_Content_Pay {
}
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<string,mixed> $order
* @return array<string,mixed>
*/
private function decode_order_note_meta(array $order): array {
if (is_array($order['meta_payload'] ?? null) && $order['meta_payload'] !== []) {
return $order['meta_payload'];
}
$note = (string) ($order['note'] ?? '');
if ($note === '') {
return [];
}
$decoded = json_decode($note, true);
return is_array($decoded) ? $decoded : [];
}
private function 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);
}
/**
@@ -244,7 +358,7 @@ class AKSRT_Content_Pay {
*
* @return array|WP_Error
*/
public function preview(int $post_id, int $user_id = 0) {
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]);
@@ -261,6 +375,16 @@ class AKSRT_Content_Pay {
? 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);
@@ -268,6 +392,45 @@ class AKSRT_Content_Pay {
$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')) {
@@ -304,6 +467,7 @@ class AKSRT_Content_Pay {
$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')
@@ -329,6 +493,9 @@ class AKSRT_Content_Pay {
'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),
@@ -367,6 +534,25 @@ class AKSRT_Content_Pay {
'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),
],
'price_type' => $price_type,
];
}
@@ -488,22 +674,92 @@ class AKSRT_Content_Pay {
*
* @return array|WP_Error
*/
public function create_cash_order(int $post_id, int $user_id, string $payment_method = 'balance', string $price_type = '') {
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]);
}
$amount = round((float) ($priced['amount'] ?? 0), 2);
// Card pass cannot stack coupon (zibll).
$payment_method = sanitize_key($payment_method);
if ($payment_method === 'card_pass') {
$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,
@@ -515,7 +771,6 @@ class AKSRT_Content_Pay {
return new WP_Error('aksrt_pay_unavailable', __('支付系统不可用。', 'aksrt'), ['status' => 500]);
}
$payment_method = sanitize_key($payment_method);
if ($payment_method === '') {
$payment_method = $user_id > 0 ? 'balance' : 'alipay';
}
@@ -523,9 +778,22 @@ class AKSRT_Content_Pay {
$payment_method = 'alipay';
}
// Resume existing pending content order for this post when amount matches (logged-in only).
$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 {
@@ -535,8 +803,17 @@ class AKSRT_Content_Pay {
'post_id' => $post_id,
'price_type' => $price_type,
'vip_level' => (int) ($priced['vip_level'] ?? 0),
'base' => (float) ($priced['base'] ?? $amount),
'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);
@@ -574,6 +851,8 @@ class AKSRT_Content_Pay {
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]);
@@ -647,6 +926,7 @@ class AKSRT_Content_Pay {
];
}
/**
* @return array{post:WP_Post,meta:array,priced:array}|WP_Error
*/
@@ -793,6 +1073,151 @@ class AKSRT_Content_Pay {
return $methods;
}
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<string,mixed> $priced
* @param array<string,mixed> $meta
* @return array|WP_Error
*/
private function apply_cash_discounts(array $priced, WP_Post $post, array $meta, int $user_id, string $coupon_code = '', bool $soft_coupon = false) {
$list_amount = round(max(0.0, (float) ($priced['amount'] ?? 0)), 2);
$pay = $list_amount;
$rebate_discount = 0.0;
$coupon_discount = 0.0;
$coupon_meta = [];
$ref = $this->resolve_referrer_context($user_id);
$referrer_id = (int) ($ref['id'] ?? 0);
$ratio = (float) ($ref['ratio'] ?? 0);
// 1) Buyer-facing 推广折扣 (fixed).
$fixed = max(0.0, (float) ($meta['pay_rebate_discount'] ?? 0));
if ($referrer_id > 0 && $ratio > 0 && $fixed > 0 && $pay > 0) {
$rebate_discount = round(min($pay, $fixed), 2);
$pay = round(max(0.0, $pay - $rebate_discount), 2);
}
// 2) Coupon after rebate discount.
$coupon_code = sanitize_text_field($coupon_code);
if ($coupon_code !== '') {
if (!$this->is_coupon_allowed((int) $post->ID, $meta)) {
$err = new WP_Error('aksrt_coupon_not_allowed', __('当前内容不支持优惠码。', 'aksrt'), ['status' => 400]);
if (!$soft_coupon) {
return $err;
}
} elseif (!class_exists('AKSRT_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],
]);
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');
+51
View File
@@ -293,6 +293,57 @@ class AKSRT_Invite {
* 公开 API:根据邀请码反查邀请人 user_id(不存在返回 0)。
* 给注册流程在 wp_create_user 之前做"邀请码是否合法"的预校验用。
*/
/**
* Resolve affiliate / invite referrer for a buyer (zibll-style).
*
* Priority:
* 1. Logged-in: inviter_id from aksrt_invite table for this invitee
* 2. Cookie invite code → resolve_code
*
* Respects pay_rebate_self_s when available (via affiliate settings).
*/
public function get_referrer(int $user_id = 0): int {
$uid = $user_id > 0 ? $user_id : get_current_user_id();
$referrer_id = 0;
if ($uid > 0) {
global $wpdb;
$table = AKSRT_DB_Migrator::table('invite');
if ($table) {
$referrer_id = (int) $wpdb->get_var($wpdb->prepare(
"SELECT inviter_id FROM {$table} WHERE invitee_id = %d AND inviter_id > 0 ORDER BY id DESC LIMIT 1",
$uid
));
}
}
if ($referrer_id <= 0) {
$code = '';
if (!empty($_COOKIE[self::COOKIE_NAME])) {
$code = sanitize_key((string) $_COOKIE[self::COOKIE_NAME]);
}
if ($code !== '') {
$referrer_id = $this->resolve_code($code);
}
}
if ($referrer_id <= 0) {
return 0;
}
// Self-purchase rebate gate (default allow, matching pay_rebate_self_s default true).
$allow_self = true;
if (class_exists('AKSRT_Settings') && method_exists('AKSRT_Settings', 'get_payment_affiliate_settings')) {
$aff = AKSRT_Settings::get_payment_affiliate_settings();
$allow_self = !isset($aff['self_s']) || !empty($aff['self_s']);
}
if ($uid > 0 && $referrer_id === $uid && !$allow_self) {
return 0;
}
return $referrer_id;
}
public function resolve_code(string $code): int {
$code = sanitize_key($code);
if ($code === '') return 0;
@@ -307,6 +307,26 @@ class AKSRT_Resource_Meta_Box {
</div>
</div>
<div class="aksrt-pmb__row">
<label><?php esc_html_e('优惠码', 'aksrt'); ?></label>
<div>
<div style="display:flex; align-items:center; gap:6px; margin-bottom:8px;">
<input type="checkbox" id="aksrt_pay_coupon_s" name="aksrt_pay_coupon_s" value="1" <?php checked(!empty($meta['coupon_s'])); ?>>
<label for="aksrt_pay_coupon_s" style="font-weight:400;padding:0;"><?php esc_html_e('允许使用优惠码(全站开关关闭时仍可对本篇启用)', 'aksrt'); ?></label>
</div>
<textarea id="aksrt_pay_coupon_desc" name="aksrt_pay_coupon_desc" style="min-height:60px;" placeholder="<?php esc_attr_e('本篇优惠码说明,可留空', 'aksrt'); ?>"><?php echo esc_textarea((string) ($meta['coupon_desc'] ?? '')); ?></textarea>
<p class="aksrt-pmb__hint"><?php esc_html_e('对齐 zibll coupon_s / coupon_desc。积分支付不使用优惠码。', 'aksrt'); ?></p>
</div>
</div>
<div class="aksrt-pmb__row">
<label for="aksrt_pay_rebate_discount"><?php esc_html_e('推广优惠金额', 'aksrt'); ?></label>
<div>
<input type="number" id="aksrt_pay_rebate_discount" name="aksrt_pay_rebate_discount" value="<?php echo esc_attr((string) ($meta['pay_rebate_discount'] ?? 0)); ?>" min="0" step="0.01">
<p class="aksrt-pmb__hint"><?php esc_html_e('有有效推荐人且开启推广返佣时,现金购买可先减此金额(买家侧推广折扣,对齐 zibll pay_rebate_discount)。0 = 不启用。', 'aksrt'); ?></p>
</div>
</div>
<div class="aksrt-pmb__row">
<label for="aksrt_pay_stock"><?php esc_html_e('库存', 'aksrt'); ?></label>
<div>
@@ -506,6 +526,9 @@ class AKSRT_Resource_Meta_Box {
'free_preview' => $_POST['aksrt_pay_free_preview'] ?? '',
'show_sales' => !empty($_POST['aksrt_pay_show_sales']),
'download_limit_over_price' => max(0, (float) ($_POST['aksrt_pay_limit_over_price'] ?? 0)),
'coupon_s' => !empty($_POST['aksrt_pay_coupon_s']),
'coupon_desc' => (string) ($_POST['aksrt_pay_coupon_desc'] ?? ''),
'pay_rebate_discount' => max(0, (float) ($_POST['aksrt_pay_rebate_discount'] ?? 0)),
]);
update_post_meta($post_id, AKSRT_Domain_Model::PAY_META_KEY, $pay_meta);
@@ -136,6 +136,15 @@ trait AKSRT_Settings_Credits_Payment_Groups {
return AKSRT_Settings_Payment_Runtime::get_paid_content_settings();
}
/**
* Content coupon global switches.
*
* @return array{enabled:bool,desc:string}
*/
public static function get_content_coupon_settings(): array {
return AKSRT_Settings_Payment_Runtime::get_content_coupon_settings();
}
/**
* @return array{enabled:bool,mode:string,packages_raw:string,package_count:int,help_text:string}
*/
@@ -383,6 +383,10 @@ class AKSRT_Settings_Home_Cms {
return AKSRT_Settings_Payment_Runtime::get_paid_content_settings();
}
public static function get_content_coupon_settings(): array {
return AKSRT_Settings_Payment_Runtime::get_content_coupon_settings();
}
public static function get_payment_recharge_settings(): array {
return AKSRT_Settings_Payment_Runtime::get_payment_recharge_settings();
}
@@ -72,6 +72,22 @@ class AKSRT_Settings_Payment_Runtime {
'remote_ext' => sanitize_text_field((string) ($settings['payment_download_remote_ext'] ?? 'zip,rar,7z')),
'alone_page' => !empty($settings['payment_down_alone_page']),
],
// Content cashier coupon (zibll coupon_post_s / coupon_desc).
'coupon_post_s' => !empty($settings['coupon_post_s']),
'coupon_desc' => sanitize_textarea_field((string) ($settings['coupon_desc'] ?? '')),
];
}
/**
* Content coupon global switches (zibll coupon_post_s).
*
* @return array{enabled:bool,desc:string}
*/
public static function get_content_coupon_settings(): array {
$settings = self::get_paid_content_settings();
return [
'enabled' => !empty($settings['coupon_post_s']),
'desc' => (string) ($settings['coupon_desc'] ?? ''),
];
}
+7
View File
@@ -137,6 +137,10 @@ class AKSRT_Domain_Model {
'show_sales' => true,
// Zibll: free daily quota overbuy price (cash or points by pay_modo).
'download_limit_over_price' => 0.0,
// Content cashier: coupon + buyer-facing 推广折扣 (zibll posts_zibpay).
'coupon_s' => false,
'coupon_desc' => '',
'pay_rebate_discount' => 0.0,
];
}
@@ -337,6 +341,9 @@ class AKSRT_Domain_Model {
$meta['free_preview'] = wp_kses_post((string) ($raw['free_preview'] ?? ''));
$meta['show_sales'] = !isset($raw['show_sales']) || !empty($raw['show_sales']);
$meta['download_limit_over_price'] = max(0, (float) ($raw['download_limit_over_price'] ?? 0));
$meta['coupon_s'] = !empty($raw['coupon_s']);
$meta['coupon_desc'] = sanitize_textarea_field((string) ($raw['coupon_desc'] ?? ''));
$meta['pay_rebate_discount'] = max(0, (float) ($raw['pay_rebate_discount'] ?? 0));
return $meta;
}
+68
View File
@@ -491,6 +491,74 @@ if (!function_exists('aksrt_get_user_pay_price')) {
}
}
/**
* Whether content cashier may accept coupons for this post (zibll coupon_post_s || coupon_s).
*/
if (!function_exists('aksrt_is_content_coupon_allowed')) {
function aksrt_is_content_coupon_allowed($post = null): bool {
$meta = function_exists('aksrt_get_pay_meta') ? aksrt_get_pay_meta($post) : [];
if (!empty($meta['coupon_s'])) {
return true;
}
if (class_exists('AKSRT_Settings') && method_exists('AKSRT_Settings', 'get_content_coupon_settings')) {
$cfg = AKSRT_Settings::get_content_coupon_settings();
return !empty($cfg['enabled']);
}
if (class_exists('AKSRT_Settings') && method_exists('AKSRT_Settings', 'get_paid_content_settings')) {
$paid = AKSRT_Settings::get_paid_content_settings();
return !empty($paid['coupon_post_s']);
}
return false;
}
}
/**
* Buyer-facing 推广折扣 amount for a post (0 if no eligible referrer).
* Cash only; mirrors zibpay_get_post_rebate_discount.
*/
if (!function_exists('aksrt_get_post_rebate_discount')) {
function aksrt_get_post_rebate_discount($post = null, int $user_id = 0): float {
$meta = function_exists('aksrt_get_pay_meta') ? aksrt_get_pay_meta($post) : [];
$fixed = max(0.0, (float) ($meta['pay_rebate_discount'] ?? 0));
if ($fixed <= 0) {
return 0.0;
}
if (!class_exists('AKSRT_Settings') || !method_exists('AKSRT_Settings', 'get_payment_affiliate_settings')) {
return 0.0;
}
$aff = AKSRT_Settings::get_payment_affiliate_settings();
if (empty($aff['enabled'])) {
return 0.0;
}
$uid = $user_id > 0 ? $user_id : (function_exists('get_current_user_id') ? (int) get_current_user_id() : 0);
$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($uid);
}
if ($referrer_id <= 0) {
return 0.0;
}
// Need a positive ratio for referrer (VIP tier of referrer preferred).
$ratio = (int) ($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 && !empty($user_ratio['vip2'])) {
$ratio = (int) $user_ratio['vip2'];
} elseif ($ref_vip >= 1 && !empty($user_ratio['vip1'])) {
$ratio = (int) $user_ratio['vip1'];
} elseif (isset($user_ratio['user'])) {
$ratio = (int) $user_ratio['user'];
}
if ($ratio <= 0) {
return 0.0;
}
return round($fixed, 2);
}
}
// ============================================================
// 状态判断
// ============================================================