RoutineServices.php 14 KB

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