send(fn () => $this->request($apiKey)->get('/account-status')); if ($response->successful()) { return true; } if (in_array($response->status(), [401, 403, 404, 422], true)) { return false; } throw new PaymentException('HitPay could not check the API key: HTTP '.$response->status()); } /** * Create a payment page ("payment request"). * * @param array $fields * @return array * * @throws PaymentException */ public function createPaymentRequest(#[\SensitiveParameter] string $apiKey, array $fields): array { $response = $this->send(fn () => $this->request($apiKey)->asForm()->post('/payment-requests', $fields)); $refused = $this->refusedMethods($response, $fields['payment_methods'] ?? []); if ($refused !== []) { throw new HitPayRefusedMethods($refused, 'HitPay refused payment methods: '.implode(', ', $refused).'. '.$response->json('message')); } if (! $response->successful() || ! is_string($response->json('id')) || ! is_string($response->json('url'))) { throw new PaymentException('HitPay could not create the payment page: HTTP '.$response->status().' '.mb_substr($response->body(), 0, 500)); } return $response->json(); } /** * A payment page and the payments made on it. * * @return array * * @throws PaymentException */ public function paymentRequest(#[\SensitiveParameter] string $apiKey, string $id): array { $response = $this->send(fn () => $this->request($apiKey)->get('/payment-requests/'.rawurlencode($id))); if (! $response->successful() || ! is_array($response->json())) { throw new PaymentException('HitPay could not find the payment: HTTP '.$response->status()); } return $response->json(); } /** * The methods HitPay said are unavailable for the account. It answers 422 with an error per method, * such as "payment_methods.0": "The selected payment method (duitnow) is unavailable for your account ...". * * @param list $methods The methods that were sent, in order * @return list */ private function refusedMethods(Response $response, array $methods): array { if ($response->status() !== 422 || ! is_array($response->json('errors'))) { return []; } $refused = []; foreach (array_keys($response->json('errors')) as $field) { if (preg_match('/^payment_methods\.(\d+)$/', (string) $field, $match) === 1 && isset($methods[(int) $match[1]])) { $refused[] = $methods[(int) $match[1]]; } } return array_values(array_unique($refused)); } private function request(#[\SensitiveParameter] string $apiKey): PendingRequest { return Http::baseUrl($this->baseUrl()) ->acceptJson() ->timeout(20) ->withHeaders([ 'X-BUSINESS-API-KEY' => $apiKey, // HitPay's FAQ: without this header some calls answer "Invalid Business API Key". 'X-Requested-With' => 'XMLHttpRequest', ]); } /** * @param callable(): Response $call * * @throws PaymentException */ private function send(callable $call): Response { try { return $call(); } catch (ConnectionException $e) { throw new PaymentException('HitPay could not be reached: '.$e->getMessage(), 0, $e); } } }