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.

74 lines
2.2 KiB

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