diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9716347 --- /dev/null +++ b/.gitignore @@ -0,0 +1,105 @@ +### PHPUnit template +# Covers PHPUnit +# Reference: https://phpunit.de/ + +# Generated files +.phpunit.result.cache +.phpunit.cache + +# PHPUnit +/app/phpunit.xml +/phpunit.xml + +# Build data +/build/ + +### Example user template template +### Example user template + +# IntelliJ project files +.idea +*.iml +out +gen +### PhpStorm template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +# root +*.lock +vendor diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d7e3d26 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Asrorbek Sultanov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..03a6cd5 --- /dev/null +++ b/README.md @@ -0,0 +1,61 @@ +# CloudPayments PHP Client + +This PHP library provides a convenient interface for interacting with the CloudPayments API. The CloudPayments API operates at `api.cloudpayments.ru` and supports various functions for payment processing, including making a payment, canceling a payment, returning money, completing payments made using a two-stage scheme, creating and canceling subscriptions for recurring payments, as well as sending invoices by mail. + +## Principle of Operation + +Parameters are passed using the POST method in the body of the request in either the "key=value" format or in JSON. The API can accept a maximum of 150,000 fields in a single request, and the timeout for receiving a response from the API is set to 5 minutes. It's important to note that if a number with a fractional part is passed into an integer field, mathematical rounding will occur without triggering an error. + +The API enforces limits on the maximum number of simultaneous requests for test terminals (5) and combat terminals (30). If the number of requests to the site currently being processed exceeds the limit, the API will return a response with HTTP code 429 (Too Many Requests) until processing is completed. For a review of these restrictions, contact your personal manager. + +The choice of parameter transfer format is determined on the client side and is controlled through the `Content-Type` request header: +- For `key=value` parameters: `Content-Type: application/x-www-form-urlencoded` +- For JSON parameters: `Content-Type: application/json` + +The system issues a response in JSON format, including at least two parameters: `Success` and `Message`: + +```json +{ + "Success": false, + "Message": "Invalid Amount value" +} +``` + +### Request Authentication + +To authenticate the request, HTTP Basic Auth is used. The login and password are sent in the HTTP request header. The Public ID serves as the login, and the API Secret serves as the password. Both values can be obtained in your personal account. If a header with authentication data is not sent in the request or incorrect data is provided, the system will return HTTP status 401 – Unauthorized. It's crucial to securely store the API secret. + +### Requires + +- php ^8.1 + +```bash +composer require asrorbek/cloudpayments-php-client +``` + +## Example usage + +```php +sendTestRequest(array( + 'Name' => 'Foo Baz', +)); + +print_r($response); + + +// Process the response as needed + +``` + +- Replace 'your_public_key' and 'your_api_secret' with the actual Public ID and API Secret obtained from your personal account. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..606857a --- /dev/null +++ b/composer.json @@ -0,0 +1,29 @@ +{ + "name": "asrorbek/cloudpayments-php-client", + "type": "library", + "license": "MIT", + "authors": [ + { + "name": "Asrorbek Sultanov", + "email": "asrorbek0325@gmail.com" + } + ], + "require": { + "php": "^8.1", + "php-curl-class/php-curl-class": "^9.18", + "ext-curl": "*" + }, + "autoload": { + "psr-4": { + "CloudPaymentsSDK\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "CloudPaymentsSDK\\Tests\\": "tests/" + } + }, + "require-dev": { + "phpunit/phpunit": "^10.5" + } +} diff --git a/src/Client/CloudPayments.php b/src/Client/CloudPayments.php new file mode 100644 index 0000000..d510313 --- /dev/null +++ b/src/Client/CloudPayments.php @@ -0,0 +1,676 @@ +httpClient = new HttpClient($publicKey, $apiSecret, $apiUrl, $enableSSL); + } + + /** + * Make a test request + * + * @param array $data + * @return object + */ + public function sendTestRequest(array $data): object + { + return $this->httpClient->sendRequest(self::METHOD_TEST, $data); + } + + + /** + * Make a one-time payment using card details. + * + * @param array $cardPaymentData + * @link https://developers.cloudpayments.ru/en/#payment-schemes + * @return object + */ + public function makeCardPaymentAutomatic(array $cardPaymentData): object + { + return $this->httpClient->sendRequest(self::CHARGE_CARD, $cardPaymentData); + } + + /** + * Make a two-step payment using card details. + * + * @param array $cardPaymentData + * @link https://developers.cloudpayments.ru/en/#payment-schemes + * @return object + */ + public function makeCardPaymentManual(array $cardPaymentData): object + { + return $this->httpClient->sendRequest(self::AUTH_CARD, $cardPaymentData); + } + + /** + * Make a payment using card details. + * + * @param array $paymentData + * @param bool $requireConfirmation + * @link https://developers.cloudpayments.ru/en/#payment-schemes + * @return object + */ + public function makeCardPayment(array $paymentData, bool $requireConfirmation = false): object + { + if ($requireConfirmation) { + return $this->makeCardPaymentManual($paymentData); + } + + return $this->makeCardPaymentAutomatic($paymentData); + } + + /** + * Make a one-step payment using a token. + * + * @param array $tokenPaymentData + * @link https://developers.cloudpayments.ru/en/#payment-schemes + * @return object + */ + public function makeTokenPaymentAutomatic(array $tokenPaymentData): object + { + return $this->httpClient->sendRequest(self::CHARGE_TOKEN, $tokenPaymentData); + } + + /** + * Make a two-step payment using a token (recurring). + * + * @param array $tokenPaymentData + * @link https://developers.cloudpayments.ru/en/#payment-schemes + * @return object + */ + public function makeTokenPaymentManual(array $tokenPaymentData): object + { + return $this->httpClient->sendRequest(self::AUTH_TOKEN, $tokenPaymentData); + } + + /** + * Make a payment using a saved card token. + * + * @param array $tokenPaymentData + * @param bool $requireConfirmation + * @link https://developers.cloudpayments.ru/en/#payment-schemes + * @return object + */ + public function makeTokenPayment(array $tokenPaymentData, bool $requireConfirmation = false): object + { + if ($requireConfirmation) { + return $this->makeTokenPaymentManual($tokenPaymentData); + } + + return $this->makeTokenPaymentAutomatic($tokenPaymentData); + } + + /** + * Completes the payment after 3-D Secure authentication. + * + * @param string $transactionId + * @param string $paRes + * @link https://developers.cloudpayments.ru/en/#3-d-secure-processing + * @return object The response from the CloudPayments API. + */ + public function complete3DSecurePayment(string $transactionId, string $paRes): object + { + $requestData = [ + "TransactionId" => $transactionId, + "PaRes" => $paRes, + ]; + return $this->httpClient->sendRequest(self::POST3D_SECURE, $requestData); + } + + + /** + * Confirm a payment with a specific transaction ID and amount. + * + * @param string $transactionId + * @param float $amount + * @link https://developers.cloudpayments.ru/en/#payment-by-a-token-recurring + * @return object + */ + public function confirmPayment(string $transactionId, float $amount): object + { + $endpoint = '/payments/confirm'; + $requestData = [ + "TransactionId" => $transactionId, + "Amount" => $amount, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Void a payment with a specific transaction ID. + * + * @param string $transactionId + * @link https://developers.cloudpayments.ru/en/#payment-confirmation + * @return object + */ + public function voidPayment(string $transactionId): object + { + $endpoint = '/payments/void'; + $requestData = [ + "TransactionId" => $transactionId, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Refund a payment with a specific transaction ID and amount. + * + * @param string $transactionId + * @param float $amount + * @link https://developers.cloudpayments.ru/en/#refund + * @return object + */ + public function refundPayment(string $transactionId, float $amount): object + { + $endpoint = '/payments/refund'; + $requestData = [ + "TransactionId" => $transactionId, + "Amount" => $amount, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Initiate a payout using card details. + * + * @param array $payoutData + * @link https://developers.cloudpayments.ru/en/#payout-by-a-cryptogram + * @return object + */ + public function initiatePayout(array $payoutData): object + { + $endpoint = '/payments/cards/topup'; + return $this->httpClient->sendRequest($endpoint, $payoutData); + } + + /** + * Initiate a payout using a saved card token. + * + * @param string $token + * @param float $amount + * @param string $accountId + * @param string $currency + * @param string|null $payer + * @param string|null $receiver + * @param string|null $invoiceId + * @link https://developers.cloudpayments.ru/en/#payout-by-a-token + * @return object + */ + public function initiatePayoutByToken(string $token, float $amount, string $accountId, string $currency, ?string $payer = null, ?string $receiver = null, ?string $invoiceId = null): object + { + $endpoint = '/payments/token/topup'; + $requestData = [ + "Token" => $token, + "Amount" => $amount, + "AccountId" => $accountId, + "Currency" => $currency, + "InvoiceId" => $invoiceId, + "Payer" => $payer, + "Receiver" => $receiver, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Get details for a specific transaction. + * + * @param string $transactionId + * @link https://developers.cloudpayments.ru/en/#transaction-details + * @return object + */ + public function getTransactionDetails(string $transactionId): object + { + $endpoint = '/payments/get'; + $requestData = [ + "TransactionId" => $transactionId, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Check the status of a payment using the invoice ID. + * + * @param string $invoiceId + * @link https://developers.cloudpayments.ru/en/#payment-status-check + * @return object + */ + public function checkPaymentStatus(string $invoiceId): object + { + $endpoint = '/v2/payments/find'; + $requestData = [ + "InvoiceId" => $invoiceId, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Get a list of transactions for a specific day. + * + * @param string $date + * @param string $timeZone + * @link https://developers.cloudpayments.ru/en/#transaction-list + * @return object + */ + public function getTransactionsForDay(string $date, string $timeZone = "UTC"): object + { + $endpoint = '/payments/list'; + $requestData = [ + "Date" => $date, + "TimeZone" => $timeZone, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Get a list of transactions for a specific period. + * + * @param string $startDate + * @param string $endDate + * @param int $pageNumber + * @param string $timeZone + * @param array $statuses + * @link https://developers.cloudpayments.ru/en/#transaction-list + * @return object + */ + public function getTransactionsForPeriod(string $startDate, string $endDate, int $pageNumber, string $timeZone = "UTC", array $statuses = []): object + { + $endpoint = '/v2/payments/list'; + $requestData = [ + "CreatedDateGte" => $startDate, + "CreatedDateLte" => $endDate, + "PageNumber" => $pageNumber, + "TimeZone" => $timeZone, + "Statuses" => $statuses, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Get a list of payment tokens. + * + * @param int $pageNumber + * @link https://developers.cloudpayments.ru/en/#token-list + * @return object + */ + public function getPaymentTokens(int $pageNumber): object + { + $endpoint = '/payments/tokens/list'; + $requestData = [ + "PageNumber" => $pageNumber, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Create a subscription for recurring payments. + * + * @param string $token + * @param string $accountId + * @param string $description + * @param string $email + * @param float $amount + * @param string $currency + * @param bool $requireConfirmation + * @param string $startDate + * @param string $interval + * @param int $period + * @param int|null $maxPeriods + * @param string|null $customerReceipt + * @link https://developers.cloudpayments.ru/en/#creation-of-subscriptions-on-recurrent-payments + * @return object + */ + public function createSubscription(string $token, string $accountId, string $description, string $email, float $amount, string $currency, bool $requireConfirmation, string $startDate, string $interval, int $period, ?int $maxPeriods = null, ?string $customerReceipt = null): object + { + $endpoint = '/subscriptions/create'; + $requestData = [ + "Token" => $token, + "AccountId" => $accountId, + "Description" => $description, + "Email" => $email, + "Amount" => $amount, + "Currency" => $currency, + "RequireConfirmation" => $requireConfirmation, + "StartDate" => $startDate, + "Interval" => $interval, + "Period" => $period, + "MaxPeriods" => $maxPeriods, + "CustomerReceipt" => $customerReceipt, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Get information about a subscription. + * + * @param string $subscriptionId + * @link https://developers.cloudpayments.ru/en/#subscription-details + * @return object + */ + public function getSubscriptionInfo(string $subscriptionId): object + { + $endpoint = '/subscriptions/get'; + $requestData = [ + "Id" => $subscriptionId, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Find subscriptions for a specific account ID. + * + * @param string $accountId + * @link https://developers.cloudpayments.ru/en/#subscriptions-search + * @return object + */ + public function findSubscriptions(string $accountId): object + { + $endpoint = '/subscriptions/find'; + $requestData = [ + "accountId" => $accountId, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Update subscription details. + * + * @param string $subscriptionId + * @param string|null $description + * @param float|null $amount + * @param string|null $currency + * @param bool|null $requireConfirmation + * @param string|null $startDate + * @param string|null $interval + * @param int|null $period + * @param int|null $maxPeriods + * @param string|null $customerReceipt + * @link https://developers.cloudpayments.ru/en/#recurrent-payments-subscription-change + * @return object + */ + public function updateSubscription(string $subscriptionId, ?string $description = null, ?float $amount = null, ?string $currency = null, ?bool $requireConfirmation = null, ?string $startDate = null, ?string $interval = null, ?int $period = null, ?int $maxPeriods = null, ?string $customerReceipt = null): object + { + $endpoint = '/subscriptions/update'; + $requestData = [ + "Id" => $subscriptionId, + "Description" => $description, + "Amount" => $amount, + "Currency" => $currency, + "RequireConfirmation" => $requireConfirmation, + "StartDate" => $startDate, + "Interval" => $interval, + "Period" => $period, + "MaxPeriods" => $maxPeriods, + "CustomerReceipt" => $customerReceipt, + "CultureName" => $this->cultureName, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Cancel a subscription. + * + * @param string $subscriptionId + * @link https://developers.cloudpayments.ru/en/#subscription-on-recurrent-payments-cancellation + * @return object + */ + public function cancelSubscription(string $subscriptionId): object + { + $endpoint = '/subscriptions/cancel'; + $requestData = [ + "Id" => $subscriptionId, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Create an invoice for a one-time payment. + * + * @param float $amount + * @param string $currency + * @param string $description + * @param string $email + * @param bool $requireConfirmation + * @param bool $sendEmail + * @param string|null $invoiceId + * @param string|null $accountId + * @param string|null $offerUri + * @param string|null $phone + * @param bool|null $sendSms + * @param bool|null $sendViber + * @param string|null $subscriptionBehavior + * @param string|null $successRedirectUrl + * @param string|null $failRedirectUrl + * @param array|null $jsonData + * @link https://developers.cloudpayments.ru/en/#invoice-creation-on-email + * @return object + */ + public function createInvoice(float $amount, string $currency, string $description, string $email, bool $requireConfirmation, bool $sendEmail, ?string $invoiceId = null, ?string $accountId = null, ?string $offerUri = null, ?string $phone = null, ?bool $sendSms = null, ?bool $sendViber = null, ?string $subscriptionBehavior = null, ?string $successRedirectUrl = null, ?string $failRedirectUrl = null, ?array $jsonData = null): object + { + $endpoint = '/orders/create'; + $requestData = [ + "Amount" => $amount, + "Currency" => $currency, + "Description" => $description, + "Email" => $email, + "RequireConfirmation" => $requireConfirmation, + "SendEmail" => $sendEmail, + "InvoiceId" => $invoiceId, + "AccountId" => $accountId, + "OfferUri" => $offerUri, + "Phone" => $phone, + "SendSms" => $sendSms, + "SendViber" => $sendViber, + "CultureName" => $this->cultureName, + "SubscriptionBehavior" => $subscriptionBehavior, + "SuccessRedirectUrl" => $successRedirectUrl, + "FailRedirectUrl" => $failRedirectUrl, + "JsonData" => $jsonData, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Cancel an order for a one-time payment. + * + * @param string $orderId + * @link https://developers.cloudpayments.ru/en/#created-invoice-cancellation + * @return object + */ + public function cancelOrder(string $orderId): object + { + $endpoint = '/orders/cancel'; + $requestData = [ + "Id" => $orderId, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * View notification settings for a specific notification type. + * + * @param string $notificationType + * @link https://developers.cloudpayments.ru/en/#view-of-notification-settings + * @return object + */ + public function viewNotificationSettings(string $notificationType): object + { + $endpoint = "/site/notifications/{$notificationType}/get"; + $requestData = [ + "Type" => $notificationType, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Updates notification settings for a specific notification type. + * + * @param string $notificationType Type of the notification. + * @param bool|null $isEnabled Whether the notification is enabled. + * @param string|null $address Notification endpoint address. + * @param string|null $httpMethod HTTP method for the notification. + * @param string|null $encoding Encoding for the notification. + * @param string|null $format Format of the notification. + * @link https://developers.cloudpayments.ru/en/#change-of-notification-settings + * @return object Response from the CloudPayments API. + */ + public function updateNotificationSettings(string $notificationType, bool $isEnabled = null, string $address = null, string $httpMethod = null, string $encoding = null, string $format = null): object + { + $endpoint = "/site/notifications/$notificationType/update"; + $requestData = [ + "Type" => $notificationType, + "IsEnabled" => $isEnabled, + "Address" => $address, + "HttpMethod" => $httpMethod, + "Encoding" => $encoding, + "Format" => $format, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Initiates an Apple Pay session. + * + * @param string $validationUrl Validation URL for Apple Pay. + * @param string|null $paymentUrl Payment URL for Apple Pay. + * @link https://developers.cloudpayments.ru/en/#start-of-apple-pay-session + * @return object Response from the CloudPayments API. + */ + public function startApplePaySession(string $validationUrl, string|null $paymentUrl = null): object + { + $endpoint = '/applepay/startsession'; + $requestData = [ + "ValidationUrl" => $validationUrl, + "PaymentUrl" => $paymentUrl, + ]; + return $this->httpClient->sendRequest($endpoint, $requestData); + } + + /** + * Sets the localization for the API requests. + * + * @param string $cultureName The culture name for localization. + * @link https://developers.cloudpayments.ru/en/#localization + * @return void + */ + public function setLocalization(string $cultureName): void + { + $this->cultureName = $cultureName; + } + + /** + * Creates a long record for CloudPayments API. + * + * @param string $ticketNumber Ticket number for the record. + * @param string $bookingRef Booking reference for the record. + * @param array $legs Array of legs for the record. + * @param array $passengers Array of passengers for the record. + * + * @return array CloudPayments long record. + */ + public function createLongRecord(string $ticketNumber, string $bookingRef, array $legs, array $passengers): array + { + return [ + "TicketNumber" => $ticketNumber, + "BookingRef" => $bookingRef, + "Legs" => $legs, + "Passengers" => $passengers, + ]; + } + + /** + * Cancels a payment transaction. + * + * @param string $transactionId Transaction ID to cancel. + * @link https://developers.cloudpayments.ru/en/#payment-cancellation + * @return object Response from the CloudPayments API. + */ + public function cancelPayment(string $transactionId): object + { + $endpoint = '/payments/void'; + $requestData = [ + "TransactionId" => $transactionId, + ]; + + return $this->httpClient->sendRequest($endpoint, $requestData); + } +} \ No newline at end of file diff --git a/src/Http/HttpClient.php b/src/Http/HttpClient.php new file mode 100644 index 0000000..edcd085 --- /dev/null +++ b/src/Http/HttpClient.php @@ -0,0 +1,101 @@ +curl = new Curl(); + } + + /** + * Sends an HTTP request to the CloudPayments API. + * + * @param string|null $url Relative URL for the API endpoint. + * @param array|null $data Data to be sent in the request body. + * @param string $method HTTP method for the request (default is "POST"). + * + * @return object Response object with status, data, message, and code. + */ + public function sendRequest(?string $url = null, ?array $data = null, string $method = "POST"): object + { + $responseObject = new \stdClass(); + $responseObject->status = false; + $responseObject->data = null; + + if(!$data) { + $responseObject->message = 'Invalid data params.'; + $responseObject->code = 400; + return $responseObject; + } + + try { + $fullUrl = $this->apiUrl ? $this->apiUrl . $url : $url; + + $ua = $_SERVER['HTTP_USER_AGENT'] ?? 'CloudPayments PHP Client'; + + $headers = [ + "Content-Type: application/json", + "User-Agent: $ua", + ]; + + $this->curl->setOpt(CURLOPT_RETURNTRANSFER, true); + $this->curl->setOpt(CURLOPT_FOLLOWLOCATION, true); + $this->curl->setOpt(CURLOPT_SSL_VERIFYHOST, $this->enableSSL ? 2 : 0); + $this->curl->setOpt(CURLOPT_SSL_VERIFYPEER, $this->enableSSL); + + $this->curl->setOpt(CURLOPT_CUSTOMREQUEST, $method); + $this->curl->setOpt(CURLOPT_URL, $fullUrl); + $this->curl->setOpt(CURLOPT_POSTFIELDS, json_encode($data)); + $this->curl->setOpt(CURLOPT_HTTPHEADER, $headers); + + $this->curl->setBasicAuthentication($this->publicKey, $this->apiSecret); + + $response = $this->curl->exec(); + + $responseObject->code = $this->curl->getHttpStatusCode(); + $responseObject->data = $response; + + if($this->curl->error) { + $responseObject->message = $this->curl->getCurlErrorMessage(); + $responseObject->code = $this->curl->getCurlErrorCode(); + } else { + $responseObject->status = true; + $responseObject->message = 'OK'; + } + } catch (\Exception $exception) { + $responseObject->message = $exception->getMessage(); + $responseObject->code = $exception->getCode(); + } finally { + $this->curl->close(); + } + + return $responseObject; + } +} diff --git a/tests/CloudPaymentsTest.php b/tests/CloudPaymentsTest.php new file mode 100644 index 0000000..c911bd7 --- /dev/null +++ b/tests/CloudPaymentsTest.php @@ -0,0 +1,35 @@ +cloudPayments = new CloudPayments('pk_123456abcedf', 'abcdefg'); + } + + public function testSendTestRequest(): void + { + $testData = [ + 'key' => 'value', + ]; + + $result = $this->cloudPayments->sendTestRequest($testData); + + $this->assertInstanceOf(\stdClass::class, $result); + } + +} \ No newline at end of file diff --git a/tests/HttpClientTest.php b/tests/HttpClientTest.php new file mode 100644 index 0000000..5cf4ea7 --- /dev/null +++ b/tests/HttpClientTest.php @@ -0,0 +1,27 @@ + 'value']; + + $result = $httpClient->sendRequest($endpoint, $data, 'GET'); + + $this->assertInstanceOf(\stdClass::class, $result); + $this->assertObjectHasProperty('status', $result); + $this->assertFalse($result->status); + + } + +} \ No newline at end of file