Passport.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\utils\Easywechat\MiniAppService;
  5. use think\Cache;
  6. /**
  7. * 通行证
  8. */
  9. class Passport extends Api
  10. {
  11. protected $noNeedLogin = ['loginWxMini', 'loginWxMiniPhone'];
  12. protected $noNeedRight = '*';
  13. protected $model = null;
  14. public function _initialize()
  15. {
  16. parent::_initialize();
  17. }
  18. /**
  19. * 微信小程序手机号授权
  20. * @return void
  21. */
  22. public function loginWxMiniPhone()
  23. {
  24. // 获取参数
  25. $params = $this->request->param();
  26. if (empty($params['code'])) {
  27. $this->error('The code is required.');
  28. }
  29. $wxMiniApp = new MiniAppService();
  30. $wx = $wxMiniApp->getUserPhone($params['code']);
  31. if (empty($wx['phone_info']['purePhoneNumber'])) {
  32. $this->error('手机号授权失败.', $wx);
  33. }
  34. $mobile = $wx['phone_info']['purePhoneNumber'];
  35. $extend = [];
  36. if (!empty($params['openid']) && $wxInfo = Cache::get($params['openid'])){
  37. $extend['mini_openid'] = $wxInfo['openid'] ?? '';
  38. $extend['mini_sessionkey'] = $wxInfo['session_key'] ?? '';
  39. }
  40. // 校验手机号登录信息
  41. list($exists, $user_id) = UserModel::checkExists('', $mobile);
  42. if (!$exists) {
  43. // 手机号不存在 创建账号
  44. $ret = $this->auth->register('1', '1', '', $mobile, $extend);
  45. if (!$ret) {
  46. $this->error("注册失败!");
  47. }
  48. $user_id = $this->auth->id;
  49. }
  50. // 写入登录Cookies和Token
  51. if (!$this->auth->direct($user_id,$extend)) {
  52. $this->error($this->auth->getError());
  53. }
  54. $userInfo = $this->auth->getUserinfo();
  55. $result = [
  56. 'token' => $userInfo['token'],
  57. // 'userInfo' => $userInfo
  58. ];
  59. $this->success('登录成功', $result);
  60. }
  61. /**
  62. * 微信小程序授权
  63. *
  64. * @return void
  65. */
  66. public function loginWxMini()
  67. {
  68. // 获取参数
  69. $params = $this->request->param();
  70. if (empty($params['code'])) {
  71. $this->error('The code is required.');
  72. }
  73. $wxMiniApp = new MiniAppService();
  74. $res = $wxMiniApp->login($params['code']);
  75. if (empty($res['openid'])) {
  76. $this->error('授权失败,请重试');
  77. }
  78. $sign = md5($res['openid']);
  79. Cache::set($sign, $res, 3600);
  80. $this->success('success', [
  81. 'openid' => $sign
  82. ]);
  83. }
  84. }