WechatUserService.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LikeShop100%开源免费商用电商系统
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | 商业版本务必购买商业授权,以免引起法律纠纷
  8. // | 禁止对系统程序代码以任何目的,任何形式的再发布
  9. // | Gitee下载:https://gitee.com/likeshop_gitee/likeshop
  10. // | 访问官网:https://www.likemarket.net
  11. // | 访问社区:https://home.likemarket.net
  12. // | 访问手册:http://doc.likemarket.net
  13. // | 微信公众号:好象科技
  14. // | 好象科技开发团队 版权所有 拥有最终解释权
  15. // +----------------------------------------------------------------------
  16. // | Author: LikeShopTeam
  17. // +----------------------------------------------------------------------
  18. namespace app\shopapi\service;
  19. use app\common\{logic\UserLogic,
  20. model\User,
  21. model\UserAuth,
  22. enum\UserTerminalEnum,
  23. service\ConfigService,
  24. service\storage\Driver as StorageDriver,
  25. Logic\DistributionLogic};
  26. use think\Exception;
  27. /**
  28. * 用户功能类(主要微信登录后创建和更新用户)
  29. * Class UserService
  30. * @package app\shopapi\service
  31. */
  32. class WechatUserService
  33. {
  34. protected int $terminal = UserTerminalEnum::WECHAT_MMP;
  35. protected array $response = [];
  36. protected ?string $code = null;
  37. protected ?string $openid = null;
  38. protected ?string $unionid = null;
  39. protected ?string $nickname = null;
  40. protected ?string $headimgurl = null;
  41. protected User $user;
  42. public function __construct(array $response,int $terminal)
  43. {
  44. $this->terminal = $terminal;
  45. $this->setParams($response);
  46. }
  47. /**
  48. * @notes 设置微信返回的用户信息
  49. * @param $response
  50. * @author cjhao
  51. * @date 2021/8/2 11:49
  52. */
  53. private function setParams($response):void
  54. {
  55. $this->response = $response;
  56. $this->openid = $response['openid'];
  57. $this->unionid = $response['unionid'] ?? '';
  58. $this->nickname = $response['nickname'] ?? '';
  59. $this->headimgurl = $response['headimgurl'] ?? '';
  60. }
  61. /**
  62. * @notes 根据微信opendid或unionid获取用户信息
  63. * @author cjhao
  64. * @date 2021/8/2 11:06
  65. */
  66. public function getResopnseByUserInfo($source = ''):self
  67. {
  68. $user = User::hasWhere('userAuth',['openid'=>$this->openid],'id,sn,nickname,avatar,mobile,disable,is_new_user')
  69. ->findOrEmpty();
  70. /*
  71. * 用户没有该端记录,且微信返回了unionid,则用unionid找该用户
  72. * 如果是小程序的静默登录,只按open_id找用户信息,如果没有用户信息,返回空,前端重新调用授权登录接口。
  73. */
  74. if($user->isEmpty() && $this->unionid && 'silent' != $source ){
  75. $user = User::hasWhere('userAuth',['unionid'=>$this->unionid],'id,sn,nickname,avatar,mobile,disable,is_new_user')
  76. ->findOrEmpty();
  77. }
  78. $this->user = $user;
  79. return $this;
  80. }
  81. /**
  82. * @notes
  83. * @param bool $isCheck 是否验证账号是否可用
  84. * @return array
  85. * @throws Exception
  86. * @author cjhao
  87. * @date 2021/8/3 11:42
  88. */
  89. public function getUserInfo($isCheck = true):array
  90. {
  91. if(!$this->user->isEmpty() && $isCheck){
  92. $this->checkAccount();
  93. }
  94. if(!$this->user->isEmpty()){
  95. $this->getToken();
  96. }
  97. return $this->user->toArray();
  98. }
  99. /**
  100. * @notes 验证账号是否可用
  101. * @return bool|string
  102. * @author cjhao
  103. * @date 2021/8/2 15:07
  104. */
  105. private function checkAccount()
  106. {
  107. if($this->user->disable){
  108. throw new Exception('您的账号被冻结,请联系客服。');
  109. }
  110. }
  111. /**
  112. * @notes 创建用户
  113. * @throws Exception
  114. * @author cjhao
  115. * @date 2021/8/2 16:26
  116. */
  117. private function createUser():void
  118. {
  119. // 获取存储引擎
  120. $config = [
  121. 'default' => ConfigService::get('storage', 'default', 'local'),
  122. 'engine' => ConfigService::get('storage')
  123. ];
  124. //设置头像
  125. if (empty($this->headimgurl)) {
  126. //默认头像
  127. $avatar = ConfigService::get('config', 'default_avatar', '');
  128. } else {
  129. if ($config['default'] == 'local') {
  130. $file_name = md5($this->openid . time()) . '.jpeg';
  131. $avatar = download_file($this->headimgurl, 'uploads/user/avatar/', $file_name);
  132. } else {
  133. $avatar = 'uploads/user/avatar/' . md5($this->openid . time()) . '.jpeg';
  134. $StorageDriver = new StorageDriver($config);
  135. if (!$StorageDriver->fetch($this->headimgurl, $avatar)) {
  136. throw new Exception( '头像保存失败:'. $StorageDriver->getError());
  137. }
  138. }
  139. }
  140. //todo 后续补充用户资料
  141. $this->user->nickname = $this->nickname;
  142. $this->user->sn = create_user_sn();
  143. $this->user->avatar = $avatar;
  144. $this->user->code = generate_code();
  145. $this->user->register_source = $this->terminal;
  146. $this->user->is_new_user = 1;
  147. $this->user->is_register_award = 0;
  148. if (empty($this->nickname)) {
  149. $this->user->nickname = '用户'. $this->user->sn;
  150. }
  151. $this->user->save();
  152. (new UserAuth)->save([
  153. 'user_id' => $this->user->id,
  154. 'openid' => $this->openid,
  155. 'unionid' => $this->unionid,
  156. 'terminal' => $this->terminal,
  157. ]);
  158. // 注册奖励
  159. UserLogic::registerAward($this->user->id);
  160. //消息通知
  161. //Hook::listen('notice', ['user_id' => $user_id, 'scene' => NoticeSetting::REGISTER_SUCCESS_NOTICE]);
  162. }
  163. /**
  164. * 更新用户信息(如果该端没授权信息,会重新写入一条该端的授权信息)
  165. * @param $response
  166. * @param $client
  167. * @param $user_id
  168. * @return array|\PDOStatement|string|\think\Model|null
  169. */
  170. private function updateUser():void
  171. {
  172. // $this->user->nickname = $this->nickname;
  173. //无头像需要更新头像
  174. if (empty($this->user->avatar)) {
  175. // 获取存储引擎
  176. $config = [
  177. 'default' => ConfigService::get('storage', 'default', 'local'),
  178. 'engine' => ConfigService::get('storage_engine')
  179. ];
  180. if ($config['default'] == 'local') {
  181. $file_name = md5($this->openid . time()) . '.jpeg';
  182. $avatar = download_file($this->headimgurl, 'uploads/user/avatar/', $file_name);
  183. } else {
  184. $avatar = 'uploads/user/avatar/' . md5($this->openid . time()) . '.jpeg';
  185. $StorageDriver = new StorageDriver($config);
  186. if (!$StorageDriver->fetch($this->headimgurl, $avatar)) {
  187. throw new Exception( '头像保存失败:'. $StorageDriver->getError());
  188. }
  189. }
  190. $this->user->avatar = $avatar;
  191. }
  192. $this->user->save();
  193. $userAuth = UserAuth::where(['user_id'=>$this->user->id,'openid'=>$this->openid])->findOrEmpty();
  194. //无该端信息,新增一条
  195. if($userAuth->isEmpty()){
  196. $userAuth->user_id = $this->user->id;
  197. $userAuth->openid = $this->openid;
  198. $userAuth->unionid = $this->unionid;
  199. $userAuth->terminal= $this->terminal;
  200. $userAuth->save();
  201. }
  202. }
  203. /**
  204. * @notes 获取token
  205. * @throws \think\db\exception\DataNotFoundException
  206. * @throws \think\db\exception\DbException
  207. * @throws \think\db\exception\ModelNotFoundException
  208. * @author cjhao
  209. * @date 2021/8/2 16:45
  210. */
  211. private function getToken()
  212. {
  213. $user = UserTokenService::setToken($this->user->id,$this->terminal);
  214. $this->user->token = $user['token'];
  215. }
  216. /**
  217. * @notes 用户授权登录,
  218. * 如果用户不存在,创建用户;用户存在,更新用户信息,并检查该端信息是否需要写入
  219. * @return WechatUserService
  220. * @throws Exception
  221. * @author cjhao
  222. * @date 2021/8/2 16:35
  223. */
  224. public function authUserLogin():self
  225. {
  226. if($this->user->isEmpty()){
  227. $this->createUser();
  228. }else{
  229. $this->updateUser();
  230. }
  231. return $this;
  232. }
  233. }