AuthController.php 14 KB

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