RoutineServices.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 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\other\QrcodeServices;
  17. use app\services\user\LoginServices;
  18. use app\services\user\UserServices;
  19. use app\services\user\UserVisitServices;
  20. use crmeb\exceptions\ApiException;
  21. use crmeb\services\CacheService;
  22. use crmeb\services\app\MiniProgramService;
  23. use crmeb\services\oauth\OAuth;
  24. /**
  25. *
  26. * Class RoutineServices
  27. * @package app\services\wechat
  28. */
  29. class RoutineServices extends BaseServices
  30. {
  31. /**
  32. * RoutineServices constructor.
  33. * @param WechatUserDao $dao
  34. */
  35. public function __construct(WechatUserDao $dao)
  36. {
  37. $this->dao = $dao;
  38. }
  39. /**
  40. * 返回用户信息的缓存key,返回是否强制绑定手机号
  41. * @param $code
  42. * @param $spread
  43. * @param $spid
  44. * @return array
  45. * @author: 吴汐
  46. * @email: 442384644@qq.com
  47. * @date: 2023/8/12
  48. */
  49. public function authType($code, $spread, $spid)
  50. {
  51. $agent_id = 0;
  52. $userInfoConfig = app()->make(OAuth::class, ['mini_program'])->oauth($code, ['silence' => true]);
  53. if (!isset($userInfoConfig['openid'])) {
  54. throw new ApiException(410078);
  55. }
  56. $routineInfo = ['unionid' => $userInfoConfig['unionid'] ?? ''];
  57. $info = app()->make(QrcodeServices::class)->getOne(['id' => $spread, 'status' => 1]);
  58. if ($spread && $info) {
  59. if ($info['third_type'] == 'agent') {
  60. $agent_id = $info['third_id'];
  61. } else {
  62. $spid = $info['third_id'];
  63. }
  64. }
  65. $openid = $userInfoConfig['openid'];
  66. $routineInfo['openid'] = $openid;
  67. $routineInfo['spid'] = $spid;
  68. $routineInfo['code'] = $spread;
  69. $routineInfo['session_key'] = $userInfoConfig['session_key'];
  70. $routineInfo['headimgurl'] = sys_config('h5_avatar');
  71. $createData = [$openid, $routineInfo, $spid, $agent_id, 'routine', 'routine'];
  72. $userInfoKey = md5($openid . '_' . time() . '_routine');
  73. CacheService::set($userInfoKey, $createData, 7200);
  74. $bindPhone = false;
  75. $user = app()->make(WechatUserServices::class)->getAuthUserInfo($openid, 'routine');
  76. if (sys_config('store_user_mobile') && (($user && $user['phone'] == '') || !$user)) $bindPhone = true;
  77. return ['bindPhone' => $bindPhone, 'key' => $userInfoKey];
  78. }
  79. /**
  80. * 根据缓存获取token
  81. * @param $key
  82. * @return array
  83. * @throws \Psr\SimpleCache\InvalidArgumentException
  84. * @throws \think\db\exception\DataNotFoundException
  85. * @throws \think\db\exception\DbException
  86. * @throws \think\db\exception\ModelNotFoundException
  87. * @author: 吴汐
  88. * @email: 442384644@qq.com
  89. * @date: 2023/8/12
  90. */
  91. public function authLogin($key)
  92. {
  93. $createData = CacheService::get($key);
  94. //写入用户信息
  95. $user = app()->make(WechatUserServices::class)->wechatOauthAfter($createData);
  96. $token = $this->createToken((int)$user['uid'], 'api');
  97. if ($token) {
  98. app()->make(UserVisitServices::class)->loginSaveVisit($user);
  99. return [
  100. 'token' => $token['token'],
  101. 'expires_time' => $token['params']['exp'],
  102. 'bindName' => (int)sys_config('get_avatar') && $user['avatar'] == sys_config('h5_avatar'),
  103. ];
  104. } else {
  105. throw new ApiException(410019);
  106. }
  107. }
  108. /**
  109. * 自动获取手机号绑定
  110. * @param $code
  111. * @param $iv
  112. * @param $encryptedData
  113. * @param $spread
  114. * @param $spid
  115. * @param string $key
  116. * @return array
  117. * @throws \Psr\SimpleCache\InvalidArgumentException
  118. * @throws \think\db\exception\DataNotFoundException
  119. * @throws \think\db\exception\ModelNotFoundException
  120. */
  121. public function authBindingPhone($code, $iv, $encryptedData, $spread, $spid, $key = '')
  122. {
  123. $wechatInfo = [];
  124. $agent_id = 0;
  125. $userType = $login_type = 'routine';
  126. if ($key) {
  127. [$openid, $wechatInfo, $spreadId, $agent_id, $login_type, $userType] = CacheService::get($key);
  128. }
  129. /** @var OAuth $oauth */
  130. $oauth = app()->make(OAuth::class, ['mini_program']);
  131. [$userInfoCong, $userInfo] = $oauth->oauth($code, [
  132. 'iv' => $iv,
  133. 'encryptedData' => $encryptedData
  134. ]);
  135. $session_key = $userInfoCong['session_key'];
  136. if (!$userInfo || !isset($userInfo['purePhoneNumber'])) {
  137. throw new ApiException(410079);
  138. }
  139. $spreadId = $spid ?? 0;
  140. /** @var QrcodeServices $qrcode */
  141. $qrcode = app()->make(QrcodeServices::class);
  142. if ($spread && ($info = $qrcode->getOne(['id' => $spread, 'status' => 1]))) {
  143. $spreadId = $info['third_id'];
  144. }
  145. $openid = $userInfoCong['openid'];
  146. $wechatInfo['openid'] = $openid;
  147. $wechatInfo['unionid'] = $userInfoCong['unionid'] ?? '';
  148. $wechatInfo['spid'] = $spreadId;
  149. $wechatInfo['code'] = $spread;
  150. $wechatInfo['session_key'] = $session_key;
  151. $wechatInfo['phone'] = $userInfo['purePhoneNumber'];
  152. /** @var WechatUserServices $wechatUserServices */
  153. $wechatUserServices = app()->make(WechatUserServices::class);
  154. //写入用户信息
  155. $user = $wechatUserServices->wechatOauthAfter([$openid, $wechatInfo, $spreadId, $agent_id, $login_type, $userType]);
  156. $token = $this->createToken((int)$user['uid'], 'api');
  157. if ($token) {
  158. app()->make(UserVisitServices::class)->loginSaveVisit($user);
  159. return [
  160. 'token' => $token['token'],
  161. 'expires_time' => $token['params']['exp'],
  162. 'bindName' => (int)sys_config('get_avatar') && $user['avatar'] == sys_config('h5_avatar'),
  163. ];
  164. } else {
  165. throw new ApiException(410019);
  166. }
  167. }
  168. /**
  169. * 小程序手机号登录
  170. * @param $key
  171. * @param $phone
  172. * @param string $spread_code
  173. * @param string $spread_spid
  174. * @param string $code
  175. * @return array
  176. * @throws \Psr\SimpleCache\InvalidArgumentException
  177. * @throws \think\db\exception\DataNotFoundException
  178. * @throws \think\db\exception\DbException
  179. * @throws \think\db\exception\ModelNotFoundException
  180. * @author: 吴汐
  181. * @email: 442384644@qq.com
  182. * @date: 2023/8/12
  183. */
  184. public function phoneLogin($key, $phone, $spread = '', $agent_id = '', $spid = '', $code = '')
  185. {
  186. if ($code == '') {
  187. [$openid, $routineInfo, $spid, $agent_id, $login_type, $userType] = CacheService::get($key);
  188. $routineInfo['phone'] = $phone;
  189. $createData = [$openid, $routineInfo, $spid, $agent_id, $login_type, $userType];
  190. } else {
  191. $userInfoConfig = app()->make(OAuth::class, ['mini_program'])->oauth($code, ['silence' => true]);
  192. if (!isset($userInfoConfig['openid'])) {
  193. throw new ApiException(410078);
  194. }
  195. $routineInfo = ['unionid' => $userInfoConfig['unionid'] ?? ''];
  196. $info = app()->make(QrcodeServices::class)->getOne(['id' => $spread, 'status' => 1]);
  197. if ($spread && $info) {
  198. $spid = $info['third_id'];
  199. }
  200. $openid = $userInfoConfig['openid'];
  201. $routineInfo['openid'] = $openid;
  202. $routineInfo['spid'] = $spid;
  203. $routineInfo['code'] = $spread;
  204. $routineInfo['session_key'] = $userInfoConfig['session_key'];
  205. $routineInfo['headimgurl'] = sys_config('h5_avatar');
  206. $routineInfo['phone'] = $phone;
  207. $createData = [$openid, $routineInfo, $spid, $agent_id, 'routine', 'routine'];
  208. }
  209. //写入用户信息
  210. $user = app()->make(WechatUserServices::class)->wechatOauthAfter($createData);
  211. $token = $this->createToken((int)$user['uid'], 'api');
  212. if ($token) {
  213. app()->make(UserVisitServices::class)->loginSaveVisit($user);
  214. return [
  215. 'token' => $token['token'],
  216. 'expires_time' => $token['params']['exp'],
  217. 'bindName' => (int)sys_config('get_avatar') && $user['avatar'] == sys_config('h5_avatar'),
  218. ];
  219. } else {
  220. throw new ApiException(410019);
  221. }
  222. }
  223. /**
  224. * 小程序绑定手机号
  225. * @param $code
  226. * @param $iv
  227. * @param $encryptedData
  228. * @return bool
  229. * @author 吴汐
  230. * @email 442384644@qq.com
  231. * @date 2023/02/24
  232. */
  233. public function bindingPhone($code, $iv, $encryptedData)
  234. {
  235. [$userInfoCong, $userInfo] = app()->make(OAuth::class, ['mini_program'])->oauth($code, [
  236. 'iv' => $iv,
  237. 'encryptedData' => $encryptedData
  238. ]);
  239. if (!$userInfo || !isset($userInfo['purePhoneNumber'])) {
  240. throw new ApiException(410079);
  241. }
  242. $uid = app()->make(WechatUserServices::class)->openidToUid($userInfoCong['openid']);
  243. $userServices = app()->make(UserServices::class);
  244. if ($userServices->count(['phone' => $userInfo['purePhoneNumber'], 'is_del' => 0])) {
  245. throw new ApiException(410028);
  246. }
  247. $res = $userServices->update(['uid' => $uid], ['phone' => $userInfo['purePhoneNumber']]);
  248. if ($res) return true;
  249. throw new ApiException(410017);
  250. }
  251. /**
  252. * 小程序创建用户后返回uid
  253. * @param $routine
  254. * @return array
  255. */
  256. public function routineOauth($routine)
  257. {
  258. $routineInfo['nickname'] = filter_emoji($routine['nickName']);//姓名
  259. $routineInfo['sex'] = $routine['gender'];//性别
  260. $routineInfo['language'] = $routine['language'];//语言
  261. $routineInfo['city'] = $routine['city'];//城市
  262. $routineInfo['province'] = $routine['province'];//省份
  263. $routineInfo['country'] = $routine['country'];//国家
  264. $routineInfo['headimgurl'] = $routine['avatarUrl'];//头像
  265. $routineInfo['openid'] = $routine['openId'];
  266. $routineInfo['session_key'] = $routine['session_key'];//会话密匙
  267. $routineInfo['unionid'] = $routine['unionId'];//用户在开放平台的唯一标识符
  268. $routineInfo['user_type'] = 'routine';//用户类型
  269. $routineInfo['phone'] = $routine['phone'] ?? $routine['purePhoneNumber'] ?? '';
  270. $spid = $routine['spid'] ?? 0;//绑定关系uid
  271. //获取是否有扫码进小程序
  272. /** @var QrcodeServices $qrcode */
  273. $qrcode = app()->make(QrcodeServices::class);
  274. if (isset($routine['code']) && $routine['code'] && ($info = $qrcode->get($routine['code']))) {
  275. $spid = $info['third_id'];
  276. }
  277. return [$routine['openId'], $routineInfo, $spid, $routine['login_type'] ?? 'routine', 'routine'];
  278. }
  279. /**
  280. * 小程序支付回调
  281. * @return \Symfony\Component\HttpFoundation\Response
  282. * @throws \EasyWeChat\Core\Exceptions\FaultException
  283. */
  284. public function notify()
  285. {
  286. return MiniProgramService::handleNotify();
  287. }
  288. /**
  289. * 获取小程序订阅消息id
  290. * @return bool|mixed|null
  291. */
  292. public function tempIds()
  293. {
  294. return CacheService::remember('TEMP_IDS_LIST', function () {
  295. /** @var SystemNotificationServices $sysNotify */
  296. $sysNotify = app()->make(SystemNotificationServices::class);
  297. return $sysNotify->getColumn([['routine_tempid', '<>', '']], 'routine_tempid', 'mark');
  298. });
  299. }
  300. /**
  301. * 获取小程序直播列表
  302. * @param $page
  303. * @param $limit
  304. * @return array|bool|mixed
  305. */
  306. public function live($page, $limit)
  307. {
  308. $list = CacheService::remember('WECHAT_LIVE_LIST_' . $page . '_' . $limit, function () use ($page, $limit) {
  309. $list = MiniProgramService::getLiveInfo((int)$page, (int)$limit);
  310. foreach ($list as &$item) {
  311. $item['_start_time'] = date('m-d H:i', $item['start_time']);
  312. }
  313. return $list;
  314. }, 600) ?: [];
  315. return $list;
  316. }
  317. /**
  318. * 更新用户信息
  319. * @param $uid
  320. * @param array $data
  321. * @return bool
  322. * @throws \think\db\exception\DataNotFoundException
  323. * @throws \think\db\exception\DbException
  324. * @throws \think\db\exception\ModelNotFoundException
  325. */
  326. public function updateUserInfo($uid, array $data)
  327. {
  328. /** @var UserServices $userServices */
  329. $userServices = app()->make(UserServices::class);
  330. $user = $userServices->getUserInfo($uid);
  331. if (!$user) {
  332. throw new ApiException(100026);
  333. }
  334. $userInfo = [];
  335. $userInfo['nickname'] = filter_emoji($data['nickName'] ?? '');//姓名
  336. $userInfo['sex'] = $data['gender'] ?? '';//性别
  337. $userInfo['language'] = $data['language'] ?? '';//语言
  338. $userInfo['city'] = $data['city'] ?? '';//城市
  339. $userInfo['province'] = $data['province'] ?? '';//省份
  340. $userInfo['country'] = $data['country'] ?? '';//国家
  341. $userInfo['headimgurl'] = $data['avatarUrl'] ?? '';//头像
  342. $userInfo['is_complete'] = 1;
  343. /** @var LoginServices $loginService */
  344. $loginService = app()->make(LoginServices::class);
  345. $loginService->updateUserInfo($userInfo, $user);
  346. //更新用户信息
  347. if (!$this->dao->update(['uid' => $user['uid'], 'user_type' => 'routine'], $userInfo)) {
  348. throw new ApiException(100013);
  349. }
  350. return true;
  351. }
  352. }