AuthController.php 13 KB

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