diff --git a/app/Services/Paddle/PaddleDiscountService.php b/app/Services/Paddle/PaddleDiscountService.php index 4a49927..d0e9430 100644 --- a/app/Services/Paddle/PaddleDiscountService.php +++ b/app/Services/Paddle/PaddleDiscountService.php @@ -17,6 +17,11 @@ class PaddleDiscountService */ public function createDiscount(Coupon $coupon): array { + $existing = $this->findExistingDiscount($coupon->code); + if ($existing !== null) { + return $existing; + } + $payload = $this->buildDiscountPayload($coupon); $response = $this->client->post('/discounts', $payload); @@ -82,6 +87,35 @@ class PaddleDiscountService return Arr::get($response, 'data', $response); } + /** + * @return array|null + */ + protected function findExistingDiscount(?string $code): ?array + { + $normalized = Str::upper(trim((string) $code)); + if ($normalized === '') { + return null; + } + + $response = $this->client->get('/discounts', [ + 'code' => $normalized, + 'per_page' => 1, + ]); + + $items = Arr::get($response, 'data', []); + if (! is_array($items) || $items === []) { + return null; + } + + $match = Collection::make($items)->first(static function ($item) use ($normalized) { + $codeValue = Str::upper((string) Arr::get($item, 'code', '')); + + return $codeValue === $normalized ? $item : null; + }); + + return is_array($match) ? $match : null; + } + /** * @return array */