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
@@ -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);
}
}
@@ -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\PaymentData;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentDataWebmoney
* Платежные данные для проведения оплаты Webmoney.
*/
class PaymentDataWebmoney extends AbstractPaymentData
{
public function __construct()
{
$this->_setType(PaymentMethodType::WEBMONEY);
}
}
@@ -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;
/**
* @deprecated Класс будет удалён в одной из будущих версий.
*/
class PaymentDataWechat extends AbstractPaymentData
{
public function __construct()
{
$this->_setType(PaymentMethodType::WECHAT);
}
}
@@ -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;
/**
* Данные для проведения оплаты через ЮMoney
*/
class PaymentDataYooMoney extends AbstractPaymentData
{
public function __construct()
{
$this->_setType(PaymentMethodType::YOO_MONEY);
}
}
@@ -0,0 +1,172 @@
<?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\Model\PaymentMethod\AbstractPaymentMethod;
/**
* Interface PaymentInterface
*
* @package YooKassa\Model
*
* @property-read string $id Идентификатор платежа
* @property-read string $status Текущее состояние платежа
* @property-read RecipientInterface $recipient Получатель платежа
* @property-read AmountInterface $amount Сумма заказа
* @property-read AbstractPaymentMethod $paymentMethod Способ проведения платежа
* @property-read AbstractPaymentMethod $payment_method Способ проведения платежа
* @property-read \DateTime $createdAt Время создания заказа
* @property-read \DateTime $created_at Время создания заказа
* @property-read \DateTime $capturedAt Время подтверждения платежа магазином
* @property-read \DateTime $captured_at Время подтверждения платежа магазином
* @property-read Confirmation\AbstractConfirmation $confirmation Способ подтверждения платежа
* @property-read AmountInterface $refundedAmount Сумма возвращенных средств платежа
* @property-read AmountInterface $refunded_amount Сумма возвращенных средств платежа
* @property-read bool $paid Признак оплаты заказа
* @property-read bool $refundable Возможность провести возврат по API
* @property-read string $receiptRegistration Состояние регистрации фискального чека
* @property-read string $receipt_registration Состояние регистрации фискального чека
* @property-read Metadata $metadata Метаданные платежа указанные мерчантом
*/
interface PaymentInterface
{
/**
* Возвращает идентификатор платежа
* @return string Идентификатор платежа
*/
function getId();
/**
* Возвращает состояние платежа
* @return string Текущее состояние платежа
*/
public function getStatus();
/**
* Возвращает получателя платежа
* @return RecipientInterface|null Получатель платежа или null если получатель не задан
*/
public function getRecipient();
/**
* Возвращает сумму
* @return AmountInterface Сумма платежа
*/
public function getAmount();
/**
* Возвращает используемый способ проведения платежа
* @return AbstractPaymentMethod Способ проведения платежа
*/
public function getPaymentMethod();
/**
* Возвращает время создания заказа
* @return \DateTime Время создания заказа
*/
public function getCreatedAt();
/**
* Возвращает время подтверждения платежа магазином или null если если время не задано
* @return \DateTime|null Время подтверждения платежа магазином
*/
public function getCapturedAt();
/**
* Возвращает способ подтверждения платежа
* @return Confirmation\AbstractConfirmation Способ подтверждения платежа
*/
public function getConfirmation();
/**
* Возвращает сумму возвращенных средств
* @return AmountInterface Сумма возвращенных средств платежа
*/
public function getRefundedAmount();
/**
* Проверяет был ли уже оплачен заказ
* @return bool Признак оплаты заказа, true если заказ оплачен, false если нет
*/
public function getPaid();
/**
* Возможность провести возврат по API
* @return bool Возможность провести возврат по API
*/
public function getRefundable();
/**
* Возвращает состояние регистрации фискального чека
* @return string Состояние регистрации фискального чека
*/
public function getReceiptRegistration();
/**
* Возвращает метаданные платежа установленные мерчантом
* @return Metadata Метаданные платежа указанные мерчантом
*/
public function getMetadata();
/**
* Возвращает время до которого можно бесплатно отменить или подтвердить платеж или null если оно не задано
* @return \DateTime|null Время, до которого можно бесплатно отменить или подтвердить платеж
* @since 1.0.2
*/
public function getExpiresAt();
/**
* Возвращает комментарий к статусу canceled: кто отменил платеж и по какой причине
* @return CancellationDetailsInterface|null Комментарий к статусу canceled
* @since 1.0.13
*/
public function getCancellationDetails();
/**
* Возвращает данные об авторизации платежа
* @return AuthorizationDetailsInterface|null Данные об авторизации платежа
* @since 1.0.18
*/
public function getAuthorizationDetails();
/**
* Возвращает данные о распределении платежа между магазинами
* @return TransferInterface[]
*/
public function getTransfers();
/**
* Возвращает сумму перечисляемая магазину за вычетом комиссий платежной системы.(только для успешных платежей)
* @return MonetaryAmount|null
*/
public function getIncomeAmount();
/**
* @return RequestorInterface
*/
public function getRequestor();
}
@@ -0,0 +1,162 @@
<?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\PaymentMethod;
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 $id Идентификатор записи о сохраненных платежных данных
* @property bool $saved Возможность многократного использования
* @property string $title Название метода оплаты
*/
abstract class AbstractPaymentMethod extends AbstractObject
{
/**
* @var string Идентификатор записи о сохраненных платежных данных
*/
private $_id;
/**
* @var string Тип объекта
*/
private $_type;
/**
* @var bool Возможность многократного использования
*/
private $_saved = false;
/**
* @var string Название метода оплаты
*/
private $_title;
/**
* @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, 'PaymentMethod.type'
);
} elseif (TypeCast::canCastToEnumString($value)) {
if (PaymentMethodType::valueExists($value)) {
$this->_type = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid value for "type" parameter in PaymentMethod', 0, 'PaymentMethod.type', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid value type for "type" parameter in PaymentMethod', 0, 'PaymentMethod.type', $value
);
}
}
/**
* @return string Идентификатор записи о сохраненных платежных данных
*/
public function getId()
{
return $this->_id;
}
/**
* @param string $value Идентификатор записи о сохраненных платежных данных
*/
public function setId($value)
{
if ($value === null || $value === '') {
$this->_id = null;
} elseif (TypeCast::canCastToString($value)) {
$this->_id = (string)$value;
} else {
throw new InvalidPropertyValueTypeException('Invalid id value type', 0, 'PaymentMethod.id', $value);
}
}
/**
* @return bool Возможность многократного использования
*/
public function getSaved()
{
return $this->_saved;
}
/**
* @param bool $value Возможность многократного использования
*/
public function setSaved($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty saved value', 0, 'PaymentMethod.saved');
} elseif (TypeCast::canCastToBoolean($value)) {
$this->_saved = (bool)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid saved value type', 0, 'PaymentMethod.saved', $value
);
}
}
/**
* @return string|null Название метода оплаты
*/
public function getTitle()
{
return $this->_title;
}
/**
* @param string $value Название метода оплаты
*/
public function setTitle($value)
{
if ($value === null || $value === '') {
$this->_title = null;
} elseif (TypeCast::canCastToString($value)) {
$this->_title = (string)$value;
} else {
throw new InvalidPropertyValueTypeException('Invalid title value type', 0, 'PaymentMethod.title', $value);
}
}
}
@@ -0,0 +1,243 @@
<?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\PaymentMethod\B2b\Sberbank;
use YooKassa\Common\AbstractObject;
/**
* Банковские реквизиты плательщика
* @property string $fullName Полное наименование организации
* @property string $shortName Сокращенное наименование организации
* @property string $address Адрес организации
* @property string $inn ИНН организации
* @property string $kpp КПП организации
* @property string $bankName Наименование банка организации
* @property string $bankBranch Отделение банка организации
* @property string $bankBik БИК банка организации
* @property string $account Номер счета организации
*/
class PayerBankDetails extends AbstractObject implements PayerBankDetailsInterface
{
/**
* @var string Полное наименование организации
*/
private $_fullName;
/**
* @var string Сокращенное наименование организации
*/
private $_shortName;
/**
* @var string Адрес организации
*/
private $_address;
/**
* @var string ИНН организации
*/
private $_inn;
/**
* @var string КПП организации
*/
private $_kpp;
/**
* @var string Наименование банка организации
*/
private $_bankName;
/**
* @var string Отделение банка организации
*/
private $_bankBranch;
/**
* @var string БИК банка организации
*/
private $_bankBik;
/**
* @var string Номер счета организации
*/
private $_account;
/**
* Возвращает полное наименование организации
* @return string Полное наименование организации
*/
public function getFullName()
{
return $this->_fullName;
}
/**
* @param string $value
*/
public function setFullName($value)
{
$this->_fullName = $value;
}
/**
* Возвращает сокращенное наименование организации
* @return string Сокращенное наименование организации
*/
public function getShortName()
{
return $this->_shortName;
}
/**
* @param string $value
*/
public function setShortName($value)
{
$this->_shortName = $value;
}
/**
* Возвращает адрес организации
* @return string Адрес организации
*/
public function getAddress()
{
return $this->_address;
}
/**
* @param string $value
*/
public function setAddress($value)
{
$this->_address = $value;
}
/**
* Возвращает ИНН организации
* @return string ИНН организации
*/
public function getInn()
{
return $this->_inn;
}
/**
* @param string $value
*/
public function setInn($value)
{
$this->_inn = $value;
}
/**
* Возвращает КПП организации
* @return string КПП организации
*/
public function getKpp()
{
return $this->_kpp;
}
/**
* @param string $value
*/
public function setKpp($value)
{
$this->_kpp = $value;
}
/**
* Возвращает наименование банка организации
* @return string Наименование банка организации
*/
public function getBankName()
{
return $this->_bankName;
}
/**
* @param string $value
*/
public function setBankName($value)
{
$this->_bankName = $value;
}
/**
* Возвращает отделение банка организации
* @return string Отделение банка организации
*/
public function getBankBranch()
{
return $this->_bankBranch;
}
/**
* @param string $value
*/
public function setBankBranch($value)
{
$this->_bankBranch = $value;
}
/**
* Возвращает БИК банка организации
* @return string БИК банка организации
*/
public function getBankBik()
{
return $this->_bankBik;
}
/**
* @param string $value
*/
public function setBankBik($value)
{
$this->_bankBik = $value;
}
/**
* Возвращает номер счета организации
* @return string Номер счета организации
*/
public function getAccount()
{
return $this->_account;
}
/**
* @param string $value
*/
public function setAccount($value)
{
$this->_account = $value;
}
}
@@ -0,0 +1,101 @@
<?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\PaymentMethod\B2b\Sberbank;
/**
* Interface PayerBankDetailsInterface
*
* @package YooKassa\Model
*
* @property-read string $fullName Полное наименование организации
* @property-read string $shortName Сокращенное наименование организации
* @property-read string $address Адрес организации
* @property-read string $inn ИНН организации
* @property-read string $kpp КПП организации
* @property-read string $bankName Наименование банка организации
* @property-read string $bankBranch Отделение банка организации
* @property-read string $bankBik БИК банка организации
* @property-read string $account Номер счета организации
*/
interface PayerBankDetailsInterface
{
/**
* Возвращает полное наименование организации
* @return string Полное наименование организации
*/
function getFullName();
/**
* Возвращает сокращенное наименование организации
* @return string Сокращенное наименование организации
*/
function getShortName();
/**
* Возвращает адрес организации
* @return string Адрес организации
*/
function getAddress();
/**
* Возвращает ИНН организации
* @return string ИНН организации
*/
function getInn();
/**
* Возвращает КПП организации
* @return string КПП организации
*/
function getKpp();
/**
* Возвращает наименование банка организации
* @return string Наименование банка организации
*/
function getBankName();
/**
* Возвращает отделение банка организации
* @return string Отделение банка организации
*/
function getBankBranch();
/**
* Возвращает БИК банка организации
* @return string БИК банка организации
*/
function getBankBik();
/**
* Возвращает номер счета организации
* @return string Номер счета организации
*/
function getAccount();
}
@@ -0,0 +1,26 @@
<?php
namespace YooKassa\Model\PaymentMethod;
use YooKassa\Common\AbstractEnum;
/**
* BankCardSource - Источник данных банковской карты
* |Код|Описание|
* --- | ---
* |apple_pay|Источник данных apple_pay|
* |google_pay|Источник данных google_pay|
*
*/
class BankCardSource extends AbstractEnum
{
const APPLE_PAY = 'apple_pay';
const GOOGLE_PAY = 'google_pay';
protected static $validValues = array(
self::APPLE_PAY => true,
self::GOOGLE_PAY => 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\PaymentMethod;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentMethodAlfaBank
* Объект, описывающий метод оплаты, при оплате через Альфа Банк.
* @property string $type Тип объекта
* @property string $login Имя пользователя в Альфа-Клике
*/
class PaymentMethodAlfaBank extends AbstractPaymentMethod
{
/**
* @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) {
$this->_login = '';
} elseif (TypeCast::canCastToString($value)) {
$this->_login = (string)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid login value type', 0, 'PaymentMethodAlfaBank.login', $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\PaymentMethod;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentMethodApplePay
* Объект, описывающий метод оплаты, при оплате через Apple Pay
* @property string $type Тип объекта
*/
class PaymentMethodApplePay extends AbstractPaymentMethod
{
public function __construct()
{
$this->_setType(PaymentMethodType::APPLE_PAY);
}
}
@@ -0,0 +1,124 @@
<?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\PaymentMethod;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Model\PaymentData\B2b\Sberbank\VatData;
use YooKassa\Model\PaymentMethod\B2b\Sberbank\PayerBankDetails;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentMethodB2bSberbank
* Объект, описывающий метод оплаты, при оплате через Сбербанк Бизнес Онлайн
*/
class PaymentMethodB2bSberbank extends AbstractPaymentMethod
{
/**
* @var string Назначение платежа
*/
private $_paymentPurpose;
/**
* @var VatData Данные об НДС
*/
private $_vatData;
/**
* @var PayerBankDetails
*/
private $_payerBankDetails;
public function __construct()
{
$this->_setType(PaymentMethodType::B2B_SBERBANK);
}
/**
* @return string
*/
public function getPaymentPurpose()
{
return $this->_paymentPurpose;
}
/**
* @param string $paymentPurpose
*/
public function setPaymentPurpose($paymentPurpose)
{
$this->_paymentPurpose = $paymentPurpose;
}
/**
* @return VatData
*/
public function getVatData()
{
return $this->_vatData;
}
/**
* @param VatData $vatData
*/
public function setVatData($vatData)
{
if(is_array($vatData)) {
$value = new VatData();
$value->fromArray($vatData);
$this->_vatData = $value;
} else if($vatData instanceof VatData){
$this->_vatData = $vatData;
} else{
throw new InvalidPropertyValueException('Invalid $vatData property type');
}
}
/**
* @return PayerBankDetails
*/
public function getPayerBankDetails()
{
return $this->_payerBankDetails;
}
/**
* @param $payerBankDetails
*/
public function setPayerBankDetails($payerBankDetails)
{
if(is_array($payerBankDetails)) {
$value = new PayerBankDetails();
$value->fromArray($payerBankDetails);
$this->_payerBankDetails = $value;
} else if($payerBankDetails instanceof PayerBankDetails){
$this->_payerBankDetails = $payerBankDetails;
} else{
throw new InvalidPropertyValueException('Invalid $payerBankDetails property type');
}
}
}
@@ -0,0 +1,343 @@
<?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\PaymentMethod;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentMethodBankCard
* Объект, описывающий метод оплаты банковской картой
* @property string $type Тип объекта
* @property string $last4 Последние 4 цифры номера карты
* @property string $first6 Первые 6 цифр номера карты
* @property string $expiryYear Срок действия, год
* @property string $expiry_year Срок действия, год
* @property string $expiryMonth Срок действия, месяц
* @property string $expiry_month Срок действия, месяц
* @property string $cardType Тип банковской карты
* @property string $card_type Тип банковской карты
* @property string $issuerCountry Тип банковской карты
* @property string $issuer_country Тип банковской карты
* @property string issuerName Тип банковской карты
* @property string $issuer_name Тип банковской карты
* @property string $source Тип банковской карты
*/
class PaymentMethodBankCard extends AbstractPaymentMethod
{
/**
* @var string Длина кода страны по ISO 3166 https://www.iso.org/obp/ui/#iso:pub:PUB500001:en
*/
const ISO_3166_CODE_LENGTH = 2;
/**
* @var string Последние 4 цифры номера карты
*/
private $_last4;
/**
* @var string Первые 6 цифр номера карты
*/
private $_first6;
/**
* @var string Срок действия, год
*/
private $_expiryYear;
/**
* @var string Срок действия, месяц
*/
private $_expiryMonth;
/**
* @var string Тип банковской карты
*/
private $_cardType;
/**
* @var string Код страны, в которой выпущена карта
*/
private $_issuerCountry;
/**
* @var string Наименование банка, выпустившего карту
*/
private $_issuerName;
/**
* @var string Источник данных банковской карты
*/
private $_source;
public function __construct()
{
$this->_setType(PaymentMethodType::BANK_CARD);
}
/**
* @return string Последние 4 цифры номера карты
*/
public function getLast4()
{
return $this->_last4;
}
/**
* @param string $value Последние 4 цифры номера карты
*/
public function setLast4($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty card last4 value', 0, 'PaymentMethodBankCard.last4');
} elseif (TypeCast::canCastToString($value)) {
if (preg_match('/^[0-9]{4}$/', (string)$value)) {
$this->_last4 = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid card last4 value', 0, 'PaymentMethodBankCard.last4', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid card last4 value type', 0, 'PaymentMethodBankCard.last4', $value
);
}
}
/**
* @return string
* @since 1.0.14
*/
public function getFirst6()
{
return $this->_first6;
}
/**
* @param $value
* @since 1.0.14
*/
public function setFirst6($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty card first6 value', 0, 'PaymentMethodBankCard.first6');
} elseif (TypeCast::canCastToString($value)) {
if (preg_match('/^[0-9]{6}$/', (string)$value)) {
$this->_first6 = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid card first6 value', 0, 'PaymentMethodBankCard.first6', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid card first6 value type', 0, 'PaymentMethodBankCard.first6', $value
);
}
}
/**
* @return string Срок действия, год
*/
public function getExpiryYear()
{
return $this->_expiryYear;
}
/**
* @param string $value Срок действия, год
*/
public function setExpiryYear($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException(
'Empty card expiry year value', 0, 'PaymentMethodBankCard.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, 'PaymentMethodBankCard.expiryYear', $value
);
}
$this->_expiryYear = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid card expiry year value', 0, 'PaymentMethodBankCard.expiryYear', $value
);
}
}
/**
* @return string Срок действия, месяц
*/
public function getExpiryMonth()
{
return $this->_expiryMonth;
}
/**
* @param string $value Срок действия, месяц
*/
public function setExpiryMonth($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException(
'Empty card expiry month value', 0, 'PaymentMethodBankCard.expiryMonth'
);
} elseif (is_numeric($value)) {
if (!preg_match('/^\d\d$/', $value)) {
throw new InvalidPropertyValueException(
'Invalid card expiry month value', 0, 'PaymentMethodBankCard.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, 'PaymentMethodBankCard.expiryMonth', $value
);
} else {
$this->_expiryMonth = (string)$value;
}
} else {
throw new InvalidPropertyValueException(
'Invalid card expiry month value', 0, 'PaymentMethodBankCard.expiryMonth', $value
);
}
}
/**
* @return string Тип банковской карты
*/
public function getCardType()
{
return $this->_cardType;
}
/**
* @param string $value Тип банковской карты
*/
public function setCardType($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty cardType value', 0, 'PaymentMethodBankCard.cardType');
} elseif (TypeCast::canCastToString($value)) {
$this->_cardType = (string)$value;
} else {
throw new InvalidPropertyValueTypeException(
'Invalid cardType value type', 0, 'PaymentMethodBankCard.cardType', $value
);
}
}
/**
* @return string
*/
public function getIssuerCountry()
{
return $this->_issuerCountry;
}
/**
* @param string $value
*/
public function setIssuerCountry($value)
{
if ($value === null || $value === '') {
$this->_issuerCountry = (string)$value;
} elseif (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException(
'Invalid issuerCountry value type', 0, 'PaymentMethodBankCard.issuerCountry', $value
);
} elseif (strlen($value) !== self::ISO_3166_CODE_LENGTH) {
throw new InvalidPropertyValueException(
'Invalid issuerCountry value', 0, 'PaymentMethodBankCard.issuerCountry', $value
);
}
$this->_issuerCountry = (string)$value;
}
/**
* @param string $value
*/
public function setIssuerName($value)
{
if ($value === null || $value === '') {
$this->_issuerName = (string)$value;
} elseif (!TypeCast::canCastToString($value)) {
throw new EmptyPropertyValueException(
'Empty issuerName value', 0, 'PaymentMethodBankCard.issuerName'
);
}
$this->_issuerName = (string)$value;
}
/**
* @return string
*/
public function getIssuerName()
{
return $this->_issuerName;
}
/**
* @param string $value
*/
public function setSource($value)
{
if ($value === null || $value === '') {
$this->_source = (string)$value;
} elseif (!TypeCast::canCastToEnumString($value)) {
throw new InvalidPropertyValueTypeException(
'Invalid source value type', 0, 'PaymentMethodBankCard.source', $value
);
} elseif (!BankCardSource::valueExists($value)) {
throw new InvalidPropertyValueException(
'Invalid source value', 0, 'PaymentMethodBankCard.source', $value
);
}
$this->_source = (string)$value;
}
/**
* @return string
*/
public function getSource()
{
return $this->_source;
}
}
@@ -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\PaymentMethod;
use YooKassa\Common\AbstractEnum;
/**
* Тип банковской карты. Возможные значения:
* - `MasterCard` (для карт Mastercard и Maestro),
* - `Visa` (для карт Visa и Visa Electron),
* - `Mir`,
* - `UnionPay`,
* - `JCB`,
* - `AmericanExpress`,
* - `DinersClub`
* - `Unknown`.
*/
class PaymentMethodCardType extends AbstractEnum
{
const MASTER_CARD = 'MasterCard';
const VISA = 'Visa';
const MIR = 'Mir';
const UNION_PAY = 'UnionPay';
const JCB = 'JCB';
const AMERICAN_EXPRESS = 'AmericanExpress';
const DINERS_CLUB = 'DinersClub';
const UNKNOWN = 'Unknown';
protected static $validValues = array(
self::MASTER_CARD => true,
self::VISA => true,
self::MIR => true,
self::UNION_PAY => true,
self::JCB => true,
self::AMERICAN_EXPRESS => true,
self::DINERS_CLUB => true,
self::UNKNOWN => true,
);
}
@@ -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\PaymentMethod;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentMethodCash
* Объект, описывающий метод оплаты, при оплате наличными через терминал.
* @property string $type Тип объекта
*/
class PaymentMethodCash extends AbstractPaymentMethod
{
public function __construct()
{
$this->_setType(PaymentMethodType::CASH);
}
}
@@ -0,0 +1,114 @@
<?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\PaymentMethod;
use YooKassa\Model\PaymentMethodType;
class PaymentMethodFactory
{
private $typeClassMap = array(
PaymentMethodType::YOO_MONEY => 'PaymentMethodYooMoney',
PaymentMethodType::BANK_CARD => 'PaymentMethodBankCard',
PaymentMethodType::SBERBANK => 'PaymentMethodSberbank',
PaymentMethodType::CASH => 'PaymentMethodCash',
PaymentMethodType::MOBILE_BALANCE => 'PaymentMethodMobileBalance',
PaymentMethodType::APPLE_PAY => 'PaymentMethodApplePay',
PaymentMethodType::GOOGLE_PAY => 'PaymentMethodGooglePay',
PaymentMethodType::QIWI => 'PaymentMethodQiwi',
PaymentMethodType::WEBMONEY => 'PaymentMethodWebmoney',
PaymentMethodType::ALFABANK => 'PaymentMethodAlfaBank',
PaymentMethodType::INSTALLMENTS => 'PaymentMethodInstallments',
PaymentMethodType::B2B_SBERBANK => 'PaymentMethodB2bSberbank',
PaymentMethodType::TINKOFF_BANK => 'PaymentMethodTinkoffBank',
PaymentMethodType::PSB => 'PaymentMethodPsb',
PaymentMethodType::WECHAT => 'PaymentMethodWechat',
);
private $optionsMap = array(
'card_type' => 'cardType',
'expiry_month' => 'expiryMonth',
'expiry_year' => 'expiryYear',
'account_number' => 'accountNumber',
);
/**
* @param string $type
*
* @return AbstractPaymentMethod
*/
public function factory($type)
{
if (!is_string($type)) {
throw new \InvalidArgumentException('Invalid payment method type value in payment factory');
}
if (!array_key_exists($type, $this->typeClassMap)) {
throw new \InvalidArgumentException('Invalid payment method data type "'.$type.'"');
}
$className = __NAMESPACE__.'\\'.$this->typeClassMap[$type];
return new $className();
}
/**
* @param array $data
* @param string|null $type
*
* @return AbstractPaymentMethod
*/
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);
$this->fillModel($paymentData, $data);
return $paymentData;
}
private function fillModel(AbstractPaymentMethod $paymentData, array $data)
{
foreach ($data as $key => $value) {
if (array_key_exists($key, $this->optionsMap)) {
$key = $this->optionsMap[$key];
}
if ($paymentData->offsetExists($key)) {
$paymentData->offsetSet($key, $value);
} else if (is_array($value)) {
$this->fillModel($paymentData, $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\PaymentMethod;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentMethodGooglePay
* Объект, описывающий метод оплаты, при оплате через Google Pay
* @property string $type Тип объекта
*/
class PaymentMethodGooglePay extends AbstractPaymentMethod
{
public function __construct()
{
$this->_setType(PaymentMethodType::GOOGLE_PAY);
}
}
@@ -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\PaymentMethod;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentMethodInstallments
* Объект, описывающий метод оплаты при оплате по частям
* @property string $type Тип объекта
*/
class PaymentMethodInstallments extends AbstractPaymentMethod
{
public function __construct()
{
$this->_setType(PaymentMethodType::INSTALLMENTS);
}
}
@@ -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\PaymentMethod;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentMethodMobileBalance
* Объект, описывающий метод оплаты, при оплате с баланса мобильного телефона.
* @property string $type Тип объекта
* @property string $phone
*/
class PaymentMethodMobileBalance extends AbstractPaymentMethod
{
/**
* Номер телефона в формате 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, 'PaymentMethodMobileBalance.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, 'PaymentMethodMobileBalance.phone', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid phone value type', 0, 'PaymentMethodMobileBalance.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\PaymentMethod;
use YooKassa\Model\PaymentMethodType;
class PaymentMethodPsb extends AbstractPaymentMethod
{
public function __construct()
{
$this->_setType(PaymentMethodType::PSB);
}
}
@@ -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\PaymentMethod;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentMethodQiwi
* Объект, описывающий метод оплаты, при оплате через Qiwi.
* @property string $type Тип объекта
*/
class PaymentMethodQiwi extends AbstractPaymentMethod
{
public function __construct()
{
$this->_setType(PaymentMethodType::QIWI);
}
}
@@ -0,0 +1,87 @@
<?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\PaymentMethod;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentMethodSberbank
* Объект, описывающий метод оплаты, при оплате через Сбербанк Онлайн
* @property string $type Тип объекта
* @property string $phone
*/
class PaymentMethodSberbank extends AbstractPaymentMethod
{
/**
* Телефон пользователя, на который зарегистрирован аккаунт в Сбербанке Онлайн.
*
* Необходим для подтверждения оплаты по смс (сценарий подтверждения `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, 'PaymentMethodSberbank.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, 'PaymentMethodSberbank.phone', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid phone value type', 0, 'PaymentMethodSberbank.phone', $value
);
}
}
}
@@ -0,0 +1,36 @@
<?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\PaymentMethod;
use YooKassa\Model\PaymentMethodType;
class PaymentMethodTinkoffBank extends AbstractPaymentMethod
{
public function __construct()
{
$this->_setType(PaymentMethodType::TINKOFF_BANK);
}
}
@@ -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\PaymentMethod;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentMethodWebmoney
* Объект, описывающий метод оплаты, при оплате через Webmoney.
* @property string $type Тип объекта
*/
class PaymentMethodWebmoney extends AbstractPaymentMethod
{
public function __construct()
{
$this->_setType(PaymentMethodType::WEBMONEY);
}
}
@@ -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\PaymentMethod;
use YooKassa\Model\PaymentMethodType;
/**
* @deprecated Класс будет удалён в одной из будущих версий.
*/
class PaymentMethodWechat extends AbstractPaymentMethod
{
public function __construct()
{
$this->_setType(PaymentMethodType::WECHAT);
}
}
@@ -0,0 +1,85 @@
<?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\PaymentMethod;
use YooKassa\Common\Exceptions\EmptyPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueException;
use YooKassa\Common\Exceptions\InvalidPropertyValueTypeException;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\PaymentMethodType;
/**
* PaymentMethodYooMoney
* Объект, описывающий метод оплаты, при оплате через ЮMoney
* @property string $type Тип объекта
* @property string $accountNumber Номер кошелька в ЮMoney с которого была произведена оплата.
* @property string $account_number Номер кошелька в ЮMoney с которого была произведена оплата.
*/
class PaymentMethodYooMoney extends AbstractPaymentMethod
{
/**
* @var string Номер кошелька в ЮMoney с которого была произведена оплата.
*/
private $_accountNumber;
public function __construct()
{
$this->_setType(PaymentMethodType::YOO_MONEY);
}
/**
* @return string Номер кошелька в ЮMoney с которого была произведена оплата.
*/
public function getAccountNumber()
{
return $this->_accountNumber;
}
/**
* @param string $value Номер кошелька в ЮMoney с которого была произведена оплата.
*/
public function setAccountNumber($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException(
'Empty accountNumber value', 0, 'PaymentMethodYooMoney.accountNumber'
);
} elseif (TypeCast::canCastToString($value)) {
if (preg_match('/^[0-9]{11,33}$/', $value)) {
$this->_accountNumber = (string)$value;
} else {
throw new InvalidPropertyValueException(
'Invalid accountNumber value', 0, 'PaymentMethodYooMoney.accountNumber', $value
);
}
} else {
throw new InvalidPropertyValueTypeException(
'Invalid accountNumber value type', 0, 'PaymentMethodYooMoney.accountNumber', $value
);
}
}
}
@@ -0,0 +1,85 @@
<?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;
/**
* PaymentMethodType - Тип источника средств для проведения платежа
* |Код|Описание|
* --- | ---
* |yoo_money|Платеж из кошелька ЮMoney|
* |bank_card|Платеж с произвольной банковской карты|
* |sberbank|Платеж СбербанкОнлайн|
* |cash|Платеж наличными|
* |mobile_balance|Платеж с баланса мобильного телефона|
* |apple_pay|Платеж ApplePay|
* |google_pay|Платеж Google Pay|
* |qiwi|Платеж из кошелька Qiwi|
* |installments|Заплатить по частям|
* |b2b_sberbank|Сбербанк Бизнес Онлайн|
* |tinkoff_bank|Интернет-банк Тинькофф|
* |psb|ПромсвязьБанк|
* |wechat|Платеж через WeChat|
*/
class PaymentMethodType extends AbstractEnum
{
const YOO_MONEY = 'yoo_money';
const BANK_CARD = 'bank_card';
const SBERBANK = 'sberbank';
const CASH = 'cash';
const MOBILE_BALANCE = 'mobile_balance';
const APPLE_PAY = 'apple_pay';
const GOOGLE_PAY = 'google_pay';
const QIWI = 'qiwi';
const WEBMONEY = 'webmoney';
const ALFABANK = 'alfabank';
const INSTALLMENTS = 'installments';
const B2B_SBERBANK = 'b2b_sberbank';
const TINKOFF_BANK = 'tinkoff_bank';
const PSB = 'psb';
/** @deprecated Будет удален в следующих версиях */
const WECHAT = 'wechat';
protected static $validValues = array(
self::YOO_MONEY => true,
self::BANK_CARD => true,
self::SBERBANK => true,
self::CASH => true,
self::MOBILE_BALANCE => false,
self::APPLE_PAY => false,
self::GOOGLE_PAY => false,
self::QIWI => true,
self::WEBMONEY => true,
self::ALFABANK => true,
self::TINKOFF_BANK => true,
self::INSTALLMENTS => true,
self::B2B_SBERBANK => true,
self::PSB => false,
self::WECHAT => true,
);
}
@@ -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;
use YooKassa\Common\AbstractEnum;
/**
* PaymentStatus - Состояние платежа
* |Код|Описание|
* --- | ---
* |pending|Ожидает оплаты покупателем|
* |waiting_for_capture|Успешно оплачен покупателем, ожидает подтверждения магазином (capture или aviso)|
* |succeeded|Успешно оплачен и подтвержден магазином|
* |canceled|Неуспех оплаты или отменен магазином (cancel)|
*
*/
class PaymentStatus extends AbstractEnum
{
const PENDING = 'pending';
const WAITING_FOR_CAPTURE = 'waiting_for_capture';
const SUCCEEDED = 'succeeded';
const CANCELED = 'canceled';
protected static $validValues = array(
self::PENDING => true,
self::WAITING_FOR_CAPTURE => true,
self::SUCCEEDED => true,
self::CANCELED => true,
);
}
@@ -0,0 +1,460 @@
<?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;
/**
* Класс данных для формирования чека в онлайн-кассе (для соблюдения 54-ФЗ)
*
* @property ReceiptCustomer $customer Информация о плательщике
* @property ReceiptItemInterface[] $items Список товаров в заказе
* @property SettlementInterface[] $settlements Массив оплат, обеспечивающих выдачу товара
* @property int $taxSystemCode Код системы налогообложения. Число 1-6.
* @property int $tax_system_code Код системы налогообложения. Число 1-6.
*/
class Receipt extends AbstractObject implements ReceiptInterface
{
/**
* @var ReceiptCustomer Информация о плательщике
*/
private $_customer;
/**
* @var ReceiptItem[] Список товаров в заказе
*/
private $_items = array();
/**
* @var Settlement[] Массив оплат, обеспечивающих выдачу товара
*/
private $_settlements = array();
/**
* @var ReceiptItem[] Список айтемов в заказе, являющихся доставкой
*/
private $_shippingItems = array();
/**
* @var int Код системы налогообложения. Число 1-6.
*/
private $_taxSystemCode;
/**
* Возвращает информацию о плательщике
*
* @return ReceiptCustomer Информация о плательщике
*/
public function getCustomer()
{
if (!$this->_customer) {
$this->_customer = new ReceiptCustomer();
}
return $this->_customer;
}
/**
* @param ReceiptCustomer $customer
*/
public function setCustomer($customer)
{
$this->_customer = $customer;
}
/**
* Возвращает список позиций в текущем чеке
*
* @return ReceiptItemInterface[] Список товаров в заказе
*/
public function getItems()
{
return $this->_items;
}
/**
* Устанавливает список позиций в чеке
*
* Если до этого в чеке уже были установлены значения, они удаляются и полностью заменяются переданным списком
* позиций. Все передаваемые значения в массиве позиций должны быть объектами класса, реализующего интерфейс
* ReceiptItemInterface, в противном случае будет выброшено исключение InvalidPropertyValueTypeException.
*
* @param ReceiptItemInterface[] $value Список товаров в заказе
*
* @throws EmptyPropertyValueException Выбрасывается если передали пустой массив значений
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве значения был передан не массив и не
* итератор, либо если одно из переданных значений не реализует интерфейс ReceiptItemInterface
*/
public function setItems($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty items value in receipt', 0, 'receipt.items');
}
if (!is_array($value) && !($value instanceof \Traversable)) {
throw new InvalidPropertyValueTypeException(
'Invalid items value type in receipt', 0, 'receipt.items', $value
);
}
$this->_items = array();
$this->_shippingItems = array();
foreach ($value as $key => $val) {
if (is_object($val) && $val instanceof ReceiptItemInterface) {
$this->addItem($val);
} else {
throw new InvalidPropertyValueTypeException(
'Invalid item value type in receipt', 0, 'receipt.items['.$key.']', $val
);
}
}
}
/**
* Добавляет товар в чек
*
* @param ReceiptItemInterface $value Объект добавляемой в чек позиции
*/
public function addItem($value)
{
$this->_items[] = $value;
if ($value->isShipping()) {
$this->_shippingItems[] = $value;
}
}
/**
* Возвращает массив оплат, обеспечивающих выдачу товара.
*
* @return SettlementInterface[] Массив оплат, обеспечивающих выдачу товара.
*/
public function getSettlements()
{
return $this->_settlements;
}
/**
* Возвращает массив оплат, обеспечивающих выдачу товара.
* @param SettlementInterface[] $value
*/
public function setSettlements($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty settlements value in receipt', 0, 'receipt.settlements');
}
if (!is_array($value) && !($value instanceof \Traversable)) {
throw new InvalidPropertyValueTypeException(
'Invalid settlements value type in receipt', 0, 'receipt.settlements', $value
);
}
$this->_settlements = array();
foreach ($value as $key => $val) {
if (is_object($val) && $val instanceof SettlementInterface) {
$this->addSettlement($val);
} else {
throw new InvalidPropertyValueTypeException(
'Invalid settlements value type in receipt', 0, 'receipt.settlements['.$key.']', $val
);
}
}
}
/**
* Добавляет оплату в чек
*
* @param SettlementInterface $value Объект добавляемой в чек позиции
*/
public function addSettlement($value)
{
$this->_settlements[] = $value;
}
/**
* Возвращает код системы налогообложения
*
* @return int Код системы налогообложения. Число 1-6.
*/
public function getTaxSystemCode()
{
return $this->_taxSystemCode;
}
/**
* Устанавливает код системы налогообложения
*
* @param int $value Код системы налогообложения. Число 1-6
*
* @throws InvalidPropertyValueTypeException Выбрасывается если переданный аргумент - не число
* @throws InvalidPropertyValueException Выбрасывается если переданный аргумент меньше одного или больше шести
*/
public function setTaxSystemCode($value)
{
if ($value === null || $value === '') {
$this->_taxSystemCode = null;
} elseif (!is_numeric($value)) {
throw new InvalidPropertyValueTypeException(
'Invalid taxSystemCode value type', 0, 'receipt.taxSystemCode'
);
} else {
$castedValue = (int)$value;
if ($castedValue < 1 || $castedValue > 6) {
throw new InvalidPropertyValueException(
'Invalid taxSystemCode value: '.$value, 0, 'receipt.taxSystemCode'
);
}
$this->_taxSystemCode = $castedValue;
}
}
/**
* Проверяет есть ли в чеке хотя бы одна позиция
*
* @return bool True если чек не пуст, false если в чеке нет ни одной позиции
*/
public function notEmpty()
{
return !empty($this->_items);
}
/**
* Возвращает стоимость заказа исходя из состава чека
*
* @param bool $withShipping Добавить ли к стоимости заказа стоимость доставки
*
* @return int Общая стоимость заказа в центах/копейках
*/
public function getAmountValue($withShipping = true)
{
$result = 0;
foreach ($this->_items as $item) {
if ($withShipping || !$item->isShipping()) {
$result += $item->getAmount();
}
}
return $result;
}
/**
* Возвращает стоимость доставки исходя из состава чека
* @return int Стоимость доставки из состава чека в центах/копейках
*/
public function getShippingAmountValue()
{
$result = 0;
foreach ($this->_items as $item) {
if ($item->isShipping()) {
$result += $item->getAmount();
}
}
return $result;
}
/**
* Подгоняет стоимость товаров в чеке к общей цене заказа
*
* @param AmountInterface $orderAmount Общая стоимость заказа
* @param bool $withShipping Поменять ли заодно и цену доставки
*/
public function normalize(AmountInterface $orderAmount, $withShipping = false)
{
$amount = $orderAmount->getIntegerValue();
if (!$withShipping) {
if ($this->_shippingItems !== null) {
if ($amount > $this->getShippingAmountValue()) {
$amount -= $this->getShippingAmountValue();
} else {
$withShipping = true;
}
}
}
$realAmount = $this->getAmountValue($withShipping);
if ($realAmount !== $amount) {
$coefficient = (float)$amount / (float)$realAmount;
$items = array();
$realAmount = 0;
foreach ($this->_items as $item) {
if ($withShipping || !$item->isShipping()) {
$price = round($coefficient * $item->getPrice()->getIntegerValue());
if ($price < 1.0) {
if ($item->getPrice()->getIntegerValue() > 1) {
$item->getPrice()->setValue(0.01);
}
$amount -= $item->getAmount();
} else {
$items[] = $item;
$realAmount += $item->getAmount();
}
}
}
uasort($items, function (ReceiptItemInterface $a, ReceiptItemInterface $b) {
if ($a->getPrice()->getIntegerValue() > $b->getPrice()->getIntegerValue()) {
return -1;
}
if ($a->getPrice()->getIntegerValue() < $b->getPrice()->getIntegerValue()) {
return 1;
}
return 0;
});
$coefficient = (float)$amount / (float)$realAmount;
$realAmount = 0;
$aloneId = null;
foreach ($items as $index => $item) {
if ($withShipping || !$item->isShipping()) {
$item->applyDiscountCoefficient($coefficient);
$realAmount += $item->getAmount();
if ($aloneId === null && $item->getQuantity() === 1.0 && !$item->isShipping()) {
$aloneId = $index;
}
}
}
if ($aloneId === null) {
foreach ($this->_items as $index => $item) {
if (!$item->isShipping()) {
$aloneId = $index;
break;
}
}
}
if ($aloneId === null) {
$aloneId = 0;
}
$diff = $amount - $realAmount;
if (abs($diff) >= 0.1) {
if ($this->_items[$aloneId]->getQuantity() === 1.0) {
$this->_items[$aloneId]->increasePrice($diff / 100.0);
} elseif ($this->_items[$aloneId]->getQuantity() > 1.0) {
$item = $this->_items[$aloneId]->fetchItem(1);
$item->increasePrice($diff / 100.0);
array_splice($this->_items, $aloneId + 1, 0, array($item));
} else {
$item = $this->_items[$aloneId]->fetchItem($this->_items[$aloneId]->getQuantity() / 2);
$item->increasePrice($diff / 100.0);
array_splice($this->_items, $aloneId + 1, 0, array($item));
}
}
}
}
/**
* @deprecated 1.3.0 Устарел — данные рекомендуется брать в параметре receipt.customer.phone.
* Возвращает номер телефона плательщика в формате ITU-T E.164 на который будет выслан чек
*
* @return string Номер телефона плательщика
*/
public function getPhone()
{
return $this->getCustomer() ? $this->getCustomer()->getPhone() : null;
}
/**
* @deprecated 1.3.0 Устарел — данные рекомендуется передавать в параметре receipt.customer.phone.
* Устанавливливает номер телефона плательщика в формате ITU-T E.164 на который будет выслан чек
*
* @param string $value Номер телефона плательщика в формате ITU-T E.164
*
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве значения была передана не строка
*/
public function setPhone($value)
{
if (!$this->getCustomer()) {
$this->setCustomer(new ReceiptCustomer());
}
$this->getCustomer()->setPhone($value);
}
/**
* @deprecated 1.3.0 Устарел — данные рекомендуется брать в параметре receipt.customer.email.
* Возвращает адрес электронной почты на который будет выслан чек
*
* @return string E-mail адрес плательщика
*/
public function getEmail()
{
return $this->getCustomer() ? $this->getCustomer()->getEmail() : null;
}
/**
* @deprecated 1.3.0 Устарел — данные рекомендуется передавать в параметре receipt.customer.email.
* Устанавливает адрес электронной почты на который будет выслан чек
*
* @param string $value E-mail адрес плательщика
*
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве значения была передана не строка
*/
public function setEmail($value)
{
if (!$this->getCustomer()) {
$this->setCustomer(new ReceiptCustomer());
}
$this->getCustomer()->setEmail($value);
}
/**
* Устанавливает значения свойств текущего объекта из массива
* @param array|\Traversable $sourceArray Ассоциативный массив с настройками
*/
public function fromArray($sourceArray)
{
if (!empty($sourceArray['customer'])) {
$sourceArray['customer'] = new ReceiptCustomer($sourceArray['customer']);
}
if (!empty($sourceArray['items'])) {
foreach ($sourceArray['items'] as $i => $itemArray) {
if (is_array($itemArray)) {
$sourceArray['items'][$i] = new ReceiptItem($itemArray);
}
}
}
if (!empty($sourceArray['settlements'])) {
foreach ($sourceArray['settlements'] as $i => $itemArray) {
if (is_array($itemArray)) {
$sourceArray['settlements'][$i] = new Settlement($itemArray);
}
}
}
parent::fromArray($sourceArray);
}
/**
* Возвращает Id объекта чека
*
* @return string Id объекта чека
*/
public function getObjectId()
{
return null;
}
}
@@ -0,0 +1,28 @@
<?php
namespace YooKassa\Model\Receipt;
use YooKassa\Common\AbstractEnum;
class AgentType extends AbstractEnum
{
const BANKING_PAYMENT_AGENT = 'banking_payment_agent';
const BANKING_PAYMENT_SUBAGENT = 'banking_payment_subagent';
const PAYMENT_AGENT = 'payment_agent';
const PAYMENT_SUBAGENT = 'payment_subagent';
const ATTORNEY = 'attorney';
const COMMISSIONER = 'commissioner';
const AGENT = 'agent';
protected static $validValues = array(
self::BANKING_PAYMENT_AGENT => true,
self::BANKING_PAYMENT_SUBAGENT => true,
self::PAYMENT_AGENT => true,
self::PAYMENT_SUBAGENT => true,
self::ATTORNEY => true,
self::COMMISSIONER => true,
self::AGENT => true,
);
}
@@ -0,0 +1,50 @@
<?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\Receipt;
use YooKassa\Common\AbstractEnum;
class PaymentMode extends AbstractEnum
{
const FULL_PREPAYMENT = 'full_prepayment';
const PARTIAL_PREPAYMENT = 'partial_prepayment';
const ADVANCE = 'advance';
const FULL_PAYMENT = 'full_payment';
const PARTIAL_PAYMENT = 'partial_payment';
const CREDIT = 'credit';
const CREDIT_PAYMENT = 'credit_payment';
protected static $validValues = array(
self::FULL_PREPAYMENT => true,
self::PARTIAL_PREPAYMENT => true,
self::ADVANCE => true,
self::FULL_PAYMENT => true,
self::PARTIAL_PAYMENT => true,
self::CREDIT => true,
self::CREDIT_PAYMENT => true,
);
}
@@ -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\Model\Receipt;
use YooKassa\Common\AbstractEnum;
class PaymentSubject extends AbstractEnum
{
const COMMODITY = 'commodity';
const EXCISE = 'excise';
const JOB = 'job';
const SERVICE = 'service';
const GAMBLING_BET = 'gambling_bet';
const GAMBLING_PRIZE = 'gambling_prize';
const LOTTERY = 'lottery';
const LOTTERY_PRIZE = 'lottery_prize';
const INTELLECTUAL_ACTIVITY = 'intellectual_activity';
const PAYMENT = 'payment';
const AGENT_COMMISSION = 'agent_commission';
const PROPERTY_RIGHT = 'property_right';
const NON_OPERATING_GAIN = 'non_operating_gain';
const INSURANCE_PREMIUM = 'insurance_premium';
const SALES_TAX = 'sales_tax';
const RESORT_FEE = 'resort_fee';
const COMPOSITE = 'composite';
const ANOTHER = 'another';
protected static $validValues = array(
self::COMMODITY => true,
self::EXCISE => true,
self::JOB => true,
self::SERVICE => true,
self::GAMBLING_BET => true,
self::GAMBLING_PRIZE => true,
self::LOTTERY => true,
self::LOTTERY_PRIZE => true,
self::INTELLECTUAL_ACTIVITY => true,
self::PAYMENT => true,
self::AGENT_COMMISSION => true,
self::PROPERTY_RIGHT => true,
self::NON_OPERATING_GAIN => true,
self::INSURANCE_PREMIUM => true,
self::SALES_TAX => true,
self::RESORT_FEE => true,
self::COMPOSITE => true,
self::ANOTHER => true,
);
}
@@ -0,0 +1,220 @@
<?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\Receipt;
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\AmountInterface;
use YooKassa\Model\CurrencyCode;
/**
* Class ReceiptItemAmount
* @package YooKassa\Model\Receipt
*
* @method fromArray($sourceArray)
*/
class ReceiptItemAmount 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);
}
}
/**
* @inheritdoc
*/
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,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\Receipt;
use YooKassa\Common\AbstractEnum;
class SettlementType extends AbstractEnum
{
const CASHLESS = 'cashless';
const PREPAYMENT = 'prepayment';
const POSTPAYMENT = 'postpayment';
const CONSIDERATION = 'consideration';
protected static $validValues = array(
self::CASHLESS => true,
self::PREPAYMENT => true,
self::POSTPAYMENT => true,
self::CONSIDERATION => true,
);
}
@@ -0,0 +1,218 @@
<?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;
/**
* Информация о плательщике
*
* @property string $fullName Для юрлица — название организации, для ИП и физического лица — ФИО.
* @property string $full_name Для юрлица — название организации, для ИП и физического лица — ФИО.
* @property string $phone Номер телефона плательщика в формате ITU-T E.164 на который будет выслан чек.
* @property string $email E-mail адрес плательщика на который будет выслан чек.
* @property string $inn ИНН плательщика (10 или 12 цифр).
*/
class ReceiptCustomer extends AbstractObject implements ReceiptCustomerInterface
{
/**
* @var string Для юрлица — название организации, для ИП и физического лица — ФИО.
*/
private $_fullName;
/**
* @var string Номер телефона плательщика в формате ITU-T E.164 на который будет выслан чек.
*/
private $_phone;
/**
* @var string E-mail адрес плательщика на который будет выслан чек.
*/
private $_email;
/**
* @var string ИНН плательщика (10 или 12 цифр).
*/
private $_inn;
/**
* Возвращает для юрлица — название организации, для ИП и физического лица — ФИО
* @return string Название организации или ФИО
*/
public function getFullName()
{
return $this->_fullName;
}
/**
* Устанавливает Название организации или ФИО
*
* @param string $value Название организации или ФИО
*
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве значения была передана не строка
*/
public function setFullName($value)
{
if ($value === null || $value === '') {
$this->_fullName = null;
} elseif (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException('Invalid full_name value type', 0, 'receipt.customer.full_name');
} elseif (strlen((string)$value) > 256) {
throw new InvalidPropertyValueException(
'Invalid full_name value: "'.$value.'"', 0, 'receipt.customer.full_name', $value
);
} else {
$this->_fullName = (string)$value;
}
}
/**
* Возвращает номер телефона плательщика в формате ITU-T E.164 на который будет выслан чек
*
* @return string Номер телефона плательщика
*/
public function getPhone()
{
return $this->_phone;
}
/**
* Устанавливает номер телефона плательщика в формате ITU-T E.164 на который будет выслан чек
*
* @param string $value Номер телефона плательщика в формате ITU-T E.164
*
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве значения была передана не строка
*/
public function setPhone($value)
{
if ($value === null || $value === '') {
$this->_phone = null;
} elseif (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException('Invalid phone value type', 0, 'receipt.customer.phone');
} else {
$this->_phone = (string)preg_replace('/\D/', '', $value);
}
}
/**
* Возвращает адрес электронной почты на который будет выслан чек
*
* @return string E-mail адрес плательщика
*/
public function getEmail()
{
return $this->_email;
}
/**
* Устанавливает адрес электронной почты на который будет выслан чек
*
* @param string $value E-mail адрес плательщика
*
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве значения была передана не строка
*/
public function setEmail($value)
{
if ($value === null || $value === '') {
$this->_email = null;
} elseif (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException('Invalid email value type', 0, 'receipt.customer.email');
} else {
$this->_email = (string)$value;
}
}
/**
* @return string
*/
public function getInn()
{
return $this->_inn;
}
/**
* Устанавливает ИНН плательщика
*
* @param string $value ИНН плательщика (10 или 12 цифр)
*
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве значения была передана не строка
* @throws InvalidPropertyValueException Выбрасывается если ИНН не соответствует формату 10 или 12 цифр
*/
public function setInn($value)
{
if ($value === null || $value === '') {
$this->_inn = null;
} elseif (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException('Invalid inn value type', 0, 'receipt.customer.inn');
} elseif (!preg_match('/^([0-9]{10}|[0-9]{12})$/', (string)$value)) {
throw new InvalidPropertyValueException('Invalid inn value: "'.$value.'"', 0, 'receipt.customer.inn');
} else {
$this->_inn = (string)$value;
}
}
/**
* Проверка на заполненность объекта
* @return bool
*/
public function isEmpty()
{
$data = $this->getFullName() . $this->getEmail() . $this->getPhone() . $this->getInn();
return empty($data);
}
/**
* @return array
*/
public function jsonSerialize()
{
$result = array();
$value = $this->getFullName();
if (!empty($value)) {
$result['full_name'] = $value;
}
$value = $this->getEmail();
if (!empty($value)) {
$result['email'] = $value;
}
$value = $this->getPhone();
if (!empty($value)) {
$result['phone'] = $value;
}
$value = $this->getInn();
if (!empty($value)) {
$result['inn'] = $value;
}
return $result;
}
}
@@ -0,0 +1,76 @@
<?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 ReceiptCustomerInterface
*
* @package YooKassa\Model
*
* @property-read string $fullName Для юрлица — название организации, для ИП и физического лица — ФИО.
* @property-read string $full_name Для юрлица — название организации, для ИП и физического лица — ФИО.
* @property-read string $phone Номер телефона плательщика в формате ITU-T E.164 на который будет выслан чек.
* @property-read string $email E-mail адрес плательщика на который будет выслан чек.
* @property-read string $inn ИНН плательщика (10 или 12 цифр).
*/
interface ReceiptCustomerInterface
{
/**
* Возвращает название организации или ФИО физического лица
*
* @return string название организации или ФИО физического лица
*/
function getFullName();
/**
* Возвращает номер телефона плательщика в формате ITU-T E.164 на который будет выслан чек
*
* @return string Номер телефона плательщика
*/
function getPhone();
/**
* Возвращает адрес электронной почты на который будет выслан чек
*
* @return string E-mail адрес плательщика
*/
function getEmail();
/**
* Возвращает ИНН плательщика
*
* @return string ИНН плательщика
*/
function getInn();
/**
* Возвращает массив полей плательщика
*
* @return array
*/
function jsonSerialize();
}
@@ -0,0 +1,90 @@
<?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 ReceiptInterface
*
* @package YooKassa\Model
*
* @property-read ReceiptCustomerInterface $customer Информация о плательщике
* @property-read ReceiptItemInterface[] $items Список товаров в заказе
* @property-read int $taxSystemCode Код системы налогообложения. Число 1-6.
* @property-read int $tax_system_code Код системы налогообложения. Число 1-6.
*/
interface ReceiptInterface
{
/**
* Возвращает Id объекта чека
*
* @return string Id объекта чека
*/
public function getObjectId();
/**
* Возвращает информацию о плательщике
*
* @return ReceiptCustomerInterface Информация о плательщике
*/
public function getCustomer();
/**
* Возвращает список позиций в текущем чеке
*
* @return ReceiptItemInterface[] Список товаров в заказе
*/
public function getItems();
/**
* Возвращает массив оплат, обеспечивающих выдачу товара.
*
* @return SettlementInterface[] Массив оплат, обеспечивающих выдачу товара.
*/
public function getSettlements();
/**
* Возвращает код системы налогообложения
*
* @return int Код системы налогообложения. Число 1-6.
*/
public function getTaxSystemCode();
/**
* Проверяет есть ли в чеке хотя бы одна позиция
*
* @return bool True если чек не пуст, false если в чеке нет ни одной позиции
*/
public function notEmpty();
/**
* Подгоняет стоимость товаров в чеке к общей цене заказа
*
* @param AmountInterface $orderAmount Общая стоимость заказа
* @param bool $withShipping Поменять ли заодно и цену доставки
*/
public function normalize(AmountInterface $orderAmount, $withShipping = false);
}
@@ -0,0 +1,694 @@
<?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\ProductCode;
use YooKassa\Helpers\TypeCast;
use YooKassa\Model\Receipt\AgentType;
use YooKassa\Model\Receipt\ReceiptItemAmount;
/**
* Информация о товарной позиции в заказе, позиция фискального чека
*
* @property string $description Наименование товара
* @property float $quantity Количество
* @property-read float $amount Суммарная стоимость покупаемого товара в копейках/центах
* @property AmountInterface $price Цена товара
* @property Supplier $supplier Информация о поставщике товара или услуги
* @property int $vatCode Ставка НДС, число 1-6
* @property int $vat_code Ставка НДС, число 1-6
* @property string $paymentSubject Признак предмета расчета
* @property string $payment_subject Признак предмета расчета
* @property string $paymentMode Признак способа расчета
* @property string $payment_mode Признак способа расчета
* @property string $productCode Код товара
* @property string $product_code Код товара
* @property string $countryOfOriginCode Код страны происхождения товара
* @property string $country_of_origin_code Код страны происхождения товара
* @property string $customsDeclarationNumber Номер таможенной декларации (от 1 до 32 символов)
* @property string $customs_declaration_number Номер таможенной декларации (от 1 до 32 символов)
* @property float $excise Сумма акциза товара с учетом копеек
* @property-write bool $isShipping Флаг доставки
*/
class ReceiptItem extends AbstractObject implements ReceiptItemInterface
{
/**
* @var string Наименование товара
*/
private $_description;
/**
* @var float Количество
*/
private $_quantity;
/**
* @var ReceiptItemAmount Цена товара
*/
private $_amount;
/**
* @var int Ставка НДС, число 1-6
*/
private $_vatCode;
/**
* @var string Признак предмета расчета.
*/
private $_paymentSubject;
/**
* @var string Признак способа расчета.
*/
private $_paymentMode;
/**
* @var string Код товара.
*/
private $_productCode;
/**
* @var string Код страны происхождения товара
*/
private $_countryOfOriginCode;
/**
* @var string Номер таможенной декларации (от 1 до 32 символов).
*/
private $_customsDeclarationNumber;
/**
* @var float Сумма акциза товара с учетом копеек. Десятичное число с точностью до 2 символов после точки.
*/
private $_excise;
/**
* @var SupplierInterface Информация о поставщике товара или услуги
*/
private $_supplier;
/**
* @var string Тип посредника, реализующего товар или услугу
*/
private $_agentType;
/**
* @var bool True если текущий айтем доставка, false если нет
*/
private $_shipping = false;
/**
* ReceiptItem constructor.
* @param array|null $data Массив для инициализации нового объекта
*/
public function __construct($data = null)
{
if (!empty($data) && is_array($data)) {
$this->fromArray($data);
}
}
/**
* Возвращает наименование товара
* @return string Наименование товара
*/
public function getDescription()
{
return $this->_description;
}
/**
* Устанавливает наименование товара
*
* @param string $value Наименование товара
*
* @throws EmptyPropertyValueException Выбрасывается если было передано пустое значение
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве аргумента была передана не строка
*/
public function setDescription($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException(
'Empty description value in ReceiptItem', 0, 'ReceiptItem.description'
);
} elseif (TypeCast::canCastToString($value)) {
$castedValue = (string)$value;
if ($castedValue === '') {
throw new EmptyPropertyValueException(
'Empty description value in ReceiptItem', 0, 'ReceiptItem.description'
);
}
$this->_description = mb_substr($castedValue, 0, 128);
} else {
throw new InvalidPropertyValueTypeException(
'Empty description value in ReceiptItem', 0, 'ReceiptItem.description', $value
);
}
}
/**
* Возвращает количество товара
* @return float Количество купленного товара
*/
public function getQuantity()
{
return $this->_quantity;
}
/**
* Устанавливает количество покупаемого товара
*
* @param int $value Количество
*
* @throws EmptyPropertyValueException Выбрасывается если было передано пустое значение
* @throws InvalidPropertyValueException Выбрасывается если в качестве аргумента был передан ноль
* или отрицательное число
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве аргумента было передано не число
*/
public function setQuantity($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException('Empty quantity value in ReceiptItem', 0, 'ReceiptItem.quantity');
} elseif (!is_numeric($value)) {
throw new InvalidPropertyValueTypeException(
'Invalid quantity value type in ReceiptItem', 0, 'ReceiptItem.quantity', $value
);
} elseif ($value <= 0.0) {
throw new InvalidPropertyValueException(
'Invalid quantity value in ReceiptItem', 0, 'ReceiptItem.quantity', $value
);
} else {
$this->_quantity = (float)$value;
}
}
/**
* Возвращает общую стоимость покупаемого товара в копейках/центах
* @return int Сумма стоимости покупаемого товара
*/
public function getAmount()
{
return (int)round($this->_amount->getIntegerValue() * $this->_quantity);
}
/**
* Возвращает цену товара
* @return AmountInterface Цена товара
*/
public function getPrice()
{
return $this->_amount;
}
/**
* Устанавливает цену товара
*
* @param AmountInterface $value Цена товара
*/
public function setPrice(AmountInterface $value)
{
$this->_amount = $value;
}
/**
* Возвращает ставку НДС
* @return int|null Ставка НДС, число 1-6, или null если ставка не задана
*/
public function getVatCode()
{
return $this->_vatCode;
}
/**
* Устанавливает ставку НДС
*
* @param int $value Ставка НДС, число 1-6
*
* @throws InvalidPropertyValueException Выбрасывается если в качестве аргумента было передано число меньше одного
* или больше шести
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве аргумента было передано не число
*/
public function setVatCode($value)
{
if ($value === null || $value === '') {
$this->_vatCode = null;
} elseif (!is_numeric($value)) {
throw new InvalidPropertyValueTypeException(
'Invalid vatId value type in ReceiptItem', 0, 'ReceiptItem.vatId', $value
);
} elseif ($value < 1 || $value > 6) {
throw new InvalidPropertyValueException(
'Invalid vatId value in ReceiptItem', 0, 'ReceiptItem.vatId', $value
);
} else {
$this->_vatCode = (int)$value;
}
}
/**
* Возвращает признак предмета расчета
* @return string|null Признак предмета расчета
*/
public function getPaymentSubject()
{
return $this->_paymentSubject;
}
/**
* Устанавливает признак предмета расчета
*
* @param string $value Признак предмета расчета
*
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве аргумента была передана не строка
*/
public function setPaymentSubject($value)
{
if ($value === null || $value === '') {
$this->_paymentSubject = null;
} elseif (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException('Invalid paymentSubject value type', 0, 'ReceiptItem.paymentSubject');
} else {
$this->_paymentSubject = $value;
}
}
/**
* Возвращает признак способа расчета
* @return string|null Признак способа расчета
*/
public function getPaymentMode()
{
return $this->_paymentMode;
}
/**
* Устанавливает признак способа расчета
*
* @param string $value Признак способа расчета
*
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве аргумента была передана не строка
*/
public function setPaymentMode($value)
{
if ($value === null || $value === '') {
$this->_paymentMode = null;
} elseif (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException(
'Invalid paymentMode value type', 0, 'ReceiptItem.paymentMode', $value
);
} else {
$this->_paymentMode = $value;
}
}
/**
* Возвращает код товара — уникальный номер, который присваивается экземпляру товара при маркировке
* @return string|null Код товара
*/
public function getProductCode()
{
return $this->_productCode;
}
/**
* Устанавливает код товара — уникальный номер, который присваивается экземпляру товара при маркировке
*
* @param string|ProductCode $value Код товара
*
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве аргумента была передана не строка
*/
public function setProductCode($value)
{
if ($value instanceof ProductCode) {
$value = (string)$value;
}
if ($value === null || $value === '') {
$this->_productCode = null;
} elseif (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException(
'Invalid productCode value type', 0, 'ReceiptItem.productCode', $value
);
} elseif (strlen((string)$value) > 96) {
throw new InvalidPropertyValueException(
'Invalid productCode value: "'.$value.'"', 0, 'ReceiptItem.productCode', $value
);
} elseif (!preg_match('/^[0-9A-F ]{2,96}$/', (string)$value)) {
throw new InvalidPropertyValueException(
'Invalid productCode value: "'.$value.'"', 0, 'ReceiptItem.productCode', $value
);
} else {
$this->_productCode = $value;
}
}
/**
* Возвращает код страны происхождения товара по общероссийскому классификатору стран мира
* @return string|null Код страны происхождения товара
*/
public function getCountryOfOriginCode()
{
return $this->_countryOfOriginCode;
}
/**
* Устанавливает код страны происхождения товара по общероссийскому классификатору стран мира
*
* @param string $value Код страны происхождения товара
*
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве аргумента была передана не строка
*/
public function setCountryOfOriginCode($value)
{
if ($value === null || $value === '') {
$this->_countryOfOriginCode = null;
} elseif (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException(
'Invalid countryOfOriginCode value type', 0, 'ReceiptItem.countryOfOriginCode', $value
);
} elseif (strlen((string)$value) != 2) {
throw new InvalidPropertyValueException(
'Invalid countryOfOriginCode value: "'.$value.'"', 0, 'ReceiptItem.countryOfOriginCode', $value
);
} elseif (!preg_match('/^[A-Z]{2}$/', (string)$value)) {
throw new InvalidPropertyValueException(
'Invalid countryOfOriginCode value: "'.$value.'"', 0, 'ReceiptItem.countryOfOriginCode', $value
);
} else {
$this->_countryOfOriginCode = $value;
}
}
/**
* Возвращает номер таможенной декларации
* @return string|null Номер таможенной декларации (от 1 до 32 символов)
*/
public function getCustomsDeclarationNumber()
{
return $this->_customsDeclarationNumber;
}
/**
* Устанавливает номер таможенной декларации (от 1 до 32 символов)
*
* @param string $value Номер таможенной декларации
*
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве аргумента была передана не строка
*/
public function setCustomsDeclarationNumber($value)
{
if ($value === null || $value === '') {
$this->_customsDeclarationNumber = null;
} elseif (!TypeCast::canCastToString($value)) {
throw new InvalidPropertyValueTypeException(
'Invalid customsDeclarationNumber value type', 0, 'ReceiptItem.customsDeclarationNumber', $value
);
} elseif (strlen((string)$value) > 32) {
throw new InvalidPropertyValueException(
'Invalid customsDeclarationNumber value: "'.$value.'"', 0, 'ReceiptItem.customsDeclarationNumber', $value
);
} else {
$this->_customsDeclarationNumber = $value;
}
}
/**
* Возвращает сумму акциза товара с учетом копеек
* @return float|null Сумма акциза товара с учетом копеек
*/
public function getExcise()
{
return $this->_excise;
}
/**
* Устанавливает сумму акциза товара с учетом копеек
*
* @param float $value Сумма акциза товара с учетом копеек
*
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве аргумента было передано не число
*/
public function setExcise($value)
{
if ($value === null || $value === '') {
$this->_excise = null;
} elseif (!is_numeric($value)) {
throw new InvalidPropertyValueTypeException(
'Invalid excise value type', 0, 'ReceiptItem.excise', $value
);
} elseif ($value <= 0.0) {
throw new InvalidPropertyValueException(
'Invalid excise value in ReceiptItem', 0, 'ReceiptItem.excise', $value
);
} else {
$this->_excise = $value;
}
}
/**
* Устанавливает флаг доставки для текущего объекта айтема в чеке
*
* @param bool $value True если айтем является доставкой, false если нет
*
* @return ReceiptItem
* @throws InvalidPropertyValueException Генерируется если передано значение невалидного типа
*/
public function setIsShipping($value)
{
if ($value === null || $value === '') {
$this->_shipping = false;
} elseif (TypeCast::canCastToBoolean($value)) {
$this->_shipping = $value ? true : false;
} else {
throw new InvalidPropertyValueException(
'Invalid isShipping value in ReceiptItem', 0, 'ReceiptItem.isShipping', $value
);
}
return $this;
}
/**
* Возвращает информацию о поставщике товара или услуги.
*
* @return SupplierInterface
*/
public function getSupplier()
{
return $this->_supplier;
}
/**
* Устанавливает информацию о поставщике товара или услуги.
*
* @param SupplierInterface|array $value
*/
public function setSupplier($value)
{
if ($value === null || $value === '') {
throw new EmptyPropertyValueException(
'Empty supplier value in receipt', 0, 'Receipt.supplier'
);
}
if (is_array($value)) {
$value = new Supplier($value);
}
if (!($value instanceof SupplierInterface)) {
throw new InvalidPropertyValueTypeException(
'Invalid supplier value type in receipt', 0, 'Receipt.supplier', $value
);
}
$this->_supplier = $value;
}
/**
* @param string $value
*/
public function setAgentType($value)
{
if ($value === null || $value === '') {
$this->_paymentMode = null;
} elseif (!TypeCast::canCastToEnumString($value)) {
throw new InvalidPropertyValueException(
'Invalid value for "agentType" parameter in Receipt.item.agentType',
0,
'Receipt.item.agentType',
$value
);
} elseif (!AgentType::valueExists($value)) {
throw new InvalidPropertyValueException(
'Invalid value for "agentType" parameter in Receipt.item.agentType',
0,
'Receipt.item.agentType',
$value
);
}
$this->_agentType = $value;
}
public function getAgentType()
{
return $this->_agentType;
}
/**
* Проверяет, является ли текущий элемент чека доствкой
* @return bool True если доставка, false если обычный товар
*/
public function isShipping()
{
return $this->_shipping;
}
/**
* Применяет для товара скидку
*
* @param float $coefficient Множитель скидки
*/
public function applyDiscountCoefficient($coefficient)
{
$this->_amount->multiply($coefficient);
}
/**
* Увеличивает цену товара на указанную величину
*
* @param float $value Сумма на которую цену товара увеличиваем
*/
public function increasePrice($value)
{
$this->_amount->increase($value);
}
/**
* Уменьшает количество покупаемого товара на указанное, возвращает объект позиции в чеке с уменьшаемым количеством
*
* @param float $count Количество на которое уменьшаем позицию в чеке
*
* @return ReceiptItem
*
* @throws EmptyPropertyValueException Выбрасывается если было передано пустое значение
* @throws InvalidPropertyValueException Выбрасывается если в качестве аргумента был передан ноль
* или отрицательное число, или число больше текущего количества покупаемого товара
* @throws InvalidPropertyValueTypeException Выбрасывается если в качестве аргумента было передано не число
*/
public function fetchItem($count)
{
if ($count === null || $count === '') {
throw new EmptyPropertyValueException(
'Empty quantity value in ReceiptItem in fetchItem method', 0, 'ReceiptItem.quantity'
);
} elseif (!is_numeric($count)) {
throw new InvalidPropertyValueTypeException(
'Invalid quantity value type in ReceiptItem in fetchItem method', 0, 'ReceiptItem.quantity', $count
);
} elseif ($count <= 0.0 || $count >= $this->_quantity) {
throw new InvalidPropertyValueException(
'Invalid quantity value in ReceiptItem in fetchItem method', 0, 'ReceiptItem.quantity', $count
);
}
$result = clone $this;
$result->setPrice(clone $this->getPrice());
$result->setQuantity($count);
$this->_quantity -= $count;
return $result;
}
/**
* Устанавливает значения свойств текущего объекта из массива
* @param array|\Traversable $sourceArray Ассоциативный массив с настройками
*/
public function fromArray($sourceArray)
{
$amount = new ReceiptItemAmount();
$amount->fromArray($sourceArray['amount']);
$sourceArray['price'] = $amount;
unset($sourceArray['amount']);
parent::fromArray($sourceArray);
}
/**
* @return array
*/
public function jsonSerialize()
{
$result = array(
'description' => $this->getDescription(),
'amount' => array(
'value' => $this->getPrice()->getValue(),
'currency' => $this->getPrice()->getCurrency(),
),
'quantity' => $this->getQuantity(),
'vat_code' => $this->getVatCode(),
);
if ($this->getPaymentSubject()) {
$result['payment_subject'] = $this->getPaymentSubject();
}
if ($this->getPaymentMode()) {
$result['payment_mode'] = $this->getPaymentMode();
}
if ($this->getProductCode()) {
$result['product_code'] = $this->getProductCode();
}
if ($this->getCountryOfOriginCode()) {
$result['country_of_origin_code'] = $this->getCountryOfOriginCode();
}
if ($this->getCustomsDeclarationNumber()) {
$result['customs_declaration_number'] = $this->getCustomsDeclarationNumber();
}
if ($this->getExcise()) {
$result['excise'] = $this->getExcise();
}
if ($this->getSupplier()) {
$result['supplier'] = $this->getSupplier()->jsonSerialize();
}
if ($this->getAgentType()) {
$result['agent_type'] = $this->getAgentType();
}
return $result;
}
}
@@ -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;
/**
* Interface ReceiptItemInterface
*
* @package YooKassa\Model
*
* @property-read string $description Наименование товара
* @property-read float $quantity Количество
* @property-read float $amount Суммарная стоимость покупаемого товара в копейках/центах
* @property-read AmountInterface $price Цена товара
* @property-read int $vatCode Ставка НДС, число 1-6
* @property-read int $vat_code Ставка НДС, число 1-6
* @property-read string $paymentSubject Признак предмета расчета
* @property-read string $payment_subject Признак предмета расчета
* @property-read string $paymentMode Признак способа расчета
* @property-read string $payment_mode Признак способа расчета
* @property-read string $productCode Код товара
* @property-read string $product_code Код товара
* @property-read string $countryOfOriginCode Код страны происхождения товара
* @property-read string $country_of_origin_code Код страны происхождения товара
* @property-read string $customsDeclarationNumber Номер таможенной декларации (от 1 до 32 символов)
* @property-read string $customs_declaration_number Номер таможенной декларации (от 1 до 32 символов)
* @property-read float $excise Сумма акциза товара с учетом копеек
*/
interface ReceiptItemInterface
{
/**
* Возвращает наименование товара
* @return string Наименование товара
*/
function getDescription();
/**
* Возвращает количество товара
* @return float Количество купленного товара
*/
function getQuantity();
/**
* Возвращает общую стоимость покупаемого товара в копейках/центах
* @return float Сумма стоимости покупаемого товара
*/
function getAmount();
/**
* Возвращает цену товара
* @return AmountInterface Цена товара
*/
function getPrice();
/**
* Возвращает ставку НДС
* @return int|null Ставка НДС, число 1-6, или null если ставка не задана
*/
function getVatCode();
/**
* Возвращает признак предмета расчета
* @return string|null Признак предмета расчета
*/
function getPaymentSubject();
/**
* Возвращает признак способа расчета
* @return string|null Признак способа расчета
*/
function getPaymentMode();
/**
* Возвращает код товара — уникальный номер, который присваивается экземпляру товара при маркировке
* @return string|null Код товара
*/
function getProductCode();
/**
* Возвращает код страны происхождения товара по общероссийскому классификатору стран мира
* @return string|null Код страны происхождения товара
*/
function getCountryOfOriginCode();
/**
* Возвращает номер таможенной декларации
* @return string|null Номер таможенной декларации (от 1 до 32 символов)
*/
function getCustomsDeclarationNumber();
/**
* Возвращает сумму акциза товара с учетом копеек
* @return float|null Сумма акциза товара с учетом копеек
*/
function getExcise();
/**
* Возвращает информацию о поставщике товара или услуги.
*
* @return SupplierInterface
*/
function getSupplier();
/**
* @return string
*/
function getAgentType();
/**
* Проверяет, является ли текущий элемент чека доставкой
* @return bool True если доставка, false если обычный товар
*/
function isShipping();
}
@@ -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;
use YooKassa\Common\AbstractEnum;
/**
* Класс с перечислением статусов доставки данных для чека в онлайн-кассу (`pending`, `succeeded` или `canceled`)
*
* Состояние регистрации фискального чека:
* <ul>
* <li>pending - Чек ожидает доставки</li>
* <li>succeeded - Успешно доставлен</li>
* <li>canceled - Чек не доставлен</li>
* </ul>
*/
class ReceiptRegistrationStatus extends AbstractEnum
{
/**
* @var string Состояние регистрации фискального чека: ожидает доставки
*/
const PENDING = 'pending';
/**
* @var string Состояние регистрации фискального чека: успешно доставлен
*/
const SUCCEEDED = 'succeeded';
/**
* @var string Состояние регистрации фискального чека: не доставлен
*/
const CANCELED = 'canceled';
protected static $validValues = array(
self::PENDING => true,
self::SUCCEEDED => true,
self::CANCELED => true,
);
}
@@ -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\Model;
use YooKassa\Common\AbstractEnum;
/**
* ReceiptType - Тип чека в онлайн-кассе.
* |Код|Описание|
* --- | ---
* |payment|Приход|
* |refund|Возврат|
* |simple|Простой|
*/
class ReceiptType extends AbstractEnum
{
/** @var string Тип чека: приход */
const PAYMENT = 'payment';
/** @var string Тип чека: возврат */
const REFUND = 'refund';
/** @var string Тип чека: простой */
const SIMPLE = 'simple';
protected static $validValues = array(
self::PAYMENT => true,
self::REFUND => true,
self::SIMPLE => true,
);
}

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