海南旅游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.

71 lines
1.8 KiB

  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\Agent;
  5. use App\Models\User;
  6. use EasyWeChat\Factory;
  7. use Illuminate\Support\Facades\Cache;
  8. /**
  9. * 小程序登录
  10. * Class Login
  11. * @package App\Http\Controllers\Api
  12. */
  13. class LoginController extends Controller
  14. {
  15. public function login()
  16. {
  17. $appid = request()->header('appid');
  18. if (!$appid) {
  19. return $this->error('appid缺失');
  20. }
  21. $agent_id = Agent::where('appid', $appid)->value('id');
  22. if (!$agent_id) {
  23. return $this->error('appid无效');
  24. }
  25. $code = request()->input('code');
  26. if (!$code) {
  27. return $this->error('Invalid code!');
  28. }
  29. $agent = Agent::select(['id', 'appid', 'appsecret'])->find($agent_id); //代理商数据
  30. $config = config('wechat.mini_program.default');
  31. $config = array_merge($config, [
  32. 'app_id' => $agent['appid'],
  33. 'secret' => $agent['appsecret'],
  34. ]);
  35. $app = Factory::miniProgram($config);
  36. $res = $app->auth->session($code);
  37. if (!isset($res['errcode']) || $res['errcode'] != 0 || empty($res['openid']) || empty($res['unionid'])) {
  38. $msg = $res['errcode'] ? $res['errcode'] . ': ' : '';
  39. $msg .= $res['errmsg'] ?? '登录失败';
  40. return $this->error($msg);
  41. }
  42. // TODO 登录部分待优化
  43. $userModel = new User();
  44. $userModel->firstOrCreate([
  45. 'openid' => $res['openid'],
  46. 'unionid' => $res['unionid'],
  47. 'agent_id' => $agent_id
  48. ], [
  49. 'nickname' => '未设置昵称',
  50. 'avatar' => '/static/images/avatar.png'
  51. ]);
  52. //保存session_key
  53. Cache::put('session_key_' . $userModel->id, $res['session_key']);
  54. // TODO 用于测试
  55. $token_key = md5($userModel->id);
  56. Cache::put($token_key, 1);
  57. Cache::put($agent['appid'], $agent['id']);
  58. // 测试代码结束
  59. return $this->success(['token' => md5($userModel->id)]);
  60. }
  61. }