WechatOfficialController.php 19 KB

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