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

79 lines
2.0 KiB

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