ThirdPartyController.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace api\modules\v1\controllers;
  3. use Yii;
  4. use yii\authclient\OAuth2;
  5. use yii\authclient\clients\Facebook;
  6. use api\controllers\OnAuthController;
  7. use common\helpers\ResultHelper;
  8. /**
  9. * 第三方授权登录
  10. *
  11. * Class ThirdPartyController
  12. * @package api\modules\v1\controllers
  13. * @author jianyan74 <751393839@qq.com>
  14. */
  15. class ThirdPartyController extends OnAuthController
  16. {
  17. public $modelClass = '';
  18. /**
  19. * 不用进行登录验证的方法
  20. * 例如: ['index', 'update', 'create', 'view', 'delete']
  21. * 默认全部需要验证
  22. *
  23. * @var array
  24. */
  25. protected $authOptional = ['auth', 'code'];
  26. /**
  27. * @var array
  28. */
  29. protected $_clients = [];
  30. /**
  31. * @return void
  32. * @throws \yii\base\InvalidConfigException
  33. */
  34. public function init()
  35. {
  36. parent::init();
  37. /** @var Facebook $oauthClient */
  38. $oauthClient = new Facebook();
  39. $oauthClient->clientId = '';
  40. $oauthClient->clientSecret = '';
  41. // 获取授权内容
  42. $oauthClient->attributeNames = [
  43. // 'id',
  44. 'name',
  45. 'email',
  46. // 'first_name',
  47. // 'last_name',
  48. ];
  49. $this->_clients['facebook'] = $oauthClient;
  50. }
  51. /**
  52. * @return array
  53. */
  54. public function actionAuth($type)
  55. {
  56. /** @var OAuth2|Facebook $oauthClient */
  57. if (empty($oauthClient = $this->_clients[$type])) {
  58. return ResultHelper::json(422, '暂不支持该登录类型');
  59. }
  60. return [
  61. 'url' => $oauthClient->buildAuthUrl(),
  62. ];
  63. }
  64. /**
  65. * @param $type
  66. * @param $code
  67. * @return array|mixed|void
  68. * @throws \yii\web\HttpException
  69. */
  70. public function actionCode($type, $code)
  71. {
  72. /** @var OAuth2|Facebook $oauthClient */
  73. if (empty($oauthClient = $this->_clients[$type])) {
  74. return ResultHelper::json(422, '暂不支持该登录类型');
  75. }
  76. $oauthClient->fetchAccessToken($code);
  77. // 获取登录的用户信息
  78. $attributes = $oauthClient->getUserAttributes();
  79. // TODO Login
  80. }
  81. }
粤ICP备19079148号