AuthController.php 13 KB

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