Skip to content

Commit

Permalink
Exception on error in response (#152)
Browse files Browse the repository at this point in the history
  • Loading branch information
seka19 authored and faustbrian committed Mar 2, 2018
1 parent 458419f commit 5dddda0
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions Provider.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,16 @@ protected function getUserByToken($token)
'https://api.vk.com/method/users.get?access_token='.$token.'&fields='.implode(',', $this->fields).$lang.'&v=3.0'
);

$response = json_decode($response->getBody()->getContents(), true)['response'][0];

return $response;
$contents = $response->getBody()->getContents();
$response = json_decode($contents, true);
if (!is_array($response) || !isset($response['response'][0])) {
throw new \RuntimeException(sprintf(
'Invalid JSON response from VK: %s',
$contents
));
}

return $response['response'][0];
}

/**
Expand Down

10 comments on commit 5dddda0

@sharpeenko
Copy link

@sharpeenko sharpeenko commented on 5dddda0 Mar 3, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I seems your code don't return email. Please, check it. Maybe it is vk's troubles. I wrote them about it.

User {#925 ▼
+accessTokenResponseBody: array:4 [▶]
+token: "e057eed7fc3bb1db6c4564e98636bcfb5e467c8feebdd216153a0985453e8f3445c54822c44d7dbfaaae1"
+refreshToken: null
+expiresIn: 86400
+id: 413325763
+nickname: "id413325763"
+name: "Андрей Иванов"
+email: null
+avatar: "https://pp.userapi.com/c834403/v834403560/b5528/GXQdye3Kj90.jpg"
+user: array:5 [▼
"uid" => 413325763
"first_name" => "Андрей"
"last_name" => "Иванов"
"screen_name" => "id413325763"
"photo" => "https://pp.userapi.com/c834403/v834403560/b5528/GXQdye3Kj90.jpg"
]
}

@avesgit
Copy link

@avesgit avesgit commented on 5dddda0 Mar 6, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Email is empty need fix plz

@faustbrian
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feel free to send a PR, this is an open source project.

@ilyahoilik
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sharpeenko, did you get an answer from VK Support? They most likely completely removed email field from users.get method response. I have no idea on how we can get it now.

@sharpeenko
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мария Иванова
ID приложений

6356921
6356849
6356518

ВОТ ЗДЕСЬ

$response = $this->getHttpClient()->get(
'https://api.vk.com/method/users.get?user_ids='.$toke..(',', $this->fields).$lang.'&https=1'
);

// ВИДИМО, СЮДА ПОПАДАЕТ НЕ ТО, ЧТО НАДО
$response = json_decode($response->getBody()->getContents(), true)['response'][0];

return array_merge($response, [
'email' => Arr::get($token, 'email'),
]);

ВОТ ТАКАЯ ОШИБКА

ErrorException in Provider.php line 54: Undefined index: response

in Provider.php line 54
at HandleExceptions->handleError('8', 'Undefined index: response', '/var/www/facefront.ru/vendor/socialiteproviders/vkontakte/Prov..', '54', array('token' => array('access_token' => '494418465b0a20b9ed871baceb9a760dcc6acf051d2dc20348ba6136eac91fe82762fd5380bc1542c012d', 'expires_in' => '86399', 'user_id' => '461040203', 'email' => 'ivanova@bibikini.ru'), 'lang' => '', 'response' => object(Response))) in Provider.php line 54
at Provider->getUserByToken(array('access_token' => '494418465b0a20b9ed871baceb9a760dcc6acf051d2dc20348ba6136eac91fe82762fd5380bc1542c012d', 'expires_in' => '86399', 'user_id' => '461040203', 'email' => 'ivanova@bibikini.ru')) in Provider.php line 101
at Provider->user() in SocialAuthController.php line 19

По моим предположениям, началось вчера, до этого работало корректно.
С уважением.

Агент поддержки
Дорогая Мария!

Ранее, если Вы не указывали в своём запросе параметр v (версию), он автоматически считался равным 3.0

Теперь параметр v с номером версии стал обязательным для всех запросов к API, всех, включая авторизацию.

Сервер вернет ошибку 8 на запрос, в котором не содержится этот параметр. Если методы в Вашем приложении стали возвращать ошибку invalid request на любой запрос или сломалась авторизация — укажите используемую версию API для возобновления работы.

Обратите внимание: мы не рекомендуем использовать в запросах номера версий ниже 5.0, поскольку старые версии (включая 3.0 и 4.0) в будущем перестанут поддерживаться.

Более подробно о грядущих изменениях мы писали здесь: vk.com/dev/version_update

Команда поддержки ВКонтакте

Мария Иванова
Большое спасибо! А e-mail ваше обновление отдает? Разработчик пакета для laravel сделал изменения, но вот что получается:

User {#925 ▼
+accessTokenResponseBody: array:4 [▶]
+token: "cc6ae90f2b02135b3ae9eb01a64ff6ee4433c9d055c0d45a5fda4f3fc25c9484a64558603547030ea2de4"
+refreshToken: null
+expiresIn: 86399
+id: 461040203
+nickname: "id461040203"
+name: "Мария Иванова"
+email: null
+avatar: "https://pp.userapi.com/c824203/v824203401/4dfb4/bdgd7jG2Io0.jpg"
+user: array:5 [▶]
}
3 мар 2018 в 9:00
Агент поддержки #907
Покажите запрос авторизации, пожалуйста.
3 мар 2018 в 14:16

Мария Иванова
Вы имеете ввиду метод?

protected function getUserByToken($token)
{
$lang = $this->getConfig('lang');
$lang = $lang ? '&language='.$lang : '';
$response = $this->getHttpClient()->get(
'https://api.vk.com/method/users.get?access_token='.$..(',', $this->fields).$lang.'&v=3.0'
);
$contents = $response->getBody()->getContents();
$response = json_decode($contents, true);
if (!is_array($response) || !isset($response['response'][0])) {
throw new \RuntimeException(sprintf(
'Invalid JSON response from VK: %s',
$contents
));
}
return $response['response'][0];
}
3 мар 2018 в 16:47
Агент поддержки #907
Вообще получить почту пользователя возможно при авторизации и только: https://vk.com/dev/authcode_flow_user (и месте, где надо кого-то авторизовать)

В scope, помимо остальных прав доступа, Вы указываете email, и, если пользователь согласился предоставить сайту адрес почты (и, конечно, если он вообще привязан к его странице), адрес возвращается Вам вместе с access_token.
3 мар 2018 в 22:54

Мария Иванова
То есть, таким способом, как раньше, email получить нельзя?
3 мар 2018 в 23:28
Агент поддержки #867
Ну Вы можете получать почту, которая на странице указана (если указана).
4 мар 2018 в 23:02
Это хороший ответЭто плохой ответ
Мария Иванова
Я не пойму. В том примере, что выше, у пользователя есть почта, привязанная к учетке вк.
'https://api.vk.com/method/users.get?access_token='.$..(',', $this->fields).$lang.'&v=3.0' здесь она должна возвращаться, или нет?
5 мар 2018 в 9:30
Агент поддержки #867
Привязанная – нет. Только та, что у казана в профиле в разделе "Контактная информация" (если она вообще там есть).
вчера в 22:59

@ilyahoilik
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Понятно. Значит теперь получать email нужно не через $user->email, а через $user->accessTokenResponseBody['email']

@avesgit
Copy link

@avesgit avesgit commented on 5dddda0 Mar 7, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ну так надо дяденьке написать как ему переписать его метод типо того
$user->email = $user->accessTokenResponseBody['email']
?? как то?

@ilyahoilik
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сомневаюсь, что это можно сделать не затрагивая SocialiteProviders/Manager

@avesgit
Copy link

@avesgit avesgit commented on 5dddda0 Mar 9, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Так а варианты то какие присесть на мозг саппорту вконтакта?

@sharpeenko
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Други, желаю вам удачи, сам от авторизации через соцсети откажусь, пока проект это позволяет. Одно могу предположить, что если наезжать на их саппорт, то они вряд-ли оперативно отреагируют реальной доработкой. Наверное, уж если кому и приседать на мозги, так это разработчику нашего пакета. Или форкать.

Please sign in to comment.