DoubanProvider.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /*
  3. * This file is part of the overtrue/socialite.
  4. *
  5. * (c) overtrue <i@overtrue.me>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace Overtrue\Socialite\Providers;
  11. use Overtrue\Socialite\AccessTokenInterface;
  12. use Overtrue\Socialite\ProviderInterface;
  13. use Overtrue\Socialite\User;
  14. /**
  15. * Class DoubanProvider.
  16. *
  17. * @see http://developers.douban.com/wiki/?title=oauth2 [使用 OAuth 2.0 访问豆瓣 API]
  18. */
  19. class DoubanProvider extends AbstractProvider implements ProviderInterface
  20. {
  21. /**
  22. * {@inheritdoc}.
  23. */
  24. protected function getAuthUrl($state)
  25. {
  26. return $this->buildAuthUrlFromBase('https://www.douban.com/service/auth2/auth', $state);
  27. }
  28. /**
  29. * {@inheritdoc}.
  30. */
  31. protected function getTokenUrl()
  32. {
  33. return 'https://www.douban.com/service/auth2/token';
  34. }
  35. /**
  36. * {@inheritdoc}.
  37. */
  38. protected function getUserByToken(AccessTokenInterface $token)
  39. {
  40. $response = $this->getHttpClient()->get('https://api.douban.com/v2/user/~me', [
  41. 'headers' => [
  42. 'Authorization' => 'Bearer '.$token->getToken(),
  43. ],
  44. ]);
  45. return json_decode($response->getBody()->getContents(), true);
  46. }
  47. /**
  48. * {@inheritdoc}.
  49. */
  50. protected function mapUserToObject(array $user)
  51. {
  52. return new User([
  53. 'id' => $this->arrayItem($user, 'id'),
  54. 'nickname' => $this->arrayItem($user, 'name'),
  55. 'name' => $this->arrayItem($user, 'name'),
  56. 'avatar' => $this->arrayItem($user, 'large_avatar'),
  57. 'email' => null,
  58. ]);
  59. }
  60. /**
  61. * {@inheritdoc}.
  62. */
  63. protected function getTokenFields($code)
  64. {
  65. return parent::getTokenFields($code) + ['grant_type' => 'authorization_code'];
  66. }
  67. /**
  68. * {@inheritdoc}.
  69. */
  70. public function getAccessToken($code)
  71. {
  72. $response = $this->getHttpClient()->post($this->getTokenUrl(), [
  73. 'form_params' => $this->getTokenFields($code),
  74. ]);
  75. return $this->parseAccessToken($response->getBody()->getContents());
  76. }
  77. }