Skip to content

Commit a0a46e0

Browse files
tezmenpython273
authored andcommitted
Get access_token by ‘code’ (from OAuth)
1 parent 79a6d06 commit a0a46e0

3 files changed

Lines changed: 47 additions & 0 deletions

File tree

examples/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
* [Отправка запросов к API (VkApi)](./simple_example.py)
77
* [Загрузка фото (VKUpload)](./upload_photo.py)
88
* [Обработка двухфакторной аутентификации](./two_factor_auth.py)
9+
* [Получение access_token из сode после OAuth авторизации](./auth_by_code.py)
910
* [Обработка капчи](./captcha_handle.py)
1011
* [Работа с пользовательским Long Poll (VkLongpoll)](./longpoll.py)
1112
* [Работа с Bots Long Poll (VkBotLongpoll)](./bot_longpoll.py)

examples/auth_by_code.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# -*- coding: utf-8 -*-
2+
from vk_api import vk_api
3+
4+
5+
def main():
6+
""" Пример получения access_token из сode после OAuth авторизации на сайте """
7+
8+
code = '18dczc1337a63427fa'
9+
redirect_url = 'http://example.com'
10+
app = 000000
11+
secret = 'dGbpoJdqNuMlGDECgO9I'
12+
13+
vk_session = vk_api.VkApi(app_id=app, client_secret=secret)
14+
15+
try:
16+
vk_session.code_auth(code, redirect_url)
17+
except vk_api.AuthError as error_msg:
18+
print(error_msg)
19+
return
20+
21+
print(vk_session.token['user_id'])
22+
print(vk_session.token['access_token'])
23+
24+
25+
if __name__ == '__main__':
26+
main()

vk_api/vk_api.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,26 @@ def server_auth(self):
472472
else:
473473
self.token = response
474474

475+
def code_auth(self, code, redirect_url):
476+
""" Получение access_token из code """
477+
values = {
478+
'client_id': self.app_id,
479+
'client_secret': self.client_secret,
480+
'v': self.api_version,
481+
'redirect_uri': redirect_url,
482+
'code': code,
483+
}
484+
485+
response = self.http.post(
486+
'https://oauth.vk.com/access_token', values
487+
).json()
488+
489+
if 'error' in response:
490+
raise AuthError(response['error_description'])
491+
else:
492+
self.token = response
493+
return response
494+
475495
def _check_token(self):
476496
""" Проверка access_token юзера на валидность """
477497

0 commit comments

Comments
 (0)