AuthController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. <?php
  2. namespace app\api\controller\wechat;
  3. use app\models\user\WechatUser;
  4. use app\Request;
  5. use crmeb\services\CacheService;
  6. use crmeb\services\MiniProgramService;
  7. use crmeb\services\UtilService;
  8. use app\models\user\UserToken;
  9. use app\models\user\User;
  10. use think\facade\Cache;
  11. use crmeb\services\SubscribeTemplateService;
  12. use think\facade\Log;
  13. use tw\redis\UserRds;
  14. /**
  15. * 小程序相关
  16. * Class AuthController
  17. * @package app\api\controller\wechat
  18. */
  19. class AuthController
  20. {
  21. /**
  22. * tw 新增函數, 小程序登錄
  23. * 過程: 小程序中運行 wx.login() 獲取 code, 然後調用 mp_auth_login
  24. * mp_auth_login 執行
  25. * 1. 從 code 解析出 openId, 根據 openId 檢查用戶,存在,則返回 token,登录成功
  26. * 2. 不存在該 openId, 則是新用戶,返回 失敗,需要小程序做 wx.getUserProfile 调用后,
  27. * 然后调用 mp_auth_login_with_userinfo 接口, 注册或刷新用户信息后,返回登录成功协议
  28. * 小程序調用成功,就登錄成功 (注意:此时有两个问题 1. 目前测试得不到 unionId;
  29. * 2. 此时用户微信资料如果变动,不会刷新)
  30. * 小程序得到失败,就要求用户授权 wx.getUserProfile 获取微信资料,生成新的用户,返回 token, 相当与注册过程。
  31. *
  32. * mp_auth_login 即使执行成功,过一段时间也要返回失败,使得小程序发起重新授权,刷新用户微信资料。
  33. *
  34. * 返回字段:
  35. *
  36. * 'token' => $token->token,
  37. * 'userInfo' => $userInfo,
  38. * 'expires_time' => strtotime($token->expires_time),
  39. * 'cache_key' => $cache_key
  40. * 以上兼容旧协议
  41. * 'status' => 0/1 0 表示正常登录成功, 1 表示需要进一步调用 wx.getUserProfile 进行授权
  42. */
  43. public function mp_auth_simple(Request $request)
  44. {
  45. list($code) = UtilService::postMore([
  46. ['code', ''],
  47. ], $request, true);
  48. // Log::debug(__FUNCTION__ . " param code: $code");
  49. try {
  50. $json2sess = MiniProgramService::getUserInfo($code);
  51. // $sess_key = $json2sess['session_key'] ?? '';
  52. $openId = $json2sess['openid'] ?? '';
  53. $unionid = $json2sess['unionid'] ?? '';
  54. // Log::debug("openid=$openId, unionid=$unionid");
  55. // find by unionid
  56. if ($unionid != '') {
  57. $uid = WechatUser::where(['unionid' => $unionid])
  58. ->where('user_type', 'routine')->value('uid');
  59. }
  60. if (!$uid && $openId != '') {
  61. $uid = WechatUser::where(['routine_openid' => $openId])->where('user_type', 'routine')->value('uid');
  62. }
  63. Log::debug("uid=$uid");
  64. if (!$uid) {
  65. return app('json')->successful([
  66. 'token' => '',
  67. 'userInfo' => [],
  68. 'expires_time' => 0,
  69. 'cache_key' => '',
  70. 'status' => 1, // 需进一步
  71. ]);
  72. }
  73. $user = User::get($uid);
  74. if (!$user) {
  75. return app('json')->successful([
  76. 'token' => '',
  77. 'userInfo' => [],
  78. 'expires_time' => 0,
  79. 'cache_key' => '',
  80. 'status' => 1, // 需进一步
  81. ]);
  82. }
  83. $token = UserToken::createToken($user, 'routine');
  84. if (!$token) {
  85. return app('json')->fail('获取用户访问token失败!');
  86. }
  87. // Log::debug("token=" . $token->token);
  88. // 缓存 session_key
  89. $cache_key = md5(time() . $code);
  90. Cache::set('eb_api_code_' . $cache_key, $json2sess, SECONDS_OF_ONEDAY);
  91. // 获取用户上次刷新时间,距今超过 2 周就刷新
  92. $ur = new UserRds();
  93. $last = $ur->get($uid, 'last_refresh');
  94. if (time() - intval($last) >= SECONDS_OF_ONEDAY * 20) {
  95. return app('json')->successful([
  96. 'token' => '',
  97. 'userInfo' => [],
  98. 'expires_time' => 0,
  99. 'cache_key' => '',
  100. 'status' => 1, // 需进一步
  101. ]);
  102. }
  103. // 返回登录成功
  104. event('UserLogin', [$user, $token]);
  105. return app('json')->successful([
  106. 'token' => $token->token,
  107. 'userInfo' => $user->toArray(),
  108. 'expires_time' => strtotime($token->expires_time),
  109. 'cache_key' => $cache_key,
  110. 'status' => 0, // 登录成功
  111. ]);
  112. } catch (\Exception $e) {
  113. Log::error(__FUNCTION__ . 'exception:' . $e->getMessage());
  114. return app('json')->fail('获取session_key失败');
  115. }
  116. }
  117. /**
  118. * @deprecated
  119. * 小程序在 mp_auth_login 返回特定值(表示用户不存在,或刷新用户信息)后,
  120. * 调用 wx.getUserProfile 获取用户信息,来注册或刷新信息。
  121. */
  122. public function mp_auth_with_userinfo(Request $request)
  123. {
  124. list($cache_key, $spread_spid, $spread_code, $iv, $encryptedData, $login_type) = UtilService::postMore([
  125. ['cache_key', ''],
  126. ['spread_spid', 0],
  127. ['spread_code', ''],
  128. ['iv', ''],
  129. ['encryptedData', ''],
  130. ['login_type', ''],
  131. ], $request, true);
  132. // 获取缓存 openId, sessionKey
  133. $json2sess = Cache::get('eb_api_code_' . $cache_key);
  134. if (!$json2sess) {
  135. return app('json')->fail('访问超时');
  136. }
  137. // 解密用户数据
  138. try {
  139. $userInfo = MiniProgramService::encryptor($json2sess['session_key'], $iv, $encryptedData);
  140. } catch (\Exception $e) {
  141. if ($e->getCode() == '-41003') return app('json')->fail('获取会话密匙失败');
  142. }
  143. if (!isset($userInfo['unionId'])) {
  144. $userInfo['unionId'] = '';
  145. }
  146. // 新增或更新
  147. $userInfo['openId'] = $json2sess['openid'];
  148. $userInfo['spid'] = $spread_spid;
  149. $userInfo['code'] = $spread_code;
  150. $userInfo['session_key'] = $json2sess['session_key'];
  151. $userInfo['login_type'] = $login_type;
  152. $uid = WechatUser::routineOauth($userInfo);
  153. $userInfo = User::where('uid', $uid)->find();
  154. // 返回
  155. if ($userInfo->login_type == 'h5' && ($h5UserInfo = User::where(['account' => $userInfo->phone, 'phone' => $userInfo->phone, 'user_type' => 'h5'])->find()))
  156. $token = UserToken::createToken($userInfo, 'routine');
  157. else
  158. $token = UserToken::createToken($userInfo, 'routine');
  159. if ($token) {
  160. event('UserLogin', [$userInfo, $token]);
  161. return app('json')->successful('登陆成功!', [
  162. 'token' => $token->token,
  163. 'userInfo' => $userInfo,
  164. 'expires_time' => strtotime($token->expires_time),
  165. 'cache_key' => $cache_key,
  166. 'status' => 0,
  167. ]);
  168. } else {
  169. return app('json')->fail('获取用户访问token失败!');
  170. }
  171. }
  172. /**
  173. * 小程序授权登录
  174. * @param Request $request
  175. * @return mixed
  176. * @throws \Psr\SimpleCache\InvalidArgumentException
  177. * @throws \think\db\exception\DataNotFoundException
  178. * @throws \think\db\exception\ModelNotFoundException
  179. * @throws \think\exception\DbException
  180. */
  181. public function mp_auth(Request $request)
  182. {
  183. $cache_key = '';
  184. list($code, $post_cache_key, $login_type) = UtilService::postMore([
  185. ['code', ''],
  186. ['cache_key', ''],
  187. ['login_type', '']
  188. ], $request, true);
  189. // Log::debug("code=$code, post_cache_key=$post_cache_key, login_type=$login_type");
  190. $session_key = Cache::get('eb_api_code_' . $post_cache_key);
  191. if (!$code && !$session_key)
  192. return app('json')->fail('授权失败,参数有误');
  193. if ($code && !$session_key) {
  194. try {
  195. /**
  196. * 属性 类型 说明
  197. openid string 用户唯一标识
  198. session_key string 会话密钥
  199. unionid string 用户在开放平台的唯一标识符,若当前小程序已绑定到微信开放平台帐号下会返回,详见 UnionID 机制说明。
  200. errcode number 错误码
  201. errmsg string 错误信息
  202. */
  203. $userInfoWx = MiniProgramService::getUserInfo($code);
  204. // Log::debug('userinfo=' . json_encode($userInfoWx));
  205. $session_key = $userInfoWx['session_key'];
  206. $cache_key = md5(time() . $code);
  207. Cache::set('eb_api_code_' . $cache_key, $session_key, 86400);
  208. } catch (\Exception $e) {
  209. return app('json')->fail('获取session_key失败,请检查您的配置!', ['line' => $e->getLine(), 'message' => $e->getMessage()]);
  210. }
  211. }
  212. $data = UtilService::postMore([
  213. ['spread_spid', 0],
  214. ['spread_code', ''],
  215. ['iv', ''],
  216. ['encryptedData', ''],
  217. ]); //获取前台传的code
  218. try {
  219. //解密获取用户信息
  220. $userInfo = MiniProgramService::encryptor($session_key, $data['iv'], $data['encryptedData']);
  221. // Log::debug('userinfo=' . json_encode($userInfo));
  222. } catch (\Exception $e) {
  223. if ($e->getCode() == '-41003') return app('json')->fail('获取会话密匙失败');
  224. }
  225. if (!isset($userInfoWx['openid'])) return app('json')->fail('openid获取失败');
  226. if (!isset($userInfo['unionId'])) {
  227. $userInfo['unionId'] = '';
  228. }
  229. $userInfo['openId'] = $userInfoWx['openid'];
  230. $userInfo['spid'] = $data['spread_spid'];
  231. $userInfo['code'] = $data['spread_code'];
  232. $userInfo['session_key'] = $session_key;
  233. $userInfo['login_type'] = $login_type;
  234. $uid = WechatUser::routineOauth($userInfo);
  235. $userInfo = User::where('uid', $uid)->find();
  236. if ($userInfo->login_type == 'h5' && ($h5UserInfo = User::where(['account' => $userInfo->phone, 'phone' => $userInfo->phone, 'user_type' => 'h5'])->find()))
  237. $token = UserToken::createToken($userInfo, 'routine');
  238. else
  239. $token = UserToken::createToken($userInfo, 'routine');
  240. if ($token) {
  241. event('UserLogin', [$userInfo, $token]);
  242. $ur = new UserRds();
  243. $ur->set($uid, 'last_refresh', time());
  244. return app('json')->successful('登陆成功!', [
  245. 'token' => $token->token,
  246. 'userInfo' => $userInfo,
  247. 'expires_time' => strtotime($token->expires_time),
  248. 'cache_key' => $cache_key
  249. ]);
  250. } else {
  251. return app('json')->fail('获取用户访问token失败!');
  252. }
  253. }
  254. /**
  255. * 获取授权logo
  256. * @param Request $request
  257. * @return mixed
  258. */
  259. public function get_logo(Request $request)
  260. {
  261. $logoType = $request->get('type', 1);
  262. switch ((int)$logoType) {
  263. case 1:
  264. $logo = sys_config('routine_logo');
  265. break;
  266. case 2:
  267. $logo = sys_config('wechat_avatar');
  268. break;
  269. default:
  270. $logo = '';
  271. break;
  272. }
  273. if (strstr($logo, 'http') === false && $logo) $logo = sys_config('site_url') . $logo;
  274. return app('json')->successful(['logo_url' => str_replace('\\', '/', $logo)]);
  275. }
  276. /**
  277. * 保存form id
  278. * @param Request $request
  279. * @return mixed
  280. */
  281. public function set_form_id(Request $request)
  282. {
  283. $formId = $request->post('formId', '');
  284. if (!$formId) return app('json')->fail('缺少form id');
  285. return app('json')->successful('保存form id 成功!', ['uid' => $request->uid()]);
  286. }
  287. /**
  288. * @api {get|post} /routine/notify 小程序支付回调
  289. * @apiName RoutineNotify
  290. * @apiGroup Wechat
  291. *
  292. */
  293. public function notify()
  294. {
  295. MiniProgramService::handleNotify();
  296. }
  297. /**
  298. * 获取小程序订阅消息id
  299. * @return mixed
  300. */
  301. public function teml_ids()
  302. {
  303. $temlIdsName = SubscribeTemplateService::getConstants();
  304. $temlIdsList = CacheService::get('TEML_IDS_LIST', function () use ($temlIdsName) {
  305. $temlId = [];
  306. foreach ($temlIdsName as $key => $item) {
  307. $temlId[strtolower($key)] = SubscribeTemplateService::setTemplateId($item);
  308. }
  309. return $temlId;
  310. });
  311. return app('json')->success($temlIdsList);
  312. }
  313. /**
  314. * 获取小程序直播列表
  315. * @param Request $request
  316. * @return mixed
  317. */
  318. public function live(Request $request)
  319. {
  320. [$page, $limit] = UtilService::getMore([
  321. ['page', 1],
  322. ['limit', 10],
  323. ], $request, true);
  324. $list = CacheService::get('WECHAT_LIVE_LIST_' . $page . '_' . $limit, function () use ($page, $limit) {
  325. $list = MiniProgramService::getLiveInfo($page, $limit);
  326. foreach ($list as &$item) {
  327. $item['_start_time'] = date('m-d H:i', $item['start_time']);
  328. }
  329. return $list;
  330. }, 600);
  331. return app('json')->success($list);
  332. }
  333. }