Skip to content

Commit

Permalink
Get access_token by ‘code’ (from OAuth)
Browse files Browse the repository at this point in the history
  • Loading branch information
tezmen authored and python273 committed Dec 14, 2018
1 parent 79a6d06 commit a0a46e0
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* [Отправка запросов к API (VkApi)](./simple_example.py)
* [Загрузка фото (VKUpload)](./upload_photo.py)
* [Обработка двухфакторной аутентификации](./two_factor_auth.py)
* [Получение access_token из сode после OAuth авторизации](./auth_by_code.py)
* [Обработка капчи](./captcha_handle.py)
* [Работа с пользовательским Long Poll (VkLongpoll)](./longpoll.py)
* [Работа с Bots Long Poll (VkBotLongpoll)](./bot_longpoll.py)
Expand Down
26 changes: 26 additions & 0 deletions examples/auth_by_code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-
from vk_api import vk_api


def main():
""" Пример получения access_token из сode после OAuth авторизации на сайте """

code = '18dczc1337a63427fa'
redirect_url = 'http://example.com'
app = 000000
secret = 'dGbpoJdqNuMlGDECgO9I'

vk_session = vk_api.VkApi(app_id=app, client_secret=secret)

try:
vk_session.code_auth(code, redirect_url)
except vk_api.AuthError as error_msg:
print(error_msg)
return

print(vk_session.token['user_id'])
print(vk_session.token['access_token'])


if __name__ == '__main__':
main()
20 changes: 20 additions & 0 deletions vk_api/vk_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,26 @@ def server_auth(self):
else:
self.token = response

def code_auth(self, code, redirect_url):
""" Получение access_token из code """
values = {
'client_id': self.app_id,
'client_secret': self.client_secret,
'v': self.api_version,
'redirect_uri': redirect_url,
'code': code,
}

response = self.http.post(
'https://oauth.vk.com/access_token', values
).json()

if 'error' in response:
raise AuthError(response['error_description'])
else:
self.token = response
return response

def _check_token(self):
""" Проверка access_token юзера на валидность """

Expand Down

0 comments on commit a0a46e0

Please sign in to comment.