WechatUserRepository.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2024 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\common\repositories\wechat;
  12. use app\common\dao\wechat\WechatUserDao;
  13. use app\common\repositories\article\ArticleRepository;
  14. use app\common\repositories\BaseRepository;
  15. use app\common\repositories\user\UserRepository;
  16. use crmeb\jobs\SendNewsJob;
  17. use crmeb\services\MiniProgramService;
  18. use crmeb\services\WechatUserGroupService;
  19. use crmeb\services\WechatUserTagService;
  20. use FormBuilder\Exception\FormBuilderException;
  21. use FormBuilder\Factory\Elm;
  22. use FormBuilder\Form;
  23. use think\db\exception\DataNotFoundException;
  24. use think\db\exception\DbException;
  25. use think\db\exception\ModelNotFoundException;
  26. use think\Exception;
  27. use think\exception\ValidateException;
  28. use think\facade\Cache;
  29. use think\facade\Db;
  30. use think\facade\Queue;
  31. use think\facade\Route;
  32. /**
  33. * Class WechatUserRepository
  34. * @package app\common\repositories\wechat
  35. * @author xaboy
  36. * @day 2020-04-28
  37. * @mixin WechatUserDao
  38. */
  39. class WechatUserRepository extends BaseRepository
  40. {
  41. /**
  42. * WechatUserRepository constructor.
  43. * @param WechatUserDao $dao
  44. */
  45. public function __construct(WechatUserDao $dao)
  46. {
  47. $this->dao = $dao;
  48. }
  49. /**
  50. * 获取小程序用户,是否需要绑定手机号
  51. * @param $code
  52. * @return array
  53. * @author Qinii
  54. * @day 2023/11/9
  55. */
  56. public function mpLoginType($code, $spread)
  57. {
  58. if (!$code )
  59. throw new ValidateException('授权失败,请获取code参数');
  60. $userInfoCong = Cache::get('eb_api_code_' . $code);
  61. if (!$userInfoCong) {
  62. try {
  63. $userInfoCong = MiniProgramService::create()->getUserInfo($code);
  64. Cache::set('eb_api_code_' . $code, $userInfoCong, 86400);
  65. } catch (Exception $e) {
  66. throw new ValidateException('获取session_key失败,请检查您的配置!'.$e->getMessage());
  67. }
  68. }
  69. $bindPhone = systemConfig('is_phone_login') == '1';
  70. $key = '';
  71. $wechat_phone_switch = systemConfig('wechat_phone_switch');
  72. if ($bindPhone) {
  73. $routineInfo = $this->dao->routineIdByWechatUser($userInfoCong['openid']);
  74. if (!$routineInfo){
  75. $info = ['session_key' => $userInfoCong->session_key, 'unionId' => $userInfoCong->unionid];
  76. $routineInfo = $this->syncRoutineUser($userInfoCong['openid'], $info, false);
  77. $routineInfo = $routineInfo[0];
  78. }
  79. $user = app()->make(UserRepository::class)->getWhere(['wechat_user_id' => $routineInfo['wechat_user_id']]);
  80. if ($user && $user['phone'])
  81. $bindPhone = false;
  82. if ($bindPhone) {
  83. $uni = uniqid(true, false) . random_int(1, 100000000);
  84. $key = 'U' . md5(time() . $uni);
  85. Cache::set('u_try' . $key, ['id' => $routineInfo['wechat_user_id'], 'type' => $routineInfo['user_type'], 'spread' => $spread], 3600);
  86. }
  87. }
  88. return compact('bindPhone','key','wechat_phone_switch');
  89. }
  90. /**
  91. * 同步公众号用户
  92. * @param string $openId
  93. * @param array $userInfo
  94. * @param bool $mode
  95. * @return mixed|void
  96. * @throws DataNotFoundException
  97. * @throws DbException
  98. * @throws ModelNotFoundException
  99. * @author xaboy
  100. * @day 2020-04-28
  101. */
  102. public function syncUser(string $openId, array $userInfo, bool $mode = false, $createUser = true)
  103. {
  104. if (($mode && (!isset($userInfo['subscribe']) || !$userInfo['subscribe'])) || !isset($userInfo['openid']))
  105. return;
  106. $wechatUser = null;
  107. $userInfo['nickname'] = filter_emoji(($userInfo['nickname'] ?? '') ?: ('微信用户U' . substr(uniqid(true, true), -6)));
  108. if (isset($userInfo['unionid']))
  109. $wechatUser = $this->dao->unionIdByWechatUser($userInfo['unionid']);
  110. if (!$wechatUser)
  111. $wechatUser = $this->dao->openIdByWechatUser($openId);
  112. unset($userInfo['qr_scene'], $userInfo['qr_scene_str'], $userInfo['qr_scene_str'], $userInfo['subscribe_scene']);
  113. if (isset($userInfo['tagid_list'])) {
  114. $userInfo['tagid_list'] = implode(',', $userInfo['tagid_list']);
  115. }
  116. return Db::transaction(function () use ($createUser, $mode, $userInfo, $wechatUser) {
  117. if ($wechatUser) {
  118. if ($mode) {
  119. unset($userInfo['nickname']);
  120. }
  121. $wechatUser->save($userInfo);
  122. } else {
  123. $wechatUser = $this->dao->create($userInfo);
  124. }
  125. if (!$createUser) return [$wechatUser];
  126. /** @var UserRepository $userRepository */
  127. $userRepository = app()->make(UserRepository::class);
  128. $user = $userRepository->syncWechatUser($wechatUser);
  129. return [$wechatUser, $user];
  130. });
  131. }
  132. public function getUserByWechat(string $openId, array $userInfo)
  133. {
  134. $wechatUser = null;
  135. if (isset($userInfo['unionid']))
  136. $wechatUser = $this->dao->unionIdByWechatUser($userInfo['unionid']);
  137. if (!$wechatUser)
  138. $wechatUser = $this->dao->openIdByWechatUser($openId);
  139. $userRepository = app()->make(UserRepository::class);
  140. $user = $userRepository->wechatUserIdBytUser($wechatUser->wechat_user_id);
  141. return [$wechatUser,$user];
  142. }
  143. /**
  144. * 同步小程序用户
  145. * @param string $routineOpenid
  146. * @param array $routine
  147. * @return mixed
  148. * @throws DataNotFoundException
  149. * @throws DbException
  150. * @throws ModelNotFoundException
  151. * @author xaboy
  152. * @day 2020-05-11
  153. */
  154. public function syncRoutineUser(string $routineOpenid, array $routine, $createUser = true)
  155. {
  156. $routineInfo = [];
  157. $nickname = $routine['nickName'] ?? '小程序用户';
  158. $routineInfo['nickname'] = $nickname; //姓名
  159. $routineInfo['sex'] = $routine['gender'] ?? 0;//性别
  160. $routineInfo['language'] = $routine['language'] ?? '';//语言
  161. $routineInfo['city'] = $routine['city'] ?? '';//城市
  162. $routineInfo['province'] = $routine['province'] ?? '';//省份
  163. $routineInfo['country'] = $routine['country'] ?? '';//国家
  164. $routineInfo['headimgurl'] = '';//头像
  165. $routineInfo['routine_openid'] = $routineOpenid;//openid
  166. $routineInfo['session_key'] = $routine['session_key'] ?? '';//会话密匙
  167. $routineInfo['unionid'] = $routine['unionId'];//用户在开放平台的唯一标识符
  168. $routineInfo['user_type'] = 'routine';//用户类型
  169. $wechatUser = null;
  170. if ($routineInfo['unionid'])
  171. $wechatUser = $this->dao->unionIdByWechatUser($routineInfo['unionid']);
  172. if (!$wechatUser)
  173. $wechatUser = $this->dao->routineIdByWechatUser($routineOpenid);
  174. return Db::transaction(function () use ($createUser, $routineInfo, $wechatUser) {
  175. if ($wechatUser) {
  176. $routineInfo['nickname'] = $wechatUser['nickname'];
  177. $routineInfo['headimgurl'] = $wechatUser['headimgurl'];
  178. $wechatUser->save($routineInfo);
  179. } else {
  180. $wechatUser = $this->dao->create($routineInfo);
  181. }
  182. if (!$createUser) return [$wechatUser];
  183. /** @var UserRepository $userRepository */
  184. $userRepository = app()->make(UserRepository::class);
  185. $user = $userRepository->syncWechatUser($wechatUser, 'routine');
  186. return [$wechatUser, $user];
  187. });
  188. }
  189. /**
  190. * 同步 app 用户
  191. * @param string $routineOpenid
  192. * @param array $routine
  193. * @return mixed
  194. * @throws DataNotFoundException
  195. * @throws DbException
  196. * @throws ModelNotFoundException
  197. * @author xaboy
  198. * @day 2020-05-11
  199. */
  200. public function syncAppUser(string $unionId, array $userInfo, $type = 'wechat', $createUser = true)
  201. {
  202. $wechatInfo = [];
  203. $wechatInfo['nickname'] = filter_emoji($userInfo['nickName'] ?? ($userInfo['nickname'] ?? ''));//姓名
  204. $wechatInfo['sex'] = $userInfo['gender'] ?? 0;//性别
  205. $wechatInfo['city'] = $userInfo['city'] ?? '';//城市
  206. $wechatInfo['province'] = $userInfo['province'] ?? '';//省份
  207. $wechatInfo['country'] = $userInfo['country'] ?? '';//国家
  208. $wechatInfo['headimgurl'] = $userInfo['avatarUrl'] ?? ($userInfo['headimgurl'] ?? '');//头像
  209. $wechatInfo['unionid'] = $unionId;//用户在开放平台的唯一标识符
  210. $wechatInfo['user_type'] = 'app';//用户类型
  211. $wechatUser = $this->dao->unionIdByWechatUser($unionId);
  212. return Db::transaction(function () use ($createUser, $type, $wechatInfo, $wechatUser) {
  213. if ($wechatUser) {
  214. unset($wechatInfo['nickname']);
  215. $wechatUser->save($wechatInfo);
  216. } else {
  217. $wechatUser = $this->dao->create($wechatInfo);
  218. }
  219. if (!$createUser) {
  220. return [$wechatUser];
  221. }
  222. /** @var UserRepository $userRepository */
  223. $userRepository = app()->make(UserRepository::class);
  224. $user = $userRepository->syncWechatUser($wechatUser, $type);
  225. return [$wechatUser, $user];
  226. });
  227. }
  228. /**
  229. * 获取列表
  230. * @param array $where
  231. * @param $page
  232. * @param $limit
  233. * @return array
  234. * @throws DataNotFoundException
  235. * @throws DbException
  236. * @throws ModelNotFoundException
  237. * @author xaboy
  238. * @day 2020-04-29
  239. */
  240. public function getList(array $where, $page, $limit)
  241. {
  242. $query = $this->dao->search($where);
  243. $count = $query->count($this->dao->getPk());
  244. $list = $query->setOption('field', [])->field('uid,openid,nickname,headimgurl,sex,country,province,city,subscribe')
  245. ->page($page, $limit)->select()->each(function ($item) {
  246. $item['subscribe_time'] = $item['subscribe_time'] ? date('Y-m-d H:i', $item['subscribe_time']) : '';
  247. return $item;
  248. });
  249. return compact('count', 'list');
  250. }
  251. /**
  252. * 用户标签表单
  253. * @param $id
  254. * @return Form
  255. * @throws DataNotFoundException
  256. * @throws DbException
  257. * @throws FormBuilderException
  258. * @throws ModelNotFoundException
  259. * @author xaboy
  260. * @day 2020-04-29
  261. */
  262. public function updateUserTagForm($id)
  263. {
  264. $wechatUserTagService = new WechatUserTagService();
  265. $lst = $wechatUserTagService->lst();
  266. $user = $this->dao->get($id);
  267. return Elm::createForm(Route::buildUrl('wechat/user/tag', ['id' => $id]), [
  268. Elm::select('tag_id', '用户标签:', explode(',', $user->tagid_list))->options(function () use ($lst) {
  269. $options = [];
  270. foreach ($lst as $item) {
  271. $options[] = ['value' => $item['id'], 'label' => $item['name']];
  272. }
  273. return $options;
  274. })->multiple(true)->placeholder('请选择用户标签')
  275. ])->setTitle('编辑用户标签');
  276. }
  277. /**
  278. * 更新用户标签
  279. * @param $id
  280. * @param array $tags
  281. * @throws DataNotFoundException
  282. * @throws DbException
  283. * @throws ModelNotFoundException
  284. * @author xaboy
  285. * @day 2020-04-29
  286. */
  287. public function updateTag($id, array $tags)
  288. {
  289. $user = $this->dao->get($id);
  290. $oTags = explode(',', $user->tagid_list);
  291. $user->save(['tagid_list' => implode(',', $tags)]);
  292. $wechatUserTagService = (new WechatUserTagService())->userTag();
  293. foreach ($oTags as $tag) {
  294. $wechatUserTagService->batchUntagUsers([$user->openid], $tag);
  295. }
  296. foreach ($tags as $tag) {
  297. $wechatUserTagService->batchTagUsers([$user->openid], $tag);
  298. }
  299. }
  300. /**
  301. * 用户分组表单
  302. * @param $id
  303. * @return Form
  304. * @throws DataNotFoundException
  305. * @throws DbException
  306. * @throws FormBuilderException
  307. * @throws ModelNotFoundException
  308. * @author xaboy
  309. * @day 2020-04-29
  310. */
  311. public function updateUserGroupForm($id)
  312. {
  313. $wechatUserGroupService = new WechatUserGroupService();
  314. $lst = $wechatUserGroupService->lst();
  315. $user = $this->dao->get($id);
  316. return Elm::createForm(Route::buildUrl('wechat/user/group', ['id' => $id]), [
  317. Elm::select('group_id', '用户标签:', (string)$user->groupid)->options(function () use ($lst) {
  318. $options = [];
  319. foreach ($lst as $item) {
  320. $options[] = ['value' => $item['id'], 'label' => $item['name']];
  321. }
  322. return $options;
  323. })->placeholder('请选择用户标签')
  324. ])->setTitle('编辑用户分组');
  325. }
  326. /**
  327. * 更新用户分组
  328. * @param $id
  329. * @param $groupid
  330. * @throws DataNotFoundException
  331. * @throws DbException
  332. * @throws ModelNotFoundException
  333. * @author xaboy
  334. * @day 2020-04-29
  335. */
  336. public function updateGroup($id, $groupid)
  337. {
  338. $user = $this->dao->get($id);
  339. $user->save(['groupid' => $groupid]);
  340. $wechatUserGroupService = (new WechatUserGroupService())->userGroup();
  341. $wechatUserGroupService->moveUser($user->openid, $groupid);
  342. }
  343. /**
  344. * 发送图文消息
  345. * @param $id
  346. * @param array $ids
  347. * @author xaboy
  348. * @day 2020-05-11
  349. */
  350. public function sendNews($id, array $ids)
  351. {
  352. if (!count($ids)) return;
  353. /** @var ArticleRepository $make */
  354. $make = app()->make(ArticleRepository::class);
  355. $articles = $make->wechatNewIdByData($id);
  356. $news = [];
  357. foreach ($articles as $article) {
  358. $news[] = [
  359. 'title' => $article['title'],
  360. 'image' => $article['image_input'],
  361. 'date' => $article['create_time'],
  362. 'description' => $article['synopsis'],
  363. 'id' => $article['article_id']
  364. ];
  365. }
  366. $make = app()->make(UserRepository::class);
  367. foreach ($ids as $_id) {
  368. $user = $make->get($_id);
  369. if ($this->dao->isSubscribeWechatUser($user->wechat_user_id)) {
  370. Queue::push(SendNewsJob::class, [$user->wechat_user_id, $news]);
  371. }
  372. }
  373. }
  374. /**
  375. * 关注公众号
  376. * @param string $openId
  377. * @author Qinii
  378. * @day 2024/4/28
  379. */
  380. public function subscribe(string $openId)
  381. {
  382. try{
  383. $this->dao->search([])->where('openid',$openId)->update(['subscribe' => 1]);
  384. }catch (Exception $e) {
  385. }
  386. }
  387. }