AuthController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. /**
  43. * @api {post} /wechat/mp_auth_simple 只利用 code 登录
  44. * @apiName PostWechatMpSimple
  45. * @apiGroup Public
  46. *
  47. */
  48. public function mp_auth_simple(Request $request)
  49. {
  50. list($code) = UtilService::postMore([
  51. ['code', ''],
  52. ], $request, true);
  53. // debuglog(__FUNCTION__ . " param code: $code");
  54. try {
  55. $json2sess = MiniProgramService::getUserInfo($code);
  56. // $sess_key = $json2sess['session_key'] ?? '';
  57. $openId = $json2sess['openid'] ?? '';
  58. $unionid = $json2sess['unionid'] ?? '';
  59. // debuglog("openid=$openId, unionid=$unionid");
  60. // find by unionid
  61. if ($unionid != '') {
  62. $uid = WechatUser::where(['unionid' => $unionid])
  63. ->where('user_type', 'routine')->value('uid');
  64. }
  65. if (!$uid && $openId != '') {
  66. $uid = WechatUser::where(['routine_openid' => $openId])->where('user_type', 'routine')->value('uid');
  67. }
  68. if (!$uid) {
  69. return app('json')->successful([
  70. 'token' => '',
  71. 'userInfo' => [],
  72. 'expires_time' => 0,
  73. 'cache_key' => '',
  74. 'status' => 1, // 需进一步
  75. ]);
  76. }
  77. $user = User::get($uid);
  78. if (!$user) {
  79. return app('json')->successful([
  80. 'token' => '',
  81. 'userInfo' => [],
  82. 'expires_time' => 0,
  83. 'cache_key' => '',
  84. 'status' => 1, // 需进一步
  85. ]);
  86. }
  87. $token = UserToken::createToken($user, 'routine');
  88. if (!$token) {
  89. return app('json')->fail('获取用户访问token失败!');
  90. }
  91. // debuglog("token=" . $token->token);
  92. // 缓存 session_key
  93. $cache_key = md5(time() . $code);
  94. Cache::set('eb_api_code_' . $cache_key, $json2sess, SECONDS_OF_ONEDAY);
  95. // 获取用户上次刷新时间,距今超过 2 周就刷新
  96. $last = (new UserRds)->get($uid, UserRds::FIELD_LASTREFRESH);
  97. if (time() - intval($last) >= SECONDS_OF_ONEDAY * 20) {
  98. return app('json')->successful([
  99. 'token' => '',
  100. 'userInfo' => [],
  101. 'expires_time' => 0,
  102. 'cache_key' => '',
  103. 'status' => 1, // 需进一步
  104. ]);
  105. }
  106. // 返回登录成功
  107. event('UserLogin', [$user, $token]);
  108. return app('json')->successful([
  109. 'token' => $token->token,
  110. 'userInfo' => $user->toArray(),
  111. 'expires_time' => strtotime($token->expires_time),
  112. 'cache_key' => $cache_key,
  113. 'status' => 0, // 登录成功
  114. ]);
  115. } catch (\Exception $e) {
  116. errlog(__FUNCTION__ . 'exception:' . $e->getMessage());
  117. return app('json')->fail('获取session_key失败');
  118. }
  119. }
  120. /**
  121. * @api {post} /wechat/mp_auth_with_userinfo 提交用户资料注册或刷新
  122. * @apiName PostWechatMpAuthWithUserinfo
  123. * @apiGroup Public
  124. *
  125. * @apiDeprecated 小程序在 mp_auth_login 返回特定值(表示用户不存在,或刷新用户信息)后,调用 wx.getUserProfile 获取用户信息,来注册或刷新信息。
  126. */
  127. public function mp_auth_with_userinfo(Request $request)
  128. {
  129. list($cache_key, $spread_spid, $spread_code, $iv, $encryptedData, $login_type) = UtilService::postMore([
  130. ['cache_key', ''],
  131. ['spread_spid', 0],
  132. ['spread_code', ''],
  133. ['iv', ''],
  134. ['encryptedData', ''],
  135. ['login_type', ''],
  136. ], $request, true);
  137. // 获取缓存 openId, sessionKey
  138. $json2sess = Cache::get('eb_api_code_' . $cache_key);
  139. if (!$json2sess) {
  140. return app('json')->fail('访问超时');
  141. }
  142. // 解密用户数据
  143. try {
  144. $userInfo = MiniProgramService::encryptor($json2sess['session_key'], $iv, $encryptedData);
  145. } catch (\Exception $e) {
  146. if ($e->getCode() == '-41003') return app('json')->fail('获取会话密匙失败');
  147. }
  148. if (!isset($userInfo['unionId'])) {
  149. $userInfo['unionId'] = '';
  150. }
  151. // 新增或更新
  152. $userInfo['openId'] = $json2sess['openid'];
  153. $userInfo['spid'] = $spread_spid;
  154. $userInfo['code'] = $spread_code;
  155. $userInfo['session_key'] = $json2sess['session_key'];
  156. $userInfo['login_type'] = $login_type;
  157. $uid = WechatUser::routineOauth($userInfo);
  158. $userInfo = User::where('uid', $uid)->find();
  159. // 返回
  160. if ($userInfo->login_type == 'h5' && ($h5UserInfo = User::where(['account' => $userInfo->phone, 'phone' => $userInfo->phone, 'user_type' => 'h5'])->find()))
  161. $token = UserToken::createToken($userInfo, 'routine');
  162. else
  163. $token = UserToken::createToken($userInfo, 'routine');
  164. if ($token) {
  165. event('UserLogin', [$userInfo, $token]);
  166. return app('json')->successful('登陆成功!', [
  167. 'token' => $token->token,
  168. 'userInfo' => $userInfo,
  169. 'expires_time' => strtotime($token->expires_time),
  170. 'cache_key' => $cache_key,
  171. 'status' => 0,
  172. ]);
  173. } else {
  174. return app('json')->fail('获取用户访问token失败!');
  175. }
  176. }
  177. /**
  178. * @api {post} /mp_auth 小程序授权登录
  179. * @apiName PostMpAuth
  180. * @apiGroup Public
  181. *
  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. // debuglog("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. // debuglog('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. ['ch', 0], // 渠道号
  219. ['encryptedData', ''],
  220. ]); //获取前台传的code
  221. try {
  222. //解密获取用户信息
  223. $userInfo = MiniProgramService::encryptor($session_key, $data['iv'], $data['encryptedData']);
  224. // debuglog('userinfo=' . json_encode($userInfo));
  225. } catch (\Exception $e) {
  226. if ($e->getCode() == '-41003') return app('json')->fail('获取会话密匙失败');
  227. }
  228. if (!isset($userInfoWx['openid'])) return app('json')->fail('openid获取失败');
  229. if (!isset($userInfo['unionId'])) {
  230. $userInfo['unionId'] = '';
  231. }
  232. $userInfo['openId'] = $userInfoWx['openid'];
  233. $userInfo['spid'] = $data['spread_spid'];
  234. $userInfo['code'] = $data['spread_code'];
  235. $userInfo['channel'] = $data['ch'];
  236. $userInfo['session_key'] = $session_key;
  237. $userInfo['login_type'] = $login_type;
  238. $uid = WechatUser::routineOauth($userInfo);
  239. $userInfo = User::where('uid', $uid)->find();
  240. if ($userInfo->login_type == 'h5' && ($h5UserInfo = User::where(['account' => $userInfo->phone, 'phone' => $userInfo->phone, 'user_type' => 'h5'])->find()))
  241. $token = UserToken::createToken($userInfo, 'routine');
  242. else
  243. $token = UserToken::createToken($userInfo, 'routine');
  244. if ($token) {
  245. event('UserLogin', [$userInfo, $token]);
  246. (new UserRds)->set($uid, UserRds::FIELD_LASTREFRESH, time());
  247. return app('json')->successful('登陆成功!', [
  248. 'token' => $token->token,
  249. 'userInfo' => $userInfo,
  250. 'expires_time' => strtotime($token->expires_time),
  251. 'cache_key' => $cache_key
  252. ]);
  253. } else {
  254. return app('json')->fail('获取用户访问token失败!');
  255. }
  256. }
  257. /**
  258. * @api {get} /wechat/get_logo 获取授权logo
  259. * @apiName GetWechatLogo
  260. * @apiGroup Public
  261. *
  262. */
  263. public function get_logo(Request $request)
  264. {
  265. $logoType = $request->get('type', 1);
  266. switch ((int)$logoType) {
  267. case 1:
  268. $logo = sys_config('routine_logo');
  269. break;
  270. case 2:
  271. $logo = sys_config('wechat_avatar');
  272. break;
  273. default:
  274. $logo = '';
  275. break;
  276. }
  277. if (strstr($logo, 'http') === false && $logo) $logo = sys_config('site_url') . $logo;
  278. return app('json')->successful(['logo_url' => str_replace('\\', '/', $logo)]);
  279. }
  280. /**
  281. * @api {post} /wechat/set_form_id 保存form id
  282. * @apiName PostWechatSetFormId
  283. * @apiGroup Public
  284. *
  285. */
  286. public function set_form_id(Request $request)
  287. {
  288. $formId = $request->post('formId', '');
  289. if (!$formId) return app('json')->fail('缺少form id');
  290. return app('json')->successful('保存form id 成功!', ['uid' => $request->uid()]);
  291. }
  292. /**
  293. * 小程序支付回调
  294. *
  295. */
  296. public function notify()
  297. {
  298. MiniProgramService::handleNotify();
  299. }
  300. /**
  301. * @api {get} /wechat/teml_ids 获取小程序订阅消息id
  302. * @apiName GetWechatTemlIds
  303. * @apiGroup Public
  304. *
  305. */
  306. public function teml_ids()
  307. {
  308. $temlIdsName = SubscribeTemplateService::getConstants();
  309. $temlIdsList = CacheService::get('TEML_IDS_LIST', function () use ($temlIdsName) {
  310. $temlId = [];
  311. foreach ($temlIdsName as $key => $item) {
  312. $temlId[strtolower($key)] = SubscribeTemplateService::setTemplateId($item);
  313. }
  314. return $temlId;
  315. });
  316. return app('json')->success($temlIdsList);
  317. }
  318. /**
  319. * @api {get} /wechat/live 获取小程序直播列表
  320. * @apiName GetWechatLive
  321. * @apiGroup Public
  322. *
  323. */
  324. public function live(Request $request)
  325. {
  326. [$page, $limit] = UtilService::getMore([
  327. ['page', 1],
  328. ['limit', 10],
  329. ], $request, true);
  330. $list = CacheService::get('WECHAT_LIVE_LIST_' . $page . '_' . $limit, function () use ($page, $limit) {
  331. $list = MiniProgramService::getLiveInfo($page, $limit);
  332. foreach ($list as &$item) {
  333. $item['_start_time'] = date('m-d H:i', $item['start_time']);
  334. }
  335. return $list;
  336. }, 600);
  337. return app('json')->success($list);
  338. }
  339. }