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

76 lines
1.9 KiB

4 years ago
  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. if (empty($res['session_key'])) {
  43. $this->error('获取session_key失败');
  44. }
  45. } catch (InvalidConfigException $e) {
  46. return $this->error($e->getMessage());
  47. }
  48. // TODO 登录部分待优化
  49. $userModel = User::firstOrCreate([
  50. 'openid' => $res['openid'] ?? '',
  51. 'unionid' => $res['unionid'] ?? '',
  52. 'agent_id' => $agent->id,
  53. ], [
  54. //'nickname' => uniqid(), 根据前端判断,不设置默认值
  55. //'avatar' => '/static/images/avatar.png'
  56. ]);
  57. //保存session_key
  58. Cache::put('session_key_' . $userModel->id, $res['session_key']);
  59. //TODO 存入初始化数据 user_channel
  60. $token_key = md5($userModel->id . env('APP_KEY'));
  61. Cache::put($token_key, $userModel->id);
  62. // 测试代码结束
  63. $userModel->token = $token_key;
  64. return $this->success($userModel);
  65. }
  66. }