Welcome to the glQiwiApi documentation!

Latest version released on PyPi python version downloads per month number of downloads for all time code grade code coverage CI
  • Why should you choose exactly glQiwiApi and not other libraries?

    1. It’s working faster than other async wrappers for qiwi and yoomoney 💥

    2. Evidently, It’s asynchronous

    3. Supports most of qiwi apis: qiwi-maps, bills, wallet and, also, yoomoney

    4. Provides support of polling and webhooks for QIWI as well as possible

    5. Furnish many utils and extensions such a currency parser, pydantic support and code coverage not less than 80% “out of the box”

    6. Full compatibility with mypy

Quick start

import asyncio

from glQiwiApi import QiwiWrapper, APIError


async def print_balance(qiwi_token: str, phone_number: str) -> None:
    """
    This function allows you to get balance of your wallet using glQiwiApi library
    """
    async with QiwiWrapper(api_access_token=qiwi_token, phone_number=phone_number) as w:
        try:
            balance = await w.get_balance()
        # handle exception if wrong credentials or really API return error
        except APIError as err:
            print(err.json())
            raise
    print(f"Your current balance is {balance.amount} {balance.currency.name}")


asyncio.run(print_balance(qiwi_token="qiwi api token", phone_number="+phone_number"))

Content

Installation

Supported Python versions: 3.7 and higher

Stable release

To install glQiwiApi, run this command in your terminal:

$ pip install glQiwiApi

This is the preferred installation method as it will always install the most recent stable release. If you do not have installed pip, this Python Installation Reference can help you in the process.

From source files

You can either clone the public repository:

$ git clone git://github.com/GLEF1X/glQiwiApi

Once you get a copy of the source files, you can install them with:

$ python setup.py install

Recommendations

You can speedup api by following next instructions:

  • Use uvloop instead of default asyncio loop.

    uvloop is a fast, drop-in replacement of the built-in asyncio event loop. uvloop is implemented in Cython and uses libuv under the hood.

    Installation:

    $ pip install uvloop
    
  • Use orjson instead of the default json module.

    orjson is a fast, correct JSON library for Python. It benchmarks as the fastest Python library for JSON and is more correct than the standard json library or other third-party libraries

    Installation:

    $ pip install orjson
    

Available API wrappers

The glQiwiApi provides capability to use two different API wrappers independently(and QIWI Maps as a branch of QIWI API)

QIWI API

class glQiwiApi.qiwi.client.QiwiWrapper(api_access_token: Optional[str] = None, phone_number: Optional[str] = None, secret_p2p: Optional[str] = None, without_context: bool = False, cache_time: Union[float, int] = 0, *args: Any, **kwargs: Any)[source]

Bases: glQiwiApi.core.abc.wrapper.Wrapper, glQiwiApi.core.mixins.HandlerCollectionMixin, glQiwiApi.core.mixins.DataMixin, glQiwiApi.core.mixins.ContextInstanceMixin[QiwiWrapper]

Delegates the work of QIWI API, webhooks, polling. Fast and versatile wrapper.

__init__(api_access_token: Optional[str] = None, phone_number: Optional[str] = None, secret_p2p: Optional[str] = None, cache_time_in_seconds: Union[float, int] = 0, session_holder: Optional[glQiwiApi.core.session.holder.AbstractSessionHolder[Any]] = None) None[source]
Parameters
  • api_access_token – QIWI API token received from https://qiwi.com/api

  • phone_number – your phone number starting with +

  • secret_p2p – QIWI P2P secret key received from https://p2p.qiwi.com/

  • cache_time_in_seconds – Time to cache requests in seconds, default 0, respectively the request will not use the cache by default

  • session_holder – obtains session and helps to manage session lifecycle. You can pass your own session holder, for example using httpx lib and use it

phone_number
api_access_token
secret_p2p
get_request_service() glQiwiApi.core.request_service.RequestService[source]
async get_current_webhook() glQiwiApi.types.qiwi.webhooks.WebHookConfig[source]

List of active (active) notification handlers, associated with your wallet can be obtained with this request. Since now only one type of hook is used - webhook, then the response contains only one data object

async get_webhook_secret_key(hook_id: str) str[source]

Each notification contains a digital signature of the message, encrypted with a key. To obtain a signature verification key, use this request.

Parameters

hook_id – UUID of webhook

Returns

Base64 encoded key

async delete_current_webhook() Optional[Dict[str, str]][source]

Method to delete webhook

async change_webhook_secret(hook_id: str) str[source]

Use this request to change the encryption key for notifications.

Parameters

hook_id – UUID of webhook

Returns

Base64 encoded key

async bind_webhook(url: Optional[Union[str, glQiwiApi.ext.webhook_url.WebhookURL]] = None, transactions_type: int = 2, *, send_test_notification: bool = False, delete_old: bool = False) Tuple[Optional[glQiwiApi.types.qiwi.webhooks.WebHookConfig], str][source]

[NON-API] EXCLUSIVE method to register new webhook or get old

Parameters
  • url – service url

  • transactions_type – 0 => incoming, 1 => outgoing, 2 => all

  • send_test_notification – test_qiwi will send you test webhook update

  • delete_old – boolean, if True - delete old webhook

Returns

Tuple of Hook and Base64-encoded key

async get_balance(*, account_number: int = 1) glQiwiApi.types.amount.CurrencyAmount[source]
async transactions(rows: int = 50, operation: glQiwiApi.types.qiwi.transaction.TransactionType = TransactionType.ALL, sources: Optional[List[glQiwiApi.types.qiwi.transaction.Source]] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None) List[glQiwiApi.types.qiwi.transaction.Transaction][source]

Method for receiving transactions on the account More detailed documentation: https://developer.qiwi.com/ru/qiwi-wallet-personal/?http#payments_list

Parameters
  • rows – number of transactions you want to receive

  • operation – The type of operations in the report for selection.

  • sources – List of payment sources, for filter

  • start_date – The starting date for searching for payments. Used only in conjunction with end_date.

  • end_date – the end date of the search for payments. Used only in conjunction with start_date.

async transaction_info(transaction_id: Union[str, int], transaction_type: glQiwiApi.types.qiwi.transaction.TransactionType) glQiwiApi.types.qiwi.transaction.Transaction[source]

Method for obtaining complete information about a transaction

Detailed documentation: https://developer.qiwi.com/ru/qiwi-wallet-personal/?python#txn_info

Parameters
  • transaction_id

  • transaction_type – only IN or OUT

Returns

Transaction object

async get_restriction() List[glQiwiApi.types.qiwi.restriction.Restriction][source]

Method to check limits on your qiwi wallet Detailed documentation: https://developer.qiwi.com/ru/qiwi-wallet-personal/?python#restrictions

Returns

List where the dictionary is located with restrictions, if there are no restrictions, it returns an empty list

async get_identification() glQiwiApi.types.qiwi.identification.Identification[source]

This method allows get your wallet identification data More detailed documentation: https://developer.qiwi.com/ru/qiwi-wallet-personal/?http#ident

async check_transaction(amount: Union[int, float], transaction_type: glQiwiApi.types.qiwi.transaction.TransactionType = TransactionType.IN, sender: Optional[str] = None, rows_num: int = 50, comment: Optional[str] = None) bool[source]

[ NON API METHOD ]

Method for verifying a transaction. This method uses self.transactions (rows = rows) “under the hood” to check payment.

For a little optimization, you can decrease rows by setting it, however, this does not guarantee the correct result

Possible values for the transaction_type parameter:
  • ‘IN’

  • ‘OUT’

  • ‘QIWI_CARD’

Parameters
  • amount – amount of payment

  • transaction_type – type of payment

  • sender – number of receiver

  • rows_num – number of payments to be checked

  • comment – comment by which the transaction will be verified

async get_limits(limit_types: Optional[List[str]] = None) Dict[str, glQiwiApi.types.qiwi.limit.Limit][source]

Function for getting limits on the qiwi wallet account Returns wallet limits as a list, if there is no limit for a certain country, then it does not include it in the list Detailed documentation:

https://developer.qiwi.com/ru/qiwi-wallet-personal/?http#limits

async get_list_of_cards() List[glQiwiApi.types.qiwi.qiwi_master.Card][source]
async authenticate(birth_date: str, first_name: str, last_name: str, patronymic: str, passport: str, oms: Optional[str] = None, inn: Optional[str] = None, snils: Optional[str] = None) Dict[Any, Any][source]

This request allows you to send data to identify your QIWI wallet. It is allowed to identify no more than 5 wallets per owner

To identify the wallet, you must send your full name, passport series number and date of birth. If the data has been verified, then the response will display your TIN and simplified wallet identification will be installed. If the data has not been verified, the wallet remains in the “Minimum” status.

Parameters
  • birth_date – Date of birth as a format string 1998-02-11

  • first_name – First name

  • last_name – Last name

  • patronymic – Middle name

  • passport – Series / Number of the passport. Ex: 4400111222

  • oms

  • snils

  • inn

async get_receipt(transaction_id: Union[str, int], transaction_type: glQiwiApi.types.qiwi.transaction.TransactionType, file_format: str = 'PDF') glQiwiApi.types.arbitrary.file.File[source]

Method for receiving a receipt in byte format or file.

Possible transaction_type values:
  • ‘IN’

  • ‘OUT’

  • ‘QIWI_CARD’

Parameters
  • transaction_id – transaction id, can be obtained by calling the to_wallet method, to_card

  • transaction_type – type of transaction: ‘IN’, ‘OUT’, ‘QIWI_CARD’

  • file_format – format of file

async get_account_info() glQiwiApi.types.qiwi.account_info.QiwiAccountInfo[source]

Метод для получения информации об аккаунте

async fetch_statistics(start_date: datetime.datetime, end_date: datetime.datetime, operation: glQiwiApi.types.qiwi.transaction.TransactionType = TransactionType.ALL, sources: Optional[List[str]] = None) glQiwiApi.types.qiwi.stats.Statistic[source]

This query is used to get summary statistics by the amount of payments for a given period. More detailed documentation: https://developer.qiwi.com/ru/qiwi-wallet-personal/?http#payments_list

:param start_date:The start date of the statistics period. :param end_date: End date of the statistics period. :param operation: The type of operations taken into account when calculating statistics.

Allowed values:

ALL - все операции, IN - только пополнения, OUT - только платежи, QIWI_CARD - только платежи по картам QIWI (QVC, QVP). По умолчанию ALL.

Parameters

sources – The sources of payments QW_RUB - рублевый счет кошелька, QW_USD - счет кошелька в долларах, QW_EUR - счет кошелька в евро, CARD - привязанные и непривязанные к кошельку банковские карты, MK - счет мобильного оператора. Если не указан, учитываются все источники платежа.

async list_of_balances() List[glQiwiApi.types.qiwi.account.Account][source]

The request gets the current account balances of your QIWI Wallet. More detailed documentation: https://developer.qiwi.com/ru/qiwi-wallet-personal/?http#balances_list

async create_new_balance(currency_alias: str) Optional[Dict[str, bool]][source]

The request creates a new account and balance in your QIWI Wallet

Parameters

currency_alias – New account alias

async available_balances() List[glQiwiApi.types.qiwi.balance.Balance][source]

The request displays account aliases, available for creation in your QIWI Wallet

async set_default_balance(currency_alias: str) Dict[Any, Any][source]

The request sets up an account for your QIWI Wallet, whose balance will be used for funding all payments by default. The account must be contained in the list of accounts, you can get the list by calling list_of_balances method

Parameters

currency_alias

async to_wallet(to_number: str, amount: Union[int, float, str], currency: str = '643', comment: Optional[str] = None) glQiwiApi.types.qiwi.payment_info.PaymentInfo[source]

Method for transferring money to another wallet

Detailed documentation: https://developer.qiwi.com/ru/qiwi-wallet-personal/?python#p2p

Parameters
  • to_number – recipient number

  • amount – the amount of money you want to transfer

  • currency – special currency code

  • comment – payment comment

async to_card(trans_sum: Union[float, int], to_card: str) glQiwiApi.types.qiwi.payment_info.PaymentInfo[source]

Method for sending funds to the card. More detailed documentation: https://developer.qiwi.com/ru/qiwi-wallet-personal/#cards

async predict_commission(to_account: str, pay_sum: Union[int, float]) glQiwiApi.types.qiwi.commission.Commission[source]

Full calc_commission of QIWI Wallet is refunded for payment in favor of the specified provider taking into account all tariffs for a given set of payment details.

Parameters
  • to_account

  • pay_sum

Returns

Commission object

async get_cross_rates() List[glQiwiApi.types.qiwi.other.CrossRate][source]

The method returns the current exchange rates and cross-rates of the QIWI Bank’s currencies.

async payment_by_payment_details(payment_sum: glQiwiApi.types.amount.CurrencyAmount, payment_method: glQiwiApi.types.qiwi.other.PaymentMethod, fields: glQiwiApi.types.qiwi.other.FreePaymentDetailsFields, payment_id: Optional[str] = None) glQiwiApi.types.qiwi.payment_info.PaymentInfo[source]

Payment for services of commercial organizations according to their bank details.

Parameters
  • payment_id – payment id, if not transmitted, is used uuid4 by default

  • payment_sum – a Sum object, which indicates the amount of the payment

  • payment_method – payment method

  • fields – payment details

async buy_qiwi_master() glQiwiApi.types.qiwi.payment_info.PaymentInfo[source]

Method for buying QIWI Master package To call API methods, you need the QIWI Wallet API token with permissions to do the following: 1. Management of virtual cards, 2. Request information about the wallet profile, 3. View payment history, 4. Making payments without SMS. You can choose these rights when creating a new api token, to use api QIWI Master

async issue_qiwi_master_card(card_alias: str = 'qvc-cpa') Optional[glQiwiApi.types.qiwi.qiwi_master.OrderDetails][source]

Issuing a new card using the Qiwi Master API

When issuing a card, 3, and possibly 3 requests are made, namely, according to the following scheme:

  • _pre_qiwi_master_request - this method creates a request

  • _confirm_qiwi_master_request - confirms the issue of the card

  • _buy_new_qiwi_card - buys a new card, if such a card is not free

Detailed documentation: https://developer.qiwi.com/ru/qiwi-wallet-personal/#qiwi-master-issue-card

async reject_p2p_bill(bill_id: str) glQiwiApi.types.qiwi.bill.Bill[source]

Use this method to cancel unpaid invoice.

async check_p2p_bill_status(bill_id: str) str[source]

Method for checking the status of a p2p transaction.

Possible transaction types:

WAITING Bill is waiting for pay

PAID Bill was paid

REJECTED Bill was rejected

EXPIRED The bill has expired. Invoice not paid

Docs: https://developer.qiwi.com/ru/p2p-payments/?shell#invoice-status

Parameters

bill_id

Returns

status of bill

async create_p2p_bill(amount: Union[int, float], bill_id: Optional[str] = None, comment: Optional[str] = None, life_time: Optional[datetime.datetime] = None, theme_code: Optional[str] = None, pay_source_filter: Optional[List[str]] = None) glQiwiApi.types.qiwi.bill.Bill[source]

It is the reliable method for integration. Parameters are sent by means of server2server requests with authorization. Method allows you to issue an invoice, successful

response contains payUrl link to redirect client on Payment Form.

Possible values of pay_source_filter:
  • ‘qw’

  • ‘card’

  • ‘mobile’

Parameters
  • amount – amount of payment

  • bill_id – unique transaction number, if not transmitted, generated automatically,

  • life_time – the date until which the invoice will be available for payment.

  • comment

  • theme_code

  • pay_source_filter – When you open the form, the following will be displayed only the translation methods specified in this parameter

async retrieve_bills(rows: int, statuses: str = 'READY_FOR_PAY') List[glQiwiApi.types.qiwi.bill.Bill][source]

A method for getting a list of your wallet’s outstanding bills.

The list is built in reverse chronological order.

By default, the list is paginated with 50 items each, but you can specify a different number of elements (no more than 50).

Filters by billing time can be used in the request, the initial account identifier.

async pay_the_invoice(invoice_uid: str, currency: str) glQiwiApi.types.qiwi.bill.InvoiceStatus[source]

Execution of unconditional payment of the invoice without SMS-confirmation.

! Warning ! To use this method correctly you need to tick “Проведение платежей без SMS” when registering QIWI API and retrieve token

Parameters
  • invoice_uid – Bill ID in QIWI system

  • currency

async refund_bill(bill_id: Union[str, int], refund_id: Union[str, int], json_bill_data: Union[glQiwiApi.types.amount.PlainAmount, Dict[str, Union[str, int]]]) glQiwiApi.types.qiwi.bill.RefundBill[source]
The method allows you to make a refund on a paid invoice.

in the JSON body of the request for the json_bill_data parameter: amount.value - refund amount. amount.currency - return currency.

Can be a dictionary or an OptionalSum object

Dictionary example: {

“amount”: {

“currency”: “RUB”, “value”: 1 }

}

Parameters
  • bill_id – unique account identifier in the merchant’s system

  • refund_id – unique identifier of the refund in the merchant’s system.

  • json_bill_data

Returns

RefundBill object

async create_p2p_keys(key_pair_name: str, server_notification_url: Optional[str] = None) glQiwiApi.types.qiwi.bill.P2PKeys[source]

Creates new pair of P2P keys to interact with P2P QIWI API

Parameters
  • key_pair_name – P2P token pair name

  • server_notification_url – url for webhooks

YooMoney API

class glQiwiApi.yoo_money.client.YooMoneyAPI(api_access_token: str, cache_time: Union[float, int] = 0, session_holder: Optional[glQiwiApi.core.session.holder.AbstractSessionHolder[Any]] = None)[source]

Bases: glQiwiApi.core.abc.wrapper.Wrapper, glQiwiApi.core.mixins.DataMixin, glQiwiApi.core.mixins.ContextInstanceMixin[YooMoneyAPI]

That class implements processing requests to YooMoney It is convenient in that it does not just give json such objects, and all this converts into pydantic models. To work with this class, you need to register a token, using the guide on the official github of the project

__init__(api_access_token: str, cache_time: Union[float, int] = 0, session_holder: Optional[glQiwiApi.core.session.holder.AbstractSessionHolder[Any]] = None) None[source]
The constructor accepts a token obtained from the method class get_access_token

and the special attribute without_context

Parameters
  • api_access_token – api token for requests

  • cache_time – Time to cache requests in seconds, default 0, respectively the request will not use the cache by default

  • session_holder – obtains session and helps to manage session lifecycle. You can pass your own session holder, for example using httpx lib and use it

api_access_token
get_request_service() glQiwiApi.core.request_service.RequestService[source]
async classmethod build_url_for_auth(scope: List[str], client_id: str, redirect_uri: str = 'https://example.com') Optional[str][source]

Method to get the link for further authorization and obtaining a token

Parameters
  • scope – OAuth2 authorization of the application by the user, the rights are transferred by the list.

  • client_id – application id, type string

  • redirect_uri – a funnel where the temporary code that you need will go to to get the main token

Returns

the link to follow and make authorization via login / password

async classmethod get_access_token(code: str, client_id: str, redirect_uri: str = 'https://example.com', client_secret: Optional[str] = None) str[source]

Method for obtaining a token for requests to the YooMoney API

Parameters
  • code – the temporary code that was obtained in the base_authorize method

  • client_id – application id, type string

  • redirect_uri – the funnel where the temporary code will go, which is needed to get the main token

  • client_secret – The secret word for authenticating the application. Specified if the service is registered with authentication.

Returns

YooMoney API TOKEN

async revoke_api_token() Optional[Dict[str, bool]][source]

Method for revoking the rights of a token, while all its rights also disappear Documentation: https://yoomoney.ru/docs/wallet/using-api/authorization/revoke-access-token

property account_info: glQiwiApi.types.yoomoney.types.AccountInfo
classmethod create_pay_form(receiver: str, quick_pay_form: str, targets: str, payment_type: str, amount: Union[int, float], form_comment: Optional[str] = None, short_dest: Optional[str] = None, label: Optional[str] = None, comment: Optional[str] = None, success_url: Optional[str] = None, need_fio: Optional[bool] = None, need_email: Optional[bool] = None, need_phone: Optional[bool] = None, need_address: Optional[bool] = None) str[source]

The YooMoney form is a set of fields with information about a transfer. You can embed payment form into your interface (for instance, a website or blog). When the sender pushes the button, the details from the form are sent to YooMoney and an order for a transfer to your wallet is initiated.

Detail docs: https://yoomoney.ru/docs/payment-buttons/using-api/forms?lang=en

Possible values for quick_pay_form:
  • shop - for a multi purpose form;

  • small - for a button;

  • donate - for a charity form.

@param receiver: Number of the YooMoney wallet which money from senders is credited to. @param quick_pay_form: @param targets: Payment purpose. @param payment_type: Payment method. Possible values: PC, AC, MC @param amount: Transfer amount (the amount debited from the sender). @param form_comment: Name of the transfer in sender’s history

(for transfers from a wallet or linked bank card). Displayed in sender’s wallet. The simplest way to create it is to combine the names of the store and product. For instance: My Store: white valenki boots

@param short_dest: Name of the transfer on the confirmation page.

We recommend using the same name as formcomment

@param label: The label that a site or app assigns to a certain transfer.

For instance, a code or order identifier may be used for this label.

@param comment: The field in which you can send sender’s comments. @param success_url: URL where the user is redirected after the transfer. @param need_fio: Sender’s full name required. @param need_email: Sender’s email address required. @param need_phone: Sender’s phone number required. @param need_address: Sender’s address required. @return: link to payment form

async retrieve_account_info() glQiwiApi.types.yoomoney.types.AccountInfo[source]

Method for getting information about user account Detailed documentation: https://yoomoney.ru/docs/wallet/user-account/account-info

Returns

объект AccountInfo

async transactions(operation_types: Optional[Union[List[glQiwiApi.types.yoomoney.types.OperationType], Tuple[glQiwiApi.types.yoomoney.types.OperationType, ...]]] = None, start_date: Optional[datetime.datetime] = None, end_date: Optional[datetime.datetime] = None, start_record: Optional[int] = None, records: int = 30, label: Optional[Union[str, int]] = None) List[glQiwiApi.types.yoomoney.types.Operation][source]

More details: https://yoomoney.ru/docs/wallet/user-account/operation-history

The method allows you to view the history of transactions (in whole or in part) in page mode. History records are displayed in reverse chronological order from most recent to earlier.

Possible values:

DEPOSITION — refill ;

PAYMENT — consumption;

INCOMING(incoming-transfers-unaccepted) — unaccepted incoming P2P transfers of any type.

Parameters
  • operation_types – Operation type

  • label – string. Selection of payments by tag value. Selects payments that have a specified parameter value label of the request-payment call.

  • start_date – Show operations from the moment in time (operations equal to start_date or later) If the parameter is absent, all operations are displayed.

  • end_date – Output operations up to the point in time (operations older than end_date). If the parameter is absent, all operations are displayed.

  • start_record

    If the parameter is present, then operations will be displayed starting

    from start_record number.

    Operations are numbered from 0. More about paginated list output

  • records – The number of transaction history records requested. Valid values are from 1 to 100, the default is 30.

async transaction_info(operation_id: str) glQiwiApi.types.yoomoney.types.OperationDetails[source]

Allows you to get detailed information about the operation from the history. Required token rights: operation-details. More detailed documentation: https://yoomoney.ru/docs/wallet/user-account/operation-details

Parameters

operation_id – Operation ID

async send(to_account: str, amount: Union[int, float], money_source: str = 'wallet', pattern_id: str = 'p2p', cvv2_code: str = '', card_type: Optional[str] = None, protect: bool = False, comment_for_history: Optional[str] = None, comment: Optional[str] = None, expire_period: int = 1) glQiwiApi.types.yoomoney.types.Payment[source]

A method for sending money to another person’s account or card. This function makes 2 requests at once, because of this you may feel a slight loss in performance,

you can use the method

_pre_process_payment and get the PreProcessPaymentResponse object, which contains information about a still unconfirmed payment

More detailed documentation: https://yoomoney.ru/docs/wallet/process-payments/process-payment

Parameters
  • pattern_id – Payment pattern ID

  • to_account – string ID of the transfer recipient (account number, phone number or email).

  • amount – Amount to be received (the invoice will be sent to the recipient’s account after payment). MINIMUM AMOUNT 2.

  • money_source – The requested payment method. wallet - from the user’s account, if you want to use a card, then you will need to pass card_type to search for a card in the list of your bank cards, and also optionally cvv2 code for making a payment

  • comment_for_history – Comment to the translation, displayed in the sender’s history.

  • card_type – Bank card type, you need to fill in, only if you want to debit funds from your card

  • cvv2_code – optional, may not be passed, however if payment by card is required, the parameter should be passed

  • comment – Comment on the transfer, displayed to the recipient.

  • protect – The value of the parameter is true - a sign that that the transfer is protected by a protection code. By default, there is no parameter (normal translation).

  • expire_period – Number of days during which: the recipient of the transfer can enter the protection code and receive a transfer to your account, the recipient of the transfer on demand can receive the transfer. The parameter value must be in the range from 1 to 365. Optional parameter. The default is 1.

async get_balance() float[source]
async accept_incoming_transaction(operation_id: str, protection_code: str) glQiwiApi.types.yoomoney.types.IncomingTransaction[source]

Acceptance of incoming transfers protected by a protection code, if you passed the protect parameter to the send method Number of reception attempts incoming transfer with a protection code is limited. When the number of attempts is exhausted, the transfer is automatically rejected (the transfer is returned to the sender). More detailed documentation: https://yoomoney.ru/docs/wallet/process-payments/incoming-transfer-accept

Parameters
  • operation_id – Operation identifier, the value of the operation_id parameter of the history () method response

  • protection_code – Protection code. A string of 4 decimal digits. Indicated for an incoming transfer protected by a protection code. Not available for on-demand transfers.

async reject_transaction(operation_id: str) Dict[str, str][source]
Cancellation of incoming transfers protected by a protection code if you transferred

in the send method the protect parameter,

and transfers on demand.

If the transfer is canceled, it is returned to the sender.

Required token rights: incoming-transfers Docs: https://yoomoney.ru/docs/wallet/process-payments/incoming-transfer-reject

Parameters

operation_id – Operation identifier, parameter value operation_id of history () method response.

async check_transaction(amount: Union[int, float], operation_type: str = 'in', comment: Optional[str] = None, rows: int = 100, recipient: Optional[str] = None) bool[source]

Method for verifying a transaction. This method uses self.transactions (rows = rows) to receive payments. For a little optimization, you can decrease rows by setting it, however, this does not guarantee the correct result

Parameters
  • amount – payment amount

  • operation_type – payment type

  • recipient – recipient number

  • rows – number of payments to be checked

  • comment – comment by which the transaction will be verified

Returns

bool, is there such a transaction in the payment history

QIWI Maps API

class glQiwiApi.qiwi.maps.QiwiMaps(cache_time: int = 0, session_holder: Optional[glQiwiApi.core.session.holder.AbstractSessionHolder[Any]] = None)[source]

Bases: glQiwiApi.core.abc.wrapper.Wrapper, glQiwiApi.core.mixins.DataMixin, glQiwiApi.core.mixins.ContextInstanceMixin[QiwiMaps]

QIWI Terminal Maps API allows you to locate QIWI terminals on the territory of the Russian Federation

__init__(cache_time: int = 0, session_holder: Optional[glQiwiApi.core.session.holder.AbstractSessionHolder[Any]] = None) None[source]
get_request_service() glQiwiApi.core.request_service.RequestService[source]
async terminals(polygon: glQiwiApi.types.qiwi.polygon.Polygon, zoom: Optional[int] = None, pop_if_inactive_x_mins: int = 30, include_partners: Optional[bool] = None, partners_ids: Optional[List[Any]] = None, cache_terminals: Optional[bool] = None, card_terminals: Optional[bool] = None, identification_types: Optional[int] = None, terminal_groups: Optional[List[Any]] = None) List[glQiwiApi.types.qiwi.terminal.Terminal][source]

Get map of terminals sent for passed polygon with additional params

Parameters
  • polygon – glQiwiApi.types.Polygon object

  • zoomhttps://tech.yandex.ru/maps/doc/staticapi/1.x/dg/concepts/map_scale-docpage/

  • pop_if_inactive_x_mins – do not show if terminal was inactive for X minutes default 0.5 hours

  • include_partners – result will include/exclude partner terminals

  • partners_ids – Not fixed IDS array look at docs

  • cache_terminals – result will include or exclude cache-acceptable terminals

  • card_terminals – result will include or exclude card-acceptable terminals

  • identification_types0 - not identified, 1 - partly identified, 2 - fully identified

  • terminal_groups – look at QiwiMaps.partners

Returns

list of Terminal instances

async partners() List[glQiwiApi.types.qiwi.partner.Partner][source]

Get terminal partners for ttpGroups :return: list of TTPGroups

Examples

Qiwi usage examples

Basic use cases

import asyncio
import datetime

from glQiwiApi import QiwiWrapper, APIError
from glQiwiApi.types import TransactionType

TOKEN = "YOUR_API_ACCESS_TOKEN"
WALLET = "+NUMBER"
SECRET_KEY = "YOUR_SECRET_P2P_TOKEN"


async def basic_usage():
    async with QiwiWrapper(
        api_access_token=TOKEN, phone_number=WALLET, secret_p2p=SECRET_KEY
    ) as wallet:
        # So you can get information on a transaction, knowing its ID and type
        print(
            await wallet.transaction_info(
                transaction_type=TransactionType.OUT, transaction_id=21249852701
            )
        )
        # This way you can get the statistics of the qiwi wallet
        # difference between end_date and start_date must be less than 90 days
        stats = await wallet.fetch_statistics(
            start_date=datetime.datetime.now() - datetime.timedelta(days=10),
            end_date=datetime.datetime.now(),
        )
        print(stats)
        # Full account information
        info = await wallet.get_account_info()
        # Get the ip address from which the last login was made
        print(info.auth_info.ip)
        # We transfer money to another wallet, while receiving the ID of the payment
        payment_id = await wallet.to_wallet(
            amount=999, to_number="some_number", comment="I love glQiwiApi"
        )
        print(payment_id)
        # handling types exceptions and get json representation
        try:
            await wallet.to_wallet(to_number="+WRONG_NUMBER", amount=999)
        except APIError as ex:
            print(ex.json())


asyncio.run(basic_usage())

QIWI P2P API

To create p2p bill you have to utilize create_p2p_bill method. Let’s go to superb example:

import asyncio

from glQiwiApi import QiwiWrapper


async def create_p2p_bill():
    async with QiwiWrapper(secret_p2p="your p2p token") as w:
        bill = await w.create_p2p_bill(amount=1)
    # probably, you wanna get pay url, so you can do it comfortably
    print(f"Link to pay bill with {bill.bill_id} id = {bill.pay_url}")


asyncio.run(create_p2p_bill())

If you go to the created link, you will see this:

bill form example

Obviously, you have to check this bill someway. There are two ways to do it. Let’s go to rapid example:

Tip

To reject p2p bill you should use reject_p2p_bill or bill.reject()

import asyncio

from glQiwiApi import QiwiWrapper


async def how_to_check_bill():
    # as shown above, we just create a bill
    async with QiwiWrapper(secret_p2p="your p2p token") as w:
        bill = await w.create_p2p_bill(amount=777)
    # laconic variant to check bill, but you might encounter to some problems with pickling it
    await bill.check()
    # So, you can use default API method
    status = await w.check_p2p_bill_status(bill.bill_id)
    if status == "PAID":
        print("It's ok")
    else:
        print("Bill was not paid")


asyncio.run(how_to_check_bill())

Usage with aiogram

Here is straightforward example how to use glQiwiApi together with aiogram

from typing import Union

from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.utils import executor

from glQiwiApi import QiwiWrapper, types as qiwi_types

wallet = QiwiWrapper(secret_p2p="YOUR_SECRET_P2P_TOKEN")

BOT_TOKEN = "BOT_TOKEN"

bot = Bot(token=BOT_TOKEN, parse_mode=types.ParseMode.HTML)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)


async def create_payment(amount: Union[float, int] = 1) -> qiwi_types.Bill:
    async with wallet:
        return await wallet.create_p2p_bill(amount=amount)


@dp.message_handler(text="I want to pay")
async def payment(message: types.Message, state: FSMContext):
    bill = await create_payment()
    await message.answer(text=f"Ok, here's your invoice:\n {bill.pay_url}")
    await state.set_state("payment")
    await state.update_data(bill=bill)


@dp.message_handler(state="payment", text="I have paid this invoice")
async def successful_payment(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        bill: qiwi_types.Bill = data.get("bill")
    status = await bill.check()
    if status:
        await message.answer("You have successfully paid your invoice")
        await state.finish()
    else:
        await message.answer("Invoice was not paid")


if __name__ == "__main__":
    executor.start_polling(dp, skip_updates=True)

Polling updates

Tip

👩🏻🎨 start_polling has the same signature as start_webhook “under the hood”

Guidelines

👩🏻🔬This API method gives a chance to hook updates without webhooks on your machine, but it’s possible to use both approaches anyway.

🧑🎓 First of all, before starting polling, you need to register handlers, just like when installing webhooks. Lets do it with decorators, but you also can do it another way, using wallet.register_transaction_handler, wallet.register_bill_handler or wallet.register_error_handler

Add handlers
import logging

from glQiwiApi import QiwiWrapper, types
from glQiwiApi.utils import executor

api_access_token = "your token"
phone_number = "your number"

wallet = QiwiWrapper(api_access_token=api_access_token, phone_number=phone_number)

logger = logging.getLogger(__name__)


@wallet.transaction_handler()
async def my_first_handler(update: types.Transaction):
    assert isinstance(update, types.Transaction)


def on_startup(wrapper: QiwiWrapper):
    logger.info("This message logged on startup")


executor.start_polling(wallet, on_startup=on_startup, skip_updates=True)

🧙♀️So, we also have to import executor Executor overview and pass on our client, that contains user-friendly functions start_polling and start_webhook.

import executor module
import logging

from glQiwiApi import QiwiWrapper, types
from glQiwiApi.utils import executor

api_access_token = "your token"
phone_number = "your number"

wallet = QiwiWrapper(api_access_token=api_access_token, phone_number=phone_number)

logger = logging.getLogger(__name__)


@wallet.transaction_handler()
async def my_first_handler(update: types.Transaction):
    assert isinstance(update, types.Transaction)


def on_startup(wrapper: QiwiWrapper):
    logger.info("This message logged on startup")


executor.start_polling(wallet, on_startup=on_startup, skip_updates=True)
Events

👨🔬 Then, you can start polling, but, let’s make it clear which arguments you should pass on to start_polling function. You can also specify events like on_shutdown or on_startup.

import logging

from glQiwiApi import QiwiWrapper, types
from glQiwiApi.utils import executor

api_access_token = "your token"
phone_number = "your number"

wallet = QiwiWrapper(api_access_token=api_access_token, phone_number=phone_number)

logger = logging.getLogger(__name__)


@wallet.transaction_handler()
async def my_first_handler(update: types.Transaction):
    assert isinstance(update, types.Transaction)


def on_startup(wrapper: QiwiWrapper):
    logger.info("This message logged on startup")


executor.start_polling(wallet, on_startup=on_startup, skip_updates=True)

😼 As you can see, in the example we have a function that we pass as an argument to on_startup. As you may have guessed, this function will be executed at the beginning of the polling.

import logging

from glQiwiApi import QiwiWrapper, types
from glQiwiApi.utils import executor

api_access_token = "your token"
phone_number = "your number"

wallet = QiwiWrapper(api_access_token=api_access_token, phone_number=phone_number)

logger = logging.getLogger(__name__)


@wallet.transaction_handler()
async def my_first_handler(update: types.Transaction):
    assert isinstance(update, types.Transaction)


def on_startup(wrapper: QiwiWrapper):
    logger.info("This message logged on startup")


executor.start_polling(wallet, on_startup=on_startup, skip_updates=True)
Aiogram + glQiwiApi = friends🤩

🧚♀️ Also, you can very easily implement simultaneous polling of updates from both aiogram and QIWI API.

In the example below, we catch all text messages and return the same “Hello” response.

polling together with aiogram
import logging

from aiogram import Bot, Dispatcher
from aiogram import types

from glQiwiApi import QiwiWrapper
from glQiwiApi.plugins.telegram.polling import TelegramPollingPlugin
from glQiwiApi.types import Transaction
from glQiwiApi.utils import executor

api_access_token = "your token"
phone_number = "your number"

bot = Bot("token from BotFather")
dp = Dispatcher(bot)

wallet = QiwiWrapper(api_access_token=api_access_token, phone_number=phone_number)

logger = logging.getLogger(__name__)


@dp.message_handler()
async def message_handler(msg: types.Message):
    await msg.answer(text="Привет😇")


@wallet.transaction_handler()
async def my_first_handler(update: Transaction):
    assert isinstance(update, Transaction)


def on_startup(wrapper: QiwiWrapper):
    logger.info("This message logged on startup")


executor.start_polling(wallet, TelegramPollingPlugin(dp), on_startup=on_startup)
Error handling
from __future__ import annotations

import logging
from typing import Any

from glQiwiApi import QiwiWrapper
from glQiwiApi.utils import executor

api_access_token = "your token"
phone_number = "your number"

wallet = QiwiWrapper(api_access_token=api_access_token, phone_number=phone_number)
logger = logging.getLogger(__name__)


@wallet.error_handler(exception=OSError)
async def os_error_handler(exception: Exception, *args: Any) -> None:
    # do something here, if exception has occurred, for example log it
    logger.exception("Exception %s occurred. WTF!!!", exception)


executor.start_polling(wallet, skip_updates=True)
Example usage without global variables😇
import logging
from typing import cast

from aiogram import Bot, Dispatcher
from aiogram import types

from glQiwiApi import QiwiWrapper
from glQiwiApi.plugins.telegram.polling import TelegramPollingPlugin
from glQiwiApi.types import Transaction
from glQiwiApi.utils import executor

api_access_token = "your token"
phone_number = "+your number"

logger = logging.getLogger(__name__)


def run_application() -> None:
    bot = Bot("token from BotFather")
    dp = Dispatcher(bot)
    wallet = QiwiWrapper(api_access_token=api_access_token, phone_number=phone_number)

    # set dispatcher to wallet instance for register aiogram handlers
    wallet["dispatcher"] = dp

    executor.start_polling(wallet, TelegramPollingPlugin(dp), on_startup=on_startup, skip_updates=True)


def register_handlers(wrapper: QiwiWrapper):
    wrapper.register_transaction_handler(qiwi_transaction_handler)
    dispatcher = cast(Dispatcher, wrapper["dispatcher"])
    dispatcher.register_message_handler(aiogram_message_handler)


async def aiogram_message_handler(msg: types.Message):
    await msg.answer(text="Привет😇")


async def qiwi_transaction_handler(update: Transaction):
    assert isinstance(update, Transaction)
    print(update)


def on_startup(wrapper: QiwiWrapper) -> None:
    logger.info("This message logged on startup")
    register_handlers(wrapper)


if __name__ == '__main__':
    run_application()

Webhooks

Caution

To correctly run the webhook you need a VPS server or configure the local machine for response to requests of QIWI API.

Caution

Firstly, you need to register webhook to your server using glQiwiApi

🐺So, to “bind” webhook and gracefully work with glQiwiApi webhook API, you need to follow this instructions:

  1. Step one(bind webhook).

import asyncio

from glQiwiApi import QiwiWrapper
from glQiwiApi.ext.url_builder import WebhookURL

wrapper = QiwiWrapper(
    api_access_token="",
    secret_p2p="",
    phone_number="+"
)


async def main():
    # some tips:
    # - webhook_path have to starts with "/"
    url = WebhookURL.create(host="https://github.com", webhook_path="/GLEF1X/glQiwiApi")  # equal to https://github.com/GLEF1X/glQiwiApi
    # Also, you can pass url as string, but it's highly recomended to use WebhookURL extension
    await wrapper.bind_webhook(url=url, delete_old=True)


asyncio.run(main())
  1. Step two(use handlers and start webhook).

Using glQiwiApi you can use two types of handlers transaction_handler and bill_handler respectively. Also, you can pass lambda filters to miss unnecessary updates from webhook.

Usage of webhooks
 1import logging
 2
 3from aiogram import Bot
 4
 5from glQiwiApi import QiwiWrapper, types
 6from glQiwiApi.core.dispatcher.webhooks.config import Path
 7from glQiwiApi.utils import executor
 8
 9TOKEN = "token from https://qiwi.com/api/"
10QIWI_SECRET = "secret token from https://qiwi.com/p2p-admin/"
11
12wallet = QiwiWrapper(api_access_token=TOKEN, secret_p2p=QIWI_SECRET)
13
14bot = Bot(token="BOT_TOKEN")
15
16logger = logging.getLogger(__name__)
17
18
19# There is a lambda expression for "cutting off" test payments
20@wallet.transaction_handler(lambda event: event.payment is not None)
21async def main(event: types.WebHook):
22    logger.info("New transaction: {}", event)
23    await bot.send_message(chat_id="1219185039", text=event.hook_id)
24
25
26@wallet.bill_handler()
27async def main2(event: types.Notification):
28    logger.info("P2P EVENT {}", event)
29
30
31# Also, you can specify a path for webhook
32# Example: http://127.0.0.1/your_path/
33# If you don't pass path in `start_webhook`
34# or dont pass on transaction_path or bill_path
35# Its ok, because it will take a default paths
36# default transaction_path = /dispatcher/qiwi/
37# default bill_path = /webhooks/qiwi/bills/
38# So, if you dont pass on paths
39# you need to register webhook with url like
40# on this example: http://your_ip:port/web_hooks/qiwi/ - for transactions
41# or http://your_ip:port/webhooks/qiwi/bills/ - for bills
42path = Path(transaction_path="/dispatcher/qiwi", bill_path="/my_webhook/")
43
44executor.start_webhook(
45    wallet,
46    # You can pass on any port, but it must be open for web
47    # You can use any VPS server to catching webhook or
48    # your configured local machine
49    path=path,
50)

Class-based handlers & filters

Tip

This section, like all the source library code, is supported by the mypy linter😁.

Class-based filters

🧙Starting with 1.0.3b2 you can use class-based filters. Here is dive-in example of usage.

from glQiwiApi import QiwiWrapper, BaseFilter, types
from glQiwiApi.utils import executor

wrapper = QiwiWrapper(secret_p2p="secret key")


class MyCustomFilter(BaseFilter):
    async def check(self, update: types.WebHook) -> bool:
        return update.version == "1.0.0"  # some expression or complicated interaction with update


@wrapper.transaction_handler(MyCustomFilter())
async def my_handler(update: types.WebHook):
    """some stuff with update"""


executor.start_webhook(wrapper)
Class-based handlers

Also, starting with 1.0.4 you can easily interact with class-based handlers.

Example of usage with decorator:

some_credentials = {
    "api_access_token": "some_token",
    "phone_number": "+some_number"
}
wrapper = QiwiWrapper(**some_credentials)

@wrapper.transaction_handler()
class MyTxnHandler(AbstractTransactionHandler):

    async def process_event(self) -> Any:
        print("HELLO FROM CLASS-BASED handler")

YooMoney

How to obtain the API token

Firstly, you have to register our application in YooMoney using the link: click.

So, you will be redirected to the same page:

example of registration form

It goes without saying, we get the client_id after registration and then use YooMoneyAPI. Here is brief example how to obtain url to get special code

import asyncio

from glQiwiApi import YooMoneyAPI


async def get_url_to_auth() -> None:
    # Get a link for authorization, follow it if we get invalid_request or some kind of error
    # means either the scope parameter is incorrectly passed, you need to reduce the list of rights or try to recreate the application
    print(await YooMoneyAPI.build_url_for_auth(
        # For payments, account verification and payment history, you need to specify scope = ["account-info", "operation-history", "operation-details", "payment-p2p"]
        scope=["account-info", "operation-history"],
        client_id='ID received when registering the application above',
        redirect_uri='the link specified during registration above in the Redirect URI field'
    ))


asyncio.run(get_url_to_auth())

Tip

In the url you will see your code as a default param of GET request e.g. https://example.com/?code=bla-bla-bla

Now you need to get the temporary code and get the token as fast as possible using the YooMoneyAPI class method:

import asyncio

from glQiwiApi import YooMoneyAPI


async def get_token() -> None:
    print(await YooMoneyAPI.get_access_token(
        code='the code obtained from the link',
        client_id='Application ID received when registering the application above',
        redirect_uri='link provided during registration'
    ))


asyncio.run(get_token())

Examples

Dive-in example.

import asyncio

from glQiwiApi import YooMoneyAPI

TOKEN = 'your token'


async def main():
    async with YooMoneyAPI(api_access_token=TOKEN) as w:
        print(await w.transactions(records=50))


asyncio.run(main())

Creating pay form.

Tip

This method is extremely weightless, cause it doesn’t send any request.

from glQiwiApi import YooMoneyAPI

TOKEN = 'your token'

link = YooMoneyAPI.create_pay_form(
    receiver="4100116602400968",
    quick_pay_form="donate",
    targets="donation",
    payment_type="PC",
    amount=50
)

print(link)

Send money to another wallet and checking this transaction

import asyncio

from glQiwiApi import YooMoneyAPI

TOKEN = 'your_token'


async def main():
  w = YooMoneyAPI(TOKEN)
  async with w:
    # So you can send funds to another account, in the example this is a transfer to account 4100116602400968
    # worth 2 rubles with the comment "I LOVE glQiwiApi"
    payment = await w.send(
      to_account='4100116602400968',
      comment='I LOVE glQiwiApi',
      amount=2
    )
    # This way you can check the transaction, whether it was received by the person on the account
    print(await w.check_transaction(amount=2, comment='I LOVE glQiwiApi',
                                    operation_type='out'))


asyncio.run(main())

Fetch account info.

import asyncio

from glQiwiApi import YooMoneyAPI

TOKEN = 'your_token'


async def main():
    w = YooMoneyAPI(TOKEN)
    async with w:
        # This gives you account information as AccountInfo pydantic model.
        get_account_info = await w.retrieve_account_info()
        print(get_account_info.account_status)
        print(get_account_info.balance)


asyncio.run(main())

Low Level API features

Query caching

glQiwiApi provides builtin cache storage and cache invalidation strategies such a InMemoryCacheStorage and APIResponsesCacheInvalidationStrategy accordingly. Obviously, you can extend functionality of library and add, for example, Redis based cache storage.

Tip

By default InMemoryCacheStorage use UnrealizedCacheInvalidationStrategy as an invalidation strategy

Straightforward example

import asyncio

from glQiwiApi.core.storage import InMemoryCacheStorage, UnrealizedCacheInvalidationStrategy

storage = InMemoryCacheStorage()  # here is UnrealizedCacheInvalidationStrategy as an invalidation strategy


async def main():
    storage.update(cached=5)
    cached = await storage.retrieve("cached")
    print(f"You have cached {cached}")


asyncio.run(main())

Types

Qiwi types

class glQiwiApi.types.qiwi.Account(*, alias: str, title: str, fsAlias: str, bankAlias: str, hasBalance: bool, balance: glQiwiApi.types.amount.CurrencyAmount = None, currency: glQiwiApi.types.amount.CurrencyModel, type: glQiwiApi.types.amount.Type = None, defaultAccount: bool)[source]

object: Account

class glQiwiApi.types.qiwi.Balance(*, alias: str, currency: glQiwiApi.types.amount.CurrencyModel)[source]

object: Balance

class glQiwiApi.types.qiwi.Bill(*, siteId: str, billId: str, amount: glQiwiApi.types.amount.HashableOptionalSum, status: glQiwiApi.types.qiwi.bill.BillStatus, creationDateTime: datetime.datetime = None, expirationDateTime: datetime.datetime = None, payUrl: str = None, customFields: glQiwiApi.types.qiwi.bill.CustomFields = None, customer: glQiwiApi.types.qiwi.bill.Customer = None, workaround_url: str = None, **extra_data: Any)[source]

Object: Bill

async check() bool[source]

Checking p2p payment status

class glQiwiApi.types.qiwi.BillError(*, serviceName: str, errorCode: str, description: str, userMessage: str, dateTime: str, traceId: str)[source]

Object: BillError

class glQiwiApi.types.qiwi.Card(*, qvx: glQiwiApi.types.qiwi.qiwi_master.CardCredentials, balance: glQiwiApi.types.amount.CurrencyAmount = None, info: glQiwiApi.types.qiwi.qiwi_master.CardInfo)[source]

object: Card description: Данные выпущенных карт

class glQiwiApi.types.qiwi.CrossRate(*, from: Union[str, glQiwiApi.types.amount.CurrencyModel], to: Union[str, glQiwiApi.types.amount.CurrencyModel], rate: float)[source]

Курс валюты

class glQiwiApi.types.qiwi.FreePaymentDetailsFields(*, name: str, extra_to_bik: str, to_bik: str, city: str, info: str = 'Коммерческие организации', is_commercial: str = '1', to_name: str, to_inn: str, to_kpp: str, nds: str, goal: str, urgent: str = '0', account: str, from_name: str, from_name_p: str, from_name_f: str, requestProtocol: str = 'qw1', toServiceId: str = '1717')[source]

Набор реквизитов платежа

account: str

Номер счета получателя

city: str

Город местонахождения получателя

extra_to_bik: str

БИК банка получателя

from_name: str

Имя плательщика

from_name_f: str

Фамилия плательщика

from_name_p: str

Отчество плательщика

goal: str

Назначение платежа

info: str

Константное значение

is_commercial: str

Служебная информация

name: str

Наименование банка получателя

nds: str

Признак уплаты НДС. Если вы оплачиваете квитанцию и в ней не указан НДС, то строка НДС не облагается. В ином случае, строка В т.ч. НДС

requestProtocol: str

Служебная информация, константа

toServiceId: str

Служебная информация, константа

to_bik: str

БИК банка получателя

to_inn: str

ИНН организации

to_kpp: str

КПП организации

to_name: str

Наименование организации

urgent: str

Признак срочного платежа (0 - нет, 1 - да). Срочный платеж выполняется от 10 минут. Возможен по будням с 9:00 до 20:30 по московскому времени. Стоимость услуги — 25 рублей.

class glQiwiApi.types.qiwi.Identification(*, id: int, firstName: str, middleName: str, lastName: str, birthDate: datetime.date, passport: str, inn: str = None, snils: str = None, oms: str = None, type: str)[source]

object: Identification

class glQiwiApi.types.qiwi.Limit(*, currency: glQiwiApi.types.amount.CurrencyModel, rest: Union[float, int], max: Union[float, int], spent: Union[float, int], interval: glQiwiApi.types.qiwi.limit.Interval, type: str)[source]

object: Limit

class glQiwiApi.types.qiwi.Notification(*, version: str, bill: glQiwiApi.types.qiwi.bill.Bill)[source]

Object: Notification

class glQiwiApi.types.qiwi.OrderDetails(*, id: str, cardAlias: str, status: str, price: glQiwiApi.types.amount.CurrencyAmount = None, cardId: str = None)[source]

object: OrderDetails

class glQiwiApi.types.qiwi.Partner(*, title: str, id: int, maps: List[str] = None)[source]

Base partner class

class glQiwiApi.types.qiwi.PaymentInfo(*, id: int, terms: str, fields: glQiwiApi.types.qiwi.payment_info.Fields = None, sum: glQiwiApi.types.amount.CurrencyAmount, source: str, transaction: glQiwiApi.types.qiwi.payment_info.TransactionInfo = None, comment: str = None)[source]

object: PaymentInfo

class glQiwiApi.types.qiwi.Polygon(lat_lon_pair_nw: Tuple[Any, ...], lat_lon_pair_se: Tuple[Any, ...])[source]

Polygon class for QiwiMaps class

class glQiwiApi.types.qiwi.RefundBill(*, amount: glQiwiApi.types.amount.PlainAmount, datetime: datetime.datetime, refundId: str, status: str)[source]

object: RefundBill

class glQiwiApi.types.qiwi.Statistic(*, incomingTotal: List[glQiwiApi.types.amount.CurrencyAmount], outgoingTotal: List[glQiwiApi.types.amount.CurrencyAmount], **extra_data: Any)[source]

object: Statistic

class glQiwiApi.types.qiwi.Terminal(*, terminalId: int, ttpId: int, lastActive: str, count: int, address: str, verified: bool, label: str, description: str = <class 'NoneType'>, cashAllowed: bool, cardAllowed: bool, identificationType: int, coordinate: glQiwiApi.types.qiwi.terminal.Coordinate)[source]

Object: Terminal

class glQiwiApi.types.qiwi.Transaction(*, txnId: int, personId: int, date: datetime.datetime, errorCode: int = None, error: str = None, status: glQiwiApi.types.qiwi.transaction.TransactionStatus, type: glQiwiApi.types.qiwi.transaction.TransactionType, statusText: str, trmTxnId: str, account: str, sum: glQiwiApi.types.amount.CurrencyAmount, commission: glQiwiApi.types.amount.CurrencyAmount, total: glQiwiApi.types.amount.CurrencyAmount, provider: glQiwiApi.types.qiwi.transaction.Provider, source: glQiwiApi.types.qiwi.transaction.Provider = None, comment: str = None, currencyRate: int, **extra_data: Any)[source]

object: Transaction

comment: Optional[str]

Комментарий к платежу

commission: glQiwiApi.types.amount.CurrencyAmount

Данные о комиссии

currency_rate: int

Курс конвертации (если применяется в транзакции)

date: datetime.datetime

Для запросов истории платежей - Дата/время платежа, во временной зоне запроса (см. параметр startDate). Для запросов данных о транзакции - Дата/время платежа, время московское

error: Optional[str]

Описание ошибки

error_code: Optional[int]

Код ошибки платежа

id: int

ID транзакции в сервисе QIWI Кошелек

person_id: int

Номер кошелька

provider: glQiwiApi.types.qiwi.transaction.Provider

Данные о провайдере.

source: Optional[glQiwiApi.types.qiwi.transaction.Provider]

Служебная информация

status: glQiwiApi.types.qiwi.transaction.TransactionStatus

Статус платежа. Возможные значения: WAITING - платеж проводится, SUCCESS - успешный платеж, ERROR - ошибка платежа.

status_text: str

Текстовое описание статуса платежа

sum: glQiwiApi.types.amount.CurrencyAmount

Данные о сумме платежа или пополнения.

to_account: str

Для платежей - номер счета получателя. Для пополнений - номер отправителя, терминала или название агента пополнения кошелька

total: glQiwiApi.types.amount.CurrencyAmount

Общие данные о платеже в формате объекта Sum

trm_transaction_id: str

Клиентский ID транзакции

type: glQiwiApi.types.qiwi.transaction.TransactionType

Тип платежа. Возможные значения: IN - пополнение, OUT - платеж, QIWI_CARD - платеж с карт QIWI (QVC, QVP).

class glQiwiApi.types.qiwi.TransactionType(value)[source]

An enumeration.

class glQiwiApi.types.qiwi.WebHook(*, hash: str = None, hookId: str, messageId: str = None, test: bool, version: str, payment: glQiwiApi.types.qiwi.webhooks.WebhookPayment = None, signature: str)[source]

Object: WebHook

signature: str

NOT API field, this signature is generating in webhook_signature_collector

classmethod webhook_signature_collector(values: Dict[Any, Any]) Dict[Any, Any][source]

Get webhook signature to confirm it with hash by base64 encoded key. payment.signFields is string. e.g. “sum.currency,sum.amount,type,account,txnId”. So, this string disassembled piece by piece recursively, because each of signField part, that separated by comma can be nested by “.”

@param values: @return:

class glQiwiApi.types.qiwi.WebHookConfig(*, hookId: str, hookType: str, txnType: str, hookParameters: glQiwiApi.types.qiwi.webhooks.HookParameters)[source]

WebHookConfig object

YooMoney types

class glQiwiApi.types.yoomoney.AccountInfo(*, account: str, balance: float, currency: str, identified: bool, account_type: str, account_status: str, balance_details: glQiwiApi.types.yoomoney.types.BalanceDetails, cards_linked: List[glQiwiApi.types.yoomoney.types.CardsLinked] = None)[source]

object: AccountInfo

account: str

Номер счета

account_status: str

Статус пользователя. Возможные значения: anonymous — анонимный счет; named — именной счет; identified — идентифицированный счет.

account_type: str

Тип счета пользователя. Возможные значения: personal — счет пользователя в ЮMoney; professional — профессиональный счет в ЮMoney

balance: float

Баланс счета

balance_details: glQiwiApi.types.yoomoney.types.BalanceDetails

Расширенная информация о балансе. По умолчанию этот блок отсутствует. Блок появляется, если сейчас или когда-либо ранее были зачисления в очереди задолженности, блокировки средств.

cards_linked: Optional[List[glQiwiApi.types.yoomoney.types.CardsLinked]]

Информация о привязанных банковских картах. Если к счету не привязано ни одной карты, параметр отсутствует. Если к счету привязана хотя бы одна карта, параметр содержит список данных о привязанных картах. pan_fragment - string Маскированный номер карты. type: string Тип карты. Может отсутствовать, если неизвестен. Возможные значения: - VISA; - MasterCard; - AmericanExpress; - JCB.

currency: str

Код валюты счета пользователя. Всегда 643 (рубль РФ по стандарту ISO 4217).

identified: bool

Верифицирован ли кошелек

class glQiwiApi.types.yoomoney.IncomingTransaction(*, status: str, protection_code_attempts_available: int, ext_action_uri: str = None, error: str = None)[source]

object: IncomingTransaction

class glQiwiApi.types.yoomoney.Operation(*, operation_id: str, status: str, datetime: datetime.datetime, title: str, direction: str, amount: Union[int, float], type: str, label: str = None, pattern_id: str = None, details: Any = None)[source]

object: Operation

amount: Union[int, float]

Сумма операции.

direction: str

Направление движения средств. Может принимать значения: - in (приход); - out (расход).

id: str

Идентификатор операции.

label: Optional[str]

Метка платежа. Присутствует для входящих и исходящих переводов другим пользователям у которых был указан параметр label вызова send()

operation_date: datetime.datetime

Дата и время совершения операции в формате строки в ISO формате с часовым поясом UTC.

operation_type: str

Тип операции. Возможные значения: payment-shop — исходящий платеж в магазин; outgoing-transfer — исходящий P2P-перевод любого типа; deposition — зачисление; incoming-transfer — входящий перевод или перевод до востребования; incoming-transfer-protected — входящий перевод с кодом протекции.

pattern_id: Optional[str]

Идентификатор шаблона, по которому совершен платеж. Присутствует только для платежей.

status: str

Статус платежа (перевода). Может принимать следующие значения: - success — платеж завершен успешно; - refused — платеж отвергнут получателем или отменен отправителем; - in_progress — платеж не завершен,

перевод не принят получателем или ожидает ввода кода протекции.

title: str

Краткое описание операции (название магазина или источник пополнения).

class glQiwiApi.types.yoomoney.OperationDetails(*, operation_id: str, status: str = None, amount: float = None, datetime: datetime.datetime = None, type: str = None, direction: str = None, comment: str = None, digital_goods: Dict[str, glQiwiApi.types.yoomoney.types.DigitalGoods] = None, details: str = None, label: str = None, answer_datetime: str = None, expires: str = None, protection_code: str = None, codepro: bool = None, message: str = None, recipient_type: str = None, recipient: str = None, sender: str = None, title: str = None, fee: float = None, amount_due: float = None, pattern_id: str = None, error: str = None)[source]

object: OperationDetails

amount: Optional[float]

Сумма операции (сумма списания со счета).

amount_due: Optional[float]

Сумма к получению. Присутствует для исходящих переводов другим пользователям.

answer_datetime: Optional[str]

Дата и время приема или отмены перевода, защищенного кодом протекции. Присутствует для входящих и исходящих переводов, защищенных кодом протекции если при вызове send вы указали protect=True при передаче аргументов. Если перевод еще не принят или не отвергнут получателем, поле отсутствует.

codepro: Optional[bool]

Перевод защищен кодом протекции. Присутствует для переводов другим пользователям.

comment: Optional[str]

Комментарий к переводу или пополнению. Присутствует в истории отправителя перевода или получателя пополнения.

details: Optional[str]

Детальное описание платежа. Строка произвольного формата, может содержать любые символы и переводы строк Необязательный параметр.

digital_goods: Optional[Dict[str, glQiwiApi.types.yoomoney.types.DigitalGoods]]

Данные о цифровом товаре (пин-коды и бонусы игр, iTunes, Xbox, etc.) Поле присутствует при успешном платеже в магазины цифровых товаров. Описание формата: https://yoomoney.ru/docs/wallet/process-payments/process-payment#digital-goods

direction: Optional[str]

направление движения средств. может принимать значения: - in (приход); - out (расход).

error: Optional[str]

Код ошибки, присутствует при ошибке выполнения запрос Возможные ошибки: illegal_param_operation_id - неверное значение параметра operation_id Все прочие значения - техническая ошибка, повторите вызов метода позднее.

expires: Optional[str]

Дата и время истечения срока действия кода протекции. Присутствует для входящих и исходящих переводов (от/другим) пользователям, защищенных кодом протекции, если при вызове send вы указали protect=True при передаче аргументов.

fee: Optional[float]

Сумма комиссии. Присутствует для исходящих переводов другим пользователям.

id: str

Идентификатор операции. Можно получить при вызове метода history()

label: Optional[str]

Метка платежа.

message: Optional[str]

Сообщение получателю перевода. Присутствует для переводов другим пользователям.

operation_date: Optional[datetime.datetime]

Дата и время совершения операции в формате строки в ISO формате с часовым поясом UTC.

operation_type: Optional[str]

Тип операции. Возможные значения: payment-shop — исходящий платеж в магазин; outgoing-transfer — исходящий P2P-перевод любого типа; deposition — зачисление; incoming-transfer — входящий перевод или перевод до востребования; incoming-transfer-protected — входящий перевод с кодом протекции.

pattern_id: Optional[str]

Идентификатор шаблона платежа, по которому совершен платеж. Присутствует только для платежей.

protection_code: Optional[str]

Код протекции. Присутствует для исходящих переводов, защищенных кодом протекции.

recipient: Optional[str]

Идентификатор получателя перевода. Присутствует для исходящих переводов другим пользователям.

recipient_type: Optional[str]

Тип идентификатора получателя перевода. Возможные значения: account — номер счета получателя в сервисе ЮMoney; phone — номер привязанного мобильного телефона получателя; email — электронная почта получателя перевода. Присутствует для исходящих переводов другим пользователям.

sender: Optional[str]

Номер счета отправителя перевода. Присутствует для входящих переводов от других пользователей.

status: Optional[str]

Статус платежа (перевода). Можно получить при вызове метода history()

title: Optional[str]

Краткое описание операции (название магазина или источник пополнения).

class glQiwiApi.types.yoomoney.OperationType(value)[source]

Типы операций YooMoney

deposition — пополнение счета (приход); payment — платежи со счета (расход); incoming_transfers_unaccepted — непринятые входящие P2P-переводы любого типа.

DEPOSITION = 'deposition'

Пополнение счета (приход);

PAYMENT = 'payment'

Платежи со счета (расход)

TRANSFERS = 'incoming-transfers-unaccepted'

непринятые входящие P2P-переводы любого типа.

class glQiwiApi.types.yoomoney.Payment(*, status: str, payment_id: str, credit_amount: float = None, payer: str = None, payee: str = None, payee_uid: Optional[Union[str, int]] = None, invoice_id: str = None, balance: float = None, error: str = None, account_unblock_uri: str = None, acs_uri: str = None, acs_params: str = None, next_retry: int = None, digital_goods: Dict[str, Dict[str, List[glQiwiApi.types.yoomoney.types.DigitalGoods]]] = None, protection_code: str = None)[source]

object: Payment

account_unblock_uri: Optional[str]

Адрес, на который необходимо отправить пользователя для разблокировки счета Поле присутствует в случае ошибки account_blocked.

balance: Optional[float]

Баланс счета пользователя после проведения платежа. Присутствует только при выполнении следующих условий: - метод выполнен успешно; - токен авторизации обладает правом account-info.

credit_amount: Optional[float]

Сумма, поступившая на счет получателя. Присутствует при успешном переводе средств на счет другого пользователя ЮMoney.

error: Optional[str]

Код ошибки при проведении платежа (пояснение к полю status). Присутствует только при ошибках.

invoice_id: Optional[str]

Номер транзакции магазина в ЮMoney. Присутствует при успешном выполнении платежа в магазин.

next_retry: Optional[int]

Рекомендуемое время, спустя которое следует повторить запрос, в миллисекундах. Поле присутствует при status=in_progress.

payee: Optional[str]

Номер счета получателя. Присутствует при успешном переводе средств на счет другого пользователя ЮMoney.

payee_uid: Optional[Union[str, int]]

Служебное значение, не фигурирует в документации

payer: Optional[str]

Номер счета плательщика. Присутствует при успешном переводе средств на счет другого пользователя ЮMoney.

payment_id: str

Идентификатор проведенного платежа. Присутствует только при успешном выполнении метода send().

protection_code: Optional[str]

Код протекции, который был сгенерирован, если при вызове метода апи send вы указали protect=True при передаче аргументов

status: str

Код результата выполнения операции. Возможные значения: success — успешное выполнение (платеж проведен). Это конечное состояние платежа. refused — отказ в проведении платежа. Причина отказа возвращается в поле error. Это конечное состояние платежа. in_progress — авторизация платежа не завершена. Приложению следует повторить запрос с теми же параметрами спустя некоторое время. ext_auth_required — для завершения авторизации платежа с использованием банковской карты требуется аутентификация по технологии 3‑D Secure. все прочие значения — состояние платежа неизвестно. Приложению следует повторить запрос с теми же параметрами спустя некоторое время.

class glQiwiApi.types.yoomoney.PreProcessPaymentResponse(*, status: str, request_id: str, recipient_account_status: str, fees: Dict[str, float], balance: float = None, recipient_account_type: str = None, recipient_identified: bool = False, recipient_masked_account: str = None, multiple_recipients_found: str = None, contract_amount: float = None, error: str = None, money_source: glQiwiApi.types.yoomoney.types.MoneySource = None, protection_code: str = None, account_unblock_uri: str = None, ext_action_uri: str = None)[source]

Объект, который вы получаете при вызове _pre_process_payment. При вызове данного метода вы не списываете деньги со своего счёта, а условно подготавливаете его к отправке. Для отправки денег на счёт используйте метод send()