WechatOfficialController.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. <?php
  2. namespace App\Http\Api;
  3. use App\Services\Login\LoginTokenService;
  4. use EasyWeChat\Factory;
  5. use EasyWeChat\Kernel\Messages\News;
  6. use EasyWeChat\Kernel\Messages\NewsItem;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Request;
  9. use Illuminate\Support\Str;
  10. use Illuminate\Http\JsonResponse;
  11. use Illuminate\Support\Facades\Cache;
  12. use Illuminate\Support\Facades\Log;
  13. /**
  14. * 微信公众号授权
  15. *
  16. * Class WechatController
  17. * @package App\Http\Seller\Controllers
  18. */
  19. class WechatOfficialController extends HttpBaseController
  20. {
  21. protected $app = '';
  22. public function __construct()
  23. {
  24. parent::__construct();
  25. $this->setWebsite(__NAMESPACE__);
  26. $config = config('easywechat.official_account.default');
  27. $this->app = Factory::officialAccount($config);
  28. }
  29. // 测试登录
  30. public function testLogin()
  31. {
  32. if ($this->isTest()) {
  33. $userId = 1;
  34. $productMid = "web";
  35. $loginToken = new LoginTokenService($this->siteInfo['token_table']);
  36. $token = $loginToken->createOnlyOneToken($userId, $productMid);
  37. return responseMessage(1001, '', $token);
  38. }
  39. }
  40. public function index2()
  41. {
  42. $this->app->server->push(function ($message) {
  43. $msgType = $message['MsgType'];
  44. if ($msgType == 'event') {
  45. $event = $message['Event'];
  46. return $this->msgEvent($event, $message);
  47. } else {
  48. return $this->msgtType($msgType, $message);
  49. }
  50. });
  51. $response = $this->app->server->serve();
  52. $response->send();
  53. exit();
  54. }
  55. public function index()
  56. {
  57. $this->app->server->push(function ($message) {
  58. $msgType = $message['MsgType'];
  59. $event = $message['Event'];
  60. $eventKey = $message['EventKey'];
  61. $openid = $message['FromUserName'];
  62. // 替换字符串
  63. $eventKey = str_replace('qrscene_', '', $eventKey);
  64. /**
  65. * 扫描带参数二维码事件
  66. */
  67. if ($msgType == 'event') {
  68. $msg = '';
  69. switch ($event) {
  70. case 'subscribe': // 1. 用户未关注时,进行关注后的事件推送
  71. case 'SCAN': // 2. 用户已关注时的事件推送
  72. // 保存用户信息
  73. $isSuccess = $this->saveUser($openid, $eventKey);
  74. if ($isSuccess) {
  75. $msg = "您好!欢迎使用 优速办公!";
  76. } else {
  77. $msg = "对不起!扫描失败,请重试!";
  78. }
  79. break;
  80. case 'unsubscribe': // 取消关注
  81. $this->loginOut($openid, $eventKey);
  82. break;
  83. }
  84. return $msg;
  85. } else {
  86. return "您好!欢迎使用 优速办公!";
  87. }
  88. });
  89. $response = $this->app->server->serve();
  90. $response->send();
  91. exit();
  92. }
  93. /**
  94. * @param $openid
  95. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  96. */
  97. private function saveUser($openid, $eventKey)
  98. {
  99. $userInfo = $this->app->user->get($openid);
  100. $sceneStr = $eventKey;
  101. // 分离产品id和session
  102. [$productMid, $sessionId] = explode(':', $sceneStr, 2);
  103. if (empty($productMid) || empty($sessionId)) {
  104. abort(500, '登录授权失败,非法操作!');
  105. }
  106. $nickname = '未知'; // 对应微信的 nickname
  107. $avatar = 'https://www.yososoft.com/static/images/softlogo.png'; // 头像网址
  108. $unionid = $userInfo['unionid'] ?? '';
  109. $wxInfo = $userInfo;
  110. $isExistUser = DB::table('user_wechat_official_account')->select('id')->where('openid', $openid)->first();
  111. if ($isExistUser) {
  112. // 更新头像
  113. $isSuccess = DB::transaction(function () use ($openid, $isExistUser, $unionid, $nickname, $avatar, $wxInfo) {
  114. DB::table('user_wechat_official_account')->where('id', $isExistUser->id)->update([
  115. 'openid' => $openid,
  116. 'unionid' => $unionid,
  117. 'nick' => $nickname,
  118. 'wx_avatar' => $avatar,
  119. 'wx_info' => json_encode($wxInfo),
  120. ]);
  121. DB::table('user')->where('id', $isExistUser->id)->update([
  122. 'unionid' => $unionid,
  123. 'username' => $nickname,
  124. 'avatar' => $avatar,
  125. ]);
  126. return true;
  127. });
  128. $userId = $isExistUser->id; // 用户id
  129. } else {
  130. // 插入数据
  131. $isSuccess = DB::transaction(function () use ($openid, $nickname, $avatar, $unionid, $wxInfo) {
  132. $userData = [
  133. 'username' => $nickname,
  134. 'avatar' => $avatar,
  135. 'roles' => json_encode([1]),
  136. 'unionid' => $unionid,
  137. 'status' => 1,
  138. 'mid' => Str::random(12),
  139. 'created_at' => time(),
  140. 'updated_at' => time(),
  141. ];
  142. $userId = DB::table('user')->insertGetId($userData);
  143. $officialData = [
  144. 'user_id' => $userId,
  145. 'openid' => $openid,
  146. 'unionid' => $unionid,
  147. 'nick' => $nickname,
  148. 'wx_avatar' => $avatar,
  149. 'wx_info' => json_encode($wxInfo),
  150. 'mid' => Str::random(12),
  151. 'created_at' => time(),
  152. 'updated_at' => time(),
  153. ];
  154. DB::table('user_wechat_official_account')->insertGetId($officialData);
  155. return $userId;
  156. });
  157. $userId = $isSuccess; // 用户id
  158. }
  159. if ($isSuccess) {
  160. // 保存生成token需要的信息
  161. $loginToken = new LoginTokenService($this->siteInfo['token_table']);
  162. $token = $loginToken->createOnlyOneToken($userId, $productMid);
  163. Cache::put('TOKEN_' . $sceneStr, $token, 5 * 60); // 有效期5分钟
  164. Log::info('33333333333333333333 === ' . 'TOKEN_' . $sceneStr . ' ==== ' . $token);
  165. // 如果用户直接点击手机登录链接,而没有扫描,则处理一下当前的扫描状态
  166. if (!Cache::get("SCAN_" . $sceneStr)) {
  167. Cache::put("SCAN_" . $sceneStr, true, 2 * 60); // 有效期2分钟
  168. }
  169. // 网页跳转,带一个随机参数,然后再通过该参数来换取session
  170. $key = md5(microtime() . $sceneStr);
  171. Cache::put($key, $token, 2 * 60); // 有效期3分钟
  172. return redirect('/mobile/#/?key=' . $key);
  173. } else {
  174. abort(500, '登录授权失败,请稍后再试!');
  175. }
  176. }
  177. private function msgEvent($event, $message)
  178. {
  179. // 场景值为 productMid:sessionId
  180. $sceneStr = $message['EventKey'] ?? '';
  181. // 新关注用户有qrscene_,替换掉
  182. $sceneStr = str_replace('qrscene_', '', $sceneStr);
  183. // $openid = Request::input('openid');
  184. switch ($event) {
  185. case 'subscribe': // 1. 用户未关注时,进行关注后的事件推送
  186. case 'SCAN': // 2. 用户已关注时的事件推送
  187. if (empty($sceneStr)) {
  188. return "欢迎你关注助友办公软件";
  189. } else {
  190. $oauthUrl = $this->app->oauth->withState(base64_encode($sceneStr))->redirect();
  191. //$oauthUrl = str_replace('https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1edb103f32029099&redirect_uri=https%3A%2F%2Fwww.qasimblog.com%2Fapi%2Fwechat%2FoauthCallback&response_type=code&scope=snsapi_userinfo&state=WHdCeXhSMW5vUHgzOjUyNDEzYTY3MWVjNzAzNDc4M2FhMWEzMDMyNmRlMjNk&connect_redirect=1#wechat_redirect', '', $oauthUrl);
  192. $items = [
  193. new NewsItem([
  194. 'title' => '',
  195. 'description' => '',
  196. 'url' => $oauthUrl,
  197. 'image' => 'https://www.qasimblog.com/static/login.jpg',
  198. ]),
  199. new NewsItem([
  200. 'title' => '点击确认登录',
  201. 'description' => '',
  202. 'url' => $oauthUrl,
  203. 'image' => 'https://www.qasimblog.com/static/logo.png',
  204. ]),
  205. ];
  206. // 记录当前的扫描状态
  207. Cache::put("SCAN_" . $sceneStr, true, 2 * 60); // 有效期2分钟
  208. return new News($items); // 发送登录链接
  209. }
  210. case 'unsubscribe': // 取消关注
  211. break;
  212. }
  213. return 'success';
  214. }
  215. private function msgtType($type, $message)
  216. {
  217. switch ($type) {
  218. case 'text':
  219. case 'image':
  220. case 'voice': //语音消息
  221. case 'video': //视频消息
  222. case 'shortvideo': // 小视频消息
  223. case 'location': // 地理位置消息
  224. case 'link': // 链接消息
  225. default:
  226. $items = [
  227. new NewsItem([
  228. 'title' => '官方客服',
  229. 'description' => '需要帮助,请联系客服!',
  230. 'url' => 'https://work.weixin.qq.com/kfid/kfc5471afeb3f4331af',
  231. 'image' => 'https://www.qasimblog.com/static/images/u10.png',
  232. ]),
  233. ];
  234. $msg = new News($items);
  235. }
  236. return $msg;
  237. }
  238. /**
  239. * 创建登录的临时二维码
  240. *
  241. * @return JsonResponse
  242. */
  243. public function createQrcode()
  244. {
  245. /**
  246. * 场景值为 productMid:sessionId
  247. */
  248. $sceneStr = Request::post('scene_str'); //
  249. if (empty($sceneStr)) {
  250. Log::error("scene_str,为空!");
  251. return responseMessage(2001, '参数错误!');
  252. }
  253. $arr = explode(':', $sceneStr, 2);
  254. if (count($arr) != 2) {
  255. Log::error("scene_str,参数错误2,为空!");
  256. return responseMessage(2002, '参数错误!');
  257. }
  258. // 缓存当前的scene,防止用户重复点击登录
  259. Cache::put('clickOne_' . md5($sceneStr), true, 5 * 60);
  260. $result = $this->app->qrcode->temporary($sceneStr, 5 * 60);
  261. if (isset($result['ticket']) && $result['ticket']) {
  262. $url = $this->app->qrcode->url($result['ticket']);
  263. return responseMessage(1001, '', ['url' => $url, 'expire_seconds' => $result['expire_seconds']]);
  264. } else {
  265. Log::error("scene_str,参数错误3,请求错误!");
  266. return responseMessage(2002, '参数错误2!');
  267. }
  268. }
  269. public function oauthCallback()
  270. {
  271. $code = Request::input('code');
  272. $state = Request::input('state');
  273. if (empty($state)) {
  274. abort(500, '登录授权失败,参数错误!');
  275. }
  276. // 场景值为 productMid:sessionId
  277. $sceneStr = base64_decode($state);
  278. if (empty($sceneStr)) {
  279. abort(500, '登录授权失败,非法操作!');
  280. }
  281. $oauth = $this->app->oauth;
  282. $user = $oauth->userFromCode($code);
  283. Log::info('22222222222222222222222 === ' . 'code' . $code );
  284. $openid = $user->getId();// 对应微信的 OPENID
  285. $nickname = $user->getNickname(); // 对应微信的 nickname
  286. $avatar = $user->getAvatar(); // 头像网址
  287. $tokenResponse = $user->getAttribute('token_response');
  288. $unionid = $tokenResponse['unionid'] ?? '';
  289. $wxInfo = $user->getAttributes();
  290. // 缓存当前的scene,防止用户重复点击登录
  291. $isClick = Cache::get('clickOne_' . md5($sceneStr));
  292. if (!$isClick) {
  293. abort(500, '登录授权失败,请重新扫码!');
  294. } else {
  295. Cache::forget('clickOne_' . md5($sceneStr));
  296. }
  297. // 分离产品id和session
  298. [$productMid, $sessionId] = explode(':', $sceneStr, 2);
  299. if (empty($productMid) || empty($sessionId)) {
  300. abort(500, '登录授权失败,非法操作!');
  301. }
  302. Log::info('$openid == ' . $openid);
  303. $isExistUser = DB::table('user_wechat_official_account')->select('id')->where('openid', $openid)->first();
  304. if ($isExistUser) {
  305. // 更新头像
  306. $isSuccess = DB::transaction(function () use ($openid, $isExistUser, $unionid, $nickname, $avatar, $wxInfo) {
  307. DB::table('user_wechat_official_account')->where('id', $isExistUser->id)->update([
  308. 'openid' => $openid,
  309. 'unionid' => $unionid,
  310. 'nick' => $nickname,
  311. 'wx_avatar' => $avatar,
  312. 'wx_info' => json_encode($wxInfo),
  313. ]);
  314. DB::table('user')->where('id', $isExistUser->id)->update([
  315. 'unionid' => $unionid,
  316. 'username' => $nickname,
  317. 'avatar' => $avatar,
  318. ]);
  319. return true;
  320. });
  321. $userId = $isExistUser->id; // 用户id
  322. } else {
  323. // 插入数据
  324. $isSuccess = DB::transaction(function () use ($openid, $nickname, $avatar, $unionid, $wxInfo) {
  325. $userData = [
  326. 'username' => $nickname,
  327. 'avatar' => $avatar,
  328. 'roles' => json_encode([1]),
  329. 'unionid' => $unionid,
  330. 'status' => 1,
  331. 'mid' => Str::random(12),
  332. 'created_at' => time(),
  333. 'updated_at' => time(),
  334. ];
  335. $userId = DB::table('user')->insertGetId($userData);
  336. $officialData = [
  337. 'user_id' => $userId,
  338. 'openid' => $openid,
  339. 'unionid' => $unionid,
  340. 'nick' => $nickname,
  341. 'wx_avatar' => $avatar,
  342. 'wx_info' => json_encode($wxInfo),
  343. 'mid' => Str::random(12),
  344. 'created_at' => time(),
  345. 'updated_at' => time(),
  346. ];
  347. DB::table('user_wechat_official_account')->insertGetId($officialData);
  348. return $userId;
  349. });
  350. $userId = $isSuccess; // 用户id
  351. }
  352. if ($isSuccess) {
  353. // 保存生成token需要的信息
  354. $loginToken = new LoginTokenService($this->siteInfo['token_table']);
  355. $token = $loginToken->createOnlyOneToken($userId, $productMid);
  356. Cache::put('TOKEN_' . $sceneStr, $token, 5 * 60); // 有效期5分钟
  357. Log::info('33333333333333333333 === ' . 'TOKEN_' . $sceneStr . ' ==== ' . $token);
  358. // 如果用户直接点击手机登录链接,而没有扫描,则处理一下当前的扫描状态
  359. if (!Cache::get("SCAN_" . $sceneStr)) {
  360. Cache::put("SCAN_" . $sceneStr, true, 2 * 60); // 有效期2分钟
  361. }
  362. // 网页跳转,带一个随机参数,然后再通过该参数来换取session
  363. $key = md5(microtime() . $sceneStr);
  364. Cache::put($key, $token, 2 * 60); // 有效期3分钟
  365. return redirect('/mobile/#/?key=' . $key);
  366. } else {
  367. abort(500, '登录授权失败,请稍后再试!');
  368. }
  369. }
  370. /**
  371. * web 网页登录
  372. *
  373. * 通过key换取session
  374. */
  375. public function key2token()
  376. {
  377. $key = Request::post('key');
  378. if (empty($key)) {
  379. return responseMessage(2001, '非法操作!');
  380. } else {
  381. $token = Cache::get($key);
  382. if ($token) {
  383. return responseMessage(1001, '', $token);
  384. } else {
  385. return responseMessage(2002, '登录失败,请重试!');
  386. }
  387. }
  388. }
  389. /**
  390. * 验证登录
  391. *
  392. * @return JsonResponse
  393. */
  394. public function checkLogin()
  395. {
  396. // 注意: 实际上不是scene_str,是sessionId
  397. $sessionId = Request::post('scene_str');
  398. if (empty($sessionId)) {
  399. return responseMessage(2001, '参数错误!');
  400. }
  401. // 过如果用户已经登录,则验证该用户是否需要更新token,7天有效
  402. $loginToken = new LoginTokenService($this->siteInfo['token_table']);
  403. if ($tokenInfo = $loginToken->checkLogin()) {
  404. //超过 7天 有效期,刷新token
  405. $limitTime = time() - $tokenInfo->updated_at;
  406. if ($limitTime > 7 * 24 * 3600) {
  407. // 需要重新登录,清除登录缓存
  408. $loginToken->destroyCurrentAccessToken();
  409. return responseMessage(2002, '登录已过期,请重新登录!');
  410. } elseif ($limitTime > 3 * 24 * 3600 && $limitTime < 7 * 24 * 3600) {
  411. // 大于3天 小于7天,则刷新token
  412. $token = $loginToken->createOnlyOneToken($tokenInfo->user_id, $tokenInfo->name);
  413. } else {
  414. $token = $loginToken->getToken();
  415. }
  416. return responseMessage(1001, '已登录!', $token);
  417. } else {
  418. $token = Cache::get('TOKEN_' . $sessionId);
  419. if (empty($token)) {
  420. return responseMessage(2003, '未登录!');
  421. } else {
  422. // 如果用户退出登录,而且缓存还没有失效,会出现检测已经登陆,
  423. // 解决:前端清除token,后端判断是否已经登陆
  424. if ($loginToken->findToken($token)) {
  425. return responseMessage(1001, 'success', $token);
  426. } else {
  427. //清除多余的缓存
  428. Cache::forget('TOKEN_' . $sessionId);
  429. Log::info('清除多余的token缓存 TOKEN_' . $sessionId);
  430. return responseMessage(2004, '未登录!');
  431. }
  432. }
  433. }
  434. }
  435. /**
  436. * 检测是否已经扫描
  437. */
  438. public function checkScan()
  439. {
  440. /**
  441. * 场景值为 productMid:sessionId
  442. */
  443. $sceneStr = Request::post('scene_str'); //
  444. if (empty($sceneStr)) {
  445. return responseMessage(2001, '参数错误!');
  446. }
  447. $isScan = Cache::get("SCAN_" . $sceneStr);
  448. if ($isScan) {
  449. // 删除缓存
  450. Cache::forget("SCAN_" . $sceneStr);
  451. return responseMessage(1001, '已扫描');
  452. } else {
  453. return responseMessage(2003, '等待中');
  454. }
  455. }
  456. }