ExtensionWechatUserEntity.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. declare(strict_types=1);
  3. namespace SixShop\Wechat\Entity;
  4. use app\model\User;
  5. use SixShop\Core\Entity\BaseEntity;
  6. use SixShop\Wechat\ChineseUtil;
  7. use SixShop\Wechat\Service\MiniApp;
  8. use think\facade\Event;
  9. /**
  10. * @mixin \SixShop\Wechat\Model\ExtensionWechatUserModel
  11. */
  12. class ExtensionWechatUserEntity extends BaseEntity
  13. {
  14. public function getUserID(string $code, string $appID = null): int
  15. {
  16. $miniApp = app()->make(MiniApp::class, [$appID]);
  17. $utils = $miniApp->getUtils();
  18. $response = $utils->codeToSession($code);
  19. $appID = $miniApp->getConfig()->get('app_id');
  20. $wechatUser = $this->where([
  21. 'openid' => $response['openid'],
  22. 'appid' => $appID
  23. ])->findOrEmpty();
  24. if ($wechatUser->isEmpty()) {
  25. $wechatUser->openid = $response['openid'];
  26. $wechatUser->appid = $appID;
  27. $wechatUser->nickname = '匿名用户';
  28. $wechatUser->user_id = $this->createNewUser();
  29. }
  30. $wechatUser->save(['session_key' => $response['session_key']]);
  31. return $wechatUser->user_id;
  32. }
  33. private function createNewUser(): int
  34. {
  35. $timestamp = time();
  36. $randomStr = bin2hex(random_bytes(3));
  37. $user = new User();
  38. $user->username = "wx_{$timestamp}_{$randomStr}";
  39. $user->nickname = ChineseUtil::randomChineseName();
  40. Event::trigger('beforeCreateUser', [$user, 'wechat' ]);
  41. $user->save();
  42. return $user->id;
  43. }
  44. public function getPhoneNumber(string $code)
  45. {
  46. $miniApp = app()->make(MiniApp::class);
  47. $response = $miniApp->getClient()->postJson('/wxa/business/getuserphonenumber', [
  48. 'code' => $code,
  49. ]);
  50. $content = $response->getContent();
  51. $data = json_decode($content, true);
  52. return $data['phone_info'];
  53. }
  54. }