ServiceProvider.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /*
  3. * This file is part of the overtrue/wechat.
  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 EasyWeChat\OfficialAccount\OAuth;
  11. use Overtrue\Socialite\SocialiteManager as Socialite;
  12. use Pimple\Container;
  13. use Pimple\ServiceProviderInterface;
  14. /**
  15. * Class ServiceProvider.
  16. *
  17. * @author overtrue <i@overtrue.me>
  18. */
  19. class ServiceProvider implements ServiceProviderInterface
  20. {
  21. /**
  22. * {@inheritdoc}.
  23. */
  24. public function register(Container $app)
  25. {
  26. $app['oauth'] = function ($app) {
  27. $socialite = (new Socialite([
  28. 'wechat' => [
  29. 'client_id' => $app['config']['app_id'],
  30. 'client_secret' => $app['config']['secret'],
  31. 'redirect' => $this->prepareCallbackUrl($app),
  32. ],
  33. ], $app['request']))->driver('wechat');
  34. $scopes = (array) $app['config']->get('oauth.scopes', ['snsapi_userinfo']);
  35. if (!empty($scopes)) {
  36. $socialite->scopes($scopes);
  37. }
  38. return $socialite;
  39. };
  40. }
  41. /**
  42. * Prepare the OAuth callback url for wechat.
  43. *
  44. * @param Container $app
  45. *
  46. * @return string
  47. */
  48. private function prepareCallbackUrl($app)
  49. {
  50. $callback = $app['config']->get('oauth.callback');
  51. if (0 === stripos($callback, 'http')) {
  52. return $callback;
  53. }
  54. $baseUrl = $app['request']->getSchemeAndHttpHost();
  55. return $baseUrl.'/'.ltrim($callback, '/');
  56. }
  57. }