- MarketPackage 模型/迁移:市场商品作为可购买实体(payable),复用 Payment 订单 - MarketPurchaseService:购买创建订单、已购判断、免费/付费门槛校验 - payment.paid 监听(核心注册,仅支付插件启用时)标记商品已购 - 市场契约:条目含 name/type/price(分)/download_url;插件市场 Tab 只显示 plugin、主题市场 Tab 只显示 theme;付费商品显示「购买」按钮与「已购买」徽章,未购买无法安装 - 新增主题市场 Tab(原仅插件页有市场) - 测试:购买/沙箱支付标记已购/重复购买/安装门槛/免费条目/支付插件禁用
115 lines
3.0 KiB
PHP
115 lines
3.0 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Blog\Services;
|
|
|
|
use App\Blog\Support\PluginManager;
|
|
use App\Models\MarketPackage;
|
|
use Plugins\Neatstudio\Payment\Models\Payment;
|
|
use Plugins\Neatstudio\Payment\Services\PaymentManager;
|
|
use RuntimeException;
|
|
|
|
class MarketPurchaseService
|
|
{
|
|
public function __construct(private PluginManager $plugins, private PaymentManager $payment)
|
|
{
|
|
}
|
|
|
|
/**
|
|
* 市场条目键:优先 item.name,缺省用下载文件名。
|
|
*/
|
|
public function itemKey(array $item): string
|
|
{
|
|
$name = $item['name'] ?? null;
|
|
|
|
if ($name) {
|
|
return (string) $name;
|
|
}
|
|
|
|
return basename((string) ($item['download_url'] ?? ''), '.zip') ?: uniqid('item-');
|
|
}
|
|
|
|
public function itemType(array $item): string
|
|
{
|
|
return $item['type'] ?? 'plugin';
|
|
}
|
|
|
|
public function requiresPayment(array $item): bool
|
|
{
|
|
return (int) ($item['price'] ?? 0) > 0;
|
|
}
|
|
|
|
/**
|
|
* 购买市场商品:创建订单并返回(null = 已购买过,无需重复支付)。
|
|
*/
|
|
public function purchase(array $item): ?Payment
|
|
{
|
|
if (! $this->plugins->isEnabled('neatstudio.payment')) {
|
|
throw new RuntimeException('付费市场商品需要启用支付插件');
|
|
}
|
|
|
|
$price = (int) ($item['price'] ?? 0);
|
|
|
|
if ($price <= 0) {
|
|
throw new RuntimeException('该商品免费,无需购买');
|
|
}
|
|
|
|
$key = $this->itemKey($item);
|
|
$type = $this->itemType($item);
|
|
$user = auth()->user();
|
|
|
|
$package = MarketPackage::query()->firstOrCreate(
|
|
['item_key' => $key, 'item_type' => $type],
|
|
[
|
|
'title' => (string) ($item['title'] ?? $key),
|
|
'price' => $price,
|
|
'status' => 'pending',
|
|
'user_id' => $user?->id,
|
|
]
|
|
);
|
|
|
|
if ($package->isPaid()) {
|
|
return null;
|
|
}
|
|
|
|
return $this->payment->createOrder(
|
|
$user ?? $this->systemUser(),
|
|
'购买商品:'.$package->title,
|
|
$price,
|
|
$package,
|
|
'alipay'
|
|
);
|
|
}
|
|
|
|
public function isPurchased(string $key, string $type = 'plugin'): bool
|
|
{
|
|
return MarketPackage::query()
|
|
->where('item_key', $key)
|
|
->where('item_type', $type)
|
|
->where('status', 'paid')
|
|
->exists();
|
|
}
|
|
|
|
/**
|
|
* 校验市场条目可否安装:免费直接装,付费需已购买。
|
|
*/
|
|
public function assertCanInstall(array $item): void
|
|
{
|
|
if ($this->requiresPayment($item) && ! $this->isPurchased($this->itemKey($item), $this->itemType($item))) {
|
|
throw new RuntimeException('该商品为付费商品,请先购买后再安装');
|
|
}
|
|
}
|
|
|
|
private function systemUser(): \App\Models\User
|
|
{
|
|
$user = \App\Models\User::query()->first();
|
|
|
|
if (! $user) {
|
|
throw new RuntimeException('无可用用户创建订单,请先登录');
|
|
}
|
|
|
|
return $user;
|
|
}
|
|
}
|