Skip to content

API Reference

In development

There is only initial API reference, thats why the provided info may be not full

Apps

App

Class for interacting with Yoomoney APIs.

Parameters:

Name Type Description Default
token str

Yoomoney application token (can get via Authorizer)

required

Attributes:

Name Type Description
token str

Yoomoney application token (can get via Authorizer)

headers Dict[str, str]

Default headers for API requests

Example:

import asyncio
from yoowallet import App
from yoowallet.types import AccountInfo

async def main():
    app: App = App("TOKEN")
    if not await app.connect():
        raise ValueError('Token is invalid!')
    app_info = await app.account_info()
    app_info.debug()

if __name__ == "__main__":
    asyncio.run(main())

Source code in yoowallet/core/app.py
class App:
    """Class for interacting with Yoomoney APIs.

    Args:
        token (str): Yoomoney application token (can get via Authorizer)

    Attributes:
        token (str): Yoomoney application token (can get via Authorizer)
        headers (Dict[str, str]): Default headers for API requests

    Example:
    ```python
    import asyncio
    from yoowallet import App
    from yoowallet.types import AccountInfo

    async def main():
        app: App = App("TOKEN")
        if not await app.connect():
            raise ValueError('Token is invalid!')
        app_info = await app.account_info()
        app_info.debug()

    if __name__ == "__main__":
        asyncio.run(main())
    ```
    """
    def __init__(self, token: str) -> None:
        self.token = token
        self._base_url = "https://yoomoney.ru"
        self.headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": f"Bearer {self.token}"
        }

    async def connect(self) -> bool:
        """Verifying App's token via getting account information

        Returns:
            True if token is valid, False if invalid
        """
        try:
            await self.account_info()
            return True
        except Exception:
            return False

    async def account_info(self) -> AccountInfo:
        """Getting account information. Needs at least this scope: ["account-info"]

        Returns:
            AccountInfo entity
        """
        # Generating URL
        url = f"{self._base_url}/api/account-info"
        async with aiohttp.ClientSession() as session:
            async with session.post(url=url, headers=self.headers) as response:
                if response.status == 200:
                    response = await response.json()
                    return AccountInfo(response)
                elif response.status == 401:
                    raise InvalidToken
                else:
                    raise AccountInfoError(f"Undefined error, answer: {response}")

    async def operation_history(
            self,
            type: Optional[List[str]] = None,
            label: Optional[str] = None,
            from_time: Optional[datetime] = None,
            till_time: Optional[datetime] = None,
            start_record: Optional[str] = None,
            records: Optional[int] = None,
            details: Optional[bool] = None
            ) -> OperationHistory:
        """Getting operation history. Needs at least this scope: ["operation-history", "operation-details"]

        Args:
            type (Optional[List[str]]): Operation types (deposition or payment)
            label (Optional[str]): Filtering value (custom operation id)
            from_time (Optional[datetime]): Operations from this timestamp
            till_time (Optional[datetime]): Operations till this timestamp
            start_record (Optional[str]): Operations from this number
            records (Optional[int]): Number of history records
            details (Optional[bool]): Show operation details (True or False)

        Returns:
            OperationHistory entity
        """
        # Generating request params
        params = {}
        if type is not None:
            params["type"] = type
        if label is not None:
            params["label"] = label
        # Defining default time format
        time_format = "%Y-%m-%dT%H:%M:%S"
        # Parsing datetimes
        if from_time is not None:
            try:
                params["from"] = datetime.strftime(from_time, time_format)
            except Exception:
                raise IllegalParamFrom("Failed to format input")
        if till_time is not None:
            try:
                params["till"] = datetime.strftime(till_time, time_format)
            except Exception:
                raise IllegalParamTill("Failed to format input")
        if start_record is not None:
            params["start_record"] = start_record
        if records is not None:
            params["records"] = str(records)
        if details is not None:
            params["details"] = details
        # Generating URL
        url = f"{self._base_url}/api/operation-history"
        async with aiohttp.ClientSession() as session:
            async with session.post(url=url, headers=self.headers, data=params) as response:
                # Errors processing
                if response.status in [401, 403]:
                    raise InvalidToken
                response = await response.json()
                if "error" in response:
                    if response["error"] == "illegal_param_type":
                        raise IllegalParamType("Try to redefine it in another way")
                    elif response["error"] == "illegal_param_start_record":
                        raise IllegalParamStartRecord("Try to redefine it in another way'")
                    elif response["error"] == "illegal_param_records":
                        raise IllegalParamRecords("Try to redefine it in another way'")
                    elif response["error"] == "illegal_param_label":
                        raise IllegalParamLabel("Try to redefine it in another way'")
                    elif response["error"] == "illegal_param_from":
                        raise IllegalParamFrom("Try to redefine it in another way'")
                    elif response["error"] == "illegal_param_till":
                        raise IllegalParamTill("Try to redefine it in another way'")
                    else:
                        raise HistoryTechicalError("Try again later'")
                return OperationHistory(response)

    async def quickpay(
            self,
            sum: float,
            payment_type: str = "AC",
            label: Optional[str] = None,
            success_url: Optional[str] = None
            ) -> Dict[str, Any]: # type: ignore
        """Creating fundraising link

        Example:
        ```python
        import asyncio
        from yoowallet import App

        async def main():
            app: App = App("TOKEN")
            if not await app.connect():
                raise ValueError('Token is invalid!')
            # Generating fundraising for 5 RUB
            payment = await app.quickpay(5.0)
            print(f"QucikPay URL is {payment['url']}")

        if __name__ == "__main__":
            asyncio.run(main())
        ```

        Args:
            sum (float): Transfer amount (the amount debited from the sender)
            payment_type (str): PC for a payment from a YooMoney wallet, AC for a payment from a bank card
            label (str): The label that a site or app assigns to a certain transfer
            success_url (str): URL where the user is redirected after the transfer

        Returns:
            Python dictionary with fields: url and amount_due (the amount, that will be received)
        """
        # Getting the number of YooMoney wallet
        receiver: str = (await self.account_info()).account
        # Computing the amount to be received
        commissions = {"PC": 0.01, "AC": 0.03}
        amount_due: float = sum*(1-commissions[payment_type])
        # Generating params
        params = {}
        params["receiver"] = receiver
        params["sum"] = sum
        params["quickpay-form"] = "button"
        params["paymentType"] = payment_type
        if label:
            params["label"] = label
        if success_url:
            params["successURL"] = success_url
        async with aiohttp.ClientSession() as session:
            async with session.post(url="https://yoomoney.ru/quickpay/confirm", headers=self.headers, data=params) as response:
                if response.status == 200:
                    return {"url": response.url, "amount_due": amount_due}
                else:
                    # There must be an error handler, but YooMoney didn't provide
                    # any error list for QuickPay :(
                    raise FailedQuickPayGen(response.status)

    async def get_by_label(self, label: str) -> Optional[Dict[str, Any]]:
        """Checks whether payment with such label exists

        Args:
            label (str): Lable of needed operation

        Returns:
            Operation details 
        """
        operation = (await self.operation_history(label = label)).operations
        if not operation or len(operation) > 1:
            return
        return operation[0]

account_info() async

Getting account information. Needs at least this scope: ["account-info"]

Returns:

Type Description
AccountInfo

AccountInfo entity

Source code in yoowallet/core/app.py
async def account_info(self) -> AccountInfo:
    """Getting account information. Needs at least this scope: ["account-info"]

    Returns:
        AccountInfo entity
    """
    # Generating URL
    url = f"{self._base_url}/api/account-info"
    async with aiohttp.ClientSession() as session:
        async with session.post(url=url, headers=self.headers) as response:
            if response.status == 200:
                response = await response.json()
                return AccountInfo(response)
            elif response.status == 401:
                raise InvalidToken
            else:
                raise AccountInfoError(f"Undefined error, answer: {response}")

connect() async

Verifying App's token via getting account information

Returns:

Type Description
bool

True if token is valid, False if invalid

Source code in yoowallet/core/app.py
async def connect(self) -> bool:
    """Verifying App's token via getting account information

    Returns:
        True if token is valid, False if invalid
    """
    try:
        await self.account_info()
        return True
    except Exception:
        return False

get_by_label(label) async

Checks whether payment with such label exists

Parameters:

Name Type Description Default
label str

Lable of needed operation

required

Returns:

Type Description
Optional[Dict[str, Any]]

Operation details

Source code in yoowallet/core/app.py
async def get_by_label(self, label: str) -> Optional[Dict[str, Any]]:
    """Checks whether payment with such label exists

    Args:
        label (str): Lable of needed operation

    Returns:
        Operation details 
    """
    operation = (await self.operation_history(label = label)).operations
    if not operation or len(operation) > 1:
        return
    return operation[0]

operation_history(type=None, label=None, from_time=None, till_time=None, start_record=None, records=None, details=None) async

Getting operation history. Needs at least this scope: ["operation-history", "operation-details"]

Parameters:

Name Type Description Default
type Optional[List[str]]

Operation types (deposition or payment)

None
label Optional[str]

Filtering value (custom operation id)

None
from_time Optional[datetime]

Operations from this timestamp

None
till_time Optional[datetime]

Operations till this timestamp

None
start_record Optional[str]

Operations from this number

None
records Optional[int]

Number of history records

None
details Optional[bool]

Show operation details (True or False)

None

Returns:

Type Description
OperationHistory

OperationHistory entity

Source code in yoowallet/core/app.py
async def operation_history(
        self,
        type: Optional[List[str]] = None,
        label: Optional[str] = None,
        from_time: Optional[datetime] = None,
        till_time: Optional[datetime] = None,
        start_record: Optional[str] = None,
        records: Optional[int] = None,
        details: Optional[bool] = None
        ) -> OperationHistory:
    """Getting operation history. Needs at least this scope: ["operation-history", "operation-details"]

    Args:
        type (Optional[List[str]]): Operation types (deposition or payment)
        label (Optional[str]): Filtering value (custom operation id)
        from_time (Optional[datetime]): Operations from this timestamp
        till_time (Optional[datetime]): Operations till this timestamp
        start_record (Optional[str]): Operations from this number
        records (Optional[int]): Number of history records
        details (Optional[bool]): Show operation details (True or False)

    Returns:
        OperationHistory entity
    """
    # Generating request params
    params = {}
    if type is not None:
        params["type"] = type
    if label is not None:
        params["label"] = label
    # Defining default time format
    time_format = "%Y-%m-%dT%H:%M:%S"
    # Parsing datetimes
    if from_time is not None:
        try:
            params["from"] = datetime.strftime(from_time, time_format)
        except Exception:
            raise IllegalParamFrom("Failed to format input")
    if till_time is not None:
        try:
            params["till"] = datetime.strftime(till_time, time_format)
        except Exception:
            raise IllegalParamTill("Failed to format input")
    if start_record is not None:
        params["start_record"] = start_record
    if records is not None:
        params["records"] = str(records)
    if details is not None:
        params["details"] = details
    # Generating URL
    url = f"{self._base_url}/api/operation-history"
    async with aiohttp.ClientSession() as session:
        async with session.post(url=url, headers=self.headers, data=params) as response:
            # Errors processing
            if response.status in [401, 403]:
                raise InvalidToken
            response = await response.json()
            if "error" in response:
                if response["error"] == "illegal_param_type":
                    raise IllegalParamType("Try to redefine it in another way")
                elif response["error"] == "illegal_param_start_record":
                    raise IllegalParamStartRecord("Try to redefine it in another way'")
                elif response["error"] == "illegal_param_records":
                    raise IllegalParamRecords("Try to redefine it in another way'")
                elif response["error"] == "illegal_param_label":
                    raise IllegalParamLabel("Try to redefine it in another way'")
                elif response["error"] == "illegal_param_from":
                    raise IllegalParamFrom("Try to redefine it in another way'")
                elif response["error"] == "illegal_param_till":
                    raise IllegalParamTill("Try to redefine it in another way'")
                else:
                    raise HistoryTechicalError("Try again later'")
            return OperationHistory(response)

quickpay(sum, payment_type='AC', label=None, success_url=None) async

Creating fundraising link

Example:

import asyncio
from yoowallet import App

async def main():
    app: App = App("TOKEN")
    if not await app.connect():
        raise ValueError('Token is invalid!')
    # Generating fundraising for 5 RUB
    payment = await app.quickpay(5.0)
    print(f"QucikPay URL is {payment['url']}")

if __name__ == "__main__":
    asyncio.run(main())

Parameters:

Name Type Description Default
sum float

Transfer amount (the amount debited from the sender)

required
payment_type str

PC for a payment from a YooMoney wallet, AC for a payment from a bank card

'AC'
label str

The label that a site or app assigns to a certain transfer

None
success_url str

URL where the user is redirected after the transfer

None

Returns:

Type Description
Dict[str, Any]

Python dictionary with fields: url and amount_due (the amount, that will be received)

Source code in yoowallet/core/app.py
async def quickpay(
        self,
        sum: float,
        payment_type: str = "AC",
        label: Optional[str] = None,
        success_url: Optional[str] = None
        ) -> Dict[str, Any]: # type: ignore
    """Creating fundraising link

    Example:
    ```python
    import asyncio
    from yoowallet import App

    async def main():
        app: App = App("TOKEN")
        if not await app.connect():
            raise ValueError('Token is invalid!')
        # Generating fundraising for 5 RUB
        payment = await app.quickpay(5.0)
        print(f"QucikPay URL is {payment['url']}")

    if __name__ == "__main__":
        asyncio.run(main())
    ```

    Args:
        sum (float): Transfer amount (the amount debited from the sender)
        payment_type (str): PC for a payment from a YooMoney wallet, AC for a payment from a bank card
        label (str): The label that a site or app assigns to a certain transfer
        success_url (str): URL where the user is redirected after the transfer

    Returns:
        Python dictionary with fields: url and amount_due (the amount, that will be received)
    """
    # Getting the number of YooMoney wallet
    receiver: str = (await self.account_info()).account
    # Computing the amount to be received
    commissions = {"PC": 0.01, "AC": 0.03}
    amount_due: float = sum*(1-commissions[payment_type])
    # Generating params
    params = {}
    params["receiver"] = receiver
    params["sum"] = sum
    params["quickpay-form"] = "button"
    params["paymentType"] = payment_type
    if label:
        params["label"] = label
    if success_url:
        params["successURL"] = success_url
    async with aiohttp.ClientSession() as session:
        async with session.post(url="https://yoomoney.ru/quickpay/confirm", headers=self.headers, data=params) as response:
            if response.status == 200:
                return {"url": response.url, "amount_due": amount_due}
            else:
                # There must be an error handler, but YooMoney didn't provide
                # any error list for QuickPay :(
                raise FailedQuickPayGen(response.status)

App (sync version)

Class for interacting with Yoomoney APIs synchronously.

Parameters:

Name Type Description Default
token str

Yoomoney application token (can get via Authorizer)

required

Attributes:

Name Type Description
token str

Yoomoney application token (can get via Authorizer)

headers Dict[str, str]

Default headers for API requests

Example:

from yoowallet.sync import App
from yoowallet.types import AccountInfo

app: App = App("TOKEN")
if not app.connect():
    raise ValueError('Token is invalid!')
app_info = app.account_info()
app_info.debug()

Source code in yoowallet/sync/app.py
class App:
    """Class for interacting with Yoomoney APIs synchronously.

    Args:
        token (str): Yoomoney application token (can get via Authorizer)

    Attributes:
        token (str): Yoomoney application token (can get via Authorizer) 
        headers (Dict[str, str]): Default headers for API requests

    Example:
    ```python
    from yoowallet.sync import App
    from yoowallet.types import AccountInfo

    app: App = App("TOKEN")
    if not app.connect():
        raise ValueError('Token is invalid!')
    app_info = app.account_info()
    app_info.debug()
    ```
    """
    def __init__(self, token: str) -> None:
        self.token = token
        self._base_url = "https://yoomoney.ru"
        self.headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": f"Bearer {self.token}"
        }

    def account_info(self) -> AccountInfo:
        """Getting account information. Needs at least this scope: ["account-info"]

        Returns:
            AccountInfo entity
        """
        # Generating URL
        url = f"{self._base_url}/api/account-info"
        response = requests.post(url=url, headers=self.headers)
        if response.status_code == 200:
            response = response.json()
            return AccountInfo(response)
        elif response.status_code == 401:
            raise InvalidToken 
        else:
            raise AccountInfoError(f"Undefined error, answer: {response}")

    def connect(self) -> bool:
        """Verifying App's token via getting account information

        Returns:
            True if token is valid, False if invalid
        """
        try:
            self.account_info()
            return True
        except Exception:
            return False

    def operation_history(
            self,
            type: Optional[List[str]] = None,
            label: Optional[str] = None,
            from_time: Optional[datetime] = None,
            till_time: Optional[datetime] = None,
            start_record: Optional[str] = None,
            records: Optional[int] = None,
            details: Optional[bool] = None
            ) -> OperationHistory:
        """Getting operation history. Needs at least this scope: ["operation-history", "operation-details"]

        Example:
        ```python
        from yoowallet.sync import App
        from yoowallet.types import OperationHistory

        app: App = App("TOKEN")
        if not app.connect():
            raise ValueError('Token is invalid!')
        app_info = app.operation_history()
        app_info.debug()
        ```

        Args:
            type (Optional[List[str]]): Operation types (deposition or payment)
            label (Optional[str]): Filtering value (custom operation id)
            from_time (Optional[datetime]): Operations from this timestamp
            till_time (Optional[datetime]): Operations till this timestamp
            start_record (Optional[str]): Operations from this number
            records (Optional[int]): Number of history records
            details (Optional[bool]): Show operation details (True or False)

        Returns:
            OperationHistory entity
        """
        # Generating request params
        params = {}
        if type is not None:
            params["type"] = type
        if label is not None:
            params["label"] = label
        # Defining default time format
        time_format = "%Y-%m-%dT%H:%M:%S"
        # Parsing datetimes
        if from_time is not None:
            try:
                params["from"] = datetime.strftime(from_time, time_format)
            except Exception:
                raise IllegalParamFrom("Failed to format input")
        if till_time is not None:
            try:
                params["till"] = datetime.strftime(till_time, time_format)
            except Exception:
                raise IllegalParamTill("Failed to format input")
        if start_record is not None:
            params["start_record"] = start_record
        if records is not None:
            params["records"] = str(records)
        if details is not None:
            params["details"] = details
        # Generating URL
        url = f"{self._base_url}/api/operation-history"
        response = requests.post(url=url, headers=self.headers, data=params) 
        # Errors processing
        if response.status_code in [401, 403]:
            raise InvalidToken
        response = response.json()
        if "error" in response:
            if response["error"] == "illegal_param_type":
                raise IllegalParamType("Try to redefine it in another way")
            elif response["error"] == "illegal_param_start_record":
                raise IllegalParamStartRecord("Try to redefine it in another way'")
            elif response["error"] == "illegal_param_records":
                raise IllegalParamRecords("Try to redefine it in another way'")
            elif response["error"] == "illegal_param_label":
                raise IllegalParamLabel("Try to redefine it in another way'")
            elif response["error"] == "illegal_param_from":
                raise IllegalParamFrom("Try to redefine it in another way'")
            elif response["error"] == "illegal_param_till":
                raise IllegalParamTill("Try to redefine it in another way'")
            else:
                raise HistoryTechicalError("Try again later'")
        return OperationHistory(response)

    def quickpay(
            self,
            sum: float,
            payment_type: str = "AC",
            label: Optional[str] = None,
            success_url: Optional[str] = None
            ) -> Dict[str, Any]: # type: ignore
        """Creating fundraising link

        Example:
        ```python
        from yoowallet.sync import App

        app: App = App("TOKEN")
        if not app.connect():
            raise ValueError('Token is invalid!')
        # Generating fundraising for 5 RUB
        payment = app.quickpay(5.0)
        print(f"QucikPay URL is {payment['url']}")
        ```

        Args:
            sum (float): Transfer amount (the amount debited from the sender)
            payment_type (str): PC for a payment from a YooMoney wallet, AC for a payment from a bank card
            label (str): The label that a site or app assigns to a certain transfer
            success_url (str): URL where the user is redirected after the transfer

        Returns:
            Python dictionary with fields: url and amount_due (the amount, that will be received)
        """
        # Getting the number of YooMoney wallet
        receiver: str = (self.account_info()).account
        # Computing the amount to be received
        commissions = {"PC": 0.01, "AC": 0.03}
        amount_due: float = sum*(1-commissions[payment_type])
        # Generating params
        params = {}
        params["receiver"] = receiver
        params["sum"] = sum
        params["quickpay-form"] = "button"
        params["paymentType"] = payment_type
        if label:
            params["label"] = label
        if success_url:
            params["successURL"] = success_url
        response = requests.post(url="https://yoomoney.ru/quickpay/confirm", headers=self.headers, data=params)
        if response.status_code == 200:
            return {"url": response.url, "amount_due": amount_due}
        else:
            # There must be an error handler, but YooMoney didn't provide
            # any error list for QuickPay :(
            raise FailedQuickPayGen(response.status_code)

    def get_by_label(self, label: str) -> Optional[Dict[str, Any]]:
        """Checks whether payment with such label exists

        Args:
            label (str): Lable of needed operation

        Returns:
            Operation details 
        """
        operation = self.operation_history(label = label).operations
        if not operation or len(operation) > 1:
            return
        return operation[0]

account_info()

Getting account information. Needs at least this scope: ["account-info"]

Returns:

Type Description
AccountInfo

AccountInfo entity

Source code in yoowallet/sync/app.py
def account_info(self) -> AccountInfo:
    """Getting account information. Needs at least this scope: ["account-info"]

    Returns:
        AccountInfo entity
    """
    # Generating URL
    url = f"{self._base_url}/api/account-info"
    response = requests.post(url=url, headers=self.headers)
    if response.status_code == 200:
        response = response.json()
        return AccountInfo(response)
    elif response.status_code == 401:
        raise InvalidToken 
    else:
        raise AccountInfoError(f"Undefined error, answer: {response}")

connect()

Verifying App's token via getting account information

Returns:

Type Description
bool

True if token is valid, False if invalid

Source code in yoowallet/sync/app.py
def connect(self) -> bool:
    """Verifying App's token via getting account information

    Returns:
        True if token is valid, False if invalid
    """
    try:
        self.account_info()
        return True
    except Exception:
        return False

get_by_label(label)

Checks whether payment with such label exists

Parameters:

Name Type Description Default
label str

Lable of needed operation

required

Returns:

Type Description
Optional[Dict[str, Any]]

Operation details

Source code in yoowallet/sync/app.py
def get_by_label(self, label: str) -> Optional[Dict[str, Any]]:
    """Checks whether payment with such label exists

    Args:
        label (str): Lable of needed operation

    Returns:
        Operation details 
    """
    operation = self.operation_history(label = label).operations
    if not operation or len(operation) > 1:
        return
    return operation[0]

operation_history(type=None, label=None, from_time=None, till_time=None, start_record=None, records=None, details=None)

Getting operation history. Needs at least this scope: ["operation-history", "operation-details"]

Example:

from yoowallet.sync import App
from yoowallet.types import OperationHistory

app: App = App("TOKEN")
if not app.connect():
    raise ValueError('Token is invalid!')
app_info = app.operation_history()
app_info.debug()

Parameters:

Name Type Description Default
type Optional[List[str]]

Operation types (deposition or payment)

None
label Optional[str]

Filtering value (custom operation id)

None
from_time Optional[datetime]

Operations from this timestamp

None
till_time Optional[datetime]

Operations till this timestamp

None
start_record Optional[str]

Operations from this number

None
records Optional[int]

Number of history records

None
details Optional[bool]

Show operation details (True or False)

None

Returns:

Type Description
OperationHistory

OperationHistory entity

Source code in yoowallet/sync/app.py
def operation_history(
        self,
        type: Optional[List[str]] = None,
        label: Optional[str] = None,
        from_time: Optional[datetime] = None,
        till_time: Optional[datetime] = None,
        start_record: Optional[str] = None,
        records: Optional[int] = None,
        details: Optional[bool] = None
        ) -> OperationHistory:
    """Getting operation history. Needs at least this scope: ["operation-history", "operation-details"]

    Example:
    ```python
    from yoowallet.sync import App
    from yoowallet.types import OperationHistory

    app: App = App("TOKEN")
    if not app.connect():
        raise ValueError('Token is invalid!')
    app_info = app.operation_history()
    app_info.debug()
    ```

    Args:
        type (Optional[List[str]]): Operation types (deposition or payment)
        label (Optional[str]): Filtering value (custom operation id)
        from_time (Optional[datetime]): Operations from this timestamp
        till_time (Optional[datetime]): Operations till this timestamp
        start_record (Optional[str]): Operations from this number
        records (Optional[int]): Number of history records
        details (Optional[bool]): Show operation details (True or False)

    Returns:
        OperationHistory entity
    """
    # Generating request params
    params = {}
    if type is not None:
        params["type"] = type
    if label is not None:
        params["label"] = label
    # Defining default time format
    time_format = "%Y-%m-%dT%H:%M:%S"
    # Parsing datetimes
    if from_time is not None:
        try:
            params["from"] = datetime.strftime(from_time, time_format)
        except Exception:
            raise IllegalParamFrom("Failed to format input")
    if till_time is not None:
        try:
            params["till"] = datetime.strftime(till_time, time_format)
        except Exception:
            raise IllegalParamTill("Failed to format input")
    if start_record is not None:
        params["start_record"] = start_record
    if records is not None:
        params["records"] = str(records)
    if details is not None:
        params["details"] = details
    # Generating URL
    url = f"{self._base_url}/api/operation-history"
    response = requests.post(url=url, headers=self.headers, data=params) 
    # Errors processing
    if response.status_code in [401, 403]:
        raise InvalidToken
    response = response.json()
    if "error" in response:
        if response["error"] == "illegal_param_type":
            raise IllegalParamType("Try to redefine it in another way")
        elif response["error"] == "illegal_param_start_record":
            raise IllegalParamStartRecord("Try to redefine it in another way'")
        elif response["error"] == "illegal_param_records":
            raise IllegalParamRecords("Try to redefine it in another way'")
        elif response["error"] == "illegal_param_label":
            raise IllegalParamLabel("Try to redefine it in another way'")
        elif response["error"] == "illegal_param_from":
            raise IllegalParamFrom("Try to redefine it in another way'")
        elif response["error"] == "illegal_param_till":
            raise IllegalParamTill("Try to redefine it in another way'")
        else:
            raise HistoryTechicalError("Try again later'")
    return OperationHistory(response)

quickpay(sum, payment_type='AC', label=None, success_url=None)

Creating fundraising link

Example:

from yoowallet.sync import App

app: App = App("TOKEN")
if not app.connect():
    raise ValueError('Token is invalid!')
# Generating fundraising for 5 RUB
payment = app.quickpay(5.0)
print(f"QucikPay URL is {payment['url']}")

Parameters:

Name Type Description Default
sum float

Transfer amount (the amount debited from the sender)

required
payment_type str

PC for a payment from a YooMoney wallet, AC for a payment from a bank card

'AC'
label str

The label that a site or app assigns to a certain transfer

None
success_url str

URL where the user is redirected after the transfer

None

Returns:

Type Description
Dict[str, Any]

Python dictionary with fields: url and amount_due (the amount, that will be received)

Source code in yoowallet/sync/app.py
def quickpay(
        self,
        sum: float,
        payment_type: str = "AC",
        label: Optional[str] = None,
        success_url: Optional[str] = None
        ) -> Dict[str, Any]: # type: ignore
    """Creating fundraising link

    Example:
    ```python
    from yoowallet.sync import App

    app: App = App("TOKEN")
    if not app.connect():
        raise ValueError('Token is invalid!')
    # Generating fundraising for 5 RUB
    payment = app.quickpay(5.0)
    print(f"QucikPay URL is {payment['url']}")
    ```

    Args:
        sum (float): Transfer amount (the amount debited from the sender)
        payment_type (str): PC for a payment from a YooMoney wallet, AC for a payment from a bank card
        label (str): The label that a site or app assigns to a certain transfer
        success_url (str): URL where the user is redirected after the transfer

    Returns:
        Python dictionary with fields: url and amount_due (the amount, that will be received)
    """
    # Getting the number of YooMoney wallet
    receiver: str = (self.account_info()).account
    # Computing the amount to be received
    commissions = {"PC": 0.01, "AC": 0.03}
    amount_due: float = sum*(1-commissions[payment_type])
    # Generating params
    params = {}
    params["receiver"] = receiver
    params["sum"] = sum
    params["quickpay-form"] = "button"
    params["paymentType"] = payment_type
    if label:
        params["label"] = label
    if success_url:
        params["successURL"] = success_url
    response = requests.post(url="https://yoomoney.ru/quickpay/confirm", headers=self.headers, data=params)
    if response.status_code == 200:
        return {"url": response.url, "amount_due": amount_due}
    else:
        # There must be an error handler, but YooMoney didn't provide
        # any error list for QuickPay :(
        raise FailedQuickPayGen(response.status_code)

Types

Entity

Bases: ABC

Abstract class, which represents the skelet of API response entities (like account info)

Parameters:

Name Type Description Default
ctx Dict[Any, Any]

Dictionary, got from raw response

required

Attributes:

Name Type Description
ctx Dict[Any, Any]

Dictionary, got from raw response

required_scope List[str]

Required permission for dealing with this entity

Source code in yoowallet/types.py
class Entity(ABC):
    """Abstract class, which represents the skelet of API response entities (like account info)

    Args:
        ctx (Dict[Any, Any]): Dictionary, got from raw response 

    Attributes:
        ctx (Dict[Any, Any]): Dictionary, got from raw response
        required_scope (List[str]): Required permission for dealing with this entity
    """
    def __init__(self, ctx: Dict[Any, Any], required_scope: List[str]) -> None:
        self._ctx = ctx
        self._required_scope = required_scope

    @property
    def ctx(self) -> Dict[Any, Any]:
        """Dictionary from raw request"""
        return self._ctx

    @property
    def required_scope(self) -> List[str]:
        """Required permissions for dealing with this entity"""
        return self._required_scope

    @property
    def keys(self) -> List[str]:
        """Available entity fields. Defining in 'parse' method"""
        return self._keys

    def parse(self) -> None:
        """Parsing provided context"""
        # List of available keys
        self._keys = list(self.ctx.keys())
        for attr in self.ctx.keys():
            setattr(self, "_"+attr, self.ctx[attr])

    def debug(self) -> None:
        """Prints debug information"""
        print(f"[?] Debug for {self.__class__.__name__}:")
        for attr in self.keys:
            print(f"- {attr} ({type(getattr(self, attr))}): {getattr(self, attr)}")

ctx: Dict[Any, Any] property

Dictionary from raw request

keys: List[str] property

Available entity fields. Defining in 'parse' method

required_scope: List[str] property

Required permissions for dealing with this entity

debug()

Prints debug information

Source code in yoowallet/types.py
def debug(self) -> None:
    """Prints debug information"""
    print(f"[?] Debug for {self.__class__.__name__}:")
    for attr in self.keys:
        print(f"- {attr} ({type(getattr(self, attr))}): {getattr(self, attr)}")

parse()

Parsing provided context

Source code in yoowallet/types.py
def parse(self) -> None:
    """Parsing provided context"""
    # List of available keys
    self._keys = list(self.ctx.keys())
    for attr in self.ctx.keys():
        setattr(self, "_"+attr, self.ctx[attr])

AccountInfo

Bases: Entity

Provides interface for account information Args: ctx (Dict[Any, Any]): Dictionary, got using '/api/account-info' request

Attributes:

Name Type Description
ctx Dict[Any, Any]

Dictionary, got using '/api/account-info' request

Source code in yoowallet/types.py
class AccountInfo(Entity):
    """Provides interface for account information
    Args:
        ctx (Dict[Any, Any]): Dictionary, got using '/api/account-info' request

    Attributes:
        ctx (Dict[Any, Any]): Dictionary, got using '/api/account-info' request 
    """
    def __init__(self, ctx: Dict[Any, Any]) -> None:
        super().__init__(ctx, ["account-info"])
        try:
            self.parse()
        except Exception as e:
            raise AccountInfoError(f"Failed to parse account info: {e}")

    # Defining fields
    @property
    def account(self) -> str:
        """User’s account number"""
        try:
            return self._account # type: ignore
        except Exception:
            raise NoSuchAttribute("account")

    @property
    def balance(self) -> str:
        """User’s account balance"""
        try:
            return self._balance # type: ignore
        except Exception:
            raise NoSuchAttribute("balance")

    @property
    def currency(self) -> str:
        """User’s account currency code (always 643)"""
        try:
            return self._currency # type: ignore
        except Exception:
            raise NoSuchAttribute("currency")

    @property
    def account_status(self) -> str:
        """The user’s status"""
        try:
            return self._account_status # type: ignore
        except Exception:
            raise NoSuchAttribute("account_status")

    @property
    def account_type(self) -> str:
        """User’s account type"""
        try:
            return self._account_type # type: ignore
        except Exception:
            raise NoSuchAttribute("account_type")

    @property
    def identified(self) -> str:
        """User’s account identification"""
        try:
            return self._identified # type: ignore
        except Exception:
            raise NoSuchAttribute("identified")

    @property
    def balance_details(self) -> Optional[Dict[str, Any]]:
        """Detailed information about the balance (by default, this section is omitted)"""
        try:
            return self._balance_details # type: ignore
        except Exception:
            raise NoSuchAttribute("balance_details")

    @property
    def cards_linked(self) -> Optional[List[Dict[str, Any]]]:
        """Information about bank cards linked to the account"""
        try:
            return self._cards_linked # type: ignore
        except Exception:
            raise NoSuchAttribute("cards_linked")

account: str property

User’s account number

account_status: str property

The user’s status

account_type: str property

User’s account type

balance: str property

User’s account balance

balance_details: Optional[Dict[str, Any]] property

Detailed information about the balance (by default, this section is omitted)

cards_linked: Optional[List[Dict[str, Any]]] property

Information about bank cards linked to the account

currency: str property

User’s account currency code (always 643)

identified: str property

User’s account identification

OperationHistory

Bases: Entity

Provides interface for operation history Args: ctx (Dict[Any, Any]): Dictionary, got using '/api/operation-history' request

Attributes:

Name Type Description
ctx Dict[Any, Any]

Dictionary, got using '/api/operation-history' request

Source code in yoowallet/types.py
class OperationHistory(Entity):
    """Provides interface for operation history 
    Args:
        ctx (Dict[Any, Any]): Dictionary, got using '/api/operation-history' request

    Attributes:
        ctx (Dict[Any, Any]): Dictionary, got using '/api/operation-history' request
    """
    def __init__(self, ctx: Dict[Any, Any]) -> None:
        super().__init__(ctx, ["operation-history", "operation-details"])
        try:
            self.parse()
        except Exception as e:
            raise OperationHistoryError(f"Failed to parse operation history: {e}")

    @property
    def next_record(self) -> str:
        """The number of the first history record on the next page"""
        try:
            return self._next_record # type: ignore
        except Exception:
            raise NoSuchAttribute("next_record")

    @property
    def operations(self) -> Optional[List[Dict[str, Any]]]:
        """List of operations"""
        try:
            return self._operations # type: ignore
        except Exception:
            raise NoSuchAttribute("operations")

next_record: str property

The number of the first history record on the next page

operations: Optional[List[Dict[str, Any]]] property

List of operations