海南旅游SAAS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.4 KiB

  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\Agent;
  5. use App\Models\Channel;
  6. use App\Models\User;
  7. use App\Models\UserChannel;
  8. use EasyWeChat\Factory;
  9. use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
  10. use Illuminate\Support\Facades\Cache;
  11. /**
  12. * 小程序登录
  13. * Class Login
  14. * @package App\Http\Controllers\Api
  15. */
  16. class LoginController extends Controller
  17. {
  18. public function login()
  19. {
  20. $appid = request()->header('appid');
  21. if (!$appid) {
  22. return $this->error('appid参数缺失');
  23. }
  24. $agent = Agent::query()->firstWhere('appid', $appid); //代理商数据
  25. if (!$agent) {
  26. return $this->error('找不到该appid相关记录');
  27. }
  28. $code = request()->input('code');
  29. if (!$code) {
  30. return $this->error('code参数缺失');
  31. }
  32. $config = config('wechat.mini_program.default');
  33. $config = array_merge($config, [
  34. 'app_id' => $agent['appid'],
  35. 'secret' => $agent['appsecret'],
  36. ]);
  37. $app = Factory::miniProgram($config);
  38. try {
  39. $res = $app->auth->session($code);
  40. if (!empty($res['errcode']) || empty($res['openid']) && empty($res['unionid'])) {
  41. $msg = $res['errmsg'] ?? '登录失败';
  42. return $this->error($msg);
  43. }
  44. if (empty($res['session_key'])) {
  45. return $this->error('获取session_key失败');
  46. }
  47. } catch (InvalidConfigException $e) {
  48. return $this->error($e->getMessage());
  49. }
  50. // TODO 登录部分待优化
  51. $userModel = User::query()->firstOrCreate([
  52. 'openid' => $res['openid'] ?? '',
  53. 'agent_id' => $agent->id,
  54. ], [
  55. 'unionid' => $res['unionid'] ?? '',
  56. ]);
  57. //保存session_key
  58. Cache::put('session_key_' . $userModel->id, $res['session_key']);
  59. //如果是新增,插入初始数据
  60. if ($userModel->wasRecentlyCreated) {
  61. $channel_ids = UserChannel::where('user_id', $userModel->id)->first();
  62. //如果不存在则存入初始数据
  63. if (!$channel_ids) {
  64. $channel_ids = Channel::where([
  65. ['agent_id', '=', $this->agent_id],
  66. ['pid', '<>', 0],
  67. ])
  68. ->orderBy('id')
  69. ->limit(8)
  70. ->pluck('id')
  71. ->toArray();
  72. //存入user_channel
  73. UserChannel::where('user_id', $userModel->id)
  74. ->insert([
  75. 'user_id' => $userModel->id,
  76. 'channels' => json_encode($channel_ids)
  77. ]);
  78. }
  79. }
  80. $token_key = md5($userModel->id . env('APP_KEY'));
  81. Cache::put($token_key, $userModel->id);
  82. // 测试代码结束
  83. $userModel->token = $token_key;
  84. return $this->success($userModel);
  85. }
  86. }