CrmUser.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace App\Http\Middleware;
  3. use App\Modules\User\Services\SiteUser;
  4. use Closure;
  5. use EasyWeChat\Foundation\Application;
  6. use Cookie;
  7. class CrmUser
  8. {
  9. /**
  10. * Handle an incoming request.
  11. *
  12. * @param \Illuminate\Http\Request $request
  13. * @param \Closure $next
  14. * @return mixed
  15. */
  16. public function handle($request, Closure $next)
  17. {
  18. $uid = Cookie::get('crm_user_id');
  19. if ($uid) {
  20. $channel_id = Cookie::get('crm_channel_id');
  21. $this->setUserGlobal($uid, $channel_id);
  22. } else {
  23. $openid = $request->get('openid');
  24. // $openid = 'oHhd20YbxxOZ34ahoE7ZrX8M8O2c';
  25. $params = $request->except('_url');
  26. if (empty($openid)) {
  27. $url = url()->current() . '?' . http_build_query($params);
  28. $params['redirect_url'] = urlencode($url);
  29. $app = new Application($this->auth($params));
  30. return $app->oauth->redirect();
  31. } else {
  32. $site_user = new SiteUser($openid);
  33. $user = $site_user->getChannelUser();
  34. Cookie::queue('crm_user_id', $user[0], env('U_COOKIE_EXPIRE'));
  35. Cookie::queue('crm_channel_id', $user[1], env('U_COOKIE_EXPIRE'));
  36. $this->setUserGlobal($user[0], $user[1]);
  37. }
  38. }
  39. return $next($request);
  40. }
  41. private function setUserGlobal($uid, $channel_id)
  42. {
  43. $user = app()->make('user');
  44. $user->id = $uid;
  45. $user->channel_id = $channel_id;
  46. }
  47. private function auth($param)
  48. {
  49. $param['appid'] = 'wx9d389a73b88bbeae';
  50. $options = [
  51. 'app_id' => 'wx9d389a73b88bbeae',
  52. 'secret' => '2f6594bb595dfa256b5512e43a32a3d3',
  53. 'oauth' => [
  54. 'scopes' => ['snsapi_base'],
  55. 'callback' => env('AUTH_CALLBACK_URL') . '?' . http_build_query($param),
  56. ],
  57. ];
  58. return $options;
  59. }
  60. }