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