mode = config('habbo.paypal.mode', 'sandbox'); $this->clientId = config("habbo.paypal.{$this->mode}.client_id", ''); $this->clientSecret = config("habbo.paypal.{$this->mode}.client_secret", ''); $baseUrl = $this->mode === 'live' ? 'https://api-m.paypal.com' : 'https://api-m.sandbox.paypal.com'; $this->client = new Client([ 'base_uri' => $baseUrl, 'timeout' => 30, 'http_errors' => false, ]); } public function getAccessToken(): ?string { $cacheKey = 'paypal_access_token_' . $this->mode; return Cache::remember($cacheKey, 32400, function () { try { $response = $this->client->post('/v1/oauth2/token', [ 'headers' => [ 'Accept' => 'application/json', 'Content-Type' => 'application/x-www-form-urlencoded', ], 'auth' => [$this->clientId, $this->clientSecret], 'form_params' => [ 'grant_type' => 'client_credentials', ], ]); $body = json_decode($response->getBody(), true); if ($response->getStatusCode() !== 200 || ! isset($body['access_token'])) { Log::error('PayPal access token request failed', [ 'status' => $response->getStatusCode(), 'response' => $body, ]); return; } return $body['access_token']; } catch (GuzzleException $e) { Log::error('PayPal access token exception', [ 'message' => $e->getMessage(), ]); return; } }); } public function createOrder(array $orderData): ?array { $accessToken = $this->getAccessToken(); if ($accessToken === null) { return null; } try { $response = $this->client->post('/v2/checkout/orders', [ 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => "Bearer {$accessToken}", 'Accept' => 'application/json', ], 'json' => $orderData, ]); $body = json_decode($response->getBody(), true); if ($response->getStatusCode() >= 400) { Log::error('PayPal create order failed', [ 'status' => $response->getStatusCode(), 'response' => $body, ]); return $body; } return $body; } catch (GuzzleException $e) { Log::error('PayPal create order exception', [ 'message' => $e->getMessage(), ]); return null; } } public function capturePaymentOrder(string $orderId): ?array { $accessToken = $this->getAccessToken(); if ($accessToken === null) { return null; } try { $response = $this->client->post("/v2/checkout/orders/{$orderId}/capture", [ 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => "Bearer {$accessToken}", 'Accept' => 'application/json', ], ]); $body = json_decode($response->getBody(), true); if ($response->getStatusCode() >= 400) { Log::error('PayPal capture order failed', [ 'status' => $response->getStatusCode(), 'response' => $body, ]); return $body; } return $body; } catch (GuzzleException $e) { Log::error('PayPal capture order exception', [ 'message' => $e->getMessage(), ]); return null; } } }