GithubHelp home page GithubHelp logo

yarbshk / pybitrix24 Goto Github PK

View Code? Open in Web Editor NEW
40.0 8.0 23.0 197 KB

The simplest zero dependency polyversion Python library for Bitrix24 REST API.

License: MIT License

Python 98.44% Makefile 1.56%
python urlib bitrix24 api-client

pybitrix24's Introduction

pybitrix24

The simplest zero dependency polyversion Python library for Bitrix24 REST API.

Features

  • Polyversion. Supported Python versions: 2.7, 3.5+.
  • Zero dependency. It's fast, lightweight and secure.
  • Reliable. Test coverage is more than 80%.
  • Just simple. Examples of usage and clear sources.

Installation

Install using pip:

$ pip install pybitrix24

Getting started

Preparation

The current section and next one can be skipped if only webhooks will be used.

To start making requests it's necessary to create an application in the marketplace first. Then create an instance of the main class with the minimum required configuration that contains hostname, client ID and secret arguments (hereafter placeholders prefixed with "my" will be used instead of real values):

>>> from pybitrix24 import Bitrix24
>>> bx24 = Bitrix24('my-subdomain.bitrix24.com', 'my.client.id', 'MyClientSecret')

Now is the time to authorize.

Bitrix24 uses OAuth2 and authorization code grant for authorization of applications. It means that account owner's credentials are hidden from developers for security reasons, therefore, it's not possible to obtain authorization code programmatically. The account owner should be always present when access is granted.

However, to make life a bit simpler there is a helper method that builds an authorization URL for requesting an authorization code:

>>> bx24.build_authorization_url()
'https://my-subdomain.bitrix24.com/oauth/authorize/?client_id=my.client.id&response_type=code'

Finally, when an authorization code is received both access and refresh tokens can be obtained:

>>> bx24.obtain_tokens('AnAuthorizationCode')
{'access_token': 'AnAccessToken', 'refresh_token': 'ARefreshToken', ...}

As it was mentioned earlier it's not possible to get the authorization code automatically but it's possible to refresh tokens after initial receiving to make the session longer (note that both tokens have 1 hour lifetime after that they'll be expired and an authorization code must be granted again):

>>> bx24.refresh_tokens()
{'access_token': 'ANewAccessToken', 'refresh_token': 'ANewRefreshToken', ...}

Congratulations, all the preparatory work is done!

Requesting resources with an access token

A further turn for requesting Bitrix24 resources. An access token injects automatically for all methods prefixed with call_ that are mentioned in this section.

To make a single call (this example requires the following permissions: user):

>>> bx24.call('user.get', {'ID': 1})
{'result': {...}}

To make a batch call that is a few calls per request (this example requires the following permissions: user,department):

>>> bx24.call_batch({
...     'get_user': ('user.current', {}), # or 'user.current'
...     'get_department': {
...         'method': 'department.get',
...         'params': {'ID': '$result[get_user][UF_DEPARTMENT]'}
...     }
... })
{'result': {'result': {...}}}

To bind an event (this method calls event.bind under the hood):

>>> bx24.call_event_bind('OnAppUpdate', 'https://example.com/')
{'result': {...}}

To unbind an event (this method calls event.unbind under the hood):

>>> bx24.call_event_unbind('OnAppUpdate', 'https://example.com/')
{'result': {...}}

Requesting resources with a webhook code

Requesting resources with an authorization code is suitable for development of 3rd-party applications that are often quite cumbersome. However, sometimes it's enough to send a few simple calls. This is where webhooks come to action.

If only webhooks are used the minimum required configuration is as simple as the following (use user_id argument if you need to make webhook calls on behalf of another user, by default 1 is used):

>>> from pybitrix24 import Bitrix24
>>> bx24 = Bitrix24('my-subdomain.bitrix24.com')

To make an inbound webhook call (this example requires the following permissions: user):

>>> bx24.call_webhook('xxxxxxxxxxxxxxxx', 'user.get', {'ID': 1})
{'result': {...}}

To make a batch call of inbound webhooks (this example requires the following permissions: user,department):

>>> bx24.call_batch_webhook('xxxxxxxxxxxxxxxx', {
...     'get_user': ('user.current', {}), # or 'user.current'
...     'get_department': {
...         'method': 'department.get',
...         'params': {'ID': '$result[get_user][UF_DEPARTMENT]'}
...     }
... })
{'result': {'result': {...}}}

That's the end of the quick introduction. Thanks!

For more details, please, explore source code or ask me. Good luck!

Copyright and License

Copyright © 2017-2020 Yurii Rabeshko. Code released under the MIT license.

pybitrix24's People

Contributors

bedrosovayulia avatar sleshery avatar yarbshk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pybitrix24's Issues

Cannot get more than 50 items while calling *.list methods

Colleagues, kindly advise how to implement reading all items from Bitrix *.list methods. I am stuck.
Code is the following:
...
resdict = bx24.call_webhook('xxxxxxxxxxxxxxx',
"crm.activity.list",
{
'order':{"ID": "DESC" },
'filter':{"OWNER_TYPE_ID": 1,'PROVIDER_ID': 'CRM_WEBFORM'},
'select':[ "ID", "SUBJECT" ],
# 'more': True, - these are my attempts, which obviously failed
# 'next': 100
}
)

The code produces the dictionary with the following params: ... 'next': 50, 'total': 450 ...

request_tokens doesn't return anything

Hi, can you please add return result in request_tokens() method, so in program code we will obtain error code and error description to make decisions what to do when error occurs.

Thank you anyway.

Automatic way to get the access token?

I’m wondering if there is an automatic way to get the access token used by request_token() rather than to have to open a browser and copy paste the code offered after the:

bx24.resolve_authorize_endpoint()

Which gives the URL that generates the access code token thingy.

What I’ve done is to store the output of authorise_endpoint() and then fire off a requests.get() with this data (ie. the URL that is generated):

authurl = bx24.resolve_authorize_endpoint()
r = requests.get(authurl)

...but I don't know how to extract the generated code variable to be used in request_tokens() ?

ERROR_METHOD_NOT_FOUND in bx24.call_batch

Hello! Batch call from example gives error:

>>> bx24.call_batch({
...    'get_user': ['user.current', {}],
...    'get_department': {
...        'method': 'department.get',
...        'params': {'ID': '$result[get_user][UF_DEPARTMENT]'}
...    }
... })
{'result': {'result': [], 'result_error': {'get_user': {'error': 'ERROR_METHOD_NOT_FOUND', 'error_description': 'Method not found!'}, 'get_department': {'error': 'ERROR_METHOD_NOT_FOUND', 'error_description': 'Method not found!'}}, 'result_total': [], 'result_next': []}}

Method crm.activity.add raises the error

Dear colleague, please help witht the following issue:
I am trying to create the Activity in B24 using webhook. Code:

from pybitrix24 import Bitrix24
bx24 = Bitrix24('consiliummedicum.bitrix24.ru',user_id=7)
bx24.call_webhook('xxxxxxxxxxxxxx', 'crm.activity.add',
{'fields':{
"TYPE_ID": 5,
"SUBJECT": "Новое дело",
"RESPONSIBLE_ID": 7,
"COMMUNICATIONS": [ { 'VALUE':"+79832322323"}],
"OWNER_TYPE_ID": 1,
"OWNER_ID": 24657,
"COMPLETED": "N",
"DESCRIPTION": "Test создания дела"
}}
)

The result is the following:
Traceback (most recent call last):
File "Consilium_8.py", line 14, in
"DESCRIPTION": "Test создания дела"
File "C:\ProgramData\Anaconda3\lib\site-packages\pybitrix24\bitrix24.py", line 283, in call_webhook
data = self._call(url, method, None, params)
File "C:\ProgramData\Anaconda3\lib\site-packages\pybitrix24\bitrix24.py", line 198, in _call
data = request(url, query, params)
File "C:\ProgramData\Anaconda3\lib\site-packages\pybitrix24\requester.py", line 29, in request
raise PBx24RequestError("Error on request", e)
pybitrix24.exceptions.PBx24RequestError: ('Error on request', <HTTPError 400: 'Bad Request'>)

Tried a variety of changes - does not work. Though other methods (crm.activity.list, crm.activity.get, crm.activity.update) do work properly with the same webhook
Can you spot what's wrong?

Re-writing multiple fields in crm.lead

Colleagues, kindly advise the way implement the following:
Need to re-write the 'EMAIL' field in crm.lead
Ideally - update - replacement of the whole list of email values to the new one.
Maybe - in two steps: delete the whole list of values and then add a new one

the following code only adds the values to the list:
bx24.call_webhook('***********', 'crm.lead.update',
{
'ID': tmpID,
'fields': 'EMAIL':{'ID':'','VALUE_TYPE': 'WORK', 'VALUE': '[email protected]', 'TYPE_ID': 'EMAIL'},
'params': { "REGISTER_SONET_EVENT": "Y"}
}
)

And the folwing code does nothing:
bx24.call_webhook('***********', 'crm.lead.update',
{
'ID': tmpID,
'fields': 'EMAIL':[],
'params': { "REGISTER_SONET_EVENT": "Y"}
}
)

Проблема с методом bx24.obtain_tokens

Пример кода на котором получаю ошибку конвертации в json и пример кода как временно обхожу эту проблему
from pybitrix24 import Bitrix24
#from bitrix24 import *
from SetupData import *
import requests

from classProjectListSetting import ProjectSetup

client_id='код client_id'
client_secret='код client_secret'

bx24 = Bitrix24('inside.сайт с битрикс.ru', client_id=client_id, client_secret=client_secret, user_id= BITRIX24USERID)
url = bx24.build_authorization_url()

#далее эмулирую авторизацию пользователя на странице
user_agent_val = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'

Создаем сессию и указываем ему наш user-agent

session = requests.Session()

r = session.get(url, headers = {
'User-Agent': user_agent_val
})

#Хотя , мы ранее указывали наш user-agent и запрос удачно прошел и вернул нам нужный ответ, но user-agent изменился на тот , который был по умолчанию. И поэтому мы обновляем его.
session.headers.update({'User-Agent':user_agent_val})

Получаем значение _xsrf из cookies

_xsrf = session.cookies.get('_xsrf', domain=".notamedia.ru")

Осуществляем вход с помощью метода POST с указанием необходимых данных

post_request = session.post(url, {

'backUrl': url,

 'AUTH_FORM':'Y',
 'TYPE':'AUTH',
 'backurl':'/ru/auth/index.php',
 'USER_LOGIN': 'логин пользователя под которым подключаемся',
 'USER_PASSWORD': 'пароль этого пользователя' ,
 'Login':'Войти'

'_xsrf':_xsrf,

'remember':'yes',

})
res = post_request.json()
code = res['code']

сейчас в лоб прописал, что бы код работал!

bx24._access_token = res['access_token']

bx24._refresh_token = res['refresh_token']

data = bx24.obtain_tokens(code=code) # на этой строке падаем с ошибкой преобразования в json, просмотри страницы на которую получаем показывает, что мы попадаем опять на страницу авторизации пользователя
#print(data)

на этом куске получаем ошибку (requester)

def decode_response(s):
if sys.version_info.major == 2:
return json.load(s)
else:
return json.loads(s.read().decode('utf-8'))

Получение authorization_code

Добрый день!
Я начинающий разработчик Bitrix24, готовлю тиражный продукт.
Не могу разобраться, как именно я получаю authorization_code после того, как получил url из метода build_authorization_url(). Подскажите, пожалуйста, как корректно пользоваться этим методом.
Заранее благодарен.

Webhook authorization

Hello. As it is said in your readme, I don't need to authorize in any way if I use only webhooks. But I tried to write a simple one, and it keeps coming back with error 401 (unauthorized). Can you help me with that?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.