AuthController.php 13 KB

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