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

73 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 EasyWeChat\Kernel\Exceptions\InvalidConfigException;
  8. use Illuminate\Support\Facades\Cache;
  9. /**
  10. * 小程序登录
  11. * Class Login
  12. * @package App\Http\Controllers\Api
  13. */
  14. class LoginController extends Controller
  15. {
  16. public function login()
  17. {
  18. $appid = request()->header('appid');
  19. if (!$appid) {
  20. return $this->error('appid参数缺失');
  21. }
  22. $agent = Agent::query()->firstWhere('appid', $appid); //代理商数据
  23. if (!$agent) {
  24. return $this->error('找不到该appid相关记录');
  25. }
  26. $code = request()->input('code');
  27. if (!$code) {
  28. return $this->error('code参数缺失');
  29. }
  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. try {
  37. $res = $app->auth->session($code);
  38. if (!empty($res['errcode']) || empty($res['openid']) && empty($res['unionid'])) {
  39. $msg = $res['errmsg'] ?? '登录失败';
  40. return $this->error($msg);
  41. }
  42. } catch (InvalidConfigException $e) {
  43. return $this->error($e->getMessage());
  44. }
  45. // TODO 登录部分待优化
  46. $userModel = new User();
  47. $userModel->firstOrCreate([
  48. 'openid' => $res['openid'] ?? '',
  49. 'unionid' => $res['unionid'] ?? '',
  50. 'agent_id' => $agent->id,
  51. ], [
  52. 'nickname' => substr(session_create_id(), 0, 10),
  53. 'avatar' => '/static/images/avatar.png'
  54. ]);
  55. //保存session_key
  56. Cache::put('session_key_' . $userModel->id, $res['session_key']);
  57. // TODO 用于测试
  58. $token_key = md5($userModel->id);
  59. Cache::put($token_key, 1);
  60. Cache::put($agent['appid'], $agent['id']);
  61. // 测试代码结束
  62. return $this->success(['token' => md5($userModel->id)]);
  63. }
  64. }