Back to Home

Python Webmoney API

python · webmoney · webmoney api

Python Webmoney API

    I needed to somehow implement support for Webmoney API ( Documentation ) in the project. I did not find any libraries in python, so I decided to write my own.


    Link to the repository

    So, there are two options for requesting api webmoney.

    • Keeper Classic - each request is signed using the WMSign program
    • Keeper Light - requests are sent via a secure HTTPS connection with a client certificate.


    I am considering only the second option. A certificate is required for the request. How to get it is written here . I managed to get the certificate only from Firefox, Chrome does not support this feature at all, and Explorer (Windows 8) issued an error. After receiving the certificate, you need to export it to a file. Kakko do it written here

    Certificate exported to pkcs12 file. It is necessary to get public and private keys from it. This is done by the commands:
        openssl pkcs12 -in path.p12 -out crt.pem -clcerts -nokeys
        openssl pkcs12 -in path.p12 -out key.pem -nocerts -nodes
    


    Work with API



    The package can be installed via pip:

    pip install webmoney-api
    


    After installation, import the libraries

    from webmoney_api import ApiInterface, WMLightAuthInterface
    


    WMLightAuthInterface is a class that describes authentication through Keeper Light.
    ApiInterface - api class.

    We connect:

    >>> api = ApiInterface(WMLightAuthInterface("/home/stas/wmcerts/crt.pem", "/home/stas/wmcerts/key.pem"))
    


    When initializing WMLightAuthInterface, we pass the path to our generated public and private keys into it.
    After connecting, the following methods are available:

    x1 - x10 - correspond to the same webmoney interfaces. Parameters are passed by name to the called method.
    Additionally, you can pass the reqn parameter - the request number.

    The method makes a request and returns data in the format:
    {"retval": ,     
    "retdesc": , 
    "response": 


    где

    • retval — код ответа, возвращаемый вебманями. 0 если запрос успешен. Коды можно посмотреть тут
    • retdesc — если retval != 0, тут лежит описание ошибки
    • response — распарсенный в OrderedDict ответ запроса. Тут лежат только данные, касающиеся запроса. Например, для запроса

      в response будет лежать распарсенный

      Парсинг осуществляется с помощью библиотеки github.com/martinblech/xmltodict


    Пример: поиск ID юзера по кошельку



    >>> api.x8(purse="R328079907035", reqn=int(time.time()))["response"]
    OrderedDict([(u'wmid', OrderedDict([(u'@available', u'0'), (u'@themselfcorrstate', u'0'), (u'@newattst', u'110'), ('#text', u'407414370132')])), (u'purse', OrderedDict([(u'@merchant_active_mode', u'-1'), (u'@merchant_allow_cashier', u'-1'), ('#text', u'R328079907035')]))])
    >>> api.x8(purse="R328079907035", reqn=int(time.time()))["response"]["wmid"]["#text"]
    u'407414370132'
    >>> api.x8(purse="R328079907035", reqn=int(time.time()))["response"]["wmid"]["@available"]
    u'0'
     


    Пример: получение истории всех выписанных счетов по кошельку



    >>> api.x4(purse="R328079907035", datestart="20100101 00:00:00", datefinish="20140501 00:00:00")
    ValueError: Error while requesting API. retval = -4, retdesc = wrong w3s.request/reqn step=2
    Request data: {'cert': ('/home/stas/wmcerts/crt.pem', '/home/stas/wmcerts/key.pem'),
     'data': '20100101 00:00:0020140501 00:00:00R328079907035',
     'url': 'https://w3s.wmtransfer.com/asp/XMLOutInvoicesCert.asp',
     'verify': False}
    


    Ошибка, т.к. не передан параметр reqn. Передадим его:
    >>> api.x4(purse="R328079907035", datestart="20100101 00:00:00", datefinish="20140501 00:00:00", reqn=int(time.time())) 
    {'response': OrderedDict([(u'@cnt', u'0'), (u'@cntA', u'0')]),
     'retdesc': None,
     'retval': u'0'}
    


    Пример: получение списка счетов на оплату



    >>> for order in api.x10(wmid="407414370132", datestart="20100101 00:00:00", datefinish="20140501 00:00:00", reqn=int(time.time()))["response"]["ininvoice"]:
    >>>     print order["orderid"], order["amount"], order["state"]
    4640849 122.40 2
    24 1.00 2
    27 0.40 2
    


    Ссылки





    Буду рад замечаниям и помощи)

    Read Next