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; } }