WechatOfficialController.php 19 KB

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