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.

66 lines
1.8 KiB

  1. <?php
  2. namespace App\Service\v3\Implementations;
  3. use App\Constants\v3\ErrorCode;
  4. use App\Constants\v3\SsdbKeys;
  5. use App\Exception\ErrorCodeException;
  6. use App\Model\v3\User;
  7. use App\TaskWorker\SSDBTask;
  8. use EasyWeChat\Factory;
  9. use Hyperf\Guzzle\CoroutineHandler;
  10. use Hyperf\Utils\ApplicationContext;
  11. use Hashids\Hashids;
  12. class WxLoginService implements \App\Service\v3\Interfaces\WxLoginServiceInterface
  13. {
  14. public function do($code)
  15. {
  16. // 微信登录
  17. $config = config('applet');
  18. $app = Factory::miniProgram($config);
  19. $app['guzzle_handler'] = CoroutineHandler::class;
  20. $result = $app->auth->session($code);
  21. if (isset($result['errcode'])&&$result['errcode'] != 0) {
  22. throw new ErrorCodeException(ErrorCode::WXLOGIN_INVALID_CODE);
  23. }
  24. // 更新或者插入用户数据
  25. $user = User::query()->firstOrCreate(
  26. ['openid' => $result['openid']],
  27. ['unionid' => $result['unionid']]
  28. )->toArray();
  29. // 登录成功
  30. $hash = ApplicationContext::getContainer()->get(Hashids::class);
  31. $hashIds = $hash->encode((int)$user['id']);
  32. $user['user_token'] = $hashIds;
  33. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  34. $ssdb->exec('setnx', $hashIds, 1);
  35. $ssdb->exec('expire', $hashIds, config('auth.user.expire_time'));
  36. $return = array_merge($user, $result);
  37. $kvs = [];
  38. foreach ($return as $k => $v) {
  39. $kvs[] = $k;
  40. $kvs[] = $v;
  41. }
  42. $ssdb->exec('multi_hset', SsdbKeys::USER_INFO.$user['id'], $kvs);
  43. return $return;
  44. }
  45. public function check($userId)
  46. {
  47. // TODO: Implement check() method.
  48. }
  49. public function undo($userId)
  50. {
  51. // TODO: Implement undo() method.
  52. }
  53. }