WechatOfficialController.php 19 KB

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