Initial Commit

This commit is contained in:
2024-02-08 12:07:49 -07:00
parent 5813b1109f
commit 43077b57ed
5471 changed files with 682195 additions and 0 deletions
+770
View File
@@ -0,0 +1,770 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa;
use Exception;
use InvalidArgumentException;
use YooKassa\Client\BaseClient;
use YooKassa\Common\Exceptions\ApiConnectionException;
use YooKassa\Common\Exceptions\ApiException;
use YooKassa\Common\Exceptions\AuthorizeException;
use YooKassa\Common\Exceptions\BadApiRequestException;
use YooKassa\Common\Exceptions\ExtensionNotFoundException;
use YooKassa\Common\Exceptions\ForbiddenException;
use YooKassa\Common\Exceptions\InternalServerError;
use YooKassa\Common\Exceptions\NotFoundException;
use YooKassa\Common\Exceptions\ResponseProcessingException;
use YooKassa\Common\Exceptions\TooManyRequestsException;
use YooKassa\Common\Exceptions\UnauthorizedException;
use YooKassa\Common\HttpVerb;
use YooKassa\Helpers\TypeCast;
use YooKassa\Helpers\UUID;
use YooKassa\Model\PaymentInterface;
use YooKassa\Model\RefundInterface;
use YooKassa\Model\Webhook\Webhook;
use YooKassa\Request\Payments\CreatePaymentRequest;
use YooKassa\Request\Payments\CreatePaymentRequestInterface;
use YooKassa\Request\Payments\CreatePaymentResponse;
use YooKassa\Request\Payments\CreatePaymentRequestSerializer;
use YooKassa\Request\Payments\Payment\CancelResponse;
use YooKassa\Request\Payments\Payment\CreateCaptureRequest;
use YooKassa\Request\Payments\Payment\CreateCaptureRequestInterface;
use YooKassa\Request\Payments\Payment\CreateCaptureRequestSerializer;
use YooKassa\Request\Payments\Payment\CreateCaptureResponse;
use YooKassa\Request\Payments\PaymentResponse;
use YooKassa\Request\Payments\PaymentsRequest;
use YooKassa\Request\Payments\PaymentsRequestInterface;
use YooKassa\Request\Payments\PaymentsRequestSerializer;
use YooKassa\Request\Payments\PaymentsResponse;
use YooKassa\Request\Receipts\AbstractReceiptResponse;
use YooKassa\Request\Receipts\CreatePostReceiptRequest;
use YooKassa\Request\Receipts\CreatePostReceiptRequestInterface;
use YooKassa\Request\Receipts\CreatePostReceiptRequestSerializer;
use YooKassa\Request\Receipts\ReceiptResponseFactory;
use YooKassa\Request\Receipts\ReceiptsRequest;
use YooKassa\Request\Receipts\ReceiptsRequestSerializer;
use YooKassa\Request\Receipts\ReceiptsResponse;
use YooKassa\Request\Refunds\CreateRefundRequest;
use YooKassa\Request\Refunds\CreateRefundRequestInterface;
use YooKassa\Request\Refunds\CreateRefundRequestSerializer;
use YooKassa\Request\Refunds\CreateRefundResponse;
use YooKassa\Request\Refunds\RefundResponse;
use YooKassa\Request\Refunds\RefundsRequest;
use YooKassa\Request\Refunds\RefundsRequestInterface;
use YooKassa\Request\Refunds\RefundsRequestSerializer;
use YooKassa\Request\Refunds\RefundsResponse;
use YooKassa\Request\Webhook\WebhookListResponse;
/**
* Класс клиента API
*
* @package YooKassa
*
* @since 1.0.1
*/
class Client extends BaseClient
{
/**
* Текущая версия библиотеки
*/
const SDK_VERSION = '2.0.7';
/**
* Получить список платежей магазина.
*
* @param PaymentsRequestInterface|array|null $filter
*
* @return PaymentsResponse
* @throws ApiException
* @throws BadApiRequestException
* @throws ForbiddenException
* @throws InternalServerError
* @throws NotFoundException
* @throws ResponseProcessingException
* @throws TooManyRequestsException
* @throws UnauthorizedException
* @throws ExtensionNotFoundException
* @throws Exception
*/
public function getPayments($filter = null)
{
$path = self::PAYMENTS_PATH;
if ($filter === null) {
$queryParams = array();
} else {
if (is_array($filter)) {
$filter = PaymentsRequest::builder()->build($filter);
}
$serializer = new PaymentsRequestSerializer();
$queryParams = $serializer->serialize($filter);
}
$response = $this->execute($path, HttpVerb::GET, $queryParams);
$paymentResponse = null;
if ($response->getCode() == 200) {
$responseArray = $this->decodeData($response);
$paymentResponse = new PaymentsResponse($responseArray);
} else {
$this->handleError($response);
}
return $paymentResponse;
}
/**
* Создание платежа.
*
* Чтобы принять оплату, необходимо создать объект платежа — `Payment`. Он содержит всю необходимую информацию
* для проведения оплаты (сумму, валюту и статус). У платежа линейный жизненный цикл, он последовательно
* переходит из статуса в статус.
*
* Необходимо указать один из параметров:
* <ul>
* <li>payment_token — оплата по одноразовому PaymentToken, сформированному виджетом YooKassa JS;</li>
* <li>payment_method_id — оплата по сохраненным платежным данным;</li>
* <li>payment_method_data — оплата по новым платежным данным.</li>
* </ul>
*
* Если не указан ни один параметр и `confirmation.type = redirect`, то в качестве `confirmation_url`
* возвращается ссылка, по которой пользователь сможет самостоятельно выбрать подходящий способ оплаты.
* Дополнительные параметры:
* <ul>
* <li>confirmation — передается, если необходимо уточнить способ подтверждения платежа;</li>
* <li>recipient — указывается при наличии нескольких товаров;</li>
* <li>metadata — дополнительные данные (передаются магазином).</li>
* </ul>
*
* @param CreatePaymentRequestInterface|array $payment
* @param string|null $idempotenceKey {@link https://yookassa.ru/developers/using-api/basics?lang=php#idempotence}
*
* @return CreatePaymentResponse
* @throws ApiException
* @throws BadApiRequestException
* @throws ForbiddenException
* @throws InternalServerError
* @throws NotFoundException
* @throws ResponseProcessingException
* @throws TooManyRequestsException
* @throws UnauthorizedException
* @throws Exception
*/
public function createPayment($payment, $idempotenceKey = null)
{
$path = self::PAYMENTS_PATH;
$headers = array();
if ($idempotenceKey) {
$headers[self::IDEMPOTENCY_KEY_HEADER] = $idempotenceKey;
} else {
$headers[self::IDEMPOTENCY_KEY_HEADER] = UUID::v4();
}
if (is_array($payment)) {
$payment = CreatePaymentRequest::builder()->build($payment);
}
$serializer = new CreatePaymentRequestSerializer();
$serializedData = $serializer->serialize($payment);
$httpBody = $this->encodeData($serializedData);
$response = $this->execute($path, HttpVerb::POST, null, $httpBody, $headers);
$paymentResponse = null;
if ($response->getCode() == 200) {
$resultArray = $this->decodeData($response);
$paymentResponse = new CreatePaymentResponse($resultArray);
} else {
$this->handleError($response);
}
return $paymentResponse;
}
/**
* Получить информацию о платеже
*
* Выдает объект платежа {@link PaymentInterface} по его уникальному идентификатору.
*
* @param string $paymentId
*
* @return PaymentInterface
* @throws ApiException
* @throws BadApiRequestException
* @throws ForbiddenException
* @throws InternalServerError
* @throws NotFoundException
* @throws ResponseProcessingException
* @throws TooManyRequestsException
* @throws UnauthorizedException
* @throws ExtensionNotFoundException
*/
public function getPaymentInfo($paymentId)
{
if ($paymentId === null) {
throw new \InvalidArgumentException('Missing the required parameter $paymentId');
} elseif (!TypeCast::canCastToString($paymentId)) {
throw new \InvalidArgumentException('Invalid paymentId value: string required');
} elseif (strlen($paymentId) !== 36) {
throw new \InvalidArgumentException('Invalid paymentId value');
}
$path = self::PAYMENTS_PATH.'/'.$paymentId;
$response = $this->execute($path, HttpVerb::GET, null);
$result = null;
if ($response->getCode() == 200) {
$resultArray = $this->decodeData($response);
$result = new PaymentResponse($resultArray);
} else {
$this->handleError($response);
}
return $result;
}
/**
* Подтверждение платежа
*
* Подтверждает вашу готовность принять платеж. Платеж можно подтвердить, только если он находится
* в статусе `waiting_for_capture`. Если платеж подтвержден успешно — значит, оплата прошла, и вы можете выдать
* товар или оказать услугу пользователю. На следующий день после подтверждения платеж попадет в реестр,
* и ЮKassa переведет деньги на ваш расчетный счет. Если вы не подтверждаете платеж до момента, указанного
* в `expire_at`, по умолчанию он отменяется, а деньги возвращаются пользователю. При оплате банковской картой
* у вас есть 7 дней на подтверждение платежа. Для остальных способов оплаты платеж необходимо подтвердить
* в течение 6 часов.
*
* @param CreateCaptureRequestInterface|array $captureRequest
* @param $paymentId
* @param $idempotencyKey {@link https://yookassa.ru/developers/using-api/basics?lang=php#idempotence}
*
* @return CreateCaptureResponse
* @throws ApiException
* @throws BadApiRequestException
* @throws ForbiddenException
* @throws InternalServerError
* @throws NotFoundException
* @throws ResponseProcessingException
* @throws TooManyRequestsException
* @throws UnauthorizedException
* @throws Exception
*/
public function capturePayment($captureRequest, $paymentId, $idempotencyKey = null)
{
if ($paymentId === null) {
throw new \InvalidArgumentException('Missing the required parameter $paymentId');
} elseif (!TypeCast::canCastToString($paymentId)) {
throw new \InvalidArgumentException('Invalid paymentId value: string required');
} elseif (strlen($paymentId) !== 36) {
throw new \InvalidArgumentException('Invalid paymentId value');
}
$path = '/payments/'.$paymentId.'/capture';
$headers = array();
if ($idempotencyKey) {
$headers[self::IDEMPOTENCY_KEY_HEADER] = $idempotencyKey;
} else {
$headers[self::IDEMPOTENCY_KEY_HEADER] = UUID::v4();
}
if (is_array($captureRequest)) {
$captureRequest = CreateCaptureRequest::builder()->build($captureRequest);
}
$serializer = new CreateCaptureRequestSerializer();
$serializedData = $serializer->serialize($captureRequest);
$httpBody = $this->encodeData($serializedData);
$response = $this->execute($path, HttpVerb::POST, null, $httpBody, $headers);
$result = null;
if ($response->getCode() == 200) {
$resultArray = $this->decodeData($response);
$result = new CreateCaptureResponse($resultArray);
} else {
$this->handleError($response);
}
return $result;
}
/**
* Отменить незавершенную оплату заказа.
*
* Отменяет платеж, находящийся в статусе `waiting_for_capture`. Отмена платежа значит, что вы
* не готовы выдать пользователю товар или оказать услугу. Как только вы отменяете платеж, мы начинаем
* возвращать деньги на счет плательщика. Для платежей банковскими картами отмена происходит мгновенно.
* Для остальных способов оплаты возврат может занимать до нескольких дней.
*
* @param $paymentId
* @param $idempotencyKey {@link https://yookassa.ru/developers/using-api/basics?lang=php#idempotence}
*
* @return CancelResponse
* @throws ApiException
* @throws BadApiRequestException
* @throws ForbiddenException
* @throws InternalServerError
* @throws NotFoundException
* @throws ResponseProcessingException
* @throws TooManyRequestsException
* @throws UnauthorizedException
* @throws Exception
*/
public function cancelPayment($paymentId, $idempotencyKey = null)
{
if ($paymentId === null) {
throw new \InvalidArgumentException('Missing the required parameter $paymentId');
} elseif (!TypeCast::canCastToString($paymentId)) {
throw new \InvalidArgumentException('Invalid paymentId value: string required');
} elseif (strlen($paymentId) !== 36) {
throw new \InvalidArgumentException('Invalid paymentId value');
}
$path = self::PAYMENTS_PATH.'/'.$paymentId.'/cancel';
$headers = array();
if ($idempotencyKey) {
$headers[self::IDEMPOTENCY_KEY_HEADER] = $idempotencyKey;
} else {
$headers[self::IDEMPOTENCY_KEY_HEADER] = UUID::v4();
}
$response = $this->execute($path, HttpVerb::POST, null, null, $headers);
$result = null;
if ($response->getCode() == 200) {
$resultArray = $this->decodeData($response);
$result = new CancelResponse($resultArray);
} else {
$this->handleError($response);
}
return $result;
}
/**
* Получить список возвратов платежей
*
* @param RefundsRequestInterface|array|null $filter
*
* @return RefundsResponse
* @throws ApiException
* @throws BadApiRequestException
* @throws ForbiddenException
* @throws InternalServerError
* @throws NotFoundException
* @throws ResponseProcessingException
* @throws TooManyRequestsException
* @throws UnauthorizedException
* @throws ExtensionNotFoundException
*/
public function getRefunds($filter = null)
{
$path = self::REFUNDS_PATH;
if ($filter === null) {
$queryParams = array();
} else {
if (is_array($filter)) {
$filter = RefundsRequest::builder()->build($filter);
}
$serializer = new RefundsRequestSerializer();
$queryParams = $serializer->serialize($filter);
}
$response = $this->execute($path, HttpVerb::GET, $queryParams);
$refundsResponse = null;
if ($response->getCode() == 200) {
$resultArray = $this->decodeData($response);
$refundsResponse = new RefundsResponse($resultArray);
} else {
$this->handleError($response);
}
return $refundsResponse;
}
/**
* Проведение возврата платежа
*
* Создает объект возврата — `Refund`. Возвращает успешно завершенный платеж по уникальному идентификатору
* этого платежа. Создание возврата возможно только для платежей в статусе `succeeded`. Комиссии за проведение
* возврата нет. Комиссия, которую ЮKassa берёт за проведение исходного платежа, не возвращается.
*
* @param CreateRefundRequestInterface|array $request
* @param null $idempotencyKey {@link https://yookassa.ru/developers/using-api/basics?lang=php#idempotence}
*
* @return CreateRefundResponse
* @throws ApiException
* @throws BadApiRequestException
* @throws ForbiddenException
* @throws InternalServerError
* @throws NotFoundException
* @throws ResponseProcessingException
* @throws TooManyRequestsException
* @throws UnauthorizedException
* @throws Exception
*/
public function createRefund($request, $idempotencyKey = null)
{
$path = self::REFUNDS_PATH;
$headers = array();
if ($idempotencyKey) {
$headers[self::IDEMPOTENCY_KEY_HEADER] = $idempotencyKey;
} else {
$headers[self::IDEMPOTENCY_KEY_HEADER] = UUID::v4();
}
if (is_array($request)) {
$request = CreateRefundRequest::builder()->build($request);
}
$serializer = new CreateRefundRequestSerializer();
$serializedData = $serializer->serialize($request);
$httpBody = $this->encodeData($serializedData);
$response = $this->execute($path, HttpVerb::POST, null, $httpBody, $headers);
$result = null;
if ($response->getCode() == 200) {
$resultArray = $this->decodeData($response);
$result = new CreateRefundResponse($resultArray);
} else {
$this->handleError($response);
}
return $result;
}
/**
* Получить информацию о возврате
*
* @param $refundId
*
* @return RefundResponse
* @throws ApiException
* @throws BadApiRequestException
* @throws ForbiddenException
* @throws InternalServerError
* @throws NotFoundException
* @throws ResponseProcessingException
* @throws TooManyRequestsException
* @throws UnauthorizedException
* @throws ExtensionNotFoundException
*/
public function getRefundInfo($refundId)
{
if ($refundId === null) {
throw new \InvalidArgumentException('Missing the required parameter $refundId');
} elseif (!TypeCast::canCastToString($refundId)) {
throw new \InvalidArgumentException('Invalid refundId value: string required');
} elseif (strlen($refundId) !== 36) {
throw new \InvalidArgumentException('Invalid refundId value');
}
$path = self::REFUNDS_PATH.'/'.$refundId;
$response = $this->execute($path, HttpVerb::GET, null);
$result = null;
if ($response->getCode() == 200) {
$resultArray = $this->decodeData($response);
$result = new RefundResponse($resultArray);
} else {
$this->handleError($response);
}
return $result;
}
/**
* Создание Webhook
* Запрос позволяет подписаться на уведомления о событии (например, на переход платежа в статус successed).
*
* @param $request
* @param null $idempotencyKey
* @return Webhook|null
*
* @throws ApiException
* @throws BadApiRequestException
* @throws AuthorizeException
* @throws ForbiddenException
* @throws InternalServerError
* @throws NotFoundException
* @throws ResponseProcessingException
* @throws TooManyRequestsException
* @throws UnauthorizedException
* @throws Exception
*/
public function addWebhook($request, $idempotencyKey = null)
{
$path = self::WEBHOOKS_PATH;
$headers = array();
if ($idempotencyKey) {
$headers[self::IDEMPOTENCY_KEY_HEADER] = $idempotencyKey;
} else {
$headers[self::IDEMPOTENCY_KEY_HEADER] = UUID::v4();
}
if (is_array($request)) {
$webhook = new Webhook($request);
} else {
$webhook = $request;
}
if (!($webhook instanceof Webhook)) {
throw new InvalidArgumentException();
}
$httpBody = $this->encodeData($webhook->jsonSerialize());
$response = $this->execute($path, HttpVerb::POST, null, $httpBody, $headers);
$result = null;
if ($response->getCode() == 200) {
$resultArray = $this->decodeData($response);
$result = new Webhook($resultArray);
} else {
$this->handleError($response);
}
return $result;
}
/**
* Удаление Webhook
* Запрос позволяет отписаться от уведомлений о событии для переданного OAuth-токена. Чтобы удалить webhook, вам нужно передать в запросе его идентификатор.
*
* @param $webhookId
* @param null $idempotencyKey
* @return Webhook|null
*
* @throws ApiException
* @throws BadApiRequestException
* @throws AuthorizeException
* @throws ForbiddenException
* @throws InternalServerError
* @throws NotFoundException
* @throws ResponseProcessingException
* @throws TooManyRequestsException
* @throws UnauthorizedException
* @throws Exception
*/
public function removeWebhook($webhookId, $idempotencyKey = null)
{
$headers = array();
if ($idempotencyKey) {
$headers[self::IDEMPOTENCY_KEY_HEADER] = $idempotencyKey;
} else {
$headers[self::IDEMPOTENCY_KEY_HEADER] = UUID::v4();
}
$path = self::WEBHOOKS_PATH.'/'.$webhookId;
$response = $this->execute($path, HttpVerb::DELETE, null, null, $headers);
$result = null;
if ($response->getCode() == 200) {
$resultArray = $this->decodeData($response);
$result = new Webhook($resultArray);
} else {
$this->handleError($response);
}
return $result;
}
/**
* Список созданных Webhook
* Запрос позволяет узнать, какие webhook есть для переданного OAuth-токена.
*
* @return WebhookListResponse|null
*
* @throws ApiException
* @throws BadApiRequestException
* @throws AuthorizeException
* @throws ForbiddenException
* @throws InternalServerError
* @throws NotFoundException
* @throws ResponseProcessingException
* @throws TooManyRequestsException
* @throws UnauthorizedException
* @throws ExtensionNotFoundException
*/
public function getWebhooks()
{
$path = self::WEBHOOKS_PATH;
$response = $this->execute($path, HttpVerb::GET, null);
$result = null;
if ($response->getCode() == 200) {
$responseArray = $this->decodeData($response);
$result = new WebhookListResponse($responseArray);
} else {
$this->handleError($response);
}
return $result;
}
/**
* Получить список платежей магазина.
*
* @param PaymentInterface|RefundInterface|array|null $filter
*
* @return ReceiptsResponse
*
* @throws ApiException
* @throws BadApiRequestException
* @throws ForbiddenException
* @throws InternalServerError
* @throws NotFoundException
* @throws ResponseProcessingException
* @throws TooManyRequestsException
* @throws UnauthorizedException
* @throws ExtensionNotFoundException
* @throws Exception
*/
public function getReceipts($filter = null)
{
$path = self::RECEIPTS_PATH;
if ($filter === null) {
$queryParams = array();
} else {
if (is_array($filter)) {
$filter = ReceiptsRequest::builder()->build($filter);
}
$serializer = new ReceiptsRequestSerializer();
$queryParams = $serializer->serialize($filter);
}
$response = $this->execute($path, HttpVerb::GET, $queryParams);
$receiptsResponse = null;
if ($response->getCode() == 200) {
$responseArray = $this->decodeData($response);
$receiptsResponse = new ReceiptsResponse($responseArray);
} else {
$this->handleError($response);
}
return $receiptsResponse;
}
/**
* @param CreatePostReceiptRequestInterface|array $receipt
* @param string|null $idempotenceKey
*
* @return AbstractReceiptResponse|null
*
* @throws ApiException
* @throws BadApiRequestException
* @throws ApiConnectionException
* @throws AuthorizeException
* @throws ForbiddenException
* @throws InternalServerError
* @throws NotFoundException
* @throws ResponseProcessingException
* @throws TooManyRequestsException
* @throws UnauthorizedException
* @throws Exception
*/
public function createReceipt($receipt, $idempotenceKey = null)
{
$path = self::RECEIPTS_PATH;
$headers = array();
if ($idempotenceKey) {
$headers[self::IDEMPOTENCY_KEY_HEADER] = $idempotenceKey;
} else {
$headers[self::IDEMPOTENCY_KEY_HEADER] = UUID::v4();
}
if (is_array($receipt)) {
$receipt = CreatePostReceiptRequest::builder()->build($receipt);
}
$serializer = new CreatePostReceiptRequestSerializer();
$serializedData = $serializer->serialize($receipt);
$httpBody = $this->encodeData($serializedData);
$response = $this->execute($path, HttpVerb::POST, null, $httpBody, $headers);
$receiptResponse = null;
if ($response->getCode() == 200) {
$resultArray = $this->decodeData($response);
$factory = new ReceiptResponseFactory();
$receiptResponse = $factory->factory($resultArray);
} else {
$this->handleError($response);
}
return $receiptResponse;
}
/**
* Информация о магазине
* Запрос позволяет получить информацию о магазине для переданного OAuth-токена.
*
* @return array|null
*
* @throws ApiException
* @throws BadApiRequestException
* @throws AuthorizeException
* @throws ForbiddenException
* @throws InternalServerError
* @throws NotFoundException
* @throws ResponseProcessingException
* @throws TooManyRequestsException
* @throws UnauthorizedException
* @throws ExtensionNotFoundException
*/
public function me()
{
$path = self::ME_PATH;
$response = $this->execute($path, HttpVerb::GET, null);
$result = null;
if ($response->getCode() == 200) {
$responseArray = $this->decodeData($response);
$result = $responseArray;
} else {
$this->handleError($response);
}
return $result;
}
}
@@ -0,0 +1,79 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Client;
use Psr\Log\LoggerInterface;
/**
* Interface ApiClientInterface
* @package YooKassa\Client
*/
interface ApiClientInterface
{
/**
* @param $path
* @param $method
* @param $queryParams
* @param $httpBody
* @param $headers
* @return mixed
*/
public function call($path, $method, $queryParams, $httpBody = null, $headers = array());
/**
* @param LoggerInterface|null $logger
*/
public function setLogger($logger);
/**
* @return UserAgent
*/
public function getUserAgent();
/**
* @param $shopId
* @return mixed
*/
public function setShopId($shopId);
/**
* @param $shopPassword
* @return mixed
*/
public function setShopPassword($shopPassword);
/**
* @param $bearerToken
* @return mixed
*/
public function setBearerToken($bearerToken);
/**
* @param array $config
*/
public function setConfig($config);
}
@@ -0,0 +1,410 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Client;
use Exception;
use Psr\Log\LoggerInterface;
use YooKassa\Common\Exceptions\ApiConnectionException;
use YooKassa\Common\Exceptions\ApiException;
use YooKassa\Common\Exceptions\AuthorizeException;
use YooKassa\Common\Exceptions\BadApiRequestException;
use YooKassa\Common\Exceptions\ExtensionNotFoundException;
use YooKassa\Common\Exceptions\ForbiddenException;
use YooKassa\Common\Exceptions\InternalServerError;
use YooKassa\Common\Exceptions\JsonException;
use YooKassa\Common\Exceptions\NotFoundException;
use YooKassa\Common\Exceptions\ResponseProcessingException;
use YooKassa\Common\Exceptions\TooManyRequestsException;
use YooKassa\Common\Exceptions\UnauthorizedException;
use YooKassa\Common\LoggerWrapper;
use YooKassa\Common\ResponseObject;
use YooKassa\Helpers\Config\ConfigurationLoader;
use YooKassa\Helpers\Config\ConfigurationLoaderInterface;
class BaseClient
{
const PAYMENTS_PATH = '/payments';
const REFUNDS_PATH = '/refunds';
const WEBHOOKS_PATH = '/webhooks';
const RECEIPTS_PATH = '/receipts';
const ME_PATH = '/me';
/**
* Имя HTTP заголовка, используемого для передачи idempotence key
*/
const IDEMPOTENCY_KEY_HEADER = 'Idempotence-Key';
/**
* Значение по умолчанию времени ожидания между запросами при отправке повторного запроса в случае получения
* ответа с HTTP статусом 202
*/
const DEFAULT_DELAY = 1800;
/**
* Значение по умолчанию количества попыток получения информации от API если пришёл ответ с HTTP статусом 202
*/
const DEFAULT_TRIES_COUNT = 3;
/**
* Значение по умолчанию количества попыток получения информации от API если пришёл ответ с HTTP статусом 202
*/
const DEFAULT_ATTEMPTS_COUNT = 3;
/**
* @var null|ApiClientInterface
*/
protected $apiClient;
/**
* @var string
*/
protected $login;
/**
* @var string
*/
protected $password;
/**
* @var array
*/
protected $config;
/**
* Время через которое будут осуществляться повторные запросы
* Значение по умолчанию - 1800 миллисекунд.
* @var int значение в миллисекундах
*/
protected $timeout;
/**
* Количество повторных запросов при ответе API статусом 202
* Значение по умолчанию 3
* @var int
*/
protected $attempts;
/**
* @var LoggerInterface|null
*/
protected $logger;
/**
* Constructor
*
* @param ApiClientInterface|null $apiClient
* @param ConfigurationLoaderInterface|null $configLoader
*/
public function __construct(ApiClientInterface $apiClient = null, ConfigurationLoaderInterface $configLoader = null)
{
if ($apiClient === null) {
$apiClient = new CurlClient();
}
if ($configLoader === null) {
$configLoader = new ConfigurationLoader();
}
$config = $configLoader->load()->getConfig();
$this->setConfig($config);
$apiClient->setConfig($config);
$this->attempts = self::DEFAULT_ATTEMPTS_COUNT;
$this->apiClient = $apiClient;
}
/**
* @param $login
* @param $password
*
* @return static $this
*/
public function setAuth($login, $password)
{
$this->login = $login;
$this->password = $password;
$this->apiClient
->setBearerToken(null)
->setShopId($this->login)
->setShopPassword($this->password);
return $this;
}
/**
* @param $token
*
* @return $this
*/
public function setAuthToken($token)
{
$this->apiClient
->setShopId(null)
->setShopPassword(null)
->setBearerToken($token);
return $this;
}
/**
* @return ApiClientInterface
*/
public function getApiClient()
{
return $this->apiClient;
}
/**
* @param ApiClientInterface $apiClient
*
* @return static $this
*/
public function setApiClient(ApiClientInterface $apiClient)
{
$this->apiClient = $apiClient;
$this->apiClient->setConfig($this->config);
$this->apiClient->setLogger($this->logger);
return $this;
}
/**
* Устанавливает логгер приложения
*
* @param null|callable|object|LoggerInterface $value Инстанс логгера
*/
public function setLogger($value)
{
if ($value === null || $value instanceof LoggerInterface) {
$this->logger = $value;
} else {
$this->logger = new LoggerWrapper($value);
}
if ($this->apiClient !== null) {
$this->apiClient->setLogger($this->logger);
}
}
/**
* @return array
*/
public function getConfig()
{
return $this->config;
}
/**
* @param array $config
*/
public function setConfig($config)
{
$this->config = $config;
}
/**
* Установка значение задержки между повторными запросами
*
* @param int $timeout
*
* @return static
*/
public function setRetryTimeout($timeout)
{
$this->timeout = $timeout;
return $this;
}
/**
* Установка значения количества попыток повторных запросов при статусе 202
*
* @param int $attempts
*
* @return static
*/
public function setMaxRequestAttempts($attempts)
{
$this->attempts = $attempts;
return $this;
}
/**
* @param $serializedData
*
* @return string
* @throws Exception
*/
protected function encodeData($serializedData)
{
if ($serializedData === array()) {
return '{}';
}
if (defined('JSON_UNESCAPED_UNICODE') && defined('JSON_UNESCAPED_SLASHES')) {
$encoded = json_encode($serializedData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} else {
$encoded = self::_unescaped(json_encode($serializedData));
}
if ($encoded === false) {
$errorCode = json_last_error();
throw new JsonException("Failed serialize json.", $errorCode);
}
return $encoded;
}
/**
* @param string $json
* @return string|false
*/
private static function _unescaped($json)
{
if ($json === false) {
return false;
}
$json = str_replace('\\/', '/', $json);
return preg_replace_callback('/\\\\u(\w{4})/', function ($matches) {
return html_entity_decode('&#x' . $matches[1] . ';', ENT_COMPAT, 'UTF-8');
}, $json);
}
/**
* @param ResponseObject $response
*
* @return array
*/
protected function decodeData(ResponseObject $response)
{
$resultArray = json_decode($response->getBody(), true);
if ($resultArray === null) {
throw new JsonException('Failed to decode response', json_last_error());
}
return $resultArray;
}
/**
* @param ResponseObject $response
*
* @throws ApiException
* @throws BadApiRequestException
* @throws ForbiddenException
* @throws InternalServerError
* @throws NotFoundException
* @throws ResponseProcessingException
* @throws TooManyRequestsException
* @throws UnauthorizedException
*/
protected function handleError(ResponseObject $response)
{
switch ($response->getCode()) {
case BadApiRequestException::HTTP_CODE:
throw new BadApiRequestException($response->getHeaders(), $response->getBody());
break;
case ForbiddenException::HTTP_CODE:
throw new ForbiddenException($response->getHeaders(), $response->getBody());
break;
case UnauthorizedException::HTTP_CODE:
throw new UnauthorizedException($response->getHeaders(), $response->getBody());
break;
case InternalServerError::HTTP_CODE:
throw new InternalServerError($response->getHeaders(), $response->getBody());
break;
case NotFoundException::HTTP_CODE:
throw new NotFoundException($response->getHeaders(), $response->getBody());
break;
case TooManyRequestsException::HTTP_CODE:
throw new TooManyRequestsException($response->getHeaders(), $response->getBody());
break;
case ResponseProcessingException::HTTP_CODE:
throw new ResponseProcessingException($response->getHeaders(), $response->getBody());
break;
default:
if ($response->getCode() > 399) {
throw new ApiException(
'Unexpected response error code',
$response->getCode(),
$response->getHeaders(),
$response->getBody()
);
}
}
}
/**
* Задержка между повторными запросами
*
* @param $response
*/
protected function delay($response)
{
$timeout = $this->timeout;
$responseData = $this->decodeData($response);
if ($timeout) {
$delay = $timeout;
} else {
if (isset($responseData['retry_after'])) {
$delay = $responseData['retry_after'];
} else {
$delay = self::DEFAULT_DELAY;
}
}
usleep($delay * 1000);
}
/**
* Выполнение запроса и обработка 202 статуса
*
* @param $path
* @param $method
* @param $queryParams
* @param null $httpBody
* @param array $headers
*
* @return mixed|ResponseObject
* @throws ApiException
* @throws AuthorizeException
* @throws ApiConnectionException
* @throws ExtensionNotFoundException
*/
protected function execute($path, $method, $queryParams, $httpBody = null, $headers = array())
{
$attempts = $this->attempts;
$response = $this->apiClient->call($path, $method, $queryParams, $httpBody, $headers);
while (in_array($response->getCode(), array(202, 500)) && $attempts > 0) {
$this->delay($response);
$attempts--;
$response = $this->apiClient->call($path, $method, $queryParams, $httpBody, $headers);
}
return $response;
}
}
@@ -0,0 +1,527 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Client;
use Psr\Log\LoggerInterface;
use YooKassa\Common\Exceptions\ApiConnectionException;
use YooKassa\Common\Exceptions\ApiException;
use YooKassa\Common\Exceptions\AuthorizeException;
use YooKassa\Common\Exceptions\ExtensionNotFoundException;
use YooKassa\Common\ResponseObject;
use YooKassa\Helpers\RawHeadersParser;
/**
* Class CurlClient
* @package YooKassa\Client
*/
class CurlClient implements ApiClientInterface
{
/**
* @var array
*/
private $config;
/**
* @var string
*/
private $shopId;
/**
* @var string
*/
private $shopPassword;
/**
* @var string
*/
private $bearerToken;
/**
* @var int
*/
private $timeout = 80;
/**
* @var int
*/
private $connectionTimeout = 30;
/**
* @var string
*/
private $proxy;
/** @var UserAgent */
private $userAgent;
/**
* @var bool
*/
private $keepAlive = true;
/**
* @var array
*/
private $defaultHeaders = array(
'Content-Type' => 'application/json',
'Accept' => 'application/json',
);
/**
* @var resource
*/
private $curl;
/**
* @var LoggerInterface|null
*/
private $logger;
/**
* CurlClient constructor.
*/
public function __construct()
{
$this->userAgent = new UserAgent();
}
/**
* @param LoggerInterface|null $logger
*/
public function setLogger($logger)
{
$this->logger = $logger;
}
/**
* @inheritdoc
*
* @param $path
* @param $method
* @param $queryParams
* @param null $httpBody
* @param array $headers
*
* @return ResponseObject
* @throws ApiConnectionException
* @throws ApiException
* @throws AuthorizeException
* @throws ExtensionNotFoundException
*/
public function call($path, $method, $queryParams, $httpBody = null, $headers = array())
{
$headers = $this->prepareHeaders($headers);
$this->logRequestParams($path, $method, $queryParams, $httpBody, $headers);
$url = $this->prepareUrl($path, $queryParams);
$this->prepareCurl($method, $httpBody, $this->implodeHeaders($headers), $url);
list($httpHeaders, $httpBody, $responseInfo) = $this->sendRequest();
if (!$this->keepAlive) {
$this->closeCurlConnection();
}
$this->logResponse($httpBody, $responseInfo, $httpHeaders);
return new ResponseObject(array(
'code' => $responseInfo['http_code'],
'headers' => $httpHeaders,
'body' => $httpBody,
));
}
/**
* @param $optionName
* @param $optionValue
*
* @return bool
*/
public function setCurlOption($optionName, $optionValue)
{
return curl_setopt($this->curl, $optionName, $optionValue);
}
/**
* @return resource
* @throws ExtensionNotFoundException
*/
private function initCurl()
{
if (!extension_loaded('curl')) {
throw new ExtensionNotFoundException('curl');
}
if (!$this->curl || !$this->keepAlive) {
$this->curl = curl_init();
}
return $this->curl;
}
/**
* Close connection
*/
public function closeCurlConnection()
{
if ($this->curl !== null) {
curl_close($this->curl);
}
}
/**
* @return array
* @throws ApiConnectionException
*/
public function sendRequest()
{
$response = curl_exec($this->curl);
$httpHeaderSize = curl_getinfo($this->curl, CURLINFO_HEADER_SIZE);
$httpHeaders = RawHeadersParser::parse(substr($response, 0, $httpHeaderSize));
$httpBody = substr($response, $httpHeaderSize);
$responseInfo = curl_getinfo($this->curl);
$curlError = curl_error($this->curl);
$curlErrno = curl_errno($this->curl);
if ($response === false) {
$this->handleCurlError($curlError, $curlErrno);
}
return array($httpHeaders, $httpBody, $responseInfo);
}
/**
* @param $method
* @param $httpBody
*/
public function setBody($method, $httpBody)
{
$this->setCurlOption(CURLOPT_CUSTOMREQUEST, $method);
if(!empty($httpBody)) {
$this->setCurlOption(CURLOPT_POSTFIELDS, $httpBody);
}
}
/**
* @param mixed $shopId
*
* @return CurlClient
*/
public function setShopId($shopId)
{
$this->shopId = $shopId;
return $this;
}
/**
* @param mixed $shopPassword
*
* @return CurlClient
*/
public function setShopPassword($shopPassword)
{
$this->shopPassword = $shopPassword;
return $this;
}
/**
* @return mixed
*/
public function getTimeout()
{
return $this->timeout;
}
/**
* @param mixed $timeout
*/
public function setTimeout($timeout)
{
$this->timeout = $timeout;
}
/**
* @return mixed
*/
public function getConnectionTimeout()
{
return $this->connectionTimeout;
}
/**
* @param mixed $connectionTimeout
*/
public function setConnectionTimeout($connectionTimeout)
{
$this->connectionTimeout = $connectionTimeout;
}
/**
* @return string
* @since 1.0.14
*/
public function getProxy()
{
return $this->proxy;
}
/**
* @param string $proxy
*
* @since 1.0.14
*/
public function setProxy($proxy)
{
$this->proxy = $proxy;
}
/**
* @return mixed
*/
public function getConfig()
{
return $this->config;
}
/**
* @inheritDoc
*/
public function setConfig($config)
{
$this->config = $config;
}
/**
* @return UserAgent
*/
public function getUserAgent()
{
return $this->userAgent;
}
/**
* @param string $bearerToken
*
* @return static $this
*/
public function setBearerToken($bearerToken)
{
$this->bearerToken = $bearerToken;
return $this;
}
/**
* @param bool $keepAlive
*
* @return CurlClient
*/
public function setKeepAlive($keepAlive)
{
$this->keepAlive = $keepAlive;
return $this;
}
/**
* @param string $error
* @param int $errno
*
* @throws ApiConnectionException
*/
private function handleCurlError($error, $errno)
{
switch ($errno) {
case CURLE_COULDNT_CONNECT:
case CURLE_COULDNT_RESOLVE_HOST:
case CURLE_OPERATION_TIMEOUTED:
$msg = 'Could not connect to YooKassa API. Please check your internet connection and try again.';
break;
case CURLE_SSL_CACERT:
case CURLE_SSL_PEER_CERTIFICATE:
$msg = 'Could not verify SSL certificate.';
break;
default:
$msg = 'Unexpected error communicating.';
}
$msg .= "\n\n(Network error [errno $errno]: $error)";
throw new ApiConnectionException($msg);
}
/**
* @return mixed
*/
private function getUrl()
{
$config = $this->config;
return $config['url'];
}
/**
* @param $headers
*
* @return array
* @throws AuthorizeException
*/
private function prepareHeaders($headers)
{
$headers = array_merge($this->defaultHeaders, $headers);
$headers[UserAgent::HEADER] = $this->getUserAgent()->getHeaderString();
if ($this->shopId && $this->shopPassword) {
$encodedAuth = base64_encode($this->shopId . ':' . $this->shopPassword);
$headers['Authorization'] = 'Basic ' . $encodedAuth;
} else if ($this->bearerToken) {
$headers['Authorization'] = 'Bearer ' . $this->bearerToken;
}
if (empty($headers['Authorization'])) {
throw new AuthorizeException('Authorization headers not set');
}
return $headers;
}
/**
* @param array $headers
* @return array
*/
private function implodeHeaders($headers)
{
return array_map(function ($key, $value) { return $key . ':' . $value; }, array_keys($headers), $headers);
}
/**
* @param $path
* @param $method
* @param $queryParams
* @param $httpBody
* @param $headers
*/
private function logRequestParams($path, $method, $queryParams, $httpBody, $headers)
{
if ($this->logger !== null) {
$message = 'Send request: ' . $method . ' ' . $path;
$context = array();
if (!empty($queryParams)) {
$context['_params'] = $queryParams;
}
if (!empty($httpBody)) {
$data = json_decode($httpBody, true);
if (JSON_ERROR_NONE !== json_last_error()) {
$data = $httpBody;
}
$context['_body'] = $data;
}
if (!empty($headers)) {
$context['_headers'] = $headers;
}
$this->logger->info($message, $context);
}
}
/**
* @param $path
* @param $queryParams
*
* @return string
*/
private function prepareUrl($path, $queryParams)
{
$url = $this->getUrl() . $path;
if (!empty($queryParams)) {
$url = $url . '?' . http_build_query($queryParams);
}
return $url;
}
/**
* @param $httpBody
* @param $responseInfo
* @param $httpHeaders
*/
private function logResponse($httpBody, $responseInfo, $httpHeaders)
{
if ($this->logger !== null) {
$message = 'Response with code ' . $responseInfo['http_code'] . ' received.';
$context = array();
if (!empty($httpBody)) {
$data = json_decode($httpBody, true);
if (JSON_ERROR_NONE !== json_last_error()) {
$data = $httpBody;
}
$context['_body'] = $data;
}
if (!empty($httpHeaders)) {
$context['_headers'] = $httpHeaders;
}
$this->logger->info($message, $context);
}
}
/**
* @param $method
* @param $httpBody
* @param $headers
* @param $url
* @throws ExtensionNotFoundException
*/
private function prepareCurl($method, $httpBody, $headers, $url)
{
$this->initCurl();
$this->setCurlOption(CURLOPT_URL, $url);
$this->setCurlOption(CURLOPT_RETURNTRANSFER, true);
$this->setCurlOption(CURLOPT_HEADER, true);
$this->setCurlOption(CURLOPT_BINARYTRANSFER, true);
if ($this->proxy) {
$this->setCurlOption(CURLOPT_PROXY, $this->proxy);
$this->setCurlOption(CURLOPT_HTTPPROXYTUNNEL, true);
}
$this->setBody($method, $httpBody);
$this->setCurlOption(CURLOPT_HTTPHEADER, $headers);
$this->setCurlOption(CURLOPT_CONNECTTIMEOUT, $this->connectionTimeout);
$this->setCurlOption(CURLOPT_TIMEOUT, $this->timeout);
}
}
@@ -0,0 +1,320 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Client;
use YooKassa\Client;
/**
* Class UserAgent
* @package YooKassa\Client
*/
class UserAgent
{
const HEADER = 'YM-User-Agent';
const VERSION_DELIMITER = '/';
const PART_DELIMITER = ' ';
private $_os = null;
private $_php = null;
private $_framework = null;
private $_cms = null;
private $_module = null;
private $_sdk = null;
/**
* UserAgent constructor.
*/
public function __construct()
{
if ($os = $this->defineOs()) {
$this->setOs($os['name'], $os['version']);
}
if ($php = $this->definePhp()) {
$this->setPhp($php['name'], $php['version']);
}
$this->setSdk('YooKassa.PHP', Client::SDK_VERSION);
}
/**
* @return string
*/
public function getHeaderString()
{
$result = array();
$result[] = $this->getOs();
$result[] = $this->getPhp();
if ($string = $this->getFramework()) {
$result[] = $string;
}
if ($string = $this->getCms()) {
$result[] = $string;
}
if ($string = $this->getModule()) {
$result[] = $string;
}
$result[] = $this->getSdk();
return implode(self::PART_DELIMITER, $result);
}
/**
* @return string
*/
public function getOs()
{
return $this->_os;
}
/**
* @param string $name
* @param string $version
*/
private function setOs($name, $version)
{
$this->_os = $this->createVersion($name, $version);
}
/**
* @return string
*/
public function getPhp()
{
return $this->_php;
}
/**
* @param string $name
* @param string $version
*/
private function setPhp($name, $version)
{
$this->_php = $this->createVersion($name, $version);
}
/**
* @return string|null
*/
public function getFramework()
{
return $this->_framework;
}
/**
* @param string $name
* @param string $version
*/
public function setFramework($name, $version)
{
$this->_framework = $this->createVersion($name, $version);
}
/**
* @return null
*/
public function getCms()
{
return $this->_cms;
}
/**
* @param string $name
* @param string $version
*/
public function setCms($name, $version)
{
$this->_cms = $this->createVersion($name, $version);
}
/**
* @return string
*/
public function getModule()
{
return $this->_module;
}
/**
* @param string $name
* @param string $version
*/
public function setModule($name, $version)
{
$this->_module = $this->createVersion($name, $version);
}
/**
* @return string
*/
public function getSdk()
{
return $this->_sdk;
}
/**
* @param string $name
* @param string $version
*/
private function setSdk($name, $version)
{
$this->_sdk = $this->createVersion($name, $version);
}
/**
* Попытка определить систему
* @return array
*/
private function defineOs()
{
if (strtolower(substr(PHP_OS, 0, 5)) === 'linux') {
if ($result = $this->parseSimpleLinuxRelease()) {
return $result;
} elseif ($result = $this->parseSmartLinuxRelease()) {
return $result;
}
} else {
return array( 'name' => php_uname('s'), 'version' => php_uname('r') );
}
return array( 'name' => 'Undefined', 'version' => '0.0.0' );
}
/**
* Возвращает информацию о версии системы
* Используется сложный вариант
* @return array|null
*/
private function parseSmartLinuxRelease()
{
$vars = array();
if ($files = glob('/etc/*elease')) {
foreach ($files as $file) {
if (is_file($file)) {
$lines = array_filter(array_map(array($this, 'callbackSmartLinux'), file($file)));
if (is_array($lines)) {
foreach ($lines as $line) {
$vars[strtoupper($line[0])] = trim($line[1]);
}
}
}
}
if (!empty($vars['NAME']) && !empty($vars['VERSION_ID'])) {
return array('name' => $vars['NAME'], 'version' => $vars['VERSION_ID']);
}
}
return null;
}
/**
* @param string $line
* @return array|bool
*/
private static function callbackSmartLinux($line)
{
$parts = explode('=', $line);
if (count($parts) !== 2) {
return false;
}
$parts[1] = trim(str_replace(array('"', "'"), '', $parts[1]));
return $parts;
}
/**
* Возвращает информацию о версии системы
* Используется простой вариант
* @return array|null
*/
private function parseSimpleLinuxRelease()
{
$vars = array();
if ($files = glob('/etc/*elease')) {
foreach ($files as $file) {
if (is_file($file)) {
$data = array_map(array($this, 'callbackSimpleLinux'), file($file));
if (!empty($data)) {
$array = array_shift($data);
if (!empty($array) && is_array($array)) {
$vars = array_merge($vars, $array);
}
}
}
}
}
return !empty($vars['name']) && !empty($vars['version']) ? $vars : null;
}
/**
* @param string $line
* @return array
*/
private static function callbackSimpleLinux($line)
{
$parse = array();
preg_match('/(.+) release (.+) (.+)/iu', $line, $parts);
if (!empty($parts[1])) {
$parse['name'] = str_replace(' ', '.', trim($parts[1]));
}
if (!empty($parts[2])) {
$parse['version'] = trim($parts[2]);
}
return $parse;
}
/**
* Определение версии PHP
* @return array
*/
private function definePhp()
{
return array(
'name' => 'PHP',
'version' => PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION
);
}
/**
* Создание строки версии компонента
* @param string $name
* @param string $version
* @return string
*/
public function createVersion($name, $version)
{
return str_replace(array(self::PART_DELIMITER, self::VERSION_DELIMITER), '.', trim($name))
. self::VERSION_DELIMITER
. str_replace(array(self::PART_DELIMITER, self::VERSION_DELIMITER), '.', trim($version));
}
}
@@ -0,0 +1,74 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common;
/**
* Базовый класс генерируемых enum'ов
*
* @package YooKassa\Common
*/
abstract class AbstractEnum
{
/**
* @var array Массив принимаемых enum'ом значений
*/
protected static $validValues = array();
/**
* Проверяет наличие значения в enum'e
* @param mixed $value Проверяемое значение
* @return bool True если значение имеется, false если нет
*/
public static function valueExists($value)
{
return array_key_exists($value, static::$validValues);
}
/**
* Возвращает все значения в enum'e
* @return array Массив значений в перечислении
*/
public static function getValidValues()
{
return array_keys(static::$validValues);
}
/**
* Возвращает значения в enum'е значения которых разрешены
* @return string[] Массив разрешённых значений
*/
public static function getEnabledValues()
{
$result = array();
foreach (static::$validValues as $key => $enabled) {
if ($enabled) {
$result[] = $key;
}
}
return $result;
}
}
@@ -0,0 +1,251 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common;
if (!defined('YOOKASSA_DATE')) {
if (version_compare(PHP_VERSION, '7.0') >= 0) {
define('YOOKASSA_DATE', "Y-m-d\TH:i:s.vP");
} else {
define('YOOKASSA_DATE', "Y-m-d\TH:i:s.uP");
}
}
if (!interface_exists('JsonSerializable')) {
require_once dirname(__FILE__) . '/legacy_json_serializable.php';
}
/**
* Базовый класс генерируемых объектов
*
* @package YooKassa\Common
*/
abstract class AbstractObject implements \ArrayAccess, \JsonSerializable
{
/**
* @var array Свойства установленные пользователем
*/
private $unknownProperties = array();
/**
* AbstractObject constructor.
* @param array $data
*/
public function __construct($data = array())
{
if (!empty($data) && is_array($data)) {
$this->fromArray($data);
}
}
/**
* Проверяет наличие свойства
* @param string $offset Имя проверяемого свойства
* @return bool True если свойство имеется, false если нет
*/
public function offsetExists($offset)
{
$method = 'get' . ucfirst($offset);
if (method_exists($this, $method)) {
return true;
}
$method = 'get' . self::matchPropertyName($offset);
if (method_exists($this, $method)) {
return true;
}
return array_key_exists($offset, $this->unknownProperties);
}
/**
* Возвращает значение свойства
* @param string $offset Имя свойства
* @return mixed Значение свойства
*/
public function offsetGet($offset)
{
$method = 'get' . ucfirst($offset);
if (method_exists($this, $method)) {
return $this->{$method} ();
}
$method = 'get' . self::matchPropertyName($offset);
if (method_exists($this, $method)) {
return $this->{$method} ();
}
return array_key_exists($offset, $this->unknownProperties) ? $this->unknownProperties[$offset] : null;
}
/**
* Устанавливает значение свойства
* @param string $offset Имя свойства
* @param mixed $value Значение свойства
*/
public function offsetSet($offset, $value)
{
$method = 'set' . ucfirst($offset);
if (method_exists($this, $method)) {
$this->{$method}($value);
} else {
$method = 'set' . self::matchPropertyName($offset);
if (method_exists($this, $method)) {
$this->{$method}($value);
} else {
$this->unknownProperties[$offset] = $value;
}
}
}
/**
* Удаляет свойство
* @param string $offset Имя удаляемого свойства
*/
public function offsetUnset($offset)
{
$method = 'set' . ucfirst($offset);
if (method_exists($this, $method)) {
$this->{$method} (null);
} else {
$method = 'set' . self::matchPropertyName($offset);
if (method_exists($this, $method)) {
$this->{$method} (null);
} else {
unset($this->unknownProperties[$offset]);
}
}
}
/**
* Возвращает значение свойства
* @param string $propertyName Имя свойства
* @return mixed Значение свойства
*/
public function __get($propertyName)
{
return $this->offsetGet($propertyName);
}
/**
* Устанавливает значение свойства
* @param string $propertyName Имя свойства
* @param mixed $value Значение свойства
*/
public function __set($propertyName, $value)
{
$this->offsetSet($propertyName, $value);
}
/**
* Проверяет наличие свойства
* @param string $propertyName Имя проверяемого свойства
* @return bool True если свойство имеется, false если нет
*/
public function __isset($propertyName)
{
return $this->offsetExists($propertyName);
}
/**
* Удаляет свойство
* @param string $propertyName Имя удаляемого свойства
*/
public function __unset($propertyName)
{
$this->offsetUnset($propertyName);
}
/**
* Устанавливает значения свойств текущего объекта из массива
* @param array|\Traversable $sourceArray Ассоциативный массив с найтройками
*/
public function fromArray($sourceArray)
{
foreach ($sourceArray as $key => $value) {
$this->offsetSet($key, $value);
}
}
/**
* Возвращает ассоциативный массив со свойствами текущего объекта для его дальнейшей JSON сериализации
* @return array Ассоциативный массив со свойствами текущего объекта
*/
public function jsonSerialize()
{
$result = array();
foreach (get_class_methods($this) as $method) {
if (strncmp('get', $method, 3) === 0) {
if ($method === 'getUnknownProperties') {
continue;
}
if ($method === 'getIterator') {
continue;
}
$property = strtolower(preg_replace('/[A-Z]/', '_\0', lcfirst(substr($method, 3))));
$value = $this->serializeValueToJson($this->{$method} ());
if ($value !== null) {
$result[$property] = $value;
}
}
}
if (!empty($this->unknownProperties)) {
foreach ($this->unknownProperties as $property => $value) {
if (!array_key_exists($property, $result)) {
$result[$property] = $this->serializeValueToJson($value);
}
}
}
return $result;
}
private function serializeValueToJson($value)
{
if ($value === null || is_scalar($value) || is_array($value)) {
return $value;
} elseif (is_object($value) && $value instanceof \JsonSerializable) {
return $value->jsonSerialize();
} elseif (is_object($value) && $value instanceof \DateTime) {
return $value->format(YOOKASSA_DATE);
}
return $value;
}
/**
* Возвращает массив свойств которые не существуют, но были заданы у объекта
* @return array Ассоциативный массив с не существующими у текущего объекта свойствами
*/
protected function getUnknownProperties()
{
return $this->unknownProperties;
}
/**
* Преобразует имя свойства из snake_case в camelCase
* @param string $property Преобразуемое значение
* @return string Значение в камэл кейсе
*/
private static function matchPropertyName($property)
{
return preg_replace('/\_(\w)/', '\1', $property);
}
}
@@ -0,0 +1,223 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Model\AmountInterface;
use YooKassa\Model\Receipt;
use YooKassa\Model\ReceiptInterface;
use YooKassa\Model\Transfer;
use YooKassa\Model\TransferInterface;
/**
* Класс объекта запроса к API
*
* @property AmountInterface $amount Сумма
* @property ReceiptInterface $receipt Данные фискального чека 54-ФЗ
* @property TransferInterface[] $transfers Данные о распределении платежа между магазинами
*
* @since 1.0.18
*/
class AbstractPaymentRequest extends AbstractRequest
{
/**
* @var AmountInterface Сумма оплаты
*/
protected $_amount;
/**
* @var Receipt Данные фискального чека 54-ФЗ
*/
protected $_receipt;
/**
* @var TransferInterface[]
*/
protected $_transfers = array();
/**
* Возвращает сумму оплаты
* @return AmountInterface Сумма оплаты
*/
public function getAmount()
{
return $this->_amount;
}
/**
* Проверяет была ли установлена сумма оплаты
* @return bool True если сумма оплаты была установлена, false если нет
*/
public function hasAmount()
{
return !empty($this->_amount);
}
/**
* Устанавливает сумму оплаты
* @param AmountInterface $value Сумма оплаты
*/
public function setAmount(AmountInterface $value)
{
$this->_amount = $value;
}
/**
* Возвращает чек, если он есть
* @return ReceiptInterface|null Данные фискального чека 54-ФЗ или null если чека нет
*/
public function getReceipt()
{
return $this->_receipt;
}
/**
* Устанавливает чек
* @param ReceiptInterface|null $value Инстанс чека или null для удаления информации о чеке
* @throws InvalidPropertyValueTypeException Выбрасывается если передан не инстанс класса чека и не null
*/
public function setReceipt($value)
{
if ($value === null || $value instanceof ReceiptInterface) {
$this->_receipt = $value;
} else {
throw new InvalidPropertyValueTypeException('Invalid receipt in Refund', 0, 'Refund.receipt', $value);
}
}
/**
* Проверяет наличие чека
* @return bool True если чек есть, false если нет
*/
public function hasReceipt()
{
return $this->_receipt !== null && $this->_receipt->notEmpty();
}
/**
* Удаляет чек из запроса
*/
public function removeReceipt()
{
$this->_receipt = null;
}
/**
* Устанавливает transfers (массив распределения денег между магазинами)
* @param TransferInterface[]|array $value
*/
public function setTransfers($value)
{
if (!is_array($value)) {
$message = 'Transfers must be an array of TransferInterface';
throw new InvalidPropertyValueTypeException($message, 0, 'Payment.transfers', $value);
}
$transfers = array();
foreach ($value as $item) {
if (is_array($item)) {
$item = new Transfer($item);
}
if (!($item instanceof TransferInterface)) {
$message = 'Transfers must be an array of TransferInterface';
throw new InvalidPropertyValueTypeException($message, 0, 'Payment.transfers', $value);
}
$transfers[] = $item;
}
$this->_transfers = $transfers;
}
/**
* Валидирует объект запроса
* @return bool True если запрос валиден и его можно отправить в API, false если нет
*/
public function validate()
{
if ($this->_amount === null) {
$this->setValidationError('Payment amount not specified');
return false;
}
$value = $this->_amount->getValue();
if (empty($value) || $value <= 0.0) {
$this->setValidationError('Invalid payment amount value: ' . $value);
return false;
}
if (!empty($this->_transfers)) {
$sum = 0;
foreach ($this->_transfers as $transfer) {
if ($transfer->getAmount() === null) {
$this->setValidationError('Payment amount not specified');
return false;
}
$value = $transfer->getAmount()->getValue();
if (empty($value) || $value <= 0.0) {
$this->setValidationError('Invalid transfer amount value: ' . $value);
return false;
}
$sum += (float) $value;
$accountId = $transfer->getAccountId();
if (empty($accountId)) {
$this->setValidationError('Transfer account id not specified');
return false;
}
}
if ($sum !== (float) $this->getAmount()->getValue()) {
$this->setValidationError('Transfer amount sum does not match top-level amount');
}
}
if ($this->getReceipt() && $this->getReceipt()->notEmpty()) {
$email = $this->getReceipt()->getCustomer()->getEmail();
$phone = $this->getReceipt()->getCustomer()->getPhone();
if (empty($email) && empty($phone)) {
$this->setValidationError('Both email and phone values are empty in receipt');
return false;
}
}
return true;
}
public function hasTransfers()
{
return !empty($this->_transfers);
}
public function getTransfers()
{
return $this->_transfers;
}
}
@@ -0,0 +1,336 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Model\AmountInterface;
use YooKassa\Model\MonetaryAmount;
use YooKassa\Model\Receipt;
use YooKassa\Model\Receipt\ReceiptItemAmount;
use YooKassa\Model\ReceiptCustomer;
use YooKassa\Model\ReceiptInterface;
use YooKassa\Model\ReceiptItem;
use YooKassa\Model\ReceiptItemInterface;
use YooKassa\Model\Transfer;
use YooKassa\Model\TransferInterface;
/**
* Базовый класс объекта платежного запроса, передаваемого в методы клиента API
*
* @package YooKassa\Common
*
* @since 1.0.18
*/
abstract class AbstractPaymentRequestBuilder extends AbstractRequestBuilder
{
/**
* @var MonetaryAmount Сумма
*/
protected $amount;
/**
* @var Receipt Объект с информацией о чеке
*/
protected $receipt;
/**
* @var TransferInterface[] Массив платежей в пользу разных мерчантов
*/
protected $transfers;
/**
* @return self
*/
protected function initCurrentObject()
{
$this->amount = new MonetaryAmount();
$this->receipt = new Receipt();
$this->transfers = array();
return $this;
}
/**
* {@inheritDoc}
*/
public function build(array $options = null)
{
return parent::build($options);
}
/**
* Устанавливает сумму
*
* @param AmountInterface|array|string $value Сумма оплаты
*
* @return self Инстанс билдера запросов
*/
public function setAmount($value)
{
if ($value === null || $value === '') {
$this->amount = new MonetaryAmount();
} elseif ($value instanceof AmountInterface) {
$this->amount->setValue($value->getValue());
$this->amount->setCurrency($value->getCurrency());
} elseif (is_array($value)) {
$this->amount->fromArray($value);
} else {
$this->amount->setValue($value);
}
return $this;
}
/**
* Устанавливает трансферы
*
* @param array|string $value Массив трансферов
*
* @return self Инстанс билдера запросов
*/
public function setTransfers($value)
{
$value = (array)$value;
$this->transfers = array();
foreach ($value as $item) {
$transfer = new Transfer();
if ($item instanceof TransferInterface) {
$transfer->setAmount($item->getAmount());
$transfer->setAccountId($item->getAccountId());
if ($item->hasPlatformFeeAmount()) {
$transfer->setPlatformFeeAmount($item->getPlatformFeeAmount());
}
} elseif (is_array($item)) {
$transfer->fromArray($item);
}
$this->transfers[] = $transfer;
}
return $this;
}
/**
* Устанавливает валюту в которой будет происходить подтверждение оплаты заказа
*
* @param string $value Валюта в которой подтверждается оплата
*
* @return self Инстанс билдера запросов
*/
public function setCurrency($value)
{
$this->amount->setCurrency($value);
foreach ($this->receipt->getItems() as $item) {
$item->getPrice()->setCurrency($value);
}
return $this;
}
/**
* Устанавливает чек
*
* @param ReceiptInterface|array $value Инстанс чека или ассоциативный массив с данными чека
*
* @return self
*
* @throws InvalidPropertyValueTypeException Генерируется если было передано значение невалидного типа
*/
public function setReceipt($value)
{
if (is_array($value)) {
$this->receipt->fromArray($value);
} elseif ($value instanceof ReceiptInterface) {
$this->receipt = clone $value;
} else {
throw new InvalidPropertyValueTypeException('Invalid receipt value type', 0, 'receipt', $value);
}
return $this;
}
/**
* Устанавлвиает список товаров для создания чека
*
* @param array $value Массив товаров в заказе
*
* @return self Инстанс билдера запросов
*
* @throws InvalidPropertyValueException Выбрасывается если хотя бы один из товаров имеет неверную структуру
*/
public function setReceiptItems($value)
{
$this->receipt->setItems(array());
$index = 0;
foreach ($value as $item) {
if ($item instanceof ReceiptItemInterface) {
$this->receipt->addItem($item);
} else {
if (empty($item['title']) && empty($item['description'])) {
throw new InvalidPropertyValueException(
'Item#'.$index.' title or description not specified',
0,
'AbstractPaymentRequestBuilder.items['.$index.'].title',
json_encode($item)
);
}
foreach (array('price', 'quantity', 'vatCode') as $property) {
if (empty($item[$property])) {
throw new InvalidPropertyValueException(
'Item#'.$index.' '.$property.' not specified',
0,
'AbstractPaymentRequestBuilder.items['.$index.'].'.$property,
json_encode($item)
);
}
}
$this->addReceiptItem(
empty($item['title']) ? $item['description'] : $item['title'],
$item['price'],
$item['quantity'],
$item['vatCode']
);
}
$index++;
}
return $this;
}
/**
* Добавляет в чек товар
*
* @param string $title Название или описание товара
* @param string $price Цена товара в валюте, заданной в заказе
* @param float $quantity Количество товара
* @param int $vatCode Ставка НДС
*
* @param null|string $paymentSubject значение перечисления PaymentSubject
* @see \YooKassa\Model\Receipt\PaymentSubject::class
*
* @param null|string $paymentMode значение перечисления PaymentMode
* @see \YooKassa\Model\Receipt\PaymentMode::class
*
* @return self Инстанс билдера запросов
*/
public function addReceiptItem($title, $price, $quantity, $vatCode, $paymentMode = null, $paymentSubject = null)
{
$item = new ReceiptItem();
$item->setDescription($title);
$item->setQuantity($quantity);
$item->setVatCode($vatCode);
$item->setPrice(new ReceiptItemAmount($price, $this->amount->getCurrency()));
$item->setPaymentSubject($paymentSubject);
$item->setPaymentMode($paymentMode);
$this->receipt->addItem($item);
return $this;
}
/**
* Добавляет в чек доставку товара
*
* @param string $title Название доставки в чеке
* @param string $price Стоимость доставки
* @param int $vatCode Ставка НДС
*
* @param null|string $paymentSubject значение перечисления PaymentSubject
* @see \YooKassa\Model\Receipt\PaymentSubject::class
*
* @param null|string $paymentMode значение перечисления PaymentMode
* @see \YooKassa\Model\Receipt\PaymentMode::class
*
* @return self Инстанс билдера запросов
*/
public function addReceiptShipping($title, $price, $vatCode, $paymentMode = null, $paymentSubject = null)
{
$item = new ReceiptItem();
$item->setDescription($title);
$item->setQuantity(1);
$item->setVatCode($vatCode);
$item->setIsShipping(true);
$item->setPrice(new ReceiptItemAmount($price, $this->amount->getCurrency()));
$item->setPaymentMode($paymentMode);
$item->setPaymentSubject($paymentSubject);
$this->receipt->addItem($item);
return $this;
}
/**
* Устанавливает адрес электронной почты получателя чека
*
* @param string $value Email получателя чека
*
* @return self Инстанс билдера запросов
*/
public function setReceiptEmail($value)
{
if (!$this->receipt->getCustomer()) {
$this->receipt->setCustomer(new ReceiptCustomer());
}
$this->receipt->getCustomer()->setEmail($value);
return $this;
}
/**
* Устанавливает телефон получателя чека
*
* @param string $value Телефон получателя чека
* @return self Инстанс билдера запросов
*
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве значения была передана не строка
*/
public function setReceiptPhone($value)
{
if (!$this->receipt->getCustomer()) {
$this->receipt->setCustomer(new ReceiptCustomer());
}
$this->receipt->getCustomer()->setPhone($value);
return $this;
}
/**
* Устанавливает код системы налогообложения.
*
* @param int $value Код системы налогообложения. Число 1-6.
*
* @return self Инстанс билдера запросов
*/
public function setTaxSystemCode($value)
{
$this->receipt->setTaxSystemCode($value);
return $this;
}
}
@@ -0,0 +1,72 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common;
/**
* Базовый класс объекта запроса, передаваемого в методы клиента API
*
* @package YooKassa\Common
*/
abstract class AbstractRequest extends AbstractObject
{
/**
* @var string Последняя ошибка валидации текущего запроса
*/
private $_validationError;
/**
* Валидирует текущий запрос, проверяет все ли нужные свойства установлены
* @return bool True если запрос валиден, false если нет
*/
abstract public function validate();
/**
* Очищает статус валидации текущего запроса
*/
public function clearValidationError()
{
$this->_validationError = null;
}
/**
* Устанавливает ошибку валидации
* @param string $value Ошибка, произошедшая при валидации объекта
*/
protected function setValidationError($value)
{
$this->_validationError = $value;
}
/**
* Возвращает последнюю ошибку валидации
* @return string Последняя произошедшая ошибка валидации
*/
public function getLastValidationError()
{
return $this->_validationError;
}
}
@@ -0,0 +1,119 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common;
use YooKassa\Common\Exceptions\InvalidPropertyException;
use YooKassa\Common\Exceptions\InvalidRequestException;
/**
* Базовый класс билдера запросов
*
* @package YooKassa\Common
*/
abstract class AbstractRequestBuilder
{
/**
* @var AbstractRequest Инстанс собираемого запроса
*/
protected $currentObject;
/**
* Конструктор, инициализирует пустой запрос, который в будущем начнём собирать
*/
public function __construct()
{
$this->currentObject = $this->initCurrentObject();
}
/**
* Инициализирует пустой запрос
* @return AbstractRequest Инстанс запроса который будем собирать
*/
abstract protected function initCurrentObject();
/**
* Строит запрос, валидирует его и возвращает, если все прошло нормально
* @param array $options Массив свойств запроса, если нужно их установить перед сборкой
* @return AbstractRequest Инстанс собранного запроса
*
* @throws InvalidRequestException Выбрасывается если при валидации запроса произошла ошибка
* @throws InvalidPropertyException Выбрасывается если не удалось установить один из параметров, переданныч в
* массиве настроек
*/
public function build(array $options = null)
{
if (!empty($options)) {
$this->setOptions($options);
}
try {
$this->currentObject->clearValidationError();
if (!$this->currentObject->validate()) {
throw new InvalidRequestException($this->currentObject);
}
} catch (InvalidRequestException $e) {
throw $e;
} catch (\Exception $e) {
throw new InvalidRequestException($this->currentObject, 0, $e);
}
$result = $this->currentObject;
$this->currentObject = $this->initCurrentObject();
return $result;
}
/**
* Устанавливает свойства запроса из массива
* @param array|\Traversable $options Массив свойств запроса
* @return AbstractRequestBuilder Инстанс текущего билдера запросов
*
* @throws \InvalidArgumentException Выбрасывается если аргумент не массив и не итерируемый объект
* @throws InvalidPropertyException Выбрасывается если не удалось установить один из параметров, переданныч
* в массиве настроек
*/
public function setOptions($options)
{
if (empty($options)) {
return $this;
}
if (!is_array($options) && !($options instanceof \Traversable)) {
throw new \InvalidArgumentException('Invalid options value in setOptions method');
}
foreach ($options as $property => $value) {
$method = 'set' . ucfirst($property);
if (method_exists($this, $method)) {
$this->{$method} ($value);
} else {
$property = str_replace('.', '_', $property);
$field = implode('', array_map('ucfirst', explode('_', $property)));
$method = 'set' . ucfirst($field);
if (method_exists($this, $method)) {
$this->{$method} ($value);
}
}
}
return $this;
}
}
@@ -0,0 +1,32 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
class ApiConnectionException extends ApiException
{
}
@@ -0,0 +1,73 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
use Exception;
class ApiException extends Exception
{
/**
* @var mixed
*/
protected $responseBody;
/**
* @var string[]
*/
protected $responseHeaders;
/**
* Constructor
*
* @param string $message Error message
* @param int $code HTTP status code
* @param string[] $responseHeaders HTTP header
* @param mixed $responseBody HTTP body
*/
public function __construct($message = "", $code = 0, $responseHeaders = array(), $responseBody = null)
{
parent::__construct($message, $code);
$this->responseHeaders = $responseHeaders;
$this->responseBody = $responseBody;
}
/**
* @return string[]
*/
public function getResponseHeaders()
{
return $this->responseHeaders;
}
/**
* @return mixed
*/
public function getResponseBody()
{
return $this->responseBody;
}
}
@@ -0,0 +1,32 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
class AuthorizeException extends ApiException
{
}
@@ -0,0 +1,64 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
class BadApiRequestException extends ApiException
{
const HTTP_CODE = 400;
public $type;
public $retryAfter;
public function __construct($responseHeaders = array(), $responseBody = null)
{
$errorData = json_decode($responseBody, true);
$message = '';
if (isset($errorData['description'])) {
$message .= $errorData['description'] . '. ';
}
if (isset($errorData['code'])) {
$message .= sprintf('Error code: %s. ', $errorData['code']);
}
if (isset($errorData['parameter'])) {
$message .= sprintf('Parameter name: %s. ', $errorData['parameter']);
}
if (isset($errorData['retry_after'])) {
$this->retryAfter = $errorData['retry_after'];
}
if (isset($errorData['type'])) {
$this->type = $errorData['type'];
}
parent::__construct(trim($message), self::HTTP_CODE, $responseHeaders, $responseBody);
}
}
@@ -0,0 +1,31 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
class EmptyPropertyValueException extends InvalidPropertyException
{
}
@@ -0,0 +1,46 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
use Exception;
class ExtensionNotFoundException extends Exception
{
/**
* Constructor
*
* @param string $name extension name
* @param int $code error code
*/
public function __construct($name, $code = 0)
{
$message = sprintf('%s extension is not loaded!', $name);
parent::__construct($message, $code);
}
}
@@ -0,0 +1,64 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
class ForbiddenException extends ApiException
{
const HTTP_CODE = 403;
public $type;
public $retryAfter;
public function __construct($responseHeaders = array(), $responseBody = null)
{
$errorData = json_decode($responseBody, true);
$message = '';
if (isset($errorData['description'])) {
$message .= $errorData['description'] . '. ';
}
if (isset($errorData['code'])) {
$message .= sprintf('Error code: %s. ', $errorData['code']);
}
if (isset($errorData['parameter'])) {
$message .= sprintf('Parameter name: %s. ', $errorData['parameter']);
}
if (isset($errorData['retry_after'])) {
$this->retryAfter = $errorData['retry_after'];
}
if (isset($errorData['type'])) {
$this->type = $errorData['type'];
}
parent::__construct(trim($message), self::HTTP_CODE, $responseHeaders, $responseBody);
}
}
@@ -0,0 +1,64 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
class InternalServerError extends ApiException
{
const HTTP_CODE = 500;
public $retryAfter;
public $type;
public function __construct($responseHeaders = array(), $responseBody = null)
{
$errorData = json_decode($responseBody, true);
$message = '';
if (isset($errorData['description'])) {
$message .= $errorData['description'] . '. ';
}
if (isset($errorData['code'])) {
$message .= sprintf('Error code: %s. ', $errorData['code']);
}
if (isset($errorData['parameter'])) {
$message .= sprintf('Parameter name: %s. ', $errorData['parameter']);
}
if (isset($errorData['retry_after'])) {
$this->retryAfter = $errorData['retry_after'];
}
if (isset($errorData['type'])) {
$this->type = $errorData['type'];
}
parent::__construct(trim($message), self::HTTP_CODE, $responseHeaders, $responseBody);
}
}
@@ -0,0 +1,55 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
class InvalidPropertyException extends \InvalidArgumentException
{
/**
* @var string
*/
private $propertyName;
/**
* InvalidValueException constructor.
* @param string $message
* @param int $code
* @param string $property
*/
public function __construct($message = "", $code = 0, $property = "")
{
parent::__construct($message, $code);
$this->propertyName = (string)$property;
}
/**
* @return string
*/
public function getProperty()
{
return $this->propertyName;
}
}
@@ -0,0 +1,58 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
class InvalidPropertyValueException extends InvalidPropertyException
{
/**
* @var mixed
*/
private $invalidValue;
/**
* InvalidPropertyValueTypeException constructor.
* @param string $message
* @param int $code
* @param string $property
* @param mixed $value
*/
public function __construct($message = '', $code = 0, $property = '', $value = null)
{
parent::__construct($message, $code, $property);
if ($value !== null) {
$this->invalidValue = $value;
}
}
/**
* @return mixed
*/
public function getValue()
{
return $this->invalidValue;
}
}
@@ -0,0 +1,62 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
class InvalidPropertyValueTypeException extends InvalidPropertyException
{
/**
* @var string
*/
private $type;
/**
* InvalidPropertyValueTypeException constructor.
* @param string $message
* @param int $code
* @param string $property
* @param mixed $value
*/
public function __construct($message = "", $code = 0, $property = "", $value = null)
{
parent::__construct($message, $code, $property);
if ($value === null) {
$this->type = 'null';
} elseif (is_object($value)) {
$this->type = get_class($value);
} else {
$this->type = gettype($value);
}
}
/**
* @return string
*/
public function getType()
{
return $this->type;
}
}
@@ -0,0 +1,62 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
use YooKassa\Common\AbstractRequest;
class InvalidRequestException extends \RuntimeException
{
/**
* @var AbstractRequest|null
*/
private $errorRequest;
/**
* InvalidRequestException constructor.
* @param AbstractRequest|string $error
* @param int $code
* @param null $previous
*/
public function __construct($error, $code = 0, $previous = null)
{
if ($error instanceof AbstractRequest) {
$message = 'Failed to build request "'.get_class($error).'": "'.$error->getLastValidationError().'"';
$this->errorRequest = $error;
} else {
$message = $error;
}
parent::__construct($message, $code, $previous);
}
/**
* @return AbstractRequest|null
*/
public function getRequestObject()
{
return $this->errorRequest;
}
}
@@ -0,0 +1,46 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
class JsonException extends \UnexpectedValueException
{
public static $errorLabels = array(
JSON_ERROR_NONE => 'No error',
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
);
public function __construct($message = "", $code = 0, $previous = null)
{
$errorMsg = isset(self::$errorLabels[$code]) ? self::$errorLabels[$code] : 'Unknown error';
$message = sprintf('%s %s', $message, $errorMsg);
parent::__construct($message, $code, $previous);
}
}
@@ -0,0 +1,64 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
class NotFoundException extends ApiException
{
const HTTP_CODE = 404;
public $type;
public $retryAfter;
public function __construct($responseHeaders = array(), $responseBody = null)
{
$errorData = json_decode($responseBody, true);
$message = '';
if (isset($errorData['description'])) {
$message .= $errorData['description'].'. ';
}
if (isset($errorData['code'])) {
$message .= sprintf('Error code: %s. ', $errorData['code']);
}
if (isset($errorData['parameter'])) {
$message .= sprintf('Parameter name: %s. ', $errorData['parameter']);
}
if (isset($errorData['retry_after'])) {
$this->retryAfter = $errorData['retry_after'];
}
if (isset($errorData['type'])) {
$this->type = $errorData['type'];
}
parent::__construct(trim($message), self::HTTP_CODE, $responseHeaders, $responseBody);
}
}
@@ -0,0 +1,56 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
class ResponseProcessingException extends ApiException
{
const HTTP_CODE = 202;
public $type;
public $retryAfter;
public function __construct($responseHeaders = array(), $responseBody = null)
{
$errorData = json_decode($responseBody, true);
$message = '';
if (isset($errorData['description'])) {
$message .= $errorData['description'] . '. ';
}
if (isset($errorData['retry_after'])) {
$this->retryAfter = $errorData['retry_after'];
}
if (isset($errorData['type'])) {
$this->type = $errorData['type'];
}
parent::__construct(trim($message), self::HTTP_CODE, $responseHeaders, $responseBody);
}
}
@@ -0,0 +1,64 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
class TooManyRequestsException extends ApiException
{
const HTTP_CODE = 429;
public $type;
public $retryAfter;
public function __construct($responseHeaders = array(), $responseBody = null)
{
$errorData = json_decode($responseBody, true);
$message = '';
if (isset($errorData['description'])) {
$message .= $errorData['description'] . '. ';
}
if (isset($errorData['code'])) {
$message .= sprintf('Error code: %s. ', $errorData['code']);
}
if (isset($errorData['parameter'])) {
$message .= sprintf('Parameter name: %s. ', $errorData['parameter']);
}
if (isset($errorData['retry_after'])) {
$this->retryAfter = $errorData['retry_after'];
}
if (isset($errorData['type'])) {
$this->type = $errorData['type'];
}
parent::__construct(trim($message), self::HTTP_CODE, $responseHeaders, $responseBody);
}
}
@@ -0,0 +1,64 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common\Exceptions;
class UnauthorizedException extends ApiException
{
const HTTP_CODE = 401;
public $type;
public $retryAfter;
public function __construct($responseHeaders = array(), $responseBody = null)
{
$errorData = json_decode($responseBody, true);
$message = '';
if (isset($errorData['description'])) {
$message .= $errorData['description'] . '. ';
}
if (isset($errorData['code'])) {
$message .= sprintf('Error code: %s. ', $errorData['code']);
}
if (isset($errorData['parameter'])) {
$message .= sprintf('Parameter name: %s. ', $errorData['parameter']);
}
if (isset($errorData['retry_after'])) {
$this->retryAfter = $errorData['retry_after'];
}
if (isset($errorData['type'])) {
$this->type = $errorData['type'];
}
parent::__construct(trim($message), self::HTTP_CODE, $responseHeaders, $responseBody);
}
}
@@ -0,0 +1,48 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common;
class HttpVerb extends AbstractEnum
{
const GET = 'GET';
const POST = 'POST';
const PATCH = 'PATCH';
const HEAD = 'HEAD';
const OPTIONS = 'OPTIONS';
const PUT = 'PUT';
const DELETE = 'DELETE';
protected static $validValues = array(
'GET' => true,
'POST' => true,
'PATCH' => true,
'HEAD' => true,
'OPTIONS' => true,
'PUT' => true,
'DELETE' => true
);
}
@@ -0,0 +1,192 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common;
use Psr\Log\InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
class LoggerWrapper implements LoggerInterface
{
/**
* @var null|callable
*/
private $loggerCallback;
/**
* @var object
*/
private $loggerInstance;
/**
* LoggerWrapper constructor.
* @param object|callable $wrapped
*/
public function __construct($wrapped)
{
if (is_object($wrapped) && method_exists($wrapped, 'log')) {
$this->loggerInstance = $wrapped;
} elseif (is_callable($wrapped)) {
$this->loggerCallback = $wrapped;
} else {
throw new InvalidArgumentException('Invalid wrapped logger');
}
}
/**
* System is unusable.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function emergency($message, array $context = array())
{
$this->log(LogLevel::EMERGENCY, $message, $context);
}
/**
* Action must be taken immediately.
*
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function alert($message, array $context = array())
{
$this->log(LogLevel::ALERT, $message, $context);
}
/**
* Critical conditions.
*
* Example: Application component unavailable, unexpected exception.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function critical($message, array $context = array())
{
$this->log(LogLevel::CRITICAL, $message, $context);
}
/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function error($message, array $context = array())
{
$this->log(LogLevel::ERROR, $message, $context);
}
/**
* Exceptional occurrences that are not errors.
*
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function warning($message, array $context = array())
{
$this->log(LogLevel::WARNING, $message, $context);
}
/**
* Normal but significant events.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function notice($message, array $context = array())
{
$this->log(LogLevel::NOTICE, $message, $context);
}
/**
* Interesting events.
*
* Example: User logs in, SQL logs.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function info($message, array $context = array())
{
$this->log(LogLevel::INFO, $message, $context);
}
/**
* Detailed debug information.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function debug($message, array $context = array())
{
$this->log(LogLevel::DEBUG, $message, $context);
}
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $context
*
* @return void
*/
public function log($level, $message, array $context = array())
{
if ($this->loggerInstance !== null) {
$this->loggerInstance->log($level, $message, $context);
} elseif ($this->loggerCallback !== null) {
call_user_func_array($this->loggerCallback, array($level, $message, $context));
}
}
}
@@ -0,0 +1,73 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Common;
class ResponseObject
{
protected $code;
protected $headers;
protected $body;
public function __construct($config = null)
{
if (isset($config['headers'])) {
$this->headers = $config['headers'];
}
if (isset($config['body'])) {
$this->body = $config['body'];
}
if (isset($config['code'])) {
$this->code = $config['code'];
}
}
/**
* @return mixed
*/
public function getHeaders()
{
return $this->headers;
}
/**
* @return mixed
*/
public function getBody()
{
return $this->body;
}
/**
* @return mixed
*/
public function getCode()
{
return $this->code;
}
}
@@ -0,0 +1,31 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
if (!interface_exists('JsonSerializable')) {
interface JsonSerializable {
public function jsonSerialize();
}
}
@@ -0,0 +1,52 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Helpers\Config;
class ConfigurationLoader implements ConfigurationLoaderInterface
{
private $configParams;
public function load($filePath = null)
{
if ($filePath) {
$data = file_get_contents($filePath);
} else {
$data = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "configuration.json");
}
$paramsArray = json_decode($data, true);
$this->configParams = $paramsArray;
return $this;
}
public function getConfig()
{
return $this->configParams;
}
}
@@ -0,0 +1,40 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Helpers\Config;
interface ConfigurationLoaderInterface
{
/**
* @return mixed
*/
public function getConfig();
/**
* @return mixed
*/
public function load();
}
@@ -0,0 +1,362 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Helpers;
/**
* Класс для формирования тега 1162 на основе кода в формате Data Matrix
*
* @example $receiptItem->setProductCode(new \YooKassa\Helpers\ProductCode('010463003759131691sgEKKPPcS25y592FLduM/='));
* @example array(... 'product_code' => (string)(new \YooKassa\Helpers\ProductCode('010463003759131691sgEKKPPcS25y5') ...);
*
* @link https://github.com/yoomoney/yookassa-sdk-php/blob/master/lib/Helpers/ProductCode.php
*
* Class ProductCode
* @package YooKassa\Helpers
*/
class ProductCode
{
const PREFIX_DATA_MATRIX = '444D';
/** @var string Код типа маркировки */
private $prefix;
/**
* @var string Global Trade Item Number
* Глобальный номер товарной продукции в единой международной базе товаров GS1 https://ru.wikipedia.org/wiki/GS1
* @example 04630037591316
*/
private $gtin;
/**
* @var string Серийный номер товара
* @example sgEKKPPcS25y5
*/
private $serial;
/** @var string Сформированный тег 1162. Формат: hex([prefix]+gtin+serial)
* @example 04 36 03 BE F5 14 73 67 45 4b 4b 50 50 63 53 32 35 79 35
*/
private $result;
/** @var bool Флаг использования кода типа маркировки */
private $usePrefix = false;
/**
* ProductCode constructor.
* @param string|null $codeDataMatrix Строка, расшифрованная из QR-кода
* @param bool|string $usePrefix Нужен ли код типа маркировки в результате
*/
public function __construct($codeDataMatrix=null, $usePrefix=false)
{
$this->preparePrefix($usePrefix);
if (!empty($codeDataMatrix)) {
if ($this->parseCodeMatrixData($codeDataMatrix)) {
$this->result = $this->calcResult();
}
}
}
/**
* Возвращает Код типа маркировки
* @return string Код типа маркировки
*/
public function getPrefix()
{
return $this->prefix;
}
/**
* Устанавливает Код типа маркировки
* @param string|int $prefix Код типа маркировки
* @return ProductCode
*/
public function setPrefix($prefix)
{
if ($prefix === null || $prefix === '') {
$this->prefix = null;
return $this;
}
if (is_int($prefix)) {
$prefix = dechex($prefix);
}
$this->prefix = str_pad($prefix, 4, '0', STR_PAD_LEFT);
return $this;
}
/**
* Возвращает Глобальный номер товарной продукции
* @return string Глобальный номер товарной продукции
*/
public function getGtin()
{
return $this->gtin;
}
/**
* Устанавливает Глобальный номер товарной продукции
* @param string$gtin Глобальный номер товарной продукции
* @return ProductCode
*/
public function setGtin($gtin)
{
if ($gtin === null || $gtin === '') {
$this->gtin = null;
} else {
$this->gtin = $gtin;
}
return $this;
}
/**
* Возвращает Серийный номер товара
* @return string Серийный номер товара
*/
public function getSerial()
{
return $this->serial;
}
/**
* Устанавливает Серийный номер товара
* @param string $serial Серийный номер товара
* @return ProductCode
*/
public function setSerial($serial)
{
if ($serial === null || $serial === '') {
$this->prefix = null;
} else {
$this->serial = $serial;
}
return $this;
}
/**
* Возвращает Сформированный тег 1162.
* @return string Сформированный тег 1162.
*/
public function getResult()
{
if (!$this->result) {
$this->result = $this->calcResult();
}
return $this->result;
}
/**
* Возвращает флаг использования кода типа маркировки
* @return bool
*/
public function isUsePrefix()
{
return $this->usePrefix;
}
/**
* Устанавливает флаг использования кода типа маркировки
* @param bool $usePrefix Флаг использования кода типа маркировки
* @return ProductCode
*/
public function setUsePrefix($usePrefix)
{
$this->usePrefix = (bool)$usePrefix;
return $this;
}
/**
* Формирует тег 1162.
* @return string|null Сформированный тег 1162.
*/
public function calcResult()
{
$result = '';
if (!$this->validate()) {
return $result;
}
if ($this->isUsePrefix()) {
$result = $this->getPrefix() ?: self::PREFIX_DATA_MATRIX;
}
$result .= $this->numToHex($this->getGtin());
$result .= $this->strToHex($this->getSerial());
return $this->chunkStr($result);
}
/**
* Устанавливает prefix и usePrefix в зависимости от входящего параметра
* @param mixed $usePrefix Код типа маркировки или bool
*/
private function preparePrefix($usePrefix)
{
if ($usePrefix) {
$this->setUsePrefix(true);
if (is_string($usePrefix) || is_int($usePrefix)) {
$this->setPrefix($usePrefix);
} else {
$this->setPrefix(self::PREFIX_DATA_MATRIX);
}
} else {
$this->setUsePrefix(false);
$this->setPrefix(null);
}
}
/**
* Извлекает необходимые данные из строки, расшифрованной из QR-кода и устанавливает соответствующие свойства.
* Возвращает результат в виде bool
* @param string $codeDataMatrix Строки, расшифрованная из QR-кода
* @return false
*/
private function parseCodeMatrixData($codeDataMatrix)
{
$string = preg_replace('#91(.+)92(.+)#i', '', $codeDataMatrix);
preg_match('#01(\d{14})21(.+)#i', $string, $matches);
$this->setGtin(!empty($matches[1]) ? $matches[1] : null);
$this->setSerial(!empty($matches[2]) ? $matches[2] : null);
return $this->validate();
}
/**
* Проверяет заполненность необходимых свойств
* @return bool
*/
public function validate()
{
return $this->getGtin() && $this->getSerial();
}
/**
* Разбивает пробелами строку на пары символов и переводит в верхний регистр
* @param string $string Подготовленная к разбиению строка
* @return string
*/
private function chunkStr($string)
{
return strtoupper(trim(chunk_split($string, 2, ' ')));
}
/**
* Переводит десятичное число в шестнадцатеричный вид и дополняет нулями до 12 символов слева
* @param string $string Входящее число (Глобальный номер товарной продукции)
* @return string
*/
private function numToHex($string)
{
return str_pad($this->base_convert($string), 12, '0', STR_PAD_LEFT);
}
/**
* Переводит число из одной системы исчисления в другую
* Замена dechex() для 32-битных версии PHP
*
* @param string $numString
* @param int $fromBase
* @param int $toBase
* @return string
*/
private function base_convert($numString, $fromBase=10, $toBase=16)
{
$chars = "0123456789abcdefghijklmnopqrstuvwxyz";
$toString = substr($chars, 0, $toBase);
$length = strlen($numString);
$result = '';
$number = array();
for ($i = 0; $i < $length; $i++) {
$number[$i] = strpos($chars, substr($numString, $i, 1));
}
do {
$divide = 0;
$newLen = 0;
for ($i = 0; $i < $length; $i++) {
$divide = $divide * $fromBase + $number[$i];
if ($divide >= $toBase) {
$number[$newLen++] = (int)($divide / $toBase);
$divide = $divide % $toBase;
} elseif ($newLen > 0) {
$number[$newLen++] = 0;
}
}
$length = $newLen;
$result = substr($toString, $divide, 1) . $result;
} while ($newLen != 0);
return $result;
}
/**
* Переводит строку в шестнадцатеричный вид
* @param string $string Входящая строка (Серийный номер товара)
* @return string
*/
private function strToHex($string)
{
$hex = '';
for ($i = 0; $i < strlen($string); $i++) {
$ord = ord($string[$i]);
$hexCode = dechex($ord);
$hex .= substr('0' . $hexCode, -2);
}
return $hex;
}
/**
* Переводит строку из шестнадцатеричного вида в обычный
* Нужен для тестирования
* @param string $hex Входящая строка в шестнадцатеричном виде
* @return string
*/
private function hexToStr($hex)
{
$string = '';
for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
$string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
}
return $string;
}
/**
* Приводит объект к строке
* @return string
*/
public function __toString()
{
return $this->getResult();
}
}
@@ -0,0 +1,166 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Helpers;
/**
* Класс хэлпера для генерации случайных значений, используется в тестах
*
* @package YooKassa\Helpers
*/
class Random
{
/**
* Возвращает рандомное целое число. По умолчанию возвращает число от нуля до PHP_INT_MAX.
* @param int|null $min Минимально возможное значение
* @param int|null $max Максимально возможное значение
* @param bool $useBest Использовать ли функцию random_int если она доступна
* @return int Рандомное целое число
* @throws \Exception
*/
public static function int($min = null, $max = null, $useBest = true)
{
if ($min === null) {
$min = 0;
}
if ($max === null) {
$max = PHP_INT_MAX;
}
if (function_exists('random_int') && $useBest) {
return random_int($min, $max);
} else {
return mt_rand($min, $max);
}
}
/**
* Возвращает рандомное число с плавающей точкой. По умолчанию возвращает значение в промежутке от нуля до едениы.
* @param float|null $min Минимально возможное значение
* @param float|null $max Максимально возможное значение
* @param bool $useBest Использовать ли функцию random_int если она доступна
* @return float Рандомное число с плавающей точкой
* @throws \Exception
*/
public static function float($min = null, $max = null, $useBest = true)
{
$random = self::int(null, null, $useBest) / PHP_INT_MAX;
if ($min === null) {
$min = 0.0;
}
if ($max === null) {
return $random + $min;
}
return ($random * ($max - $min)) + $min;
}
/**
* Возвращает строку из рандомных символов
* @param int $length Длина возвращаемой строки, или минимальная длина, если передан парамтр $maxLength
* @param int|null $maxLength Если параметр не равен null, возвращает сроку длиной от $length до $maxLength
* @param string|array|null $characters Строка или массив используемых в строке символов
* @param bool $useBest Использовать ли функцию random_int если она доступна
* @return string Строка, состоящая из рандомных символов
* @throws \Exception
*/
public static function str($length, $maxLength = null, $characters = null, $useBest = true)
{
$result = '';
if ($maxLength !== null) {
if (is_string($maxLength)) {
$characters = $maxLength;
} else {
$length = self::int($length, $maxLength, $useBest);
}
}
if ($characters === null) {
for ($i = 0; $i < $length; $i++) {
$chr = chr(self::int(32, 125, $useBest));
$result .= $chr;
}
} else {
for ($i = 0; $i < $length; $i++) {
$chr = $characters[self::int(0, strlen($characters) - 1, $useBest)];
$result .= $chr;
}
}
return $result;
}
/**
* Возвращает строку, состоящую из символов '0123456789abcdef'
* @param int $length Длина возвращаемой строки
* @param bool $useBest Использовать ли функцию random_int если она доступна
* @return string Строка, состоящая из рандомных символов
* @throws \Exception
*/
public static function hex($length, $useBest = true)
{
return self::str($length, '0123456789abcdef', $useBest);
}
/**
* Возвращает рандомную последовательность байт
* @param int $length Длина возвращаемой строки
* @param bool $useBest Использовать ли функцию random_int если она доступна
* @return string Строка, состоящая из рандомных символов
* @throws \Exception
*/
public static function bytes($length, $useBest = true)
{
if (function_exists('random_bytes') && $useBest) {
$result = random_bytes($length);
} else {
$result = '';
for ($i = 0; $i < $length; $i++) {
$chr = chr(self::int(0, 255));
$result .= $chr;
}
}
return $result;
}
/**
* Возвращает рандомное значение из переданного массива
* @param array $values Массив источник данных
* @param bool $useBest Использовать ли функцию random_int если она доступна
* @return mixed Случайное значение из переданного массива
* @throws \Exception
*/
public static function value(array $values, $useBest = true)
{
return $values[self::int(0, count($values) - 1, $useBest)];
}
/**
* Возвращает рандомное буллево значение
* @return bool Либо true либо false, одно из двух
* @throws \Exception
*/
public static function bool()
{
return self::int(0, 1) === 1;
}
}
@@ -0,0 +1,63 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Helpers;
class RawHeadersParser
{
public static function parse($rawHeaders)
{
$headers = array();
$key = '';
foreach (explode("\n", $rawHeaders) as $headerRow) {
if (trim($headerRow) === '') {
break;
}
$headerArray = explode(':', $headerRow, 2);
if (isset($headerArray[1])) {
if (!isset($headers[$headerArray[0]])) {
$headers[trim($headerArray[0])] = trim($headerArray[1]);
} elseif (is_array($headers[$headerArray[0]])) {
$headers[trim($headerArray[0])] = array_merge($headers[trim($headerArray[0])], array(trim($headerArray[1])));
} else {
$headers[trim($headerArray[0])] = array_merge(array($headers[trim($headerArray[0])]), array(trim($headerArray[1])));
}
$key = $headerArray[0];
} else {
if (substr($headerArray[0], 0, 1) === "\t") {
$headers[$key] .= "\r\n\t" . trim($headerArray[0]);
} elseif (!$key) {
$headers[0] = trim($headerArray[0]);
}
}
}
return $headers;
}
}
@@ -0,0 +1,58 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Helpers;
/**
* Класс объекта, кастящегося в строку, используется только в тестах
*
* @package YooKassa\Helpers
*/
class StringObject
{
/**
* @var string Значение, возвращаемое методом __toString
*/
private $value;
/**
* StringObject constructor.
* @param string $value
*/
public function __construct($value)
{
$this->value = (string)$value;
}
/**
* Возвращает строковое значение текущего объекта
* @return string Строковое представление объекта
*/
public function __toString()
{
return $this->value;
}
}
@@ -0,0 +1,126 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Helpers;
use DateTime;
use Exception;
/**
* Класс хэлпер для преобразования типов значений
*
* @package YooKassa\Helpers
*/
class TypeCast
{
/**
* Проверяет может ли переданное значение быть преобразовано в строку
* @param mixed $value Проверяемое значение
* @return bool True если значение преобразовать в строку можно, false если нет
*/
public static function canCastToString($value)
{
if (is_scalar($value)) {
return !is_bool($value) && !is_resource($value);
} elseif (is_object($value)) {
return method_exists($value, '__toString');
}
return false;
}
/**
* Проверяет можно ли преобразовать переданное значение в строку из перечисления
* @param mixed $value Проверяемое значение
* @return bool True если значение преобразовать в строку можно, false если нет
*/
public static function canCastToEnumString($value)
{
if (is_string($value) && $value !== '') {
return true;
} elseif (is_object($value)) {
return method_exists($value, '__toString');
}
return false;
}
/**
* Проверяет, можно ли преобразовать переданное значение в объект даты-времени
* @param mixed $value Провеяремое значение
* @return bool True если значение можно преобразовать в объект даты, false если нет
*/
public static function canCastToDateTime($value)
{
if ($value instanceof DateTime) {
return true;
} elseif (is_numeric($value)) {
$value = (float)$value;
return $value >= 0;
} elseif (is_string($value)) {
return $value !== '';
} elseif (is_object($value)) {
return method_exists($value, '__toString') && ((string)$value) !== '';
}
return false;
}
/**
* Преобразует переданне значение в объект типа \DateTime
* @param string|int|DateTime $value Преобразуемое значение
* @return DateTime|null Объект типа \DateTime или null если при парсинг даты не удался
* @throws Exception
*/
public static function castToDateTime($value)
{
if ($value instanceof DateTime) {
return clone $value;
}
if (is_numeric($value)) {
$date = new DateTime();
$date->setTimestamp((int)$value);
} elseif (is_string($value) || (is_object($value) && method_exists($value, '__toString'))) {
$date = date_create((string)$value);
if ($date === false) {
$date = null;
}
} else {
$date = null;
}
return $date;
}
/**
* Проверяет можно ли преобразовать переданное значение в буллево значение
* @param mixed $value Проверяемое значение
* @return bool True если значение качтится в bool, false если нет
*/
public static function canCastToBoolean($value)
{
if (is_numeric($value) || is_bool($value)) {
return true;
}
return false;
}
}
@@ -0,0 +1,23 @@
<?php
namespace YooKassa\Helpers;
class UUID
{
/**
* @return string
* @throws \Exception
*/
public static function v4()
{
$hexData = bin2hex(Random::bytes(16));
$parts = str_split($hexData, 4);
$parts[3] = '4' . substr($parts[3], 1);
$parts[4] = '8' . substr($parts[4], 1);
return vsprintf('%s%s-%s-%s-%s-%s%s%s',
$parts
);
}
}
@@ -0,0 +1,256 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
use YooKassa\Common\AbstractObject;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
/**
* Class Airline
*/
class Airline extends AbstractObject implements AirlineInterface
{
/**
* @var string Номер бронирования. Обязателен на этапе создания платежа.
*/
private $_bookingReference;
/**
* @var string Уникальный номер билета. Обязателен на этапе подтверждения платежа
*/
private $_ticketNumber;
/**
* @var PassengerInterface[]
*/
private $_passengers;
/**
* @var LegInterface[]
*/
private $_legs;
/**
* @inheritdoc
*/
public function getBookingReference()
{
return $this->_bookingReference;
}
/**
* @param string $value
*/
public function setBookingReference($value)
{
if ($value === null || $value === '') {
$this->_bookingReference = null;
} elseif (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException('Invalid booking reference value type', 0,
'airline.booking_reference');
} elseif (mb_strlen((string)$value, 'utf-8') > 20) {
throw new InvalidPropertyValueException('Invalid booking reference value: "'.$value.'"', 0,
'airline.booking_reference');
} else {
$this->_bookingReference = (string)$value;
}
}
/**
* @inheritdoc
*/
public function getTicketNumber()
{
return $this->_ticketNumber;
}
/**
* @param string $value
*/
public function setTicketNumber($value)
{
if ($value === null || $value === '') {
$this->_ticketNumber = null;
} elseif (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException('Invalid ticket number value type', 0,
'airline.ticket_number');
} elseif (!preg_match('/^[0-9]{1,150}$/', (string)$value)) {
throw new InvalidPropertyValueException('Invalid ticket_number value: "'.$value.'"', 0,
'airline.ticket_number');
} else {
$this->_ticketNumber = (string)$value;
}
}
/**
* @inheritdoc
*/
public function getPassengers()
{
return $this->_passengers;
}
/**
* @param array|PassengerInterface[] $value
*/
public function setPassengers($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty passengers value in airline', 0, 'airline.passengers');
}
if (!is_array($value) && !($value instanceof \Traversable)) {
throw new InvalidPropertyValueTypeException(
'Invalid passengers value type in airline', 0, 'airline.passengers', $value
);
}
$this->_passengers = array();
foreach ($value as $key => $val) {
try {
$this->addPassenger($val);
} catch (InvalidPropertyValueTypeException $exception) {
throw new InvalidPropertyValueTypeException(
'Invalid passenger value type in airline', 0, 'airline.passengers['.$key.']', $val
);
}
}
}
/**
* @param array|PassengerInterface $value
*/
public function addPassenger($value)
{
if ($value instanceof PassengerInterface) {
$this->_passengers[] = $value;
} elseif (is_array($value)) {
$passenger = new Passenger();
$passenger->fromArray($value);
$this->_passengers[] = $passenger;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid passenger value type in airline', 0
);
}
}
/**
* @inheritdoc
*/
public function getLegs()
{
return $this->_legs;
}
/**
* @param array|LegInterface[] $value
*/
public function setLegs($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty legs value in airline', 0, 'airline.passengers');
}
if (!is_array($value) && !($value instanceof \Traversable)) {
throw new InvalidPropertyValueTypeException(
'Invalid legs value type in airline', 0, 'airline.legs', $value
);
}
$this->_legs = array();
foreach ($value as $key => $val) {
try {
$this->addLeg($val);
} catch (InvalidPropertyValueTypeException $exception) {
throw new InvalidPropertyValueTypeException(
'Invalid legs value type in airline', 0, 'airline.legs['.$key.']', $val
);
}
}
}
/**
* @param array|LegInterface $value
*/
public function addLeg($value)
{
if ($value instanceof LegInterface) {
$this->_legs[] = $value;
} elseif (is_array($value)) {
$leg = new Leg();
$leg->fromArray($value);
$this->_legs[] = $leg;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid passenger value type in airline', 0
);
}
}
/**
* Првоерка на наличие данных
* @return bool
*/
public function notEmpty()
{
return $this->_legs || $this->_passengers || $this->_ticketNumber || $this->_bookingReference;
}
/**
* @inheritdoc
*/
public function fromArray($sourceArray)
{
if (is_array($sourceArray['passengers']) && !empty($sourceArray['passengers'])) {
$sourceArray['passengers'] = array_map(function ($passengerData) {
if (is_array($passengerData)) {
$passenger = new Passenger();
$passenger->fromArray($passengerData);
return $passenger;
} elseif ($passengerData instanceof PassengerInterface) {
return $passengerData;
}
}, $sourceArray['passengers']);
}
if (is_array($sourceArray['legs']) && !empty($sourceArray['legs'])) {
$sourceArray['legs'] = array_map(function ($legData) {
if (is_array($legData)) {
$leg = new Leg();
$leg->fromArray($legData);
return $leg;
} elseif ($legData instanceof LegInterface) {
return $legData;
}
}, $sourceArray['legs']);
}
parent::fromArray($sourceArray);
}
}
@@ -0,0 +1,59 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
interface AirlineInterface
{
/**
* Номер бронирования. Обязателен на этапе создания платежа.
*
* @return string
*/
public function getBookingReference();
/**
* Уникальный номер билета. Обязателен на этапе подтверждения платежа
*
* @return string
*/
public function getTicketNumber();
/**
* Список объектов-контейнеров с данными пассажиров
*
* @return PassengerInterface[]
*/
public function getPassengers();
/**
* Список объектов-контейнеров с данными о маршруте
*
* @return LegInterface[]
*/
public function getLegs();
}
@@ -0,0 +1,67 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
/**
* Interface AmountInterface
*
* @package YooKassa\Model
*
* @property-read string $value Сумма
* @property-read string $currency Код валюты
*/
interface AmountInterface
{
/**
* Возвращает значение суммы
* @return string Сумма
*/
public function getValue();
/**
* @param $value
*/
public function setValue($value);
/**
* Возвращает сумму в копейках в виде целого числа
* @return int Сумма в копейках/центах
*/
public function getIntegerValue();
/**
* Возвращает валюту
* @return string Код валюты
*/
public function getCurrency();
/**
* Устанавливает код валюты
* @param string $value Код валюты
*/
public function setCurrency($value);
}
@@ -0,0 +1,127 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
use YooKassa\Common\AbstractObject;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
/**
* AuthorizationDetails - Данные об авторизации платежа
*
* @property $rrn Retrieval Reference Number — уникальный идентификатор транзакции в системе эмитента
* @property string $authCode Код авторизации банковской карты
*/
class AuthorizationDetails extends AbstractObject implements AuthorizationDetailsInterface
{
/**
* @var string Уникальный идентификатор транзакции
*/
private $_rrn = '';
/**
* @var string Код авторизации банковской карты
*/
private $_authCode = '';
/**
* @param string|null $rrn Уникальный идентификатор транзакции
* @param string|null $authCode Код авторизации банковской карты
*/
public function __construct($rrn = null, $authCode = null)
{
if ($rrn !== null) {
$this->setRrn($rrn);
}
if ($authCode !== null) {
$this->setAuthCode($authCode);
}
}
/**
* Возвращает уникальный идентификатор транзакции
*
* @return string|null Уникальный идентификатор транзакции
*/
public function getRrn()
{
return $this->_rrn;
}
/**
* Возвращает код авторизации банковской карты
*
* @return string|null Код авторизации банковской карты
*/
public function getAuthCode()
{
return $this->_authCode;
}
/**
* @return array
*/
public function jsonSerialize()
{
return array(
'rrn' => $this->_rrn,
'auth_code' => $this->_authCode,
);
}
/**
* Устанавливает уникальный идентификатор транзакции
* @param $value
*/
public function setRrn($value)
{
if ($value === null || $value === '') {
$this->_rrn = $value;
} elseif (TypeCast::canCastToEnumString($value)) {
$this->_rrn = (string)$value;
} else {
throw new InvalidPropertyValueTypeException('Invalid rrn value type', 0,
'authorization_details.rrn', $value);
}
}
/**
* Устанавливает код авторизации банковской карты
* @param $value
*/
public function setAuthCode($value)
{
if ($value === null || $value === '') {
$this->_authCode = $value;
} elseif (TypeCast::canCastToEnumString($value)) {
$this->_authCode = (string)$value;
} else {
throw new InvalidPropertyValueTypeException('Invalid auth_code value type', 0,
'authorization_details.auth_code', $value);
}
}
}
@@ -0,0 +1,51 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
/**
* Interface AuthorizationDetailsInterface - Данные об авторизации платежа
*
* @package YooKassa\Model
*
* @property-read string $rrn Retrieval Reference Number — уникальный идентификатор транзакции в системе эмитента
* @property-read string $authCode Код авторизации банковской карты
*/
interface AuthorizationDetailsInterface
{
/**
* Возвращает Retrieval Reference Number — уникальный идентификатор транзакции в системе эмитента
* @return string|null Уникальный идентификатор транзакции
*/
function getRrn();
/**
* Возвращает код авторизации банковской карты
* @return string|null Код авторизации банковской карты
*/
function getAuthCode();
}
@@ -0,0 +1,127 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
use YooKassa\Common\AbstractObject;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
/**
* CancellationDetails - Комментарий к отмене платежа
*
* @property string $party Инициатор отмены платежа
* @property string $reason Причина отмены платежа
*/
class CancellationDetails extends AbstractObject implements CancellationDetailsInterface
{
/**
* @var string Инициатор отмены платежа
*/
private $_party = '';
/**
* @var string Причина отмены платежа
*/
private $_reason = '';
/**
* CancellationDetails constructor.
* @param string|null $party Инициатор отмены платежа
* @param string|null $reason Причина отмены платежа
*/
public function __construct($party = null, $reason = null)
{
if ($party !== null) {
$this->setParty($party);
}
if ($reason !== null) {
$this->setReason($reason);
}
}
/**
* Возвращает участника процесса платежа, который принял решение об отмене транзакции
*
* @return string Инициатор отмены платежа
*/
public function getParty()
{
return $this->_party;
}
/**
* Возвращает причину отмены платежа
*
* @return string Причина отмены платежа
*/
public function getReason()
{
return $this->_reason;
}
/**
* @return array
*/
public function jsonSerialize()
{
return array(
'party' => $this->_party,
'reason' => $this->_reason,
);
}
/**
* Устанавливает участника процесса платежа, который принял решение об отмене транзакции
* @param $value
*/
public function setParty($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty party value', 0, 'cancellation_details.party');
} elseif (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException('Invalid party value type', 0, 'cancellation_details.party', $value);
} else {
$this->_party = strtolower((string)$value);
}
}
/**
* Устанавливает причину отмены платежа
* @param $value
*/
public function setReason($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty reason value', 0, 'cancellation_details.reason');
} elseif (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException('Invalid reason value type', 0, 'cancellation_details.reason');
} else {
$this->_reason = strtolower((string)$value);
}
}
}
@@ -0,0 +1,51 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
/**
* Interface CancellationDetailsInterface
*
* @package YooKassa\Model
*
* @property-read string $party Участник процесса платежа, который принял решение об отмене транзакции.
* @property-read string $reason Причина отмены платежа.
*/
interface CancellationDetailsInterface
{
/**
* Возвращает участника процесса платежа, который принял решение об отмене транзакции
* @return string Участник процесса платежа
*/
function getParty();
/**
* Возвращает причину отмены платежа
* @return string Причина отмены платежа
*/
function getReason();
}
@@ -0,0 +1,57 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
use YooKassa\Common\AbstractEnum;
/**
* CancellationDetailsPartyCode - Возможные инициаторы отмены платежа
*/
class CancellationDetailsPartyCode extends AbstractEnum
{
/**
* Продавец товаров и услуг
*/
const MERCHANT = 'merchant';
/**
* ЮKassa
*/
const YOO_KASSA = 'yoo_kassa';
/**
* «Внешние» участники платежного процесса (например, эмитент, сторонний платежный сервис)
*/
const PAYMENT_NETWORK = 'payment_network';
protected static $validValues = array(
self::MERCHANT => true,
self::YOO_KASSA => true,
self::PAYMENT_NETWORK => true,
);
}
@@ -0,0 +1,77 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
use YooKassa\Common\AbstractEnum;
/**
* CancellationDetailsReasonCode - Возможные причины отмены платежа
*/
class CancellationDetailsReasonCode extends AbstractEnum
{
const THREE_D_SECURE_FAILED = '3d_secure_failed';
const CALL_ISSUER = 'call_issuer';
const CARD_EXPIRED = 'card_expired';
const COUNTRY_FORBIDDEN = 'country_forbidden';
const FRAUD_SUSPECTED = 'fraud_suspected';
const GENERAL_DECLINE = 'general_decline';
const IDENTIFICATION_REQUIRED = 'identification_required';
const INSUFFICIENT_FUNDS = 'insufficient_funds';
const INVALID_CARD_NUMBER = 'invalid_card_number';
const INVALID_CSC = 'invalid_csc';
const ISSUER_UNAVAILABLE = 'issuer_unavailable';
const PAYMENT_METHOD_LIMIT_EXCEEDED = 'payment_method_limit_exceeded';
const PAYMENT_METHOD_RESTRICTED = 'payment_method_restricted';
const PERMISSION_REVOKED = 'permission_revoked';
const INTERNAL_TIMEOUT = 'internal_timeout';
const CANCELED_BY_MERCHANT = 'canceled_by_merchant';
const PAYMENT_EXPIRED = 'payment_expired';
const EXPIRED_ON_CONFIRMATION = 'expired_on_confirmation';
const EXPIRED_ON_CAPTURE = 'expired_on_capture';
protected static $validValues = array(
self::THREE_D_SECURE_FAILED => true,
self::CALL_ISSUER => true,
self::CARD_EXPIRED => true,
self::COUNTRY_FORBIDDEN => true,
self::FRAUD_SUSPECTED => true,
self::GENERAL_DECLINE => true,
self::IDENTIFICATION_REQUIRED => true,
self::INSUFFICIENT_FUNDS => true,
self::INVALID_CARD_NUMBER => true,
self::INVALID_CSC => true,
self::ISSUER_UNAVAILABLE => true,
self::PAYMENT_METHOD_LIMIT_EXCEEDED => true,
self::PAYMENT_METHOD_RESTRICTED => true,
self::PERMISSION_REVOKED => true,
self::INTERNAL_TIMEOUT => true,
self::CANCELED_BY_MERCHANT => true,
self::PAYMENT_EXPIRED => true,
self::EXPIRED_ON_CONFIRMATION => true,
self::EXPIRED_ON_CAPTURE => true,
);
}
@@ -0,0 +1,83 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\Confirmation;
use YooKassa\Common\AbstractObject;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\ConfirmationType;
/**
* Способ подтверждения платежа.
*
* @property-read string $type
*
* @method getConfirmationUrl
* @method getConfirmationToken
* @method getConfirmationData
*/
abstract class AbstractConfirmation extends AbstractObject
{
/**
* @var string
*/
private $_type;
/**
* @return string
*/
public function getType()
{
return $this->_type;
}
/**
* @param string $value
*/
protected function _setType($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException(
'Empty value for "type" parameter in Confirmation', 0, 'confirmation.type'
);
} elseif (TypeCast::canCastToEnumString($value)) {
if (ConfirmationType::valueExists($value)) {
$this->_type = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid value for "type" parameter in Confirmation', 0, 'confirmation.type', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid value type for "type" parameter in Confirmation', 0, 'confirmation.type', $value
);
}
}
}
@@ -0,0 +1,42 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\Confirmation;
use YooKassa\Model\ConfirmationType;
/**
* Сценарий при котором необходимо получить одноразовый код от плательщика для подтверждения платежа
*
* @package YooKassa\Model\Confirmation
*/
class ConfirmationCodeVerification extends AbstractConfirmation
{
public function __construct()
{
$this->_setType(ConfirmationType::CODE_VERIFICATION);
}
}
@@ -0,0 +1,42 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\Confirmation;
use YooKassa\Model\ConfirmationType;
/**
* Сценарий при котором необходимо направить плательщика в приложение партнера
*
* @package YooKassa\Model\Confirmation
*/
class ConfirmationDeepLink extends AbstractConfirmation
{
public function __construct()
{
$this->_setType(ConfirmationType::DEEPLINK);
}
}
@@ -0,0 +1,68 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\Confirmation;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\ConfirmationType;
/**
* @property string $confirmationToken Токен для checkout.js
*/
class ConfirmationEmbedded extends AbstractConfirmation
{
private $confirmationToken;
public function __construct()
{
$this->_setType(ConfirmationType::EMBEDDED);
}
/**
* @return string
*/
public function getConfirmationToken()
{
return $this->confirmationToken;
}
/**
* @param string $confirmationToken
*/
public function setConfirmationToken($confirmationToken)
{
if ($confirmationToken === null || $confirmationToken === '') {
$this->confirmationToken = null;
} elseif (TypeCast::canCastToString($confirmationToken)) {
$this->confirmationToken = (string)$confirmationToken;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid confirmationToken value type', 0, 'confirmationEmbedded.confirmationToken', $confirmationToken
);
}
}
}
@@ -0,0 +1,43 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\Confirmation;
use YooKassa\Model\ConfirmationType;
/**
* Сценарий при котором необходимо ожидать пока пользователь самостоятельно подтвердит платеж. Например,
* пользователь подтверждает платеж ответом на SMS или в приложении партнера
*
* @package YooKassa\Model\Confirmation
*/
class ConfirmationExternal extends AbstractConfirmation
{
public function __construct()
{
$this->_setType(ConfirmationType::EXTERNAL);
}
}
@@ -0,0 +1,92 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\Confirmation;
use YooKassa\Model\ConfirmationType;
/**
* Class ConfirmationFactory
*
* @package YooKassa\Model\Confirmation
*/
class ConfirmationFactory
{
private $typeClassMap = array(
ConfirmationType::CODE_VERIFICATION => 'ConfirmationCodeVerification',
ConfirmationType::DEEPLINK => 'ConfirmationDeepLink',
ConfirmationType::EXTERNAL => 'ConfirmationExternal',
ConfirmationType::REDIRECT => 'ConfirmationRedirect',
ConfirmationType::EMBEDDED => 'ConfirmationEmbedded',
ConfirmationType::QR => 'ConfirmationQr',
);
/**
* @param string $type
*
* @return AbstractConfirmation
*/
public function factory($type)
{
if (!is_string($type)) {
throw new \InvalidArgumentException('Invalid confirmation value in confirmation factory');
}
if (!array_key_exists($type, $this->typeClassMap)) {
throw new \InvalidArgumentException('Invalid confirmation value type "'.$type.'"');
}
$className = __NAMESPACE__.'\\'.$this->typeClassMap[$type];
return new $className();
}
/**
* @param array $data
* @param string|null $type
*
* @return AbstractConfirmation
*/
public function factoryFromArray(array $data, $type = null)
{
if ($type === null) {
if (array_key_exists('type', $data)) {
$type = $data['type'];
unset($data['type']);
} else {
throw new \InvalidArgumentException(
'Parameter type not specified in ConfirmationFactory.factoryFromArray()'
);
}
}
$confirmation = $this->factory($type);
foreach ($data as $key => $value) {
if ($confirmation->offsetExists($key)) {
$confirmation->offsetSet($key, $value);
}
}
return $confirmation;
}
}
@@ -0,0 +1,69 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\Confirmation;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\ConfirmationType;
/**
* @property string $confirmationData URL для создания QR-кода
* @property string $confirmation_data URL для создания QR-кода
*/
class ConfirmationQr extends AbstractConfirmation
{
private $_confirmationData;
public function __construct()
{
$this->_setType(ConfirmationType::QR);
}
/**
* @return string
*/
public function getConfirmationData()
{
return $this->_confirmationData;
}
/**
* @param string $confirmationData
*/
public function setConfirmationData($confirmationData)
{
if ($confirmationData === null || $confirmationData === '') {
$this->_confirmationData = null;
} elseif (TypeCast::canCastToString($confirmationData)) {
$this->_confirmationData = (string)$confirmationData;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid confirmationData value type', 0, 'confirmationQr.confirmationData', $confirmationData
);
}
}
}
@@ -0,0 +1,143 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\Confirmation;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\ConfirmationType;
/**
* Сценарий, при котором необходимо отправить плательщика на веб-страницу ЮKassa или партнера для
* подтверждения платежа
*
* @property bool $enforce Требование принудительного подтверждения платежа покупателем, требование 3-D Secure для
* оплаты банковскими картами. По умолчанию определяется политикой платежной системы.
* @property string $returnUrl URL на который вернется плательщик после подтверждения или отмены платежа на
* странице партнера.
* @property string $return_url URL на который вернется плательщик после подтверждения или отмены платежа на
* странице партнера.
* @property string $confirmationUrl URL на который необходимо перенаправить плательщика для подтверждения оплаты.
* @property string $confirmation_url URL на который необходимо перенаправить плательщика для подтверждения оплаты.
*/
class ConfirmationRedirect extends AbstractConfirmation
{
/**
* @var bool Требование принудительного подтверждения платежа покупателем, требование 3-D Secure для оплаты
* банковскими картами. По умолчанию определяется политикой платежной системы.
*/
private $_enforce;
/**
* @var string URL на который вернется плательщик после подтверждения или отмены платежа на странице партнера.
*/
private $_returnUrl;
/**
* @var string URL на который необходимо перенаправить плательщика для подтверждения оплаты.
*/
private $_confirmationUrl;
public function __construct()
{
$this->_setType(ConfirmationType::REDIRECT);
}
/**
* @return bool Требование принудительного подтверждения платежа покупателем, требование 3-D Secure для
* оплаты банковскими картами. По умолчанию определяется политикой платежной системы.
*/
public function getEnforce()
{
return $this->_enforce;
}
/**
* @param bool $value Требование принудительного подтверждения платежа покупателем, требование 3-D Secure
* для оплаты банковскими картами. По умолчанию определяется политикой платежной системы.
*/
public function setEnforce($value)
{
if ($value === null || $value === '') {
$this->_enforce = null;
} elseif (TypeCast::canCastToBoolean($value)) {
$this->_enforce = (bool)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid enforce value type', 0, 'confirmationRedirect.enforce', $value
);
}
}
/**
* @return string URL на который вернется плательщик после подтверждения или отмены платежа на странице партнера.
*/
public function getReturnUrl()
{
return $this->_returnUrl;
}
/**
* @param string $value URL на который вернется плательщик после подтверждения или отмены платежа на
* странице партнера.
*/
public function setReturnUrl($value)
{
if ($value === null || $value === '') {
$this->_returnUrl = null;
} elseif (TypeCast::canCastToString($value)) {
$this->_returnUrl = (string)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid returnUrl value type', 0, 'confirmationRedirect.returnUrl', $value
);
}
}
/**
* @return string URL на который необходимо перенаправить плательщика для подтверждения оплаты.
*/
public function getConfirmationUrl()
{
return $this->_confirmationUrl;
}
/**
* @param string $value URL на который необходимо перенаправить плательщика для подтверждения оплаты.
*/
public function setConfirmationUrl($value)
{
if ($value === null || $value === '') {
$this->_confirmationUrl = null;
} elseif (TypeCast::canCastToString($value)) {
$this->_confirmationUrl = (string)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid confirmationUrl value type', 0, 'confirmationRedirect.confirmationUrl', $value
);
}
}
}
@@ -0,0 +1,112 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\ConfirmationAttributes;
use YooKassa\Common\AbstractObject;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\ConfirmationType;
/**
* Способ подтверждения платежа
*
* @property-read string $type
*/
abstract class AbstractConfirmationAttributes extends AbstractObject
{
/**
* @var string
*/
private $_type;
/**
* @var string
*/
private $_locale;
/**
* @return string
*/
public function getType()
{
return $this->_type;
}
/**
* @param string $value
*/
protected function _setType($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException(
'Empty value for "type" parameter in ConfirmationAttributes', 0, 'confirmationAttributes.type'
);
} elseif (TypeCast::canCastToEnumString($value)) {
if (ConfirmationType::valueExists($value)) {
$this->_type = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid value for "type" parameter in ConfirmationAttributes', 0, 'confirmationAttributes.type', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid value type for "type" parameter in ConfirmationAttributes', 0, 'confirmationAttributes.type', $value
);
}
}
/**
* @return string
*/
public function getLocale()
{
return $this->_locale;
}
/**
* @param string $value
*/
public function setLocale($value)
{
if ($value === null || $value === '') {
$this->_locale = null;
} elseif (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException(
'Invalid value type for "locale" parameter in ConfirmationAttributes', 0, 'confirmationAttributes.locale', $value
);
} elseif (!preg_match('/^[a-z]{2}_[A-Z]{2}$/', (string)$value)) {
throw new InvalidPropertyValueException(
'Invalid value type for "locale" parameter in ConfirmationAttributes', 0, 'confirmationAttributes.locale', $value
);
} else {
$this->_locale = (string)$value;
}
}
}
@@ -0,0 +1,42 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\ConfirmationAttributes;
use YooKassa\Model\ConfirmationType;
/**
* Сценарий при котором необходимо получить одноразовый код от плательщика для подтверждения платежа
*
* @package YooKassa\Model\ConfirmationAttributes
*/
class ConfirmationAttributesCodeVerification extends AbstractConfirmationAttributes
{
public function __construct()
{
$this->_setType(ConfirmationType::CODE_VERIFICATION);
}
}
@@ -0,0 +1,42 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\ConfirmationAttributes;
use YooKassa\Model\ConfirmationType;
/**
* Сценарий при котором необходимо направить плательщика в приложение партнера
*
* @package YooKassa\Model\ConfirmationAttributes
*/
class ConfirmationAttributesDeepLink extends AbstractConfirmationAttributes
{
public function __construct()
{
$this->_setType(ConfirmationType::DEEPLINK);
}
}
@@ -0,0 +1,37 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\ConfirmationAttributes;
use YooKassa\Model\ConfirmationType;
class ConfirmationAttributesEmbedded extends AbstractConfirmationAttributes
{
public function __construct()
{
$this->_setType(ConfirmationType::EMBEDDED);
}
}
@@ -0,0 +1,42 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\ConfirmationAttributes;
use YooKassa\Model\ConfirmationType;
/**
* Сценарий при котором необходимо ожидать пока пользователь самостоятельно подтвердит платеж. Например,
* пользователь подтверждает платеж ответом на SMS или в приложении партнера
* @package YooKassa\Model\ConfirmationAttributes
*/
class ConfirmationAttributesExternal extends AbstractConfirmationAttributes
{
public function __construct()
{
$this->_setType(ConfirmationType::EXTERNAL);
}
}
@@ -0,0 +1,92 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\ConfirmationAttributes;
use YooKassa\Model\ConfirmationType;
/**
* Class ConfirmationAttributesFactory
*
* @package YooKassa\Model\ConfirmationAttributes
*/
class ConfirmationAttributesFactory
{
private $typeClassMap = array(
ConfirmationType::CODE_VERIFICATION => 'ConfirmationAttributesCodeVerification',
ConfirmationType::DEEPLINK => 'ConfirmationAttributesDeepLink',
ConfirmationType::EXTERNAL => 'ConfirmationAttributesExternal',
ConfirmationType::REDIRECT => 'ConfirmationAttributesRedirect',
ConfirmationType::EMBEDDED => 'ConfirmationAttributesEmbedded',
ConfirmationType::QR => 'ConfirmationAttributesQr',
);
/**
* @param string $type
*
* @return AbstractConfirmationAttributes
*/
public function factory($type)
{
if (!is_string($type)) {
throw new \InvalidArgumentException('Invalid confirmation attributes value in confirmation factory');
}
if (!array_key_exists($type, $this->typeClassMap)) {
throw new \InvalidArgumentException('Invalid confirmation attributes value type "'.$type.'"');
}
$className = __NAMESPACE__.'\\'.$this->typeClassMap[$type];
return new $className();
}
/**
* @param array $data
* @param string|null $type
*
* @return AbstractConfirmationAttributes
*/
public function factoryFromArray(array $data, $type = null)
{
if ($type === null) {
if (array_key_exists('type', $data)) {
$type = $data['type'];
unset($data['type']);
} else {
throw new \InvalidArgumentException(
'Parameter type not specified in ConfirmationAttributesFactory.factoryFromArray()'
);
}
}
$confirmation = $this->factory($type);
foreach ($data as $key => $value) {
if ($confirmation->offsetExists($key)) {
$confirmation->offsetSet($key, $value);
}
}
return $confirmation;
}
}
@@ -0,0 +1,37 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\ConfirmationAttributes;
use YooKassa\Model\ConfirmationType;
class ConfirmationAttributesQr extends AbstractConfirmationAttributes
{
public function __construct()
{
$this->_setType(ConfirmationType::QR);
}
}
@@ -0,0 +1,109 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\ConfirmationAttributes;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\ConfirmationType;
/**
* @property bool $enforce Требование принудительного подтверждения платежа покупателем, требование 3-D Secure для
* оплаты банковскими картами. По умолчанию определяется политикой платежной системы.
* @property string $returnUrl URL на который вернется плательщик после подтверждения или отмены платежа
* на странице партнера.
* @property string $return_url URL на который вернется плательщик после подтверждения или отмены платежа
* на странице партнера.
*/
class ConfirmationAttributesRedirect extends AbstractConfirmationAttributes
{
/**
* @var bool Требование принудительного подтверждения платежа покупателем, требование 3-D Secure для оплаты
* банковскими картами. По умолчанию определяется политикой платежной системы.
*/
private $_enforce;
/**
* @var string URL на который вернется плательщик после подтверждения или отмены платежа на странице партнера.
*/
private $_returnUrl;
public function __construct()
{
$this->_setType(ConfirmationType::REDIRECT);
}
/**
* @return bool Требование принудительного подтверждения платежа покупателем, требование 3-D Secure для
* оплаты банковскими картами. По умолчанию определяется политикой платежной системы.
*/
public function getEnforce()
{
return $this->_enforce;
}
/**
* @param bool $value Требование принудительного подтверждения платежа покупателем, требование 3-D Secure
* для оплаты банковскими картами. По умолчанию определяется политикой платежной системы.
*/
public function setEnforce($value)
{
if ($value === null || $value === '') {
$this->_enforce = null;
} elseif (TypeCast::canCastToBoolean($value)) {
$this->_enforce = (bool)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid enforce value type', 0, 'confirmationAttributesRedirect.enforce', $value
);
}
}
/**
* @return string URL на который вернется плательщик после подтверждения или отмены платежа на странице партнера.
*/
public function getReturnUrl()
{
return $this->_returnUrl;
}
/**
* @param string $value URL на который вернется плательщик после подтверждения или отмены платежа
* на странице партнера.
*/
public function setReturnUrl($value)
{
if ($value === null || $value === '') {
$this->_returnUrl = null;
} elseif (TypeCast::canCastToString($value)) {
$this->_returnUrl = (string)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid returnUrl value type', 0, 'confirmationAttributesRedirect.returnUrl', $value
);
}
}
}
@@ -0,0 +1,59 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
use YooKassa\Common\AbstractEnum;
/**
* ConfirmationType - Тип пользовательского процесса подтверждения платежа
* |Код|Описание|
* --- | ---
* |redirect|Необходимо направить плательщика на страницу партнера|
* |external|Необходимо ождать пока плательщик самостоятельно подтвердит платеж|
* |deeplink|Необходимо направить плательщика в приложение партнера|
* |code_verification|Необходимо получить одноразовый код от плательщика для подтверждения платежа|
* |embedded|Необходимо получить токен для checkout.js|
* |qr|Необходимо получить QR-код|
*/
class ConfirmationType extends AbstractEnum
{
const REDIRECT = 'redirect';
const EXTERNAL = 'external';
const DEEPLINK = 'deeplink';
const CODE_VERIFICATION = 'code_verification';
const EMBEDDED = 'embedded';
const QR = 'qr';
protected static $validValues = array(
self::REDIRECT => true,
self::EXTERNAL => true,
self::DEEPLINK => false,
self::CODE_VERIFICATION => false,
self::EMBEDDED => true,
self::QR => true,
);
}
@@ -0,0 +1,53 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
use YooKassa\Common\AbstractEnum;
/**
* CurrencyCode - Код валюты, ISO-4217 3-alpha currency symbol
*/
class CurrencyCode extends AbstractEnum
{
const RUB = 'RUB';
const USD = 'USD';
const EUR = 'EUR';
const BYN = 'BYN';
const CNY = 'CNY';
const KZT = 'KZT';
const UAH = 'UAH';
protected static $validValues = array(
self::RUB => true,
self::USD => true,
self::EUR => true,
self::BYN => true,
self::CNY => true,
self::KZT => true,
self::UAH => true,
);
}
+129
View File
@@ -0,0 +1,129 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
use YooKassa\Common\AbstractObject;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
class Leg extends AbstractObject implements LegInterface
{
const ISO8601 = 'Y-m-d';
/**
* @var string Трёхбуквенный IATA-код аэропорта вылета
*/
private $_departureAirport;
/**
* @var string Трёхбуквенный IATA-код аэропорта прилёта
*/
private $_destinationAirport;
/**
* @var string Дата вылета в формате YYYY-MM-DD ISO 8601:2004
*/
private $_departureDate;
/**
* @inheritdoc
*/
public function getDepartureAirport()
{
return $this->_departureAirport;
}
/**
* @param string $value
*/
public function setDepartureAirport($value)
{
if (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException('Invalid departure_airport value type', 0,
'airline.departure_airport');
} elseif (!preg_match('/^[A-Z]{3}$/', (string)$value)) {
throw new InvalidPropertyValueException('Invalid departure_airport value: "'.$value.'"', 0,
'airline.departure_airport');
} else {
$this->_departureAirport = (string)$value;
}
}
/**
* @inheritdoc
*/
public function getDestinationAirport()
{
return $this->_destinationAirport;
}
/**
* @param string $value
*/
public function setDestinationAirport($value)
{
if (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException('Invalid destination_airport value type', 0,
'airline.destination_airport');
} elseif (!preg_match('/^[A-Z]{3}$/', (string)$value)) {
throw new InvalidPropertyValueException('Invalid destination_airport value: "'.$value.'"', 0,
'airline.destination_airport');
} else {
$this->_destinationAirport = (string)$value;
}
}
/**
* @inheritdoc
*/
public function getDepartureDate()
{
return $this->_departureDate;
}
/**
* @param \DateTime|string $value
* @throws \Exception
*/
public function setDepartureDate($value)
{
if (TypeCast::canCastToDateTime($value)) {
$departureDate = TypeCast::castToDateTime($value);
if ($departureDate === null) {
throw new InvalidPropertyValueException(
'Invalid departure_date value in airline.legs', 0, 'airline.legs'
);
}
$this->_departureDate = $departureDate->format(self::ISO8601);
} else {
throw new InvalidPropertyValueTypeException(
'Invalid departure_date value type in airline.legs', 0, 'airline.legs'
);
}
}
}
@@ -0,0 +1,45 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
interface LegInterface
{
/**
* @return string Трёхбуквенный IATA-код аэропорта вылета
*/
public function getDepartureAirport();
/**
* @return string Трёхбуквенный IATA-код аэропорта прилёта
*/
public function getDestinationAirport();
/**
* @return string Дата вылета в формате YYYY-MM-DD ISO 8601:2004
*/
public function getDepartureDate();
}
@@ -0,0 +1,59 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
use YooKassa\Common\AbstractObject;
/**
* Metadata - Метаданные платежа указанные мерчантом.
* Мерчант может добавлять произвольные данные к платежам в виде набора пар ключ-значение.
* Имена ключей уникальны.
*
*/
class Metadata extends AbstractObject implements \IteratorAggregate, \Countable
{
public function toArray()
{
return $this->getUnknownProperties();
}
/**
* @return \Iterator
*/
public function getIterator()
{
return new \ArrayIterator($this->getUnknownProperties());
}
/**
* @return int
*/
public function count()
{
return count($this->getUnknownProperties());
}
}
@@ -0,0 +1,224 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
use YooKassa\Common\AbstractObject;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
/**
* MonetaryAmount - Сумма определенная в валюте
*
* @property string $value Сумма
* @property string $currency Код валюты
*/
class MonetaryAmount extends AbstractObject implements AmountInterface
{
/**
* @var int Сумма
*/
private $_value = 0;
/**
* @var string Код валюты
*/
private $_currency = CurrencyCode::RUB;
/**
* MonetaryAmount constructor.
* @param string|null $value Сумма
* @param string|null $currency Код валюты
*/
public function __construct($value = null, $currency = null)
{
if ($value !== null && $value > 0.0) {
$this->setValue($value);
}
if ($currency !== null) {
$this->setCurrency($currency);
}
}
/**
* Возвращает значение суммы
* @return string Сумма
*/
public function getValue()
{
if ($this->_value < 10) {
return '0.0' . $this->_value;
} elseif ($this->_value < 100) {
return '0.' . $this->_value;
} else {
return substr($this->_value, 0, -2) . '.' . substr($this->_value, -2);
}
}
/**
* Устанавливает сумму
* @param string $value Сумма
*
* @throws EmptyPropertyValueException Генерируется если было передано пустое значение
* @throws InvalidPropertyValueTypeException Генерируется если было передано значение невалидного типа
* @throws InvalidPropertyValueException Генерируется если было передано не валидное значение
*/
public function setValue($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty amount value', 0, 'amount.value');
}
if (!is_numeric($value)) {
throw new InvalidPropertyValueTypeException('Invalid amount value type', 0, 'amount.value', $value);
}
if ($value <= 0.0) {
throw new InvalidPropertyValueException('Invalid amount value: "'.$value.'"', 0, 'amount.value', $value);
}
$castedValue = (int)round($value * 100.0);
if ($castedValue <= 0.0) {
throw new InvalidPropertyValueException('Invalid amount value: "'.$value.'"', 0, 'amount.value', $value);
}
$this->_value = $castedValue;
}
/**
* Возвращает сумму в копейках в виде целого числа
* @return int Сумма в копейках/центах
*/
public function getIntegerValue()
{
return $this->_value;
}
/**
* Возвращает валюту
* @return string Код валюты
*/
public function getCurrency()
{
return $this->_currency;
}
/**
* Устанавливает код валюты
* @param string $value Код валюты
*
* @throws EmptyPropertyValueException Генерируется если было передано пустое значение
* @throws InvalidPropertyValueTypeException Генерируется если было передано значение невалидного типа
* @throws InvalidPropertyValueException Генерируется если был передан неподдерживаемый код валюты
*/
public function setCurrency($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty currency value', 0, 'amount.currency');
}
if (TypeCast::canCastToEnumString($value)) {
$value = strtoupper((string)$value);
if (CurrencyCode::valueExists($value)) {
$this->_currency = $value;
} else {
throw new InvalidPropertyValueException(
'Invalid currency value: "' . $value . '"', 0, 'amount.currency', $value
);
}
} else {
throw new InvalidPropertyValueTypeException('Invalid currency value type', 0, 'amount.currency', $value);
}
}
/**
* Умножает текущую сумму на указанный коэффициент
* @param float $coefficient Множитель
*
* @throws EmptyPropertyValueException Выбрасывается если передано пустое значение
* @throws InvalidPropertyValueTypeException Выбрасывается если было передано не число
* @throws InvalidPropertyValueException Выбрасывается если переданное значение меньше или равно нулю, либо если
* после умножения получили значение равное нулю
*/
public function multiply($coefficient)
{
if ($coefficient === null || $coefficient === '') {
throw new EmptyPropertyValueException('Empty coefficient in multiply method', 0, 'amount.value');
}
if (!is_numeric($coefficient)) {
throw new InvalidPropertyValueTypeException(
'Invalid coefficient type in multiply method', 0, 'amount.value', $coefficient
);
}
if ($coefficient <= 0.0) {
throw new InvalidPropertyValueException(
'Invalid coefficient in multiply method: "' . $coefficient . '"', 0, 'amount.value', $coefficient
);
}
$castedValue = (int)round($coefficient * $this->_value);
if ($castedValue === 0) {
throw new InvalidPropertyValueException(
'Invalid coefficient value in multiply method: "' . $coefficient . '"', 0, 'amount.value', $coefficient
);
}
$this->_value = $castedValue;
}
/**
* Увеличивает сумму на указанное значение
* @param int $value Значение которое будет прибавлено к текущему
*
* @throws EmptyPropertyValueException Выбрасывается если передано пустое значение
* @throws InvalidPropertyValueTypeException Выбрасывается если было передано не число
* @throws InvalidPropertyValueException Выбрасывается если после сложения получилась сумма меньше или равная нулю
*/
public function increase($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty amount value in increase method', 0, 'amount.value');
}
if (!is_numeric($value)) {
throw new InvalidPropertyValueTypeException(
'Invalid amount value type in increase method', 0, 'amount.value', $value
);
}
$castedValue = (int)round($this->_value + $value * 100.0);
if ($castedValue <= 0) {
throw new InvalidPropertyValueException(
'Invalid amount value in increase method: "' . $value . '"', 0, 'amount.value', $value
);
}
$this->_value = $castedValue;
}
/**
* @return array
*/
public function jsonSerialize()
{
return array(
'value' => sprintf('%.2f',$this->_value / 100.0),
'currency' => $this->_currency,
);
}
}
@@ -0,0 +1,138 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\Notification;
use YooKassa\Common\AbstractObject;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\NotificationEventType;
use YooKassa\Model\NotificationType;
/**
* Базовый класс уведомлений
*
* @package YooKassa\Model\Notification
*
* @property-read string $type Тип уведомления в виде строки
* @property-read string $event Тип события
*/
abstract class AbstractNotification extends AbstractObject
{
/**
* @var string Тип уведомления
*/
private $_type;
/**
* @var string Тип произошедшего события
*/
private $_event;
/**
* Возвращает тип уведомления
*
* Тип уведомления - одна из констант, указанных в перечислении {@link NotificationType}.
*
* @return string Тип уведомления в виде строки
*/
public function getType()
{
return $this->_type;
}
/**
* Устанавливает тип уведомления
*
* @param string $value Тип уведомления
*
* @throws EmptyPropertyValueException Выбрасывается если в качестве значения было передано пустое значение
* @throws InvalidPropertyValueException Выбрасывается если переданное значение не найдено в перечислении типов
* нотификаций
* @throws InvalidPropertyValueTypeException Выбрасывается если переданное значение не является строкой
*/
protected function _setType($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty parameter "type" in Notification', 0, 'notification.type');
} elseif (TypeCast::canCastToEnumString($value)) {
if (NotificationType::valueExists($value)) {
$this->_type = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid value for "type" parameter in Notification', 0, 'notification.type', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid value type for "type" parameter in Notification', 0, 'notification.type', $value
);
}
}
/**
* Возвращает тип события
*
* Тип события - одна из констант, указанных в перечислении {@link NotificationEventType}.
*
* @return string Тип события
*/
public function getEvent()
{
return $this->_event;
}
/**
* Устанавливает тип события
*
* @param string $value Тип события
*
* @throws EmptyPropertyValueException Выбрасывается если в качестве значения было передано пустое значение
* @throws InvalidPropertyValueException Выбрасывается если переданное значение не найдено в перечислении типов
* событий
* @throws InvalidPropertyValueTypeException Выбрасывается если переданное значение не является строкой
*/
protected function _setEvent($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty parameter "event" in Notification', 0, 'notification.event');
} elseif (TypeCast::canCastToEnumString($value)) {
if (NotificationEventType::valueExists($value)) {
$this->_event = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid value for "event" parameter in Notification', 0, 'notification.event', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid value type for "event" parameter in Notification', 0, 'notification.event', $value
);
}
}
}
@@ -0,0 +1,99 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\Notification;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Model\NotificationEventType;
use YooKassa\Model\NotificationType;
use YooKassa\Model\Payment;
use YooKassa\Model\PaymentInterface;
use YooKassa\Request\Payments\PaymentResponse;
class NotificationCanceled extends AbstractNotification
{
/**
* Объект платежа, для которого пришла нотификация. Так как нотификация может быть сгенерирована и поставлена в
* очередь на отправку гораздо раньше, чем она будет получена на сайте, то опираться на статус пришедшего
* платежа не стоит, лучше запросить текущую информацию о платеже у API.
*
* @var Payment Объект платежа
*/
private $_object;
/**
* Конструктор объекта нотификации о возможности подтверждения платежа
*
* Инициализирует текущий объект из ассоциативного массива, который просто путём JSON десериализации получен из
* тела пришедшего запроса. При конструировании проверяется валидность типа передаваемого уведомления, если
* передать уведомление не того типа, будет сгенерировано исключение типа {@link InvalidPropertyValueException}
*
* @param array $source Ассоциативный массив с информацией о уведомлении
*
* @throws InvalidPropertyValueException Генерируется если значение типа нотификации или события не равны
* "notification" и "payment.canceled" соответственно, что может говорить о том, что переданные в
* конструктор данные не являются уведомлением нужного типа.
*/
public function __construct(array $source)
{
$this->_setType(NotificationType::NOTIFICATION);
$this->_setEvent(NotificationEventType::PAYMENT_CANCELED);
if (!empty($source['type'])) {
if ($this->getType() !== $source['type']) {
throw new InvalidPropertyValueException(
'Invalid value for "type" parameter in Notification', 0, 'notification.type', $source['type']
);
}
}
if (!empty($source['event'])) {
if ($this->getEvent() !== $source['event']) {
throw new InvalidPropertyValueException(
'Invalid value for "event" parameter in Notification', 0, 'notification.event', $source['event']
);
}
}
if (empty($source['object'])) {
throw new EmptyPropertyValueException('Parameter object in NotificationSucceeded is empty');
}
$this->_object = new PaymentResponse($source['object']);
}
/**
* Возвращает объект с информацией о платеже, уведомление о котором хранится в текущем объекте
*
* Так как нотификация может быть сгенерирована и поставлена в очередь на отправку гораздо раньше, чем она будет
* получена на сайте, то опираться на статус пришедшего платежа не стоит, лучше запросить текущую информацию о
* платеже у API.
*
* @return PaymentInterface Объект с информацией о платеже
*/
public function getObject()
{
return $this->_object;
}
}
@@ -0,0 +1,63 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\Notification;
use YooKassa\Model\Notification\AbstractNotification;
use YooKassa\Model\NotificationEventType;
class NotificationFactory
{
private $typeClassMap = array(
NotificationEventType::PAYMENT_CANCELED => 'NotificationCanceled',
NotificationEventType::REFUND_SUCCEEDED => 'NotificationRefundSucceeded',
NotificationEventType::PAYMENT_SUCCEEDED => 'NotificationSucceeded',
NotificationEventType::PAYMENT_WAITING_FOR_CAPTURE => 'NotificationWaitingForCapture',
);
/**
* @param array $data
* @return AbstractNotification
*/
public function factory(array $data)
{
if (!array_key_exists('event', $data)) {
throw new \InvalidArgumentException(
'Parameter event not specified in NotificationFactory.factory()'
);
}
if (!is_string($data['event'])) {
throw new \InvalidArgumentException('Invalid notification type value in notification factory');
}
if (!array_key_exists($data['event'], $this->typeClassMap)) {
throw new \InvalidArgumentException('Invalid notification data type "' . $data['event'] . '"');
}
$className = __NAMESPACE__ . '\\' . $this->typeClassMap[$data['event']];
return new $className($data);
}
}
@@ -0,0 +1,98 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\Notification;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Model\NotificationEventType;
use YooKassa\Model\NotificationType;
use YooKassa\Model\Refund;
use YooKassa\Model\RefundInterface;
use YooKassa\Request\Refunds\RefundResponse;
class NotificationRefundSucceeded extends AbstractNotification
{
/**
* Объект возварата, для которого пришла нотификация. Так как нотификация может быть сгенерирована и поставлена в
* очередь на отправку гораздо раньше, чем она будет получена на сайте, то опираться на статус пришедшего
* возврата не стоит, лучше запросить текущую информацию о возврате у API.
*
* @var Refund Объект платежа
*/
private $_object;
/**
* Конструктор объекта нотификации
*
* Инициализирует текущий объект из ассоциативного массива, который просто путём JSON десериализации получен из
* тела пришедшего запроса. При конструировании проверяется валидность типа передаваемого уведомления, если
* передать уведомление не того типа, будет сгенерировано исключение типа {@link InvalidPropertyValueException}
*
* @param array $source Ассоциативный массив с информацией о уведомлении
*
* @throws InvalidPropertyValueException Генерируется если значение типа нотификации или события не равны
* "notification" и "refund.succeeded" соответственно, что может говорить о том, что переданные в
* конструктор данные не являются уведомлением нужного типа.
*/
public function __construct(array $source)
{
$this->_setType(NotificationType::NOTIFICATION);
$this->_setEvent(NotificationEventType::REFUND_SUCCEEDED);
if (!empty($source['type'])) {
if ($this->getType() !== $source['type']) {
throw new InvalidPropertyValueException(
'Invalid value for "type" parameter in Notification', 0, 'notification.type', $source['type']
);
}
}
if (!empty($source['event'])) {
if ($this->getEvent() !== $source['event']) {
throw new InvalidPropertyValueException(
'Invalid value for "event" parameter in Notification', 0, 'notification.event', $source['event']
);
}
}
if (empty($source['object'])) {
throw new EmptyPropertyValueException('Parameter object in NotificationSucceeded is empty');
}
$this->_object = new RefundResponse($source['object']);
}
/**
* Возвращает объект с информацией о возврате, уведомление о котором хранится в текущем объекте
*
* Так как нотификация может быть сгенерирована и поставлена в очередь на отправку гораздо раньше, чем она будет
* получена на сайте, то опираться на статус пришедшего возврата не стоит, лучше запросить текущую информацию о
* возврате у API.
*
* @return RefundInterface Объект с информацией о возврате
*/
public function getObject()
{
return $this->_object;
}
}
@@ -0,0 +1,105 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\Notification;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Model\NotificationEventType;
use YooKassa\Model\NotificationType;
use YooKassa\Model\Payment;
use YooKassa\Model\PaymentInterface;
use YooKassa\Request\Payments\PaymentResponse;
/**
* Класс объекта, присылаемого API при изменении статуса платежа на "succeeded"
*
* @package YooKassa\Model\Notification
*
* @property-read PaymentInterface $object Объект с информацией о платеже
*/
class NotificationSucceeded extends AbstractNotification
{
/**
* Объект платежа, для которого пришла нотификация. Так как нотификация может быть сгенерирована и поставлена в
* очередь на отправку гораздо раньше, чем она будет получена на сайте, то опираться на статус пришедшего
* платежа не стоит, лучше запросить текущую информацию о платеже у API.
*
* @var Payment Объект платежа
*/
private $_object;
/**
* Конструктор объекта нотификации о возможности подтверждения платежа
*
* Инициализирует текущий объект из ассоциативного массива, который просто путём JSON десериализации получен из
* тела пришедшего запроса. При конструировании проверяется валидность типа передаваемого уведомления, если
* передать уведомление не того типа, будет сгенерировано исключение типа {@link InvalidPropertyValueException}
*
* @param array $source Ассоциативный массив с информацией о уведомлении
*
* @throws InvalidPropertyValueException Генерируется если значение типа нотификации или события не равны
* "notification" и "payment.succeeded" соответственно, что может говорить о том, что переданные в
* конструктор данные не являются уведомлением нужного типа.
*/
public function __construct(array $source)
{
$this->_setType(NotificationType::NOTIFICATION);
$this->_setEvent(NotificationEventType::PAYMENT_SUCCEEDED);
if (!empty($source['type'])) {
if ($this->getType() !== $source['type']) {
throw new InvalidPropertyValueException(
'Invalid value for "type" parameter in Notification', 0, 'notification.type', $source['type']
);
}
}
if (!empty($source['event'])) {
if ($this->getEvent() !== $source['event']) {
throw new InvalidPropertyValueException(
'Invalid value for "event" parameter in Notification', 0, 'notification.event', $source['event']
);
}
}
if (empty($source['object'])) {
throw new EmptyPropertyValueException('Parameter object in NotificationSucceeded is empty');
}
$this->_object = new PaymentResponse($source['object']);
}
/**
* Возвращает объект с информацией о платеже, уведомление о котором хранится в текущем объекте
*
* Так как нотификация может быть сгенерирована и поставлена в очередь на отправку гораздо раньше, чем она будет
* получена на сайте, то опираться на статус пришедшего платежа не стоит, лучше запросить текущую информацию о
* платеже у API.
*
* @return PaymentInterface Объект с информацией о платеже
*/
public function getObject()
{
return $this->_object;
}
}
@@ -0,0 +1,109 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\Notification;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Model\NotificationEventType;
use YooKassa\Model\NotificationType;
use YooKassa\Model\Payment;
use YooKassa\Model\PaymentInterface;
use YooKassa\Request\Payments\PaymentResponse;
/**
* Класс объекта, присылаемого API при изменении статуса платежа на "waiting_for_capture"
*
* При создании платежа с флагом "capture" равным false, после того как клиент проводит платёж, от API на эндпоинт,
* указанный в настройках API посылается уведомление о том, что платёж теперь может быть проведён. В классе описана
* структура такого объекта для магазинов, которые получают уведомления на HTTPS endpoint.
*
* @package YooKassa\Model\Notification
*
* @property-read PaymentInterface $object Объект с информацией о платеже, который можно подтвердить или отменить
*/
class NotificationWaitingForCapture extends AbstractNotification
{
/**
* Объект платежа, для которого пришла нотификация. Так как нотификация может быть сгенерирована и поставлена в
* очередь на отправку гораздо раньше, чем она будет получена на сайте, то опираться на статус пришедшего
*платежа не стоит, лучше запросить текущую информацию о платеже у API.
*
* @var Payment Объект платежа
*/
private $_object;
/**
* Конструктор объекта нотификации о возможности подтверждения платежа
*
* Инициализирует текущий объект из ассоциативного массива, который просто путём JSON десериализации получен из
* тела пришедшего запроса. При конструировании проверяется валидность типа передаваемого уведомления, если
* передать уведомление не того типа, будет сгенерировано исключение типа {@link InvalidPropertyValueException}
*
* @param array $source Ассоциативный массив с информацией о уведомлении
*
* @throws InvalidPropertyValueException Генерируется если значение типа нотификации или события не равны
* "notification" и "payment.waiting_for_capture" соответственно, что может говорить о том, что переданные в
* конструктор данные не являются уведомлением нужного типа.
*/
public function __construct(array $source)
{
$this->_setType(NotificationType::NOTIFICATION);
$this->_setEvent(NotificationEventType::PAYMENT_WAITING_FOR_CAPTURE);
if (!empty($source['type'])) {
if ($this->getType() !== $source['type']) {
throw new InvalidPropertyValueException(
'Invalid value for "type" parameter in Notification', 0, 'notification.type', $source['type']
);
}
}
if (!empty($source['event'])) {
if ($this->getEvent() !== $source['event']) {
throw new InvalidPropertyValueException(
'Invalid value for "event" parameter in Notification', 0, 'notification.event', $source['event']
);
}
}
if (empty($source['object'])) {
throw new EmptyPropertyValueException('Parameter object in NotificationWaitingForCapture is empty');
}
$this->_object = new PaymentResponse($source['object']);
}
/**
* Возвращает объект с информацией о платеже, уведомление о котором хранится в текущем объекте
*
* Так как нотификация может быть сгенерирована и поставлена в очередь на отправку гораздо раньше, чем она будет
* получена на сайте, то опираться на статус пришедшего платежа не стоит, лучше запросить текущую информацию о
* платеже у API.
*
* @return PaymentInterface Объект с информацией о платеже, который можно подтвердить или отменить
*/
public function getObject()
{
return $this->_object;
}
}
@@ -0,0 +1,44 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
use YooKassa\Common\AbstractEnum;
class NotificationEventType extends AbstractEnum
{
const PAYMENT_WAITING_FOR_CAPTURE = 'payment.waiting_for_capture';
const PAYMENT_SUCCEEDED = 'payment.succeeded';
const PAYMENT_CANCELED = 'payment.canceled';
const REFUND_SUCCEEDED = 'refund.succeeded';
protected static $validValues = array(
self::PAYMENT_WAITING_FOR_CAPTURE => true,
self::PAYMENT_SUCCEEDED => true,
self::PAYMENT_CANCELED => true,
self::REFUND_SUCCEEDED => true,
);
}
@@ -0,0 +1,38 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
use YooKassa\Common\AbstractEnum;
class NotificationType extends AbstractEnum
{
const NOTIFICATION = 'notification';
protected static $validValues = array(
self::NOTIFICATION => true,
);
}
@@ -0,0 +1,112 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
use YooKassa\Common\AbstractObject;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
class Passenger extends AbstractObject implements PassengerInterface
{
/**
* @var string
*/
private $_firstName;
/**
* @var string
*/
private $_lastName;
/**
* @inheritdoc
*/
public function getFirstName()
{
return $this->_firstName;
}
/**
* @param $value
*/
public function setFirstName($value)
{
if (empty($value) || is_numeric($value)) {
throw new InvalidPropertyValueTypeException(
'Invalid first_name value type in Passenger object', 0, 'airline.passengers', $value
);
} else if (TypeCast::canCastToString($value)) {
$length = mb_strlen((string)$value, 'utf-8');
if ($length > 64) {
throw new InvalidPropertyValueException(
'Invalid first_name value length in Passenger object',
0, 'airline.passengers', $value
);
}
$this->_firstName = (string)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid first_name value type in Passenger object', 0, 'airline.passengers', $value
);
}
}
/**
* @inheritdoc
*/
public function getLastName()
{
return $this->_lastName;
}
/**
* @param $value
*/
public function setLastName($value)
{
if (empty($value) || is_numeric($value)) {
throw new InvalidPropertyValueTypeException(
'Invalid last_name value type in Passenger object', 0, 'airline.passengers', $value
);
} else if (TypeCast::canCastToString($value)) {
$length = mb_strlen((string)$value, 'utf-8');
if ($length > 64) {
throw new InvalidPropertyValueException(
'Invalid last_name value length in Passenger object',
0, 'airline.passengers', $value
);
}
$this->_lastName = (string)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid last_name value type in Passenger object', 0, 'airline.passengers', $value
);
}
}
}
@@ -0,0 +1,41 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
interface PassengerInterface
{
/**
* @return string
*/
public function getFirstName();
/**
* @return string
*/
public function getLastName();
}
@@ -0,0 +1,704 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model;
use YooKassa\Common\AbstractObject;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\PaymentMethod\AbstractPaymentMethod;
/**
* Payment - Данные о платеже
*
* @property string $id Идентификатор платежа
* @property string $status Текущее состояние платежа
* @property RecipientInterface $recipient Получатель платежа
* @property AmountInterface $amount Сумма заказа
* @property string $description Описание транзакци
* @property AbstractPaymentMethod $paymentMethod Способ проведения платежа
* @property AbstractPaymentMethod $payment_method Способ проведения платежа
* @property \DateTime $createdAt Время создания заказа
* @property \DateTime $created_at Время создания заказа
* @property \DateTime $capturedAt Время подтверждения платежа магазином
* @property \DateTime $captured_at Время подтверждения платежа магазином
* @property \DateTime $expiresAt Время, до которого можно бесплатно отменить или подтвердить платеж
* @property \DateTime $expires_at Время, до которого можно бесплатно отменить или подтвердить платеж
* @property Confirmation\AbstractConfirmation $confirmation Способ подтверждения платежа
* @property AmountInterface $refundedAmount Сумма возвращенных средств платежа
* @property AmountInterface $refunded_amount Сумма возвращенных средств платежа
* @property bool $paid Признак оплаты заказа
* @property bool $refundable Возможность провести возврат по API
* @property string $receiptRegistration Состояние регистрации фискального чека
* @property string $receipt_registration Состояние регистрации фискального чека
* @property Metadata $metadata Метаданные платежа указанные мерчантом
* @property CancellationDetailsInterface $cancellationDetails Комментарий к отмене платежа
* @property CancellationDetailsInterface $cancellation_details Комментарий к отмене платежа
* @property AuthorizationDetailsInterface $authorizationDetails Данные об авторизации платежа
* @property AuthorizationDetailsInterface $authorization_details Данные об авторизации платежа
* @property TransferInterface[] $transfers Данные о распределении платежа между магазинами
*/
class Payment extends AbstractObject implements PaymentInterface
{
const MAX_LENGTH_DESCRIPTION = 128;
/**
* @var string Идентификатор платежа
*/
private $_id;
/**
* @var string Текущее состояние платежа
*/
private $_status;
/**
* @var RecipientInterface|null Получатель платежа
*/
private $_recipient;
/**
* @var AmountInterface
*/
private $_amount;
/**
* @var string
*/
private $_description;
/**
* @var AbstractPaymentMethod Способ проведения платежа
*/
private $_paymentMethod;
/**
* @var \DateTime Время создания заказа
*/
private $_createdAt;
/**
* @var \DateTime Время подтверждения платежа магазином
*/
private $_capturedAt;
/**
* @var Confirmation\AbstractConfirmation Способ подтверждения платежа
*/
private $_confirmation;
/**
* @var AmountInterface Сумма возвращенных средств платежа
*/
private $_refundedAmount;
/**
* @var bool Признак оплаты заказа
*/
private $_paid;
/**
* @var bool Возможность провести возврат по API
*/
private $_refundable;
/**
* @var string Состояние регистрации фискального чека
*/
private $_receiptRegistration;
/**
* @var Metadata Метаданные платежа указанные мерчантом
*/
private $_metadata;
/**
* Время, до которого можно бесплатно отменить или подтвердить платеж. В указанное время платеж в статусе
* `waiting_for_capture` будет автоматически отменен.
*
* @var \DateTime Время, до которого можно бесплатно отменить или подтвердить платеж
* @since 1.0.2
*/
private $_expiresAt;
/**
* Комментарий к статусу canceled: кто отменил платеж и по какой причине
* @var CancellationDetailsInterface
* @since 1.0.13
*/
private $_cancellationDetails;
/**
* Данные об авторизации платежа
* @var AuthorizationDetailsInterface
* @since 1.0.18
*/
private $_authorizationDetails;
/**
* @var TransferInterface[]
*/
private $_transfers = array();
/**
* @var MonetaryAmount
*/
private $_incomeAmount;
/**
* @var RequestorInterface
*/
private $_requestor;
/**
* Признак тестовой операции.
* @var boolean
* @since 1.1.3
*/
private $_test;
/**
* Возвращает идентификатор платежа
* @return string Идентификатор платежа
*/
public function getId()
{
return $this->_id;
}
/**
* Устанавливает идентификатор платежа
* @param string $value Идентификатор платежа
*
* @throws InvalidPropertyValueException Выбрасывается если длина переданной строки не равна 36
* @throws InvalidPropertyValueTypeException Выбрасывается если в метод была передана не строка
*/
public function setId($value)
{
if (TypeCast::canCastToString($value)) {
$length = mb_strlen($value, 'utf-8');
if ($length != 36) {
throw new InvalidPropertyValueException('Invalid payment id value', 0, 'Payment.id', $value);
}
$this->_id = (string)$value;
} else {
throw new InvalidPropertyValueTypeException('Invalid payment id value type', 0, 'Payment.id', $value);
}
}
/**
* Возвращает состояние платежа
* @return string Текущее состояние платежа
*/
public function getStatus()
{
return $this->_status;
}
/**
* Устанавливает статус платежа
* @param string $value Статус платежа
*
* @throws InvalidPropertyValueException Выбрасывается если переданная строка не является валидным статусом
* @throws InvalidPropertyValueTypeException Выбрасывается если в метод была передана не строка
*/
public function setStatus($value)
{
if (TypeCast::canCastToEnumString($value)) {
if (!PaymentStatus::valueExists((string)$value)) {
throw new InvalidPropertyValueException('Invalid payment status value', 0, 'Payment.status', $value);
}
$this->_status = (string)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid payment status value type', 0, 'Payment.status', $value
);
}
}
/**
* Возвращает получателя платежа
* @return RecipientInterface|null Получатель платежа или null если получатель не задан
*/
public function getRecipient()
{
return $this->_recipient;
}
/**
* Устанавливает получателя платежа
* @param RecipientInterface $value Объект с информацией о получателе платежа
*/
public function setRecipient(RecipientInterface $value)
{
$this->_recipient = $value;
}
/**
* Возвращает сумму
* @return AmountInterface Сумма платежа
*/
public function getAmount()
{
return $this->_amount;
}
/**
* Устанавливает сумму платежа
* @param AmountInterface $value Сумма платежа
*/
public function setAmount(AmountInterface $value)
{
$this->_amount = $value;
}
/**
* Возвращает описание транзакции
* @return string
*/
public function getDescription()
{
return $this->_description;
}
/**
* Устанавливает описание транзакции
* @param string $value
*
* @throws InvalidPropertyValueException Выбрасывается если переданное значение превышает допустимую длину
* @throws InvalidPropertyValueTypeException Выбрасывается если переданное значение не является строкой
*/
public function setDescription($value)
{
if ($value === null || $value === '') {
$this->_description = null;
} elseif (TypeCast::canCastToString($value)) {
$length = mb_strlen((string)$value, 'utf-8');
if ($length > self::MAX_LENGTH_DESCRIPTION) {
throw new InvalidPropertyValueException(
'Invalid description value', 0, 'CreatePaymentRequest.description', $value
);
}
$this->_description = (string)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid description value type', 0, 'CreatePaymentRequest.description', $value
);
}
}
/**
* Возвращает используемый способ проведения платежа
* @return AbstractPaymentMethod Способ проведения платежа
*/
public function getPaymentMethod()
{
return $this->_paymentMethod;
}
/**
* @param AbstractPaymentMethod $value
*/
public function setPaymentMethod(AbstractPaymentMethod $value)
{
$this->_paymentMethod = $value;
}
/**
* Возвращает время создания заказа
* @return \DateTime Время создания заказа
*/
public function getCreatedAt()
{
return $this->_createdAt;
}
/**
* Устанавливает время создания заказа
* @param \DateTime|string|int $value Время создания заказа
*
* @throws EmptyPropertyValueException Выбрасывается если в метод была передана пустая дата
* @throws InvalidPropertyValueException Выбрасвается если передали строку, которую не удалось привести к дате
* @throws InvalidPropertyValueTypeException|\Exception Выбрасывается если был передан аргумент, который невозможно
* интерпретировать как дату или время
*/
public function setCreatedAt($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty created_at value', 0, 'payment.createdAt');
} elseif (TypeCast::canCastToDateTime($value)) {
$dateTime = TypeCast::castToDateTime($value);
if ($dateTime === null) {
throw new InvalidPropertyValueException('Invalid created_at value', 0, 'payment.createdAt', $value);
}
$this->_createdAt = $dateTime;
} else {
throw new InvalidPropertyValueTypeException('Invalid created_at value', 0, 'payment.createdAt', $value);
}
}
/**
* Возвращает время подтверждения платежа магазином или null если если время не задано
* @return \DateTime|null Время подтверждения платежа магазином
*/
public function getCapturedAt()
{
return $this->_capturedAt;
}
/**
* Устанавливает время подтверждения платежа магазином
* @param \DateTime|string|int|null $value Время подтверждения платежа магазином
*
* @throws InvalidPropertyValueException Выбрасвается если передали строку, которую не удалось привести к дате
* @throws InvalidPropertyValueTypeException|\Exception Выбрасывается если был передан аргумент, который невозможно
* интерпретировать как дату или время
*/
public function setCapturedAt($value)
{
if ($value === null || $value === '') {
$this->_capturedAt = null;
} elseif (TypeCast::canCastToDateTime($value)) {
$dateTime = TypeCast::castToDateTime($value);
if ($dateTime === null) {
throw new InvalidPropertyValueException('Invalid captured_at value', 0, 'payment.capturedAt', $value);
}
$this->_capturedAt = $dateTime;
} else {
throw new InvalidPropertyValueTypeException('Invalid captured_at value', 0, 'payment.capturedAt', $value);
}
}
/**
* Возвращает способ подтверждения платежа
* @return Confirmation\AbstractConfirmation Способ подтверждения платежа
*/
public function getConfirmation()
{
return $this->_confirmation;
}
/**
* Устанавливает способ подтверждения платежа
* @param Confirmation\AbstractConfirmation $value Способ подтверждения платежа
*/
public function setConfirmation(Confirmation\AbstractConfirmation $value)
{
$this->_confirmation = $value;
}
/**
* Возвращает сумму возвращенных средств
* @return AmountInterface Сумма возвращенных средств платежа
*/
public function getRefundedAmount()
{
return $this->_refundedAmount;
}
/**
* Устанавливает сумму возвращенных средств
* @param AmountInterface $value Сумма возвращенных средств платежа
*/
public function setRefundedAmount(AmountInterface $value)
{
$this->_refundedAmount = $value;
}
/**
* Проверяет был ли уже оплачен заказ
* @return bool Признак оплаты заказа, true если заказ оплачен, false если нет
*/
public function getPaid()
{
return $this->_paid;
}
/**
* Устанавливает флаг оплаты заказа
* @param bool $value Признак оплаты заказа
*
* @throws EmptyPropertyValueException Выбрасывается если переданный аргумент пуст
* @throws InvalidPropertyValueTypeException Выбрасывается если переданный аргумент не кастится в булево значение
*/
public function setPaid($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty payment paid flag value', 0, 'Payment.paid');
} elseif (TypeCast::canCastToBoolean($value)) {
$this->_paid = (bool)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid payment paid flag value type', 0, 'Payment.paid', $value
);
}
}
/**
* Проверяет возможность провести возврат по API
* @return bool Возможность провести возврат по API, true если есть, false если нет
*/
public function getRefundable()
{
return $this->_refundable;
}
/**
* Устанавливает возможность провести возврат по API
* @param bool $value Возможность провести возврат по API
*
* @throws EmptyPropertyValueException Выбрасывается если переданный аргумент пуст
* @throws InvalidPropertyValueTypeException Выбрасывается если переданный аргумент не кастится в булево значение
*/
public function setRefundable($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty payment refundable flag value', 0, 'Payment.refundable');
} elseif (TypeCast::canCastToBoolean($value)) {
$this->_refundable = (bool)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid payment refundable flag value type', 0, 'Payment.refundable', $value
);
}
}
/**
* Возвращает состояние регистрации фискального чека
* @return string Состояние регистрации фискального чека
*/
public function getReceiptRegistration()
{
return $this->_receiptRegistration;
}
/**
* Устанавливает состояние регистрации фискального чека
* @param string $value Состояние регистрации фискального чека
*
* @throws InvalidPropertyValueException Выбрасывается если переданное состояние регистрации не существует
* @throws InvalidPropertyValueTypeException Выбрасывается если переданный аргумент не строка
*/
public function setReceiptRegistration($value)
{
if ($value === null || $value === '') {
$this->_receiptRegistration = null;
} elseif (TypeCast::canCastToEnumString($value)) {
if (ReceiptRegistrationStatus::valueExists($value)) {
$this->_receiptRegistration = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid receipt_registration value', 0, 'payment.receiptRegistration', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid receipt_registration value type', 0, 'payment.receiptRegistration', $value
);
}
}
/**
* Возвращает метаданные платежа установленные мерчантом
* @return Metadata Метаданные платежа указанные мерчантом
*/
public function getMetadata()
{
return $this->_metadata;
}
/**
* Устанавливает метаданные платежа
* @param Metadata $value Метаданные платежа указанные мерчантом
*/
public function setMetadata(Metadata $value)
{
$this->_metadata = $value;
}
/**
* Возвращает время до которого можно бесплатно отменить или подтвердить платеж или null если оно не задано
* @return \DateTime|null Время, до которого можно бесплатно отменить или подтвердить платеж
*
* @since 1.0.2
*/
public function getExpiresAt()
{
return $this->_expiresAt;
}
/**
* Устанавливает время до которого можно бесплатно отменить или подтвердить платеж
* @param \DateTime|string|int|null $value Время, до которого можно бесплатно отменить или подтвердить платеж
*
* @throws InvalidPropertyValueException Выбрасывается если передали строку, которую не удалось привести к дате
* @throws InvalidPropertyValueTypeException|\Exception Выбрасывается если был передан аргумент, который невозможно
* интерпретировать как дату или время
*
* @since 1.0.2
*/
public function setExpiresAt($value)
{
if ($value === null || $value === '') {
$this->_expiresAt = null;
} elseif (TypeCast::canCastToDateTime($value)) {
$dateTime = TypeCast::castToDateTime($value);
if ($dateTime === null) {
throw new InvalidPropertyValueException('Invalid expires_at value', 0, 'payment.expires_at', $value);
}
$this->_expiresAt = $dateTime;
} else {
throw new InvalidPropertyValueTypeException('Invalid expires_at value', 0, 'payment.expires_at', $value);
}
}
/**
* Возвращает комментарий к статусу canceled: кто отменил платеж и по какой причине
* @return CancellationDetailsInterface|null Комментарий к статусу canceled
* @since 1.0.13
*/
public function getCancellationDetails()
{
return $this->_cancellationDetails;
}
/**
* Устанавливает комментарий к статусу canceled: кто отменил платеж и по какой причине
* @param CancellationDetailsInterface $value Комментарий к статусу canceled
*/
public function setCancellationDetails(CancellationDetailsInterface $value)
{
$this->_cancellationDetails = $value;
}
/**
* Возвращает данные об авторизации платежа
* @return AuthorizationDetailsInterface|null Данные об авторизации платежа
* @since 1.0.18
*/
public function getAuthorizationDetails()
{
return $this->_authorizationDetails;
}
/**
* Устанавливает данные об авторизации платежа
* @param AuthorizationDetailsInterface $value Данные об авторизации платежа
*/
public function setAuthorizationDetails(AuthorizationDetailsInterface $value)
{
$this->_authorizationDetails = $value;
}
/**
* Устанавливает transfers (массив распределения денег между магазинами)
* @param $value
*/
public function setTransfers($value)
{
if (!is_array($value)) {
$message = 'Transfers must be an array of TransferInterface';
throw new InvalidPropertyValueTypeException($message, 0, 'Payment.transfers', $value);
}
foreach ($value as $item) {
if (!($item instanceof TransferInterface)) {
$message = 'Transfers must be an array of TransferInterface';
throw new InvalidPropertyValueTypeException($message, 0, 'Payment.transfers', $value);
}
}
$this->_transfers = $value;
}
public function getTransfers()
{
return $this->_transfers;
}
/**
* @param MonetaryAmount $amount
*/
public function setIncomeAmount(MonetaryAmount $amount)
{
$this->_incomeAmount = $amount;
}
public function getIncomeAmount()
{
return $this->_incomeAmount;
}
/**
* @param $value
*/
public function setRequestor($value)
{
if (is_array($value)) {
$value = new Requestor($value);
}
if (!($value instanceof RequestorInterface)) {
throw new InvalidPropertyValueTypeException('Invalid Requestor type', 0, 'Payment.requestor', $value);
}
$this->_requestor = $value;
}
/**
* @return RequestorInterface
*/
public function getRequestor()
{
return $this->_requestor;
}
/**
* @return bool
*/
public function getTest()
{
return $this->_test;
}
/**
* @param bool $test
*/
public function setTest($test)
{
if ($test === null || $test === '') {
throw new EmptyPropertyValueException('Empty payment test flag value', 0, 'Payment.test');
} elseif (TypeCast::canCastToBoolean($test)) {
$this->_test = (bool)$test;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid payment test flag value type', 0, 'Payment.test', $test
);
}
}
}
@@ -0,0 +1,78 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData;
use YooKassa\Common\AbstractObject;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\PaymentMethodType;
/**
* Данные используемые для создания метода оплаты.
* @property string $type
*/
abstract class AbstractPaymentData extends AbstractObject
{
/**
* @var string
*/
private $_type;
/**
* @return string
*/
public function getType()
{
return $this->_type;
}
/**
* @param string $value
*/
protected function _setType($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException(
'Empty payment data type', 0, 'paymentData.type'
);
} elseif (TypeCast::canCastToEnumString($value)) {
if (PaymentMethodType::valueExists($value)) {
$this->_type = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid value for "type" parameter in PaymentData', 0, 'paymentData.type', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid value type for "type" parameter in PaymentData', 0, 'paymentData.type', $value
);
}
}
}
@@ -0,0 +1,167 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData\B2b\Sberbank;
use YooKassa\Common\AbstractObject;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\AmountInterface;
use YooKassa\Model\MonetaryAmount;
/**
* Данные об НДС
* @property string $type Способ расчёта НДС
* @property string $rate Данные об НДС в случае, если сумма НДС включена в сумму платежа
* @property AmountInterface $amount Сумма НДС
*/
class VatData extends AbstractObject implements VatDataInterface
{
/**
* @var string Способ расчёта НДС
*/
private $_type;
/**
* @var string Налоговая ставка НДС
*/
private $_rate;
/**
* @var AmountInterface Сумма НДС
*/
private $_amount;
/**
* VatData constructor.
* @param string|null $type Способ расчёта НДС
* @param string|null $rate Налоговая ставка НДС
* @param AmountInterface|null $amount Сумма НДС
*/
public function __construct($type = null, $rate = null, $amount = null)
{
if ($type !== null) {
$this->setType($type);
}
if ($rate !== null) {
$this->setRate($rate);
}
if ($amount !== null) {
$this->setAmount($amount);
}
}
/**
* @return string Способ расчёта НДС
*/
public function getType()
{
return $this->_type;
}
/**
* Устанавливает способ расчёта НДС
* @param string $value Способ расчёта НДС
*
* @throws InvalidPropertyValueException Выбрасывается если переданная строка не является валидным способом
* @throws InvalidPropertyValueTypeException Выбрасывается если в метод была передана не строка
*/
public function setType($value)
{
if (TypeCast::canCastToEnumString($value)) {
if (!VatDataType::valueExists((string)$value)) {
throw new InvalidPropertyValueException('Invalid B2bSberbankVatData.type value', 0,
'B2bSberbankVatData.type', $value);
}
$this->_type = (string)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid B2bSberbankVatData.type value type', 0, 'B2bSberbankVatData.type', $value
);
}
}
/**
* @return string Налоговая ставка НДС
*/
public function getRate()
{
return $this->_rate;
}
/**
* Устанавливает налоговую ставку НДС
* @param string $value Налоговая ставка НДС
*
* @throws InvalidPropertyValueException Выбрасывается если переданная строка не является валидной ставкой
* @throws InvalidPropertyValueTypeException Выбрасывается если в метод была передана не строка
*/
public function setRate($value)
{
if (TypeCast::canCastToString($value)) {
if (!VatDataRate::valueExists((string)$value)) {
throw new InvalidPropertyValueException('Invalid B2bSberbankVatData.rate value', 0,
'B2bSberbankVatData.rate', $value);
}
$this->_rate = (string)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid B2bSberbankVatData.rate value type', 0, 'B2bSberbankVatData.rate', $value
);
}
}
/**
* Возвращает сумму НДС
* @return AmountInterface Сумма НДС
*/
public function getAmount()
{
return $this->_amount;
}
/**
* Устанавливает сумму НДС
* @param AmountInterface|array|null $value Сумма НДС
*/
public function setAmount($value)
{
if ($value === null) {
$this->_amount = null;
} elseif ($value instanceof AmountInterface) {
$this->_amount = $value;
} elseif (is_array($value)) {
$this->_amount = new MonetaryAmount();
$this->_amount->fromArray($value);
} else {
throw new InvalidPropertyValueTypeException(
'Invalid B2bSberbankVatData.amount value type', 0, 'B2bSberbankVatData.amount', $value
);
}
}
}
@@ -0,0 +1,60 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData\B2b\Sberbank;
use YooKassa\Model\AmountInterface;
/**
* Interface VatDataInterface
*
* @package YooKassa\Model
*
* @property-read string $type Способ расчёта НДС
* @property-read string $rate Данные об НДС в случае, если сумма НДС включена в сумму платежа
* @property-read AmountInterface $amount Сумма НДС
*/
interface VatDataInterface
{
/**
* Возвращает способ расчёта НДС
* @return string Способ расчёта НДС
*/
function getType();
/**
* Возвращает данные об НДС
* @return string Данные об НДС
*/
function getRate();
/**
* Возвращает сумму НДС
* @return AmountInterface Сумма НДС
*/
function getAmount();
}
@@ -0,0 +1,54 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData\B2b\Sberbank;
use YooKassa\Common\AbstractEnum;
/**
* PaymentDataB2bSberbankVatDataRate - Налоговая ставка НДС
* |Код|Описание|
* --- | ---
* |7|7%|
* |10|10%|
* |18|18%|
* |20|20%|
*/
class VatDataRate extends AbstractEnum
{
const RATE_7 = '7';
const RATE_10 = '10';
const RATE_18 = '18';
const RATE_20 = '20';
protected static $validValues = array(
self::RATE_7 => true,
self::RATE_10 => true,
self::RATE_18 => true,
self::RATE_20 => true,
);
}
@@ -0,0 +1,51 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData\B2b\Sberbank;
use YooKassa\Common\AbstractEnum;
/**
* PaymentDataB2bSberbankVatDataType - Способ расчёта НДС
* |Код|Описание|
* --- | ---
* |calculated|Сумма НДС включена в сумму платежа|
* |mixed|Разные ставки НДС для разных товаров|
* |untaxed|Сумма платежа НДС не облагается|
*/
class VatDataType extends AbstractEnum
{
const CALCULATED = 'calculated';
const MIXED = 'mixed';
const UNTAXED = 'untaxed';
protected static $validValues = array(
self::CALCULATED => true,
self::MIXED => true,
self::UNTAXED => true,
);
}
@@ -0,0 +1,74 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentDataAlfabank
* Платежные данные для проведения оплаты через Альфа Клик или Альфа Молнию.
* @property string $login Имя пользователя в Альфа-Клике
*/
class PaymentDataAlfabank extends AbstractPaymentData
{
/**
* @var string Имя пользователя в Альфа-Клике
*/
private $_login;
public function __construct()
{
$this->_setType(PaymentMethodType::ALFABANK);
}
/**
* @return string Имя пользователя в Альфа-Клике
*/
public function getLogin()
{
return $this->_login;
}
/**
* @param string $value Имя пользователя в Альфа-Клике
*/
public function setLogin($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty login value', 0, 'PaymentDataAlfabank.login');
} elseif (TypeCast::canCastToString($value)) {
$this->_login = (string)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid login value type', 0, 'PaymentDataAlfabank.login', $value
);
}
}
}
@@ -0,0 +1,78 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentDataApplePay
* Платежные данные для проведения оплаты при помощи Apple Pay
* @property string $type Тип объекта
* @property string $paymentData содержимое поля paymentData объекта PKPaymentToken, закодированное в Base64
* @property string $payment_data содержимое поля paymentData объекта PKPaymentToken, закодированное в Base64
*/
class PaymentDataApplePay extends AbstractPaymentData
{
/**
* @var string содержимое поля paymentData объекта PKPaymentToken, закодированное в Base64
*/
private $_paymentData;
public function __construct()
{
$this->_setType(PaymentMethodType::APPLE_PAY);
}
/**
* @return string содержимое поля paymentData объекта PKPaymentToken, закодированное в Base64
*/
public function getPaymentData()
{
return $this->_paymentData;
}
/**
* @param string $value содержимое поля paymentData объекта PKPaymentToken, закодированное в Base64
*/
public function setPaymentData($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException(
'Empty value for paymentData', 0, 'PaymentDataApplePay.paymentData'
);
} elseif (TypeCast::canCastToString($value)) {
$this->_paymentData = (string)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid value type for paymentData', 0, 'PaymentDataApplePay.paymentData', $value
);
}
}
}
@@ -0,0 +1,120 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\PaymentData\B2b\Sberbank\VatData;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentDataB2BSberbank
* Платежные данные для проведения оплаты при помощи Сбербанк Бизнес Онлайн.
* @property string $paymentPurpose Назначение платежа
* @property VatData $vatData Данные об НДС
*/
class PaymentDataB2bSberbank extends AbstractPaymentData
{
/**
* @var string Назначение платежа
*/
private $_paymentPurpose;
/**
* @var VatData Данные об НДС
*/
private $_vatData;
public function __construct()
{
$this->_setType(PaymentMethodType::B2B_SBERBANK);
}
/**
* @return string Назначение платежа
*/
public function getPaymentPurpose()
{
return $this->_paymentPurpose;
}
/**
* @param string $value Назначение платежа
*/
public function setPaymentPurpose($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty paymentPurpose value', 0,
'PaymentDataB2bSberbank.paymentPurpose');
} elseif (TypeCast::canCastToString($value)) {
if (preg_match('/^.{1,210}$/', $value)) {
$this->_paymentPurpose = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid paymentPurpose value', 0, 'PaymentDataB2bSberbank.paymentPurpose', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid paymentPurpose value type', 0, 'PaymentDataB2bSberbank.paymentPurpose', $value
);
}
}
/**
* @return VatData Данные об НДС
*/
public function getVatData()
{
return $this->_vatData;
}
/**
* @param VatData|array|null $value Данные об НДС
*/
public function setVatData($value)
{
if ($value === null || $value === array()) {
$this->_vatData = null;
} elseif ($value instanceof VatData) {
$this->_vatData = $value;
} elseif (is_array($value) || $value instanceof \Traversable) {
$vatData = new VatData();
foreach ($value as $property => $val) {
$vatData->offsetSet($property, $val);
}
$this->_vatData = $vatData;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid vatData value type in PaymentDataB2BSberbank', 0,
'PaymentDataB2BSberbank.vatData', $value
);
}
}
}
@@ -0,0 +1,80 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentDataBankCard
* Платежные данные для проведения оплаты при помощи банковской карты
*
* @property PaymentDataBankCardCard $card Данные банковской карты
*/
class PaymentDataBankCard extends AbstractPaymentData
{
/**
* Необходим при оплате PCI-DSS данными.
* @var PaymentDataBankCardCard Данные банковской карты
*/
private $_card;
public function __construct()
{
$this->_setType(PaymentMethodType::BANK_CARD);
}
/**
* @return PaymentDataBankCardCard Данные банковской карты
*/
public function getCard()
{
return $this->_card;
}
/**
* @param PaymentDataBankCardCard|array $value Данные банковской карты
*/
public function setCard($value)
{
if ($value === null || $value === '' || $value === array()) {
$this->_card = null;
} elseif (is_object($value) && $value instanceof PaymentDataBankCardCard) {
$this->_card = $value;
} elseif (is_array($value) || $value instanceof \Traversable) {
$card = new PaymentDataBankCardCard();
foreach ($value as $property => $val) {
$card->offsetSet($property, $val);
}
$this->_card = $card;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid card value type in PaymentDataBankCard', 0, 'PaymentDataBankCard.card', $value
);
}
}
}
@@ -0,0 +1,239 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData;
use YooKassa\Common\AbstractObject;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
/**
* Данные банковской карты
* Необходим при оплате PCI-DSS данными.
* @property string $number Номер банковской карты
* @property string $expiryYear Срок действия, год, YY
* @property string $expiry_year Срок действия, год, YY
* @property string $expiryMonth Срок действия, месяц, MM
* @property string $expiry_month Срок действия, месяц, MM
* @property string $csc CVV2/CVC2 код
* @property string $cardholder Имя держателя карты
*/
class PaymentDataBankCardCard extends AbstractObject
{
/**
* @var string Номер банковской карты
*/
private $_number;
/**
* @var string Срок действия, год, YY
*/
private $_expiryYear;
/**
* @var string Срок действия, месяц, MM
*/
private $_expiryMonth;
/**
* @var string CVV2/CVC2 код
*/
private $_csc;
/**
* @var string Имя держателя карты
*/
private $_cardholder;
/**
* @return string Номер банковской карты
*/
public function getNumber()
{
return $this->_number;
}
/**
* @param string $value Номер банковской карты
*/
public function setNumber($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty card number value', 0, 'PaymentDataBankCardCard.number');
} elseif (TypeCast::canCastToString($value)) {
if (preg_match('/^[0-9]{16,19}$/', (string)$value)) {
$this->_number = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid card number value', 0, 'PaymentDataBankCardCard.number', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid card number value type', 0, 'PaymentDataBankCardCard.number', $value
);
}
}
/**
* @return string Срок действия, год, YYYY
*/
public function getExpiryYear()
{
return $this->_expiryYear;
}
/**
* @param string $value Срок действия, год, YYYY
*/
public function setExpiryYear($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException(
'Empty card expiry year value', 0, 'PaymentDataBankCardCard.expiryYear'
);
} elseif (is_numeric($value)) {
if (!preg_match('/^\d\d\d\d$/', $value) || $value < 2000 || $value > 2200) {
throw new InvalidPropertyValueException(
'Invalid card expiry year value', 0, 'PaymentDataBankCardCard.expiryYear', $value
);
}
$this->_expiryYear = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid card expiry year value', 0, 'PaymentDataBankCardCard.expiryYear', $value
);
}
}
/**
* @return string Срок действия, месяц, MM
*/
public function getExpiryMonth()
{
return $this->_expiryMonth;
}
/**
* @param string $value Срок действия, месяц, MM
*/
public function setExpiryMonth($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException(
'Empty card expiry month value', 0, 'PaymentDataBankCardCard.expiryMonth'
);
} elseif (is_numeric($value)) {
if (!preg_match('/^\d\d$/', $value)) {
throw new InvalidPropertyValueException(
'Invalid card expiry month value', 0, 'PaymentDataBankCardCard.expiryMonth', $value
);
}
if (is_string($value) && $value[0] == '0') {
$month = (int)($value[1]);
} else {
$month = (int)$value;
}
if ($month < 1 || $month > 12) {
throw new InvalidPropertyValueException(
'Invalid card expiry month value', 0, 'PaymentDataBankCardCard.expiryMonth', $value
);
} else {
$this->_expiryMonth = (string)$value;
}
} else {
throw new InvalidPropertyValueException(
'Invalid card expiry month value', 0, 'PaymentDataBankCardCard.expiryMonth', $value
);
}
}
/**
* @return string CVV2/CVC2 код
*/
public function getCsc()
{
return $this->_csc;
}
/**
* @param string $value CVV2/CVC2 код
*/
public function setCsc($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException(
'Empty card CSC code value', 0, 'PaymentDataBankCardCard.csc'
);
} elseif (is_numeric($value)) {
if (preg_match('/^\d{3,4}$/', $value)) {
$this->_csc = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid card CSC code value', 0, 'PaymentDataBankCardCard.csc', $value
);
}
} else {
throw new InvalidPropertyValueException(
'Invalid card CSC code value', 0, 'PaymentDataBankCardCard.csc', $value
);
}
}
/**
* @return string Имя держателя карты
*/
public function getCardholder()
{
return $this->_cardholder;
}
/**
* @param string $value Имя держателя карты
*/
public function setCardholder($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException(
'Empty card holder value', 0, 'PaymentDataBankCardCard.cardholder'
);
} elseif (TypeCast::canCastToString($value)) {
if (preg_match('/^[a-zA-Z\s]{1,26}$/', $value)) {
$this->_cardholder = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid card holder value', 0, 'PaymentDataBankCardCard.cardholder', $value
);
}
} else {
throw new InvalidPropertyValueException(
'Invalid card holder value', 0, 'PaymentDataBankCardCard.cardholder', $value
);
}
}
}
@@ -0,0 +1,81 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentDataCash
* Платежные данные для проведения оплаты Qiwi.
* @property string $phone
*/
class PaymentDataCash extends AbstractPaymentData
{
/**
* Номер телефона в формате ITU-T E.164 на который будет отправлена информация для оплаты.
* @var string
*/
private $_phone;
public function __construct()
{
$this->_setType(PaymentMethodType::CASH);
}
/**
* @return string
*/
public function getPhone()
{
return $this->_phone;
}
/**
* @param string $value
*/
public function setPhone($value)
{
if ($value === null || $value === '') {
$this->_phone = null;
} elseif (TypeCast::canCastToString($value)) {
if (preg_match('/^[0-9]{4,15}$/', $value)) {
$this->_phone = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid phone value', 0, 'PaymentDataCash.phone', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid phone value type', 0, 'PaymentDataCash.phone', $value
);
}
}
}
@@ -0,0 +1,95 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData;
use YooKassa\Model\PaymentMethodType;
class PaymentDataFactory
{
private $typeClassMap = array(
PaymentMethodType::YOO_MONEY => 'PaymentDataYooMoney',
PaymentMethodType::BANK_CARD => 'PaymentDataBankCard',
PaymentMethodType::SBERBANK => 'PaymentDataSberbank',
PaymentMethodType::CASH => 'PaymentDataCash',
PaymentMethodType::MOBILE_BALANCE => 'PaymentDataMobileBalance',
PaymentMethodType::APPLE_PAY => 'PaymentDataApplePay',
PaymentMethodType::GOOGLE_PAY => 'PaymentDataGooglePay',
PaymentMethodType::QIWI => 'PaymentDataQiwi',
PaymentMethodType::WEBMONEY => 'PaymentDataWebmoney',
PaymentMethodType::ALFABANK => 'PaymentDataAlfabank',
PaymentMethodType::INSTALLMENTS => 'PaymentDataInstallments',
PaymentMethodType::B2B_SBERBANK => 'PaymentDataB2bSberbank',
PaymentMethodType::TINKOFF_BANK => 'PaymentDataTinkoffBank',
PaymentMethodType::WECHAT => 'PaymentDataWechat',
);
/**
* @param string $type
*
* @return AbstractPaymentData
*/
public function factory($type)
{
if (!is_string($type)) {
throw new \InvalidArgumentException('Invalid payment type value in payment factory');
}
if (!array_key_exists($type, $this->typeClassMap)) {
throw new \InvalidArgumentException('Invalid payment data type "'.$type.'"');
}
$className = __NAMESPACE__.'\\'.$this->typeClassMap[$type];
return new $className();
}
/**
* @param array $data
* @param string|null $type
*
* @return AbstractPaymentData
*/
public function factoryFromArray(array $data, $type = null)
{
if ($type === null) {
if (array_key_exists('type', $data)) {
$type = $data['type'];
unset($data['type']);
} else {
throw new \InvalidArgumentException(
'Parameter type not specified in PaymentDataFactory.factoryFromArray()'
);
}
}
$paymentData = $this->factory($type);
foreach ($data as $key => $value) {
if ($paymentData->offsetExists($key)) {
$paymentData->offsetSet($key, $value);
}
}
return $paymentData;
}
}
@@ -0,0 +1,108 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentDataGooglePay
* Платежные данные для проведения оплаты при помощи Google Pay.
* @property string $paymentMethodToken Криптограмма Payment Token Cryptography для проведения оплаты через Google Pay
* @property string $googleTransactionId Уникальный идентификатор транзакции, выданный Google
*/
class PaymentDataGooglePay extends AbstractPaymentData
{
/**
* @var string Криптограмма Payment Token Cryptography для проведения оплаты через Google Pay
*/
private $_paymentMethodToken;
/**
* @var string Уникальный идентификатор транзакции, выданный Google
*/
private $_googleTransactionId;
public function __construct()
{
$this->_setType(PaymentMethodType::GOOGLE_PAY);
}
/**
* @return string Криптограмма Payment Token Cryptography для проведения оплаты через Google Pay
*/
public function getPaymentMethodToken()
{
return $this->_paymentMethodToken;
}
/**
* @param string $value Криптограмма Payment Token Cryptography для проведения оплаты через Google Pay
*/
public function setPaymentMethodToken($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException(
'Empty value for paymentMethodToken', 0, 'PaymentDataGooglePay.paymentMethodToken'
);
} elseif (TypeCast::canCastToString($value)) {
$this->_paymentMethodToken = (string)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid value type for paymentMethodToken', 0, 'PaymentDataGooglePay.paymentMethodToken', $value
);
}
}
/**
* @return string Уникальный идентификатор транзакции, выданный Google
*/
public function getGoogleTransactionId()
{
return $this->_googleTransactionId;
}
/**
* @param string $value Уникальный идентификатор транзакции, выданный Google
*/
public function setGoogleTransactionId($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException(
'Empty value for googleTransactionId', 0, 'PaymentDataGooglePay.googleTransactionId'
);
} elseif (TypeCast::canCastToString($value)) {
$this->_googleTransactionId = (string)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid value type for googleTransactionId', 0, 'PaymentDataGooglePay.googleTransactionId', $value
);
}
}
}
@@ -0,0 +1,40 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData;
use YooKassa\Model\PaymentMethodType;
/**
* Данные для проведения оплаты по частям
*/
class PaymentDataInstallments extends AbstractPaymentData
{
public function __construct()
{
$this->_setType(PaymentMethodType::INSTALLMENTS);
}
}
@@ -0,0 +1,82 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentDataMobileBalance
* Платежные данные для проведения оплаты Qiwi.
* @property string $phone
*/
class PaymentDataMobileBalance extends AbstractPaymentData
{
/**
* Номер телефона в формате ITU-T E.164 с которого плательщик собирается произвести оплату.
* @var string
*/
private $_phone;
public function __construct()
{
$this->_setType(PaymentMethodType::MOBILE_BALANCE);
}
/**
* @return string
*/
public function getPhone()
{
return $this->_phone;
}
/**
* @param string $value
*/
public function setPhone($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty phone value', 0, 'PaymentDataMobileBalance.phone');
} elseif (TypeCast::canCastToString($value)) {
if (preg_match('/^[0-9]{4,15}$/', $value)) {
$this->_phone = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid phone value', 0, 'PaymentDataMobileBalance.phone', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid phone value type', 0, 'PaymentDataMobileBalance.phone', $value
);
}
}
}
@@ -0,0 +1,81 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentDataQiwi
* Платежные данные для проведения оплаты Qiwi.
*/
class PaymentDataQiwi extends AbstractPaymentData
{
/**
* Номер телефона в формате ITU-T E.164 с которого плательщик собирается произвести оплату.
* @var string
*/
private $_phone;
public function __construct()
{
$this->_setType(PaymentMethodType::QIWI);
}
/**
* @return string
*/
public function getPhone()
{
return $this->_phone;
}
/**
* @param string $value
*/
public function setPhone($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty phone value', 0, 'PaymentDataQiwi.phone');
} elseif (TypeCast::canCastToString($value)) {
if (preg_match('/^[0-9]{4,15}$/', $value)) {
$this->_phone = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid phone value', 0, 'PaymentDataQiwi.phone', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid phone value type', 0, 'PaymentDataQiwi.phone', $value
);
}
}
}
@@ -0,0 +1,86 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentDataSberbank
* Платежные данные для проведения оплаты при помощи Сбербанк Онлайн.
* @property string $phone
*/
class PaymentDataSberbank extends AbstractPaymentData
{
/**
* Телефон пользователя, на который зарегистрирован аккаунт в Сбербанке Онлайн.
*
* Необходим для подтверждения оплаты по смс (сценарий подтверждения `external`).
* Указывается в формате [ITU-T E.164](https://ru.wikipedia.org/wiki/E.164), например `79000000000`.
*
* @var string Телефон пользователя
*/
private $_phone;
public function __construct()
{
$this->_setType(PaymentMethodType::SBERBANK);
}
/**
* @return string
*/
public function getPhone()
{
return $this->_phone;
}
/**
* @param string $value
*/
public function setPhone($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty phone value', 0, 'PaymentDataSberbank.phone');
} elseif (TypeCast::canCastToString($value)) {
if (preg_match('/^[0-9]{4,15}$/', $value)) {
$this->_phone = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid phone value', 0, 'PaymentDataSberbank.phone', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid phone value type', 0, 'PaymentDataSberbank.phone', $value
);
}
}
}
@@ -0,0 +1,37 @@
<?php
/**
* The MIT License
*
* Copyright (c) 2020 "YooMoney", NBСO LLC
*
* 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.
*/
namespace YooKassa\Model\PaymentData;
use YooKassa\Model\PaymentMethodType;
class PaymentDataTinkoffBank extends AbstractPaymentData
{
public function __construct()
{
$this->_setType(PaymentMethodType::TINKOFF_BANK);
}
}

Some files were not shown because too many files have changed in this diff Show More