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

64 lines
1.7 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 Illuminate\Support\Facades\Cache;
  7. use Illuminate\Support\Facades\Http;
  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. $base_url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=JSCODE&grant_type=authorization_code';
  31. $url = sprintf($base_url, $agent['appid'], $agent['appsecret']);
  32. $res = Http::get($url)->json();
  33. if (!array_key_exists('errcode', $res) || $res['errcode'] != 0 || empty($res['openid'])) {
  34. $msg = $res['errcode'] ? $res['errcode'] . ': ' : '';
  35. $msg .= $res['errmsg'] ?? '登录失败';
  36. return $this->error($msg); //TODO 测试时注释掉
  37. }
  38. // TODO 登录部分待优化
  39. $userModel = new User();
  40. $userModel->firstOrCreate([
  41. 'openid' => $res['openid'],
  42. 'unionid' => $res['unionid'],
  43. 'agent_id' => $agent_id
  44. ], [
  45. 'nickname' => '未设置昵称',
  46. 'avatar' => '/static/images/avatar.png'
  47. ]);
  48. // TODO 用于测试
  49. $token_key = md5($userModel->id);
  50. Cache::put($token_key, 1);
  51. Cache::put($agent['appid'], $agent['id']);
  52. // 测试代码结束
  53. return $this->success(['token' => md5($userModel->id)]);
  54. }
  55. }