RoutineServices.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. @file_put_contents('quanju.txt', $key."-微信手机登录routine\r\n", 8);
  124. $wechatInfo = [];
  125. $agent_id = 0;
  126. $userType = $login_type = 'routine';
  127. if ($key) {
  128. [$openid, $wechatInfo, $spreadId, $agent_id, $login_type, $userType] = CacheService::get($key);
  129. }
  130. /** @var OAuth $oauth */
  131. $oauth = app()->make(OAuth::class, ['mini_program']);
  132. [$userInfoCong, $userInfo] = $oauth->oauth($code, [
  133. 'iv' => $iv,
  134. 'encryptedData' => $encryptedData
  135. ]);
  136. $session_key = $userInfoCong['session_key'];
  137. if (!$userInfo || !isset($userInfo['purePhoneNumber'])) {
  138. throw new ApiException(410079);
  139. }
  140. $spreadId = $spid ?? 0;
  141. /** @var QrcodeServices $qrcode */
  142. $qrcode = app()->make(QrcodeServices::class);
  143. if ($spread && ($info = $qrcode->getOne(['id' => $spread, 'status' => 1]))) {
  144. $spreadId = $info['third_id'];
  145. }
  146. $openid = $userInfoCong['openid'];
  147. $wechatInfo['openid'] = $openid;
  148. $wechatInfo['unionid'] = $userInfoCong['unionid'] ?? '';
  149. $wechatInfo['spid'] = $spreadId;
  150. $wechatInfo['code'] = $spread;
  151. $wechatInfo['session_key'] = $session_key;
  152. $wechatInfo['phone'] = $userInfo['purePhoneNumber'];
  153. /** @var WechatUserServices $wechatUserServices */
  154. $wechatUserServices = app()->make(WechatUserServices::class);
  155. //写入用户信息
  156. $user = $wechatUserServices->wechatOauthAfter([$openid, $wechatInfo, $spreadId, $agent_id, $login_type, $userType]);
  157. $token = $this->createToken((int)$user['uid'], 'api');
  158. if ($token) {
  159. app()->make(UserVisitServices::class)->loginSaveVisit($user);
  160. return [
  161. 'token' => $token['token'],
  162. 'expires_time' => $token['params']['exp'],
  163. 'bindName' => (int)sys_config('get_avatar') && $user['avatar'] == sys_config('h5_avatar'),
  164. ];
  165. } else {
  166. throw new ApiException(410019);
  167. }
  168. }
  169. /**
  170. * 小程序手机号登录
  171. * @param $key
  172. * @param $phone
  173. * @param string $spread_code
  174. * @param string $spread_spid
  175. * @param string $code
  176. * @return array
  177. * @throws \Psr\SimpleCache\InvalidArgumentException
  178. * @throws \think\db\exception\DataNotFoundException
  179. * @throws \think\db\exception\DbException
  180. * @throws \think\db\exception\ModelNotFoundException
  181. * @author: 吴汐
  182. * @email: 442384644@qq.com
  183. * @date: 2023/8/12
  184. */
  185. public function phoneLogin($key, $phone, $spread = '', $agent_id = '', $spid = '', $code = '')
  186. {
  187. if ($code == '') {
  188. [$openid, $routineInfo, $spid, $agent_id, $login_type, $userType] = CacheService::get($key);
  189. $routineInfo['phone'] = $phone;
  190. $createData = [$openid, $routineInfo, $spid, $agent_id, $login_type, $userType];
  191. } else {
  192. $userInfoConfig = app()->make(OAuth::class, ['mini_program'])->oauth($code, ['silence' => true]);
  193. if (!isset($userInfoConfig['openid'])) {
  194. throw new ApiException(410078);
  195. }
  196. $routineInfo = ['unionid' => $userInfoConfig['unionid'] ?? ''];
  197. $info = app()->make(QrcodeServices::class)->getOne(['id' => $spread, 'status' => 1]);
  198. if ($spread && $info) {
  199. $spid = $info['third_id'];
  200. }
  201. $openid = $userInfoConfig['openid'];
  202. $routineInfo['openid'] = $openid;
  203. $routineInfo['spid'] = $spid;
  204. $routineInfo['code'] = $spread;
  205. $routineInfo['session_key'] = $userInfoConfig['session_key'];
  206. $routineInfo['headimgurl'] = sys_config('h5_avatar');
  207. $routineInfo['phone'] = $phone;
  208. $createData = [$openid, $routineInfo, $spid, $agent_id, 'routine', 'routine'];
  209. }
  210. //写入用户信息
  211. $user = app()->make(WechatUserServices::class)->wechatOauthAfter($createData);
  212. $token = $this->createToken((int)$user['uid'], 'api');
  213. if ($token) {
  214. app()->make(UserVisitServices::class)->loginSaveVisit($user);
  215. return [
  216. 'token' => $token['token'],
  217. 'expires_time' => $token['params']['exp'],
  218. 'bindName' => (int)sys_config('get_avatar') && $user['avatar'] == sys_config('h5_avatar'),
  219. ];
  220. } else {
  221. throw new ApiException(410019);
  222. }
  223. }
  224. /**
  225. * 小程序绑定手机号
  226. * @param $code
  227. * @param $iv
  228. * @param $encryptedData
  229. * @return bool
  230. * @author 吴汐
  231. * @email 442384644@qq.com
  232. * @date 2023/02/24
  233. */
  234. public function bindingPhone($code, $iv, $encryptedData)
  235. {
  236. [$userInfoCong, $userInfo] = app()->make(OAuth::class, ['mini_program'])->oauth($code, [
  237. 'iv' => $iv,
  238. 'encryptedData' => $encryptedData
  239. ]);
  240. if (!$userInfo || !isset($userInfo['purePhoneNumber'])) {
  241. throw new ApiException(410079);
  242. }
  243. $uid = app()->make(WechatUserServices::class)->openidToUid($userInfoCong['openid']);
  244. $userServices = app()->make(UserServices::class);
  245. if ($userServices->count(['phone' => $userInfo['purePhoneNumber'], 'is_del' => 0])) {
  246. throw new ApiException(410028);
  247. }
  248. $res = $userServices->update(['uid' => $uid], ['phone' => $userInfo['purePhoneNumber']]);
  249. if ($res) return true;
  250. throw new ApiException(410017);
  251. }
  252. /**
  253. * 小程序创建用户后返回uid
  254. * @param $routine
  255. * @return array
  256. */
  257. public function routineOauth($routine)
  258. {
  259. $routineInfo['nickname'] = filter_emoji($routine['nickName']);//姓名
  260. $routineInfo['sex'] = $routine['gender'];//性别
  261. $routineInfo['language'] = $routine['language'];//语言
  262. $routineInfo['city'] = $routine['city'];//城市
  263. $routineInfo['province'] = $routine['province'];//省份
  264. $routineInfo['country'] = $routine['country'];//国家
  265. $routineInfo['headimgurl'] = $routine['avatarUrl'];//头像
  266. $routineInfo['openid'] = $routine['openId'];
  267. $routineInfo['session_key'] = $routine['session_key'];//会话密匙
  268. $routineInfo['unionid'] = $routine['unionId'];//用户在开放平台的唯一标识符
  269. $routineInfo['user_type'] = 'routine';//用户类型
  270. $routineInfo['phone'] = $routine['phone'] ?? $routine['purePhoneNumber'] ?? '';
  271. $spid = $routine['spid'] ?? 0;//绑定关系uid
  272. //获取是否有扫码进小程序
  273. /** @var QrcodeServices $qrcode */
  274. $qrcode = app()->make(QrcodeServices::class);
  275. if (isset($routine['code']) && $routine['code'] && ($info = $qrcode->get($routine['code']))) {
  276. $spid = $info['third_id'];
  277. }
  278. return [$routine['openId'], $routineInfo, $spid, $routine['login_type'] ?? 'routine', 'routine'];
  279. }
  280. /**
  281. * 小程序支付回调
  282. * @return \Symfony\Component\HttpFoundation\Response
  283. * @throws \EasyWeChat\Core\Exceptions\FaultException
  284. */
  285. public function notify()
  286. {
  287. return MiniProgramService::handleNotify();
  288. }
  289. /**
  290. * 获取小程序订阅消息id
  291. * @return bool|mixed|null
  292. */
  293. public function tempIds()
  294. {
  295. return CacheService::remember('TEMP_IDS_LIST', function () {
  296. /** @var SystemNotificationServices $sysNotify */
  297. $sysNotify = app()->make(SystemNotificationServices::class);
  298. return $sysNotify->getColumn([['routine_tempid', '<>', '']], 'routine_tempid', 'mark');
  299. });
  300. }
  301. /**
  302. * 获取小程序直播列表
  303. * @param $page
  304. * @param $limit
  305. * @return array|bool|mixed
  306. */
  307. public function live($page, $limit)
  308. {
  309. $list = CacheService::remember('WECHAT_LIVE_LIST_' . $page . '_' . $limit, function () use ($page, $limit) {
  310. $list = MiniProgramService::getLiveInfo((int)$page, (int)$limit);
  311. foreach ($list as &$item) {
  312. $item['_start_time'] = date('m-d H:i', $item['start_time']);
  313. }
  314. return $list;
  315. }, 600) ?: [];
  316. return $list;
  317. }
  318. /**
  319. * 更新用户信息
  320. * @param $uid
  321. * @param array $data
  322. * @return bool
  323. * @throws \think\db\exception\DataNotFoundException
  324. * @throws \think\db\exception\DbException
  325. * @throws \think\db\exception\ModelNotFoundException
  326. */
  327. public function updateUserInfo($uid, array $data)
  328. {
  329. /** @var UserServices $userServices */
  330. $userServices = app()->make(UserServices::class);
  331. $user = $userServices->getUserInfo($uid);
  332. if (!$user) {
  333. throw new ApiException(100026);
  334. }
  335. $userInfo = [];
  336. $userInfo['nickname'] = filter_emoji($data['nickName'] ?? '');//姓名
  337. $userInfo['sex'] = $data['gender'] ?? '';//性别
  338. $userInfo['language'] = $data['language'] ?? '';//语言
  339. $userInfo['city'] = $data['city'] ?? '';//城市
  340. $userInfo['province'] = $data['province'] ?? '';//省份
  341. $userInfo['country'] = $data['country'] ?? '';//国家
  342. $userInfo['headimgurl'] = $data['avatarUrl'] ?? '';//头像
  343. $userInfo['is_complete'] = 1;
  344. /** @var LoginServices $loginService */
  345. $loginService = app()->make(LoginServices::class);
  346. $loginService->updateUserInfo($userInfo, $user);
  347. //更新用户信息
  348. if (!$this->dao->update(['uid' => $user['uid'], 'user_type' => 'routine'], $userInfo)) {
  349. throw new ApiException(100013);
  350. }
  351. return true;
  352. }
  353. }