RoutineServices.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 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\other\QrcodeServices;
  16. use app\services\user\LoginServices;
  17. use app\services\user\UserServices;
  18. use app\services\user\UserVisitServices;
  19. use crmeb\services\CacheService;
  20. use crmeb\services\template\Template;
  21. use crmeb\services\wechat\MiniProgram;
  22. use crmeb\services\wechat\WechatResponse;
  23. use think\exception\ValidateException;
  24. use think\facade\Config;
  25. /**
  26. *
  27. * Class RoutineServices
  28. * @package app\services\wechat
  29. * @mixin WechatUserDao
  30. */
  31. class RoutineServices extends BaseServices
  32. {
  33. /**
  34. * @var string
  35. */
  36. protected $sessionKey = 'eb_routine_api_code_';
  37. /**
  38. * RoutineServices constructor.
  39. * @param WechatUserDao $dao
  40. */
  41. public function __construct(WechatUserDao $dao)
  42. {
  43. $this->dao = $dao;
  44. }
  45. public function serve()
  46. {
  47. ob_clean();
  48. return MiniProgram::serve();
  49. }
  50. /**
  51. * 返回用户信息的缓存key,返回是否强制绑定手机号
  52. * @param $code
  53. * @param $spread_uid
  54. * @param $spread_code
  55. * @return array
  56. */
  57. public function authType($code, $spread_uid, $spread_code)
  58. {
  59. $userInfoConfig = $this->getUserInfoByCode((string)$code);
  60. $userInfo['unionId'] = $userInfoConfig['unionid'] ?? '';
  61. $userInfo['openid'] = $userInfoConfig['openid'];
  62. $userInfo['spread_uid'] = $spread_uid;
  63. $userInfo['spared_code'] = $spread_code;
  64. $userInfo['session_key'] = $userInfoConfig['session_key'] ?? '';
  65. $userInfo['login_type'] = 'routine';
  66. [$openid, $wechatInfo, $spread_uid, $login_type, $userType] = $createData = $this->routineOauth($userInfo);
  67. /** @var WechatUserServices $wechatUserServices */
  68. $wechatUserServices = app()->make(WechatUserServices::class);
  69. $user = $wechatUserServices->getAuthUserInfo($openid, $userType);
  70. $userInfoKey = md5($openid . '_' . time() . '_rouine');
  71. CacheService::setTokenBucket($userInfoKey, $createData, 7200);
  72. $bindPhone = false;
  73. if (sys_config('store_user_mobile') && (($user && $user['phone'] == '') || !$user)) $bindPhone = true;
  74. return ['bindPhone' => $bindPhone, 'key' => $userInfoKey];
  75. }
  76. /**
  77. * 根据缓存获取token
  78. * @param $key
  79. * @return array
  80. * @throws \Psr\SimpleCache\InvalidArgumentException
  81. * @throws \think\db\exception\DataNotFoundException
  82. * @throws \think\db\exception\ModelNotFoundException
  83. */
  84. public function authLogin($key)
  85. {
  86. [$openid, $wechatInfo, $spread_uid, $login_type, $userType] = CacheService::getTokenBucket($key);
  87. /** @var WechatUserServices $wechatUserServices */
  88. $wechatUserServices = app()->make(WechatUserServices::class);
  89. //写入用户信息
  90. $user = $wechatUserServices->wechatOauthAfter([$openid, $wechatInfo, $spread_uid, $login_type, $userType]);
  91. return $this->getReturnInfo($user);
  92. }
  93. /**
  94. * 小程序手机号登录
  95. * @param $key
  96. * @param $phone
  97. * @param $spread_uid
  98. * @param $spread_code
  99. * @param $code
  100. * @return array
  101. * @throws \think\db\exception\DataNotFoundException
  102. * @throws \think\db\exception\ModelNotFoundException
  103. */
  104. public function phoneLogin($key, $phone, $spread_uid, $spread_code, $code = '')
  105. {
  106. if ($code == '') {
  107. [$openid, $wechatInfo, $spread_uid, $login_type, $userType] = CacheService::get($key);
  108. $wechatInfo['phone'] = $phone;
  109. $createData = [$openid, $wechatInfo, $spread_uid, $login_type, $userType];
  110. } else {
  111. $userInfoConfig = $this->getUserInfoByCode((string)$code);
  112. $openid = $userInfoConfig['openid'];
  113. $wechatInfo['openid'] = $openid;
  114. $wechatInfo['unionid'] = $userInfoConfig['unionid'] ?? '';
  115. $wechatInfo['spread_uid'] = $spread_uid;
  116. $wechatInfo['spread_code'] = $spread_code;
  117. $wechatInfo['session_key'] = $userInfoConfig['session_key'] ?? '';
  118. $wechatInfo['phone'] = $phone;
  119. $createData = [$openid, $wechatInfo, $spread_uid, 'routine', 'routine'];
  120. }
  121. /** @var WechatUserServices $wechatUserServices */
  122. $wechatUserServices = app()->make(WechatUserServices::class);
  123. //写入用户信息
  124. $user = $wechatUserServices->wechatOauthAfter($createData);
  125. return $this->getReturnInfo($user);
  126. }
  127. /**
  128. * 小程序绑定手机号
  129. * @param $code
  130. * @param $iv
  131. * @param $encryptedData
  132. * @return mixed
  133. * @throws \think\db\exception\DataNotFoundException
  134. * @throws \think\db\exception\ModelNotFoundException
  135. */
  136. public function bindingPhone($code, $iv, $encryptedData)
  137. {
  138. $userInfoConfig = $this->getUserInfoByCode((string)$code);
  139. $userInfo = $this->encryptorUserInfo($userInfoConfig, $iv, $encryptedData);
  140. if (!$userInfo || !isset($userInfo['purePhoneNumber'])) {
  141. throw new ValidateException('获取用户信息失败');
  142. }
  143. $openid = $userInfoConfig['openid'];
  144. $wechatInfo['openid'] = $openid;
  145. $wechatInfo['unionid'] = $userInfoConfig['unionid'] ?? '';
  146. $wechatInfo['session_key'] = $userInfoConfig['session_key'] ?? '';
  147. $wechatInfo['phone'] = $userInfo['purePhoneNumber'];
  148. $createData = $this->routineOauth($wechatInfo);
  149. $wechatInfo = $createData[1] ?? [];
  150. /** @var WechatUserServices $wechatUserServices */
  151. $wechatUserServices = app()->make(WechatUserServices::class);
  152. //写入用户信息
  153. $user = $wechatUserServices->wechatOauthAfter([$openid, $wechatInfo, 0, 'routine', 'routine']);
  154. return $user;
  155. }
  156. /**
  157. * 获取小程序订阅消息id
  158. * @return mixed
  159. */
  160. public function temlIds()
  161. {
  162. $temlIdsName = Config::get('template.stores.subscribe.template_id', []);
  163. $temlIdsList = CacheService::handler('TEMPLATE')->remember('TEML_IDS_LIST', function () use ($temlIdsName) {
  164. $temlId = [];
  165. $templdata = new Template('subscribe');
  166. foreach ($temlIdsName as $key => $item) {
  167. $temlId[strtolower($key)] = $templdata->getTempId($item);
  168. }
  169. return $temlId;
  170. });
  171. return $temlIdsList;
  172. }
  173. /**
  174. * 获取小程序直播列表
  175. * @param $pgae
  176. * @param $limit
  177. * @return mixed
  178. */
  179. public function live($page, $limit)
  180. {
  181. $list = CacheService::get('WECHAT_LIVE_LIST_' . $page . '_' . $limit, function () use ($page, $limit) {
  182. $list = MiniProgram::getLiveInfo((int)$page, (int)$limit);
  183. foreach ($list as &$item) {
  184. $item['_start_time'] = date('m-d H:i', $item['start_time']);
  185. }
  186. return $list;
  187. }, 600) ?: [];
  188. return $list;
  189. }
  190. /**
  191. * 通过code获取授权信息
  192. * @param string $code
  193. * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
  194. */
  195. public function getUserInfoByCode(string $code)
  196. {
  197. if (!$code)
  198. throw new ValidateException('授权失败,参数有误');
  199. try {
  200. $userInfoConfig = MiniProgram::getUserInfo($code);
  201. } catch (\Exception $e) {
  202. throw new ValidateException('授权失败,请检查您的配置!:' . $e->getMessage() . 'line' . $e->getLine());
  203. }
  204. $userInfoConfig = new WechatResponse($userInfoConfig);
  205. if (!isset($userInfoConfig['openid']) || !$userInfoConfig['openid']) {
  206. throw new ValidateException('openid获取失败');
  207. }
  208. return $userInfoConfig->toArray();
  209. }
  210. /**
  211. * 解密获取用户信息
  212. * @param $userInfoConfig
  213. * @param $iv
  214. * @param $encryptedData
  215. * @return mixed
  216. */
  217. public function encryptorUserInfo($userInfoConfig, $iv, $encryptedData)
  218. {
  219. if (!$userInfoConfig)
  220. throw new ValidateException('授权失败,参数有误');
  221. $session_key = $userInfoConfig['session_key'] ?? '';
  222. if (!$session_key) {
  223. throw new ValidateException('获取session_key失败,参数有误');
  224. }
  225. try {
  226. //解密获取用户信息
  227. $userInfo = MiniProgram::decryptData($session_key, $iv, $encryptedData);
  228. } catch (\Exception $e) {
  229. $userInfo = [];
  230. if ($e->getCode() == '-41003') {
  231. throw new ValidateException('获取会话密匙失败');
  232. }
  233. }
  234. return $userInfo;
  235. }
  236. /**
  237. * 处理小程序授权获取用户信息
  238. * @param $routine
  239. * @return array
  240. */
  241. public function routineOauth($routine)
  242. {
  243. $routineInfo['nickname'] = isset($routine['nickName']) ? filter_emoji($routine['nickName']) : (isset($routine['nickname']) ? filter_emoji($routine['nickname']) : '');//姓名
  244. $routineInfo['sex'] = $routine['gender'] ?? '';//性别
  245. $routineInfo['language'] = $routine['language'] ?? '';//语言
  246. $routineInfo['city'] = $routine['city'] ?? '';//城市
  247. $routineInfo['province'] = $routine['province'] ?? "";//省份
  248. $routineInfo['country'] = $routine['country'] ?? '';//国家
  249. $routineInfo['headimgurl'] = $routine['avatarUrl'] ?? $routine['headimgurl'] ?? sys_config('h5_avatar');//头像
  250. $routineInfo['openid'] = $routine['openid'] ?? '';
  251. $routineInfo['session_key'] = $routine['session_key'] ?? '';//会话密匙
  252. $routineInfo['unionid'] = $routine['unionId'] ?? $routine['unionid'] ?? '';//用户在开放平台的唯一标识符
  253. $routineInfo['user_type'] = 'routine';//用户类型
  254. $routineInfo['phone'] = $routine['phone'] ?? $routine['purePhoneNumber'] ?? '';
  255. $spread_uid = (int)($routine['spread_uid'] ?? 0);//绑定关系uid
  256. if (!$spread_uid && isset($routine['spread_code']) && $routine['spread_code']) {
  257. //获取是否有扫码进小程序
  258. /** @var QrcodeServices $qrcode */
  259. $qrcode = app()->make(QrcodeServices::class);
  260. $info = $qrcode->get((int)$routine['spread_code']);
  261. if ($info) {
  262. $spread_uid = $info['third_id'];
  263. }
  264. }
  265. return [$routine['openid'] ?? '', $routineInfo, $spread_uid, $routine['login_type'] ?? 'routine', 'routine'];
  266. }
  267. /**
  268. * 获取返回信息
  269. * @param $user
  270. * @param string $userType
  271. * @return array
  272. */
  273. public function getReturnInfo($user, string $userType = 'routine')
  274. {
  275. if (!$user || !isset($user['uid']) || !$user['uid']) {
  276. throw new ValidateException('获取用户信息失败');
  277. }
  278. $token = $this->createToken((int)$user['uid'], $userType, $user['pwd']);
  279. if (!$token) {
  280. throw new ValidateException('登录失败!');
  281. }
  282. /** @var UserVisitServices $visitServices */
  283. $visitServices = app()->make(UserVisitServices::class);
  284. $visitServices->loginSaveVisit($user);
  285. $token['store_user_avatar'] = (int)sys_config('store_user_avatar', 0);
  286. $user['store_user_avatar'] = $token['store_user_avatar'];
  287. $token['userInfo'] = $user;
  288. $token['expires_time'] = $token['params']['exp'] ?? 0;
  289. return $token;
  290. }
  291. /**
  292. * 小程序授权登录
  293. * @param $code
  294. * @param $post_cache_key
  295. * @param $login_type
  296. * @param $spread_spid
  297. * @param $spread_code
  298. * @param $iv
  299. * @param $encryptedData
  300. * @return mixed
  301. */
  302. public function mp_auth($code, $post_cache_key, $login_type, $spread_spid, $spread_code, $iv, $encryptedData)
  303. {
  304. $userInfoConfig = $this->getUserInfoByCode((string)$code);
  305. $userInfo = $this->encryptorUserInfo($userInfoConfig, $iv, $encryptedData);
  306. $userInfo['unionId'] = $userInfoConfig['unionid'] ?? '';
  307. $userInfo['openid'] = $userInfoConfig['openid'];
  308. $userInfo['spread_uid'] = $spread_spid;
  309. $userInfo['spread_code'] = $spread_code;
  310. $userInfo['session_key'] = $userInfoConfig['session_key'] ?? '';
  311. $userInfo['login_type'] = $login_type;
  312. [$openid, $wechatInfo, $spread_uid, $login_type, $userType] = $createData = $this->routineOauth($userInfo);
  313. /** @var WechatUserServices $wechatUserServices */
  314. $wechatUserServices = app()->make(WechatUserServices::class);
  315. $user = $wechatUserServices->getAuthUserInfo($openid, $userType);
  316. if (!$user) {
  317. $user = $wechatUserServices->wechatOauthAfter($createData);
  318. } else {
  319. //更新用户信息
  320. $wechatUserServices->wechatUpdata([$user['uid'], $wechatInfo]);
  321. }
  322. return $this->getReturnInfo($user);
  323. }
  324. /**
  325. * 小程序授权登录
  326. * @param $code
  327. * @param $spread_uid
  328. * @param $spread_code
  329. * @param $iv
  330. * @param $encryptedData
  331. * @return array
  332. * @throws \think\db\exception\DataNotFoundException
  333. * @throws \think\db\exception\ModelNotFoundException
  334. */
  335. public function newAuth($code, $spread_uid, $spread_code, $iv, $encryptedData)
  336. {
  337. $userInfoConfig = $this->getUserInfoByCode((string)$code);
  338. $userInfo = $this->encryptorUserInfo($userInfoConfig, $iv, $encryptedData);
  339. $userInfo['unionId'] = $userInfoConfig['unionid'] ?? '';
  340. $userInfo['openid'] = $userInfoConfig['openid'];
  341. $userInfo['spread_uid'] = $spread_uid;
  342. $userInfo['spared_code'] = $spread_code;
  343. $userInfo['session_key'] = $userInfoConfig['session_key'] ?? '';
  344. $userInfo['login_type'] = 'routine';
  345. [$openid, $wechatInfo, $spread_uid, $login_type, $userType] = $createData = $this->routineOauth($userInfo);
  346. /** @var WechatUserServices $wechatUserServices */
  347. $wechatUserServices = app()->make(WechatUserServices::class);
  348. $user = $wechatUserServices->getAuthUserInfo($openid, $userType);
  349. //获取是否强制绑定手机号
  350. $storeUserMobile = sys_config('store_user_mobile');
  351. if ($storeUserMobile && !$user) {
  352. $userInfoKey = md5($openid . '_' . time() . '_rouine');
  353. CacheService::setTokenBucket($userInfoKey, $createData, 7200);
  354. return ['key' => $userInfoKey];
  355. } else if (!$user) {
  356. $user = $wechatUserServices->wechatOauthAfter($createData);
  357. } else {
  358. //更新用户信息
  359. $wechatUserServices->wechatUpdata([$user['uid'], $wechatInfo]);
  360. }
  361. return $this->getReturnInfo($user);
  362. }
  363. /**
  364. * 静默授权
  365. * @param $code
  366. * @param $spread_code
  367. * @return mixed
  368. */
  369. public function silenceAuth(string $code, int $spread_code, int $spread_uid, bool $notLogin = false)
  370. {
  371. $userInfoConfig = $this->getUserInfoByCode($code);
  372. $routineInfo = [];
  373. $routineInfo['unionid'] = $userInfoConfig['unionid'] ?? '';
  374. $routineInfo['openid'] = $userInfoConfig['openid'];
  375. $routineInfo['spread_uid'] = $spread_uid;
  376. $routineInfo['spread_code'] = $spread_code;
  377. $routineInfo['headimgurl'] = sys_config('h5_avatar');
  378. [$openid, $wechatInfo, $spread_uid, $login_type, $userType] = $createData = $this->routineOauth($routineInfo);
  379. /** @var WechatUserServices $wechatUserServices */
  380. $wechatUserServices = app()->make(WechatUserServices::class);
  381. $user = $wechatUserServices->getAuthUserInfo($openid, $userType);
  382. if (!$user) {
  383. //获取是否强制绑定手机号
  384. $storeUserMobile = sys_config('store_user_mobile');
  385. if ($notLogin || $storeUserMobile) {
  386. $userInfoKey = md5($openid . '_' . time() . '_routine');
  387. CacheService::setTokenBucket($userInfoKey, $createData, 7200);
  388. return ['auth_login' => 1, 'key' => $userInfoKey];
  389. } else {
  390. //写入用户信息
  391. $user = $wechatUserServices->wechatOauthAfter($createData);
  392. }
  393. } else {
  394. //更新用户信息
  395. $wechatUserServices->wechatUpdata([$user['uid'], ['spread_uid' => $spread_uid]]);
  396. }
  397. return $this->getReturnInfo($user);
  398. }
  399. /**
  400. * 手机号登录 静默授权绑定关系
  401. * @param $code
  402. * @param $spread_code
  403. * @return mixed
  404. */
  405. public function silenceAuthBindingPhone($code, $spread_code, $spread_uid, $phone)
  406. {
  407. $userInfoConfig = $this->getUserInfoByCode((string)$code);
  408. $routineInfo = [];
  409. $routineInfo['unionid'] = $userInfoConfig['unionid'] ?? '';
  410. $openid = $userInfoConfig['openid'];
  411. $routineInfo['openid'] = $openid;
  412. $routineInfo['spread_uid'] = $spread_uid;
  413. $routineInfo['spread_code'] = $spread_code;
  414. $routineInfo['headimgurl'] = sys_config('h5_avatar');
  415. $routineInfo['phone'] = $phone;
  416. $createData = $this->routineOauth($routineInfo);
  417. /** @var WechatUserServices $wechatUserServices */
  418. $wechatUserServices = app()->make(WechatUserServices::class);
  419. //写入用户信息
  420. $user = $wechatUserServices->wechatOauthAfter($createData);
  421. return $this->getReturnInfo($user);
  422. }
  423. /**
  424. * 自动获取手机号绑定
  425. * @param $code
  426. * @param $iv
  427. * @param $encryptedData
  428. * @param $spread_code
  429. * @param $spread_uid
  430. * @param $key
  431. * @return array
  432. * @throws \Psr\SimpleCache\InvalidArgumentException
  433. * @throws \think\db\exception\DataNotFoundException
  434. * @throws \think\db\exception\ModelNotFoundException
  435. */
  436. public function authBindingPhone($code, $iv, $encryptedData, $spread_code, $spread_uid, $key = '')
  437. {
  438. $wechatInfo = [];
  439. $userType = $login_type = 'routine';
  440. if ($key) {
  441. [$openid, $wechatInfo, $spread_uid, $login_type, $userType] = $createData = CacheService::getTokenBucket($key);
  442. }
  443. $userInfoConfig = $this->getUserInfoByCode((string)$code);
  444. $userInfo = $this->encryptorUserInfo($userInfoConfig, $iv, $encryptedData);
  445. if (!$userInfo || !isset($userInfo['purePhoneNumber'])) {
  446. throw new ValidateException('获取用户信息失败');
  447. }
  448. $openid = $userInfoConfig['openid'];
  449. $wechatInfo['openid'] = $openid;
  450. $wechatInfo['unionid'] = $userInfoConfig['unionid'] ?? '';
  451. $wechatInfo['spread_uid'] = $spread_uid;
  452. $wechatInfo['spread_code'] = $spread_code;
  453. $wechatInfo['session_key'] = $userInfoConfig['session_key'] ?? '';
  454. $wechatInfo['phone'] = $userInfo['purePhoneNumber'];
  455. $createData = $this->routineOauth($wechatInfo);
  456. $wechatInfo = $createData[1] ?? [];
  457. /** @var WechatUserServices $wechatUserServices */
  458. $wechatUserServices = app()->make(WechatUserServices::class);
  459. //写入用户信息
  460. $user = $wechatUserServices->wechatOauthAfter([$openid, $wechatInfo, $spread_uid, $login_type, $userType]);
  461. return $this->getReturnInfo($user);
  462. }
  463. /**
  464. * 更新用户信息
  465. * @param $uid
  466. * @param array $data
  467. * @return bool
  468. * @throws \think\db\exception\DataNotFoundException
  469. * @throws \think\db\exception\DbException
  470. * @throws \think\db\exception\ModelNotFoundException
  471. */
  472. public function updateUserInfo($uid, array $data)
  473. {
  474. /** @var UserServices $userServices */
  475. $userServices = app()->make(UserServices::class);
  476. $user = $userServices->getUserInfo($uid);
  477. if (!$user) {
  478. throw new ValidateException('数据不存在');
  479. }
  480. $userInfo = [];
  481. $userInfo['nickname'] = filter_emoji($data['nickName'] ?? '');//姓名
  482. $userInfo['sex'] = $data['gender'] ?? '';//性别
  483. $userInfo['language'] = $data['language'] ?? '';//语言
  484. $userInfo['city'] = $data['city'] ?? '';//城市
  485. $userInfo['province'] = $data['province'] ?? '';//省份
  486. $userInfo['country'] = $data['country'] ?? '';//国家
  487. $userInfo['headimgurl'] = $data['avatarUrl'] ?? '';//头像
  488. $userInfo['is_complete'] = 1;
  489. /** @var LoginServices $loginService */
  490. $loginService = app()->make(LoginServices::class);
  491. $loginService->updateUserInfo($userInfo, $user);
  492. //更新用户信息
  493. if (!$this->dao->update(['uid' => $user['uid'], 'user_type' => 'routine'], $userInfo)) {
  494. throw new ValidateException('更新失败');
  495. }
  496. return true;
  497. }
  498. }