RoutineServices.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\services\wechat;
  13. use app\services\BaseServices;
  14. use app\dao\wechat\WechatUserDao;
  15. use app\services\message\SystemNotificationServices;
  16. use app\services\message\TemplateMessageServices;
  17. use app\services\other\QrcodeServices;
  18. use app\services\user\LoginServices;
  19. use app\services\user\UserServices;
  20. use app\services\user\UserVisitServices;
  21. use crmeb\exceptions\ApiException;
  22. use crmeb\services\CacheService;
  23. use crmeb\services\app\MiniProgramService;
  24. use crmeb\services\oauth\OAuth;
  25. /**
  26. *
  27. * Class RoutineServices
  28. * @package app\services\wechat
  29. */
  30. class RoutineServices extends BaseServices
  31. {
  32. /**
  33. * RoutineServices constructor.
  34. * @param WechatUserDao $dao
  35. */
  36. public function __construct(WechatUserDao $dao)
  37. {
  38. $this->dao = $dao;
  39. }
  40. /**
  41. * 小程序授权登录
  42. * @param $code
  43. * @param $post_cache_key
  44. * @param $login_type
  45. * @param $spread_spid
  46. * @param $spread_code
  47. * @param $iv
  48. * @param $encryptedData
  49. * @return array
  50. * @throws \think\db\exception\DataNotFoundException
  51. * @throws \think\db\exception\ModelNotFoundException
  52. */
  53. public function mp_auth($code, $post_cache_key, $login_type, $spread_spid, $spread_code, $iv, $encryptedData)
  54. {
  55. /** @var OAuth $oauth */
  56. $oauth = app()->make(OAuth::class, ['mini_program']);
  57. [$userInfoCong, $userInfo] = $oauth->oauth($code, [
  58. 'iv' => $iv,
  59. 'encryptedData' => $encryptedData
  60. ]);
  61. $session_key = $userInfoCong['session_key'];
  62. $userInfo['unionId'] = isset($userInfoCong['unionid']) ? $userInfoCong['unionid'] : '';
  63. $userInfo['openId'] = $openid = $userInfoCong['openid'];
  64. $userInfo['spid'] = $spread_spid;
  65. $userInfo['code'] = $spread_code;
  66. $userInfo['session_key'] = $session_key;
  67. $userInfo['login_type'] = $login_type;
  68. $createData = $this->routineOauth($userInfo);
  69. /** @var WechatUserServices $wechatUserServices */
  70. $wechatUserServices = app()->make(WechatUserServices::class);
  71. $user = $wechatUserServices->getAuthUserInfo($openid, 'routine');
  72. if (!$user) {
  73. $user = $wechatUserServices->wechatOauthAfter($createData);
  74. } else {
  75. //更新用户信息
  76. $wechatUserServices->wechatUpdata([$user['uid'], $createData[1]]);
  77. }
  78. $token = $this->createToken((int)$user['uid'], 'routine');
  79. if ($token) {
  80. /** @var UserVisitServices $visitServices */
  81. $visitServices = app()->make(UserVisitServices::class);
  82. $visitServices->loginSaveVisit($user);
  83. return [
  84. 'userInfo' => $user
  85. ];
  86. } else
  87. throw new ApiException(410038);
  88. }
  89. /**
  90. * 小程序授权登录
  91. * @param $code
  92. * @param $spid
  93. * @param $spread
  94. * @param $iv
  95. * @param $encryptedData
  96. * @return array
  97. * @throws \think\db\exception\DataNotFoundException
  98. * @throws \think\db\exception\ModelNotFoundException
  99. */
  100. public function newAuth($code, $spid, $spread, $iv, $encryptedData)
  101. {
  102. if (!$code) {
  103. throw new ApiException(100100);
  104. }
  105. /** @var OAuth $oauth */
  106. $oauth = app()->make(OAuth::class, ['mini_program']);
  107. [$userInfoCong, $userInfo] = $oauth->oauth($code, [
  108. 'iv' => $iv,
  109. 'encryptedData' => $encryptedData
  110. ]);
  111. $session_key = $userInfoCong['session_key'];
  112. $userInfo['unionId'] = isset($userInfoCong['unionid']) ? $userInfoCong['unionid'] : '';
  113. $userInfo['openId'] = $openid = $userInfoCong['openid'];
  114. $userInfo['spid'] = $spid;
  115. $userInfo['code'] = $spread;
  116. $userInfo['session_key'] = $session_key;
  117. $userInfo['login_type'] = 'routine';
  118. $createData = $this->routineOauth($userInfo);
  119. /** @var WechatUserServices $wechatUserServices */
  120. $wechatUserServices = app()->make(WechatUserServices::class);
  121. $user = $wechatUserServices->getAuthUserInfo($openid, 'routine');
  122. //获取是否强制绑定手机号
  123. $storeUserMobile = sys_config('store_user_mobile');
  124. if ($storeUserMobile && !$user) {
  125. $userInfoKey = md5($openid . '_' . time() . '_rouine');
  126. CacheService::setTokenBucket($userInfoKey, $createData, 7200);
  127. return ['key' => $userInfoKey];
  128. } else if (!$user) {
  129. $user = $wechatUserServices->wechatOauthAfter($createData);
  130. } else {
  131. //更新用户信息
  132. $wechatUserServices->wechatUpdata([$user['uid'], $createData[1]]);
  133. }
  134. $token = $this->createToken((int)$user['uid'], 'routine');
  135. if ($token) {
  136. /** @var UserVisitServices $visitServices */
  137. $visitServices = app()->make(UserVisitServices::class);
  138. $visitServices->loginSaveVisit($user);
  139. $token['userInfo'] = $user;
  140. return $token;
  141. } else
  142. throw new ApiException(410019);
  143. }
  144. /**
  145. * 小程序创建用户后返回uid
  146. * @param $routine
  147. * @return array
  148. */
  149. public function routineOauth($routine)
  150. {
  151. $routineInfo['nickname'] = filter_emoji($routine['nickName']);//姓名
  152. $routineInfo['sex'] = $routine['gender'];//性别
  153. $routineInfo['language'] = $routine['language'];//语言
  154. $routineInfo['city'] = $routine['city'];//城市
  155. $routineInfo['province'] = $routine['province'];//省份
  156. $routineInfo['country'] = $routine['country'];//国家
  157. $routineInfo['headimgurl'] = $routine['avatarUrl'];//头像
  158. $routineInfo['openid'] = $routine['openId'];
  159. $routineInfo['session_key'] = $routine['session_key'];//会话密匙
  160. $routineInfo['unionid'] = $routine['unionId'];//用户在开放平台的唯一标识符
  161. $routineInfo['user_type'] = 'routine';//用户类型
  162. $routineInfo['phone'] = $routine['phone'] ?? $routine['purePhoneNumber'] ?? '';
  163. $spid = $routine['spid'] ?? 0;//绑定关系uid
  164. //获取是否有扫码进小程序
  165. /** @var QrcodeServices $qrcode */
  166. $qrcode = app()->make(QrcodeServices::class);
  167. if (isset($routine['code']) && $routine['code'] && ($info = $qrcode->get($routine['code']))) {
  168. $spid = $info['third_id'];
  169. }
  170. return [$routine['openId'], $routineInfo, $spid, $routine['login_type'] ?? 'routine', 'routine'];
  171. }
  172. /**
  173. * 小程序支付回调
  174. * @return \Symfony\Component\HttpFoundation\Response
  175. * @throws \EasyWeChat\Core\Exceptions\FaultException
  176. */
  177. public function notify()
  178. {
  179. return MiniProgramService::handleNotify();
  180. }
  181. /**
  182. * 获取小程序订阅消息id
  183. * @return bool|mixed|null
  184. */
  185. public function tempIds()
  186. {
  187. return CacheService::get('TEMP_IDS_LIST', function () {
  188. /** @var SystemNotificationServices $sysNotify */
  189. $sysNotify = app()->make(SystemNotificationServices::class);
  190. $marks = $sysNotify->getColumn([['routine_id', '>', 0]], 'routine_id', 'mark');
  191. $ids = array_values($marks);
  192. /** @var TemplateMessageServices $tempMsgServices */
  193. $tempMsgServices = app()->make(TemplateMessageServices::class);
  194. $list = $tempMsgServices->getColumn([['id', 'in', $ids]], 'tempid', 'id');
  195. $tempIdsList = [];
  196. foreach ($marks as $key => $item) {
  197. $tempIdsList[$key] = $list[$item];
  198. }
  199. return $tempIdsList;
  200. });
  201. }
  202. /**
  203. * 获取小程序直播列表
  204. * @param $page
  205. * @param $limit
  206. * @return array|bool|mixed
  207. */
  208. public function live($page, $limit)
  209. {
  210. $list = CacheService::get('WECHAT_LIVE_LIST_' . $page . '_' . $limit, function () use ($page, $limit) {
  211. $list = MiniProgramService::getLiveInfo((int)$page, (int)$limit);
  212. foreach ($list as &$item) {
  213. $item['_start_time'] = date('m-d H:i', $item['start_time']);
  214. }
  215. return $list;
  216. }, 600) ?: [];
  217. return $list;
  218. }
  219. /**
  220. * 静默授权
  221. * @param $code
  222. * @param $spread
  223. * @param $spid
  224. * @return array
  225. * @throws \Psr\SimpleCache\InvalidArgumentException
  226. * @throws \think\db\exception\DataNotFoundException
  227. * @throws \think\db\exception\ModelNotFoundException
  228. */
  229. public function silenceAuth($code, $spread, $spid)
  230. {
  231. /** @var OAuth $oauth */
  232. $oauth = app()->make(OAuth::class, ['mini_program']);
  233. $userInfoConfig = $oauth->oauth($code, ['silence' => true]);
  234. if (!isset($userInfoConfig['openid'])) {
  235. throw new ApiException(410078);
  236. }
  237. $routineInfo = [
  238. 'unionid' => $userInfoConfig['unionid'] ?? ''
  239. ];
  240. /** @var QrcodeServices $qrcode */
  241. $qrcode = app()->make(QrcodeServices::class);
  242. if ($spread && ($info = $qrcode->getOne(['id' => $spread, 'status' => 1]))) {
  243. $spid = $info['third_id'];
  244. }
  245. $openid = $userInfoConfig['openid'];
  246. $routineInfo['openid'] = $openid;
  247. $routineInfo['headimgurl'] = sys_config('h5_avatar');
  248. /** @var WechatUserServices $wechatUserServices */
  249. $wechatUserServices = app()->make(WechatUserServices::class);
  250. $user = $wechatUserServices->getAuthUserInfo($openid, 'routine');
  251. $createData = [$openid, $routineInfo, $spid, '', 'routine'];
  252. //获取是否强制绑定手机号
  253. $storeUserMobile = sys_config('store_user_mobile');
  254. if ($storeUserMobile && !$user) {
  255. $userInfoKey = md5($openid . '_' . time() . '_routine');
  256. CacheService::setTokenBucket($userInfoKey, $createData, 7200);
  257. return ['key' => $userInfoKey];
  258. } else if (!$user) {
  259. //写入用户信息
  260. $user = $wechatUserServices->wechatOauthAfter($createData);
  261. $token = $this->createToken((int)$user['uid'], 'routine');
  262. if ($token) {
  263. return $token;
  264. } else
  265. throw new ApiException(410019);
  266. } else {
  267. //更新用户信息
  268. $wechatUserServices->wechatUpdata([$user['uid'], ['code' => $spid]]);
  269. $token = $this->createToken((int)$user['uid'], 'routine');
  270. /** @var UserVisitServices $visitServices */
  271. $visitServices = app()->make(UserVisitServices::class);
  272. $visitServices->loginSaveVisit($user);
  273. if ($token) {
  274. return $token;
  275. } else
  276. throw new ApiException(410019);
  277. }
  278. }
  279. /**
  280. * 静默授权
  281. * @param $code
  282. * @param $spread
  283. * @param $spid
  284. * @return array
  285. * @throws \Psr\SimpleCache\InvalidArgumentException
  286. */
  287. public function silenceAuthNoLogin($code, $spread, $spid)
  288. {
  289. /** @var OAuth $oauth */
  290. $oauth = app()->make(OAuth::class, ['mini_program']);
  291. $userInfoConfig = $oauth->oauth($code, ['silence' => true]);
  292. if (!isset($userInfoConfig['openid'])) {
  293. throw new ApiException(410078);
  294. }
  295. $routineInfo = [
  296. 'unionid' => $userInfoConfig['unionid'] ?? ''
  297. ];
  298. /** @var QrcodeServices $qrcode */
  299. $qrcode = app()->make(QrcodeServices::class);
  300. if ($spread && ($info = $qrcode->getOne(['id' => $spread, 'status' => 1]))) {
  301. $spid = $info['third_id'];
  302. }
  303. $openid = $userInfoConfig['openid'];
  304. $routineInfo['openid'] = $openid;
  305. $routineInfo['headimgurl'] = sys_config('h5_avatar');
  306. /** @var WechatUserServices $wechatUserServices */
  307. $wechatUserServices = app()->make(WechatUserServices::class);
  308. $user = $wechatUserServices->getAuthUserInfo($openid, 'routine');
  309. $createData = [$openid, $routineInfo, $spid, '', 'routine'];
  310. if (!$user) {
  311. $userInfoKey = md5($openid . '_' . time() . '_routine');
  312. CacheService::setTokenBucket($userInfoKey, $createData, 7200);
  313. return ['auth_login' => 1, 'key' => $userInfoKey];
  314. } else {
  315. //更新用户信息
  316. $wechatUserServices->wechatUpdata([$user['uid'], ['code' => $spid]]);
  317. $token = $this->createToken((int)$user['uid'], 'routine');
  318. /** @var UserVisitServices $visitServices */
  319. $visitServices = app()->make(UserVisitServices::class);
  320. $visitServices->loginSaveVisit($user);
  321. if ($token) {
  322. $token['userInfo'] = $user;
  323. return $token;
  324. } else
  325. throw new ApiException(410019);
  326. }
  327. }
  328. /**
  329. * 手机号登录 静默授权绑定关系
  330. * @param $code
  331. * @param $spread
  332. * @param $spid
  333. * @param $phone
  334. * @return array
  335. * @throws \think\db\exception\DataNotFoundException
  336. * @throws \think\db\exception\ModelNotFoundException
  337. */
  338. public function silenceAuthBindingPhone($code, $spread, $spid, $phone)
  339. {
  340. /** @var OAuth $oauth */
  341. $oauth = app()->make(OAuth::class, ['mini_program']);
  342. $userInfoConfig = $oauth->oauth($code, ['silence' => true]);
  343. if (!isset($userInfoConfig['openid'])) {
  344. throw new ApiException(410078);
  345. }
  346. $routineInfo = [
  347. 'unionid' => $userInfoConfig['unionid'] ?? ''
  348. ];
  349. /** @var QrcodeServices $qrcode */
  350. $qrcode = app()->make(QrcodeServices::class);
  351. if ($spread && ($info = $qrcode->getOne(['id' => $spread, 'status' => 1]))) {
  352. $spid = $info['third_id'];
  353. }
  354. $openid = $userInfoConfig['openid'];
  355. $routineInfo['openid'] = $openid;
  356. $routineInfo['headimgurl'] = sys_config('h5_avatar');
  357. $routineInfo['phone'] = $phone;
  358. /** @var WechatUserServices $wechatUserServices */
  359. $wechatUserServices = app()->make(WechatUserServices::class);
  360. $createData = [$openid, $routineInfo, $spid, '', 'routine'];
  361. //写入用户信息
  362. $user = $wechatUserServices->wechatOauthAfter($createData);
  363. $token = $this->createToken((int)$user['uid'], 'routine');
  364. /** @var UserVisitServices $visitServices */
  365. $visitServices = app()->make(UserVisitServices::class);
  366. $visitServices->loginSaveVisit($user);
  367. if ($token) {
  368. return $token;
  369. } else
  370. throw new ApiException(410019);
  371. }
  372. /**
  373. * 自动获取手机号绑定
  374. * @param $code
  375. * @param $iv
  376. * @param $encryptedData
  377. * @param $spread
  378. * @param $spid
  379. * @param string $key
  380. * @return array
  381. * @throws \Psr\SimpleCache\InvalidArgumentException
  382. * @throws \think\db\exception\DataNotFoundException
  383. * @throws \think\db\exception\ModelNotFoundException
  384. */
  385. public function authBindingPhone($code, $iv, $encryptedData, $spread, $spid, $key = '')
  386. {
  387. $wechatInfo = [];
  388. $userInfo = [];
  389. $userType = $login_type = 'routine';
  390. if ($key) {
  391. [$openid, $wechatInfo, $spreadId, $login_type, $userType] = $createData = CacheService::getTokenBucket($key);
  392. }
  393. /** @var OAuth $oauth */
  394. $oauth = app()->make(OAuth::class, ['mini_program']);
  395. [$userInfoCong, $userInfo] = $oauth->oauth($code, [
  396. 'iv' => $iv,
  397. 'encryptedData' => $encryptedData
  398. ]);
  399. $session_key = $userInfoCong['session_key'];
  400. if (!$userInfo || !isset($userInfo['purePhoneNumber'])) {
  401. throw new ApiException(410079);
  402. }
  403. $spreadId = $spid ?? 0;
  404. /** @var QrcodeServices $qrcode */
  405. $qrcode = app()->make(QrcodeServices::class);
  406. if ($spread && ($info = $qrcode->getOne(['id' => $spread, 'status' => 1]))) {
  407. $spreadId = $info['third_id'];
  408. }
  409. $openid = $userInfoCong['openid'];
  410. $wechatInfo['openid'] = $openid;
  411. $wechatInfo['unionid'] = $userInfoCong['unionid'] ?? '';
  412. $wechatInfo['spid'] = $spreadId;
  413. $wechatInfo['code'] = $spread;
  414. $wechatInfo['session_key'] = $session_key;
  415. $wechatInfo['phone'] = $userInfo['purePhoneNumber'];
  416. /** @var WechatUserServices $wechatUserServices */
  417. $wechatUserServices = app()->make(WechatUserServices::class);
  418. //写入用户信息
  419. $user = $wechatUserServices->wechatOauthAfter([$openid, $wechatInfo, $spreadId, $login_type, $userType]);
  420. $token = $this->createToken((int)$user['uid'], 'routine');
  421. if ($token) {
  422. /** @var UserVisitServices $visitServices */
  423. $visitServices = app()->make(UserVisitServices::class);
  424. $visitServices->loginSaveVisit($user);
  425. return [
  426. 'token' => $token['token'],
  427. 'userInfo' => $user,
  428. 'expires_time' => $token['params']['exp'],
  429. ];
  430. } else
  431. throw new ApiException(410019);
  432. }
  433. /**
  434. * 更新用户信息
  435. * @param $uid
  436. * @param array $data
  437. * @return bool
  438. * @throws \think\db\exception\DataNotFoundException
  439. * @throws \think\db\exception\DbException
  440. * @throws \think\db\exception\ModelNotFoundException
  441. */
  442. public function updateUserInfo($uid, array $data)
  443. {
  444. /** @var UserServices $userServices */
  445. $userServices = app()->make(UserServices::class);
  446. $user = $userServices->getUserInfo($uid);
  447. if (!$user) {
  448. throw new ApiException(100026);
  449. }
  450. $userInfo = [];
  451. $userInfo['nickname'] = filter_emoji($data['nickName'] ?? '');//姓名
  452. $userInfo['sex'] = $data['gender'] ?? '';//性别
  453. $userInfo['language'] = $data['language'] ?? '';//语言
  454. $userInfo['city'] = $data['city'] ?? '';//城市
  455. $userInfo['province'] = $data['province'] ?? '';//省份
  456. $userInfo['country'] = $data['country'] ?? '';//国家
  457. $userInfo['headimgurl'] = $data['avatarUrl'] ?? '';//头像
  458. $userInfo['is_complete'] = 1;
  459. /** @var LoginServices $loginService */
  460. $loginService = app()->make(LoginServices::class);
  461. $loginService->updateUserInfo($userInfo, $user);
  462. //更新用户信息
  463. if (!$this->dao->update(['uid' => $user['uid'], 'user_type' => 'routine'], $userInfo)) {
  464. throw new ApiException(100013);
  465. }
  466. return true;
  467. }
  468. }