RoutineServices.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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\CacheService as Cache;
  21. use crmeb\services\MiniProgramService;
  22. use crmeb\services\template\Template;
  23. use think\exception\ValidateException;
  24. use think\facade\Config;
  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 mixed
  50. */
  51. public function mp_auth($code, $post_cache_key, $login_type, $spread_spid, $spread_code, $iv, $encryptedData)
  52. {
  53. $session_key = Cache::get('eb_api_code_' . $post_cache_key);
  54. $userInfoCong = [];
  55. if (!$code && !$session_key)
  56. throw new ValidateException('授权失败,参数有误');
  57. if ($code && !$session_key) {
  58. try {
  59. $userInfoCong = MiniProgramService::getUserInfo($code);
  60. $session_key = $userInfoCong['session_key'];
  61. $cache_key = md5(time() . $code);
  62. Cache::set('eb_api_code_' . $cache_key, $session_key, 86400);
  63. if (!isset($userInfoCong['openid'])) {
  64. throw new ValidateException('openid获取失败');
  65. }
  66. } catch (\Exception $e) {
  67. throw new ValidateException('获取session_key失败,请检查您的配置!:' . $e->getMessage() . 'line' . $e->getLine());
  68. }
  69. }
  70. try {
  71. //解密获取用户信息
  72. $userInfo = MiniProgramService::encryptor($session_key, $iv, $encryptedData);
  73. } catch (\Exception $e) {
  74. if ($e->getCode() == '-41003') {
  75. throw new ValidateException('获取会话密匙失败');
  76. }
  77. }
  78. $userInfo['unionId'] = isset($userInfoCong['unionid']) ? $userInfoCong['unionid'] : '';
  79. $userInfo['openId'] = $openid = $userInfoCong['openid'];
  80. $userInfo['spid'] = $spread_spid;
  81. $userInfo['code'] = $spread_code;
  82. $userInfo['session_key'] = $session_key;
  83. $userInfo['login_type'] = $login_type;
  84. $createData = $this->routineOauth($userInfo);
  85. /** @var WechatUserServices $wechatUserServices */
  86. $wechatUserServices = app()->make(WechatUserServices::class);
  87. $user = $wechatUserServices->getAuthUserInfo($openid, 'routine');
  88. if (!$user) {
  89. $user = $wechatUserServices->wechatOauthAfter($createData);
  90. } else {
  91. //更新用户信息
  92. $wechatUserServices->wechatUpdata([$user['uid'], $createData[1]]);
  93. }
  94. $token = $this->createToken((int)$user['uid'], 'routine');
  95. if ($token) {
  96. /** @var UserVisitServices $visitServices */
  97. $visitServices = app()->make(UserVisitServices::class);
  98. $visitServices->loginSaveVisit($user);
  99. return [
  100. 'userInfo' => $user
  101. ];
  102. } else
  103. throw new ValidateException('获取用户访问token失败!');
  104. }
  105. /**
  106. * 小程序授权登录
  107. * @param $code
  108. * @param $spid
  109. * @param $spread
  110. * @param $iv
  111. * @param $encryptedData
  112. * @return array
  113. * @throws \think\db\exception\DataNotFoundException
  114. * @throws \think\db\exception\ModelNotFoundException
  115. */
  116. public function newAuth($code, $spid, $spread, $iv, $encryptedData)
  117. {
  118. if (!$code)
  119. throw new ValidateException('授权失败,参数有误');
  120. $session_key = '';
  121. try {
  122. $userInfoCong = MiniProgramService::getUserInfo($code);
  123. $session_key = $userInfoCong['session_key'];
  124. } catch (\Exception $e) {
  125. throw new ValidateException('获取session_key失败,请检查您的配置!:' . $e->getMessage() . 'line' . $e->getLine());
  126. }
  127. if (!isset($userInfoCong['openid'])) {
  128. throw new ValidateException('openid获取失败');
  129. }
  130. try {
  131. //解密获取用户信息
  132. $userInfo = MiniProgramService::encryptor($session_key, $iv, $encryptedData);
  133. } catch (\Exception $e) {
  134. if ($e->getCode() == '-41003') {
  135. throw new ValidateException('获取会话密匙失败');
  136. }
  137. }
  138. if (!isset($userInfoCong['openid'])) {
  139. throw new ValidateException('openid获取失败');
  140. }
  141. $userInfo['unionId'] = isset($userInfoCong['unionid']) ? $userInfoCong['unionid'] : '';
  142. $userInfo['openId'] = $openid = $userInfoCong['openid'];
  143. $userInfo['spid'] = $spid;
  144. $userInfo['code'] = $spread;
  145. $userInfo['session_key'] = $session_key;
  146. $userInfo['login_type'] = 'routine';
  147. $createData = $this->routineOauth($userInfo);
  148. /** @var WechatUserServices $wechatUserServices */
  149. $wechatUserServices = app()->make(WechatUserServices::class);
  150. $user = $wechatUserServices->getAuthUserInfo($openid, 'routine');
  151. //获取是否强制绑定手机号
  152. $storeUserMobile = sys_config('store_user_mobile');
  153. if ($storeUserMobile && !$user) {
  154. $userInfoKey = md5($openid . '_' . time() . '_rouine');
  155. Cache::setTokenBucket($userInfoKey, $createData, 7200);
  156. return ['key' => $userInfoKey];
  157. } else if (!$user) {
  158. $user = $wechatUserServices->wechatOauthAfter($createData);
  159. } else {
  160. //更新用户信息
  161. $wechatUserServices->wechatUpdata([$user['uid'], $createData[1]]);
  162. }
  163. $token = $this->createToken((int)$user['uid'], 'routine');
  164. if ($token) {
  165. /** @var UserVisitServices $visitServices */
  166. $visitServices = app()->make(UserVisitServices::class);
  167. $visitServices->loginSaveVisit($user);
  168. $token['userInfo'] = $user;
  169. return $token;
  170. } else
  171. throw new ValidateException('登录失败');
  172. }
  173. /**
  174. * 小程序创建用户后返回uid
  175. * @param $routineInfo
  176. * @return mixed
  177. */
  178. public function routineOauth($routine)
  179. {
  180. $routineInfo['nickname'] = filter_emoji($routine['nickName']);//姓名
  181. $routineInfo['sex'] = $routine['gender'];//性别
  182. $routineInfo['language'] = $routine['language'];//语言
  183. $routineInfo['city'] = $routine['city'];//城市
  184. $routineInfo['province'] = $routine['province'];//省份
  185. $routineInfo['country'] = $routine['country'];//国家
  186. $routineInfo['headimgurl'] = $routine['avatarUrl'];//头像
  187. $routineInfo['openid'] = $routine['openId'];
  188. $routineInfo['session_key'] = $routine['session_key'];//会话密匙
  189. $routineInfo['unionid'] = $routine['unionId'];//用户在开放平台的唯一标识符
  190. $routineInfo['user_type'] = 'routine';//用户类型
  191. $routineInfo['phone'] = $routine['phone'] ?? $routine['purePhoneNumber'] ?? '';
  192. $spid = $routine['spid'] ?? 0;//绑定关系uid
  193. //获取是否有扫码进小程序
  194. /** @var QrcodeServices $qrcode */
  195. $qrcode = app()->make(QrcodeServices::class);
  196. if (isset($routine['code']) && $routine['code'] && ($info = $qrcode->get($routine['code']))) {
  197. $spid = $info['third_id'];
  198. }
  199. return [$routine['openId'], $routineInfo, $spid, $routine['login_type'] ?? 'routine', 'routine'];
  200. }
  201. /**
  202. * 小程序支付回调
  203. */
  204. public function notify()
  205. {
  206. return MiniProgramService::handleNotify();
  207. }
  208. /**
  209. * 获取小程序订阅消息id
  210. * @return mixed
  211. */
  212. public function temlIds()
  213. {
  214. $temlIdsName = Config::get('template.stores.subscribe.template_id', []);
  215. $temlIdsList = Cache::get('TEML_IDS_LIST', function () use ($temlIdsName) {
  216. $temlId = [];
  217. $templdata = new Template('subscribe');
  218. foreach ($temlIdsName as $key => $item) {
  219. $temlId[strtolower($key)] = $templdata->getTempId($item);
  220. }
  221. return $temlId;
  222. });
  223. return $temlIdsList;
  224. }
  225. /**
  226. * 获取小程序直播列表
  227. * @param $pgae
  228. * @param $limit
  229. * @return mixed
  230. */
  231. public function live($page, $limit)
  232. {
  233. $list = Cache::get('WECHAT_LIVE_LIST_' . $page . '_' . $limit, function () use ($page, $limit) {
  234. $list = MiniProgramService::getLiveInfo((int)$page, (int)$limit);
  235. foreach ($list as &$item) {
  236. $item['_start_time'] = date('m-d H:i', $item['start_time']);
  237. }
  238. return $list;
  239. }, 600) ?: [];
  240. return $list;
  241. }
  242. /**
  243. * 静默授权
  244. * @param $code
  245. * @param $spread
  246. * @return mixed
  247. */
  248. public function silenceAuth($code, $spread, $spid)
  249. {
  250. $userInfoConfig = MiniProgramService::getUserInfo($code);
  251. if (!isset($userInfoConfig['openid'])) {
  252. throw new ValidateException('静默授权失败');
  253. }
  254. $routineInfo = [
  255. 'unionid' => $userInfoConfig['unionid'] ?? ''
  256. ];
  257. /** @var QrcodeServices $qrcode */
  258. $qrcode = app()->make(QrcodeServices::class);
  259. if ($spread && ($info = $qrcode->getOne(['id' => $spread, 'status' => 1]))) {
  260. $spid = $info['third_id'];
  261. }
  262. $openid = $userInfoConfig['openid'];
  263. $routineInfo['openid'] = $openid;
  264. $routineInfo['headimgurl'] = sys_config('h5_avatar');
  265. /** @var WechatUserServices $wechatUserServices */
  266. $wechatUserServices = app()->make(WechatUserServices::class);
  267. $user = $wechatUserServices->getAuthUserInfo($openid, 'routine');
  268. $createData = [$openid, $routineInfo, $spid, '', 'routine'];
  269. //获取是否强制绑定手机号
  270. $storeUserMobile = sys_config('store_user_mobile');
  271. if ($storeUserMobile && !$user) {
  272. $userInfoKey = md5($openid . '_' . time() . '_routine');
  273. Cache::setTokenBucket($userInfoKey, $createData, 7200);
  274. return ['key' => $userInfoKey];
  275. } else if (!$user) {
  276. //写入用户信息
  277. $user = $wechatUserServices->wechatOauthAfter($createData);
  278. $token = $this->createToken((int)$user['uid'], 'routine');
  279. if ($token) {
  280. return $token;
  281. } else
  282. throw new ValidateException('登录失败');
  283. } else {
  284. //更新用户信息
  285. $wechatUserServices->wechatUpdata([$user['uid'], ['code' => $spid]]);
  286. $token = $this->createToken((int)$user['uid'], 'routine');
  287. /** @var UserVisitServices $visitServices */
  288. $visitServices = app()->make(UserVisitServices::class);
  289. $visitServices->loginSaveVisit($user);
  290. if ($token) {
  291. return $token;
  292. } else
  293. throw new ValidateException('登录失败');
  294. }
  295. }
  296. /**
  297. * 静默授权
  298. * @param $code
  299. * @param $spread
  300. * @return mixed
  301. */
  302. public function silenceAuthNoLogin($code, $spread, $spid)
  303. {
  304. $userInfoConfig = MiniProgramService::getUserInfo($code);
  305. if (!isset($userInfoConfig['openid'])) {
  306. throw new ValidateException('静默授权失败');
  307. }
  308. $routineInfo = [
  309. 'unionid' => $userInfoConfig['unionid'] ?? ''
  310. ];
  311. /** @var QrcodeServices $qrcode */
  312. $qrcode = app()->make(QrcodeServices::class);
  313. if ($spread && ($info = $qrcode->getOne(['id' => $spread, 'status' => 1]))) {
  314. $spid = $info['third_id'];
  315. }
  316. $openid = $userInfoConfig['openid'];
  317. $routineInfo['openid'] = $openid;
  318. $routineInfo['headimgurl'] = sys_config('h5_avatar');
  319. /** @var WechatUserServices $wechatUserServices */
  320. $wechatUserServices = app()->make(WechatUserServices::class);
  321. $user = $wechatUserServices->getAuthUserInfo($openid, 'routine');
  322. $createData = [$openid, $routineInfo, $spid, '', 'routine'];
  323. if (!$user) {
  324. $userInfoKey = md5($openid . '_' . time() . '_routine');
  325. Cache::setTokenBucket($userInfoKey, $createData, 7200);
  326. return ['auth_login' => 1, 'key' => $userInfoKey];
  327. } else {
  328. //更新用户信息
  329. $wechatUserServices->wechatUpdata([$user['uid'], ['code' => $spid]]);
  330. $token = $this->createToken((int)$user['uid'], 'routine');
  331. /** @var UserVisitServices $visitServices */
  332. $visitServices = app()->make(UserVisitServices::class);
  333. $visitServices->loginSaveVisit($user);
  334. if ($token) {
  335. $token['userInfo'] = $user;
  336. return $token;
  337. } else
  338. throw new ValidateException('登录失败');
  339. }
  340. }
  341. /**
  342. * 手机号登录 静默授权绑定关系
  343. * @param $code
  344. * @param $spread
  345. * @return mixed
  346. */
  347. public function silenceAuthBindingPhone($code, $spread, $spid, $phone)
  348. {
  349. $userInfoConfig = MiniProgramService::getUserInfo($code);
  350. if (!isset($userInfoConfig['openid'])) {
  351. throw new ValidateException('静默授权失败');
  352. }
  353. $routineInfo = [
  354. 'unionid' => $userInfoConfig['unionid'] ?? ''
  355. ];
  356. /** @var QrcodeServices $qrcode */
  357. $qrcode = app()->make(QrcodeServices::class);
  358. if ($spread && ($info = $qrcode->getOne(['id' => $spread, 'status' => 1]))) {
  359. $spid = $info['third_id'];
  360. }
  361. $openid = $userInfoConfig['openid'];
  362. $routineInfo['openid'] = $openid;
  363. $routineInfo['headimgurl'] = sys_config('h5_avatar');
  364. $routineInfo['phone'] = $phone;
  365. /** @var WechatUserServices $wechatUserServices */
  366. $wechatUserServices = app()->make(WechatUserServices::class);
  367. $createData = [$openid, $routineInfo, $spid, '', 'routine'];
  368. //写入用户信息
  369. $user = $wechatUserServices->wechatOauthAfter($createData);
  370. $token = $this->createToken((int)$user['uid'], 'routine');
  371. /** @var UserVisitServices $visitServices */
  372. $visitServices = app()->make(UserVisitServices::class);
  373. $visitServices->loginSaveVisit($user);
  374. if ($token) {
  375. return $token;
  376. } else
  377. throw new ValidateException('登录失败');
  378. }
  379. /**
  380. * 自动获取手机号绑定
  381. * @param $code
  382. * @param $spread
  383. * @return mixed
  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. try {
  394. $userInfoCong = MiniProgramService::getUserInfo($code);
  395. $session_key = $userInfoCong['session_key'];
  396. } catch (\Exception $e) {
  397. throw new ValidateException('获取session_key失败,请检查您的配置!:' . $e->getMessage() . 'line' . $e->getLine());
  398. }
  399. try {
  400. //解密获取用户信息
  401. $userInfo = MiniProgramService::encryptor($session_key, $iv, $encryptedData);
  402. if (!$userInfo || !isset($userInfo['purePhoneNumber'])) {
  403. throw new ValidateException('获取用户信息失败');
  404. }
  405. } catch (\Exception $e) {
  406. if ($e->getCode() == '-41003') {
  407. throw new ValidateException('获取会话密匙失败');
  408. }
  409. }
  410. $spreadId = $spid ?? 0;
  411. /** @var QrcodeServices $qrcode */
  412. $qrcode = app()->make(QrcodeServices::class);
  413. if ($spread && ($info = $qrcode->getOne(['id' => $spread, 'status' => 1]))) {
  414. $spreadId = $info['third_id'];
  415. }
  416. $openid = $userInfoCong['openid'];
  417. $wechatInfo['openid'] = $openid;
  418. $wechatInfo['unionid'] = $userInfoCong['unionid'] ?? '';
  419. $wechatInfo['spid'] = $spreadId;
  420. $wechatInfo['code'] = $spread;
  421. $wechatInfo['session_key'] = $session_key;
  422. $wechatInfo['phone'] = $userInfo['purePhoneNumber'];
  423. /** @var WechatUserServices $wechatUserServices */
  424. $wechatUserServices = app()->make(WechatUserServices::class);
  425. //写入用户信息
  426. $user = $wechatUserServices->wechatOauthAfter([$openid, $wechatInfo, $spreadId, $login_type, $userType]);
  427. $token = $this->createToken((int)$user['uid'], 'routine');
  428. if ($token) {
  429. /** @var UserVisitServices $visitServices */
  430. $visitServices = app()->make(UserVisitServices::class);
  431. $visitServices->loginSaveVisit($user);
  432. return [
  433. 'token' => $token['token'],
  434. 'userInfo' => $user,
  435. 'expires_time' => $token['params']['exp'],
  436. ];
  437. } else
  438. throw new ValidateException('登录失败');
  439. }
  440. public function updateUserInfo($uid, array $data)
  441. {
  442. /** @var UserServices $userServices */
  443. $userServices = app()->make(UserServices::class);
  444. $user = $userServices->getUserInfo($uid);
  445. if (!$user) {
  446. throw new ValidateException('数据不存在');
  447. }
  448. $userInfo = [];
  449. $userInfo['nickname'] = filter_emoji($data['nickName'] ?? '');//姓名
  450. $userInfo['sex'] = $data['gender'] ?? '';//性别
  451. $userInfo['language'] = $data['language'] ?? '';//语言
  452. $userInfo['city'] = $data['city'] ?? '';//城市
  453. $userInfo['province'] = $data['province'] ?? '';//省份
  454. $userInfo['country'] = $data['country'] ?? '';//国家
  455. $userInfo['headimgurl'] = $data['avatarUrl'] ?? '';//头像
  456. $userInfo['is_complete'] = 1;
  457. /** @var LoginServices $loginService */
  458. $loginService = app()->make(LoginServices::class);
  459. $loginService->updateUserInfo($userInfo, $user);
  460. //更新用户信息
  461. if (!$this->dao->update(['uid' => $user['uid'], 'user_type' => 'routine'], $userInfo)) {
  462. throw new ValidateException('更新失败');
  463. }
  464. return true;
  465. }
  466. }