CrmUser.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace App\Http\Middleware;
  3. use App\Client\User\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. //\Log::info('crm middleware info openid is :'.$openid);
  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. //\Log::info('crm middleware info');
  35. //\Log::info($user);
  36. Cookie::queue('crm_user_id', $user[0], env('U_COOKIE_EXPIRE'));
  37. Cookie::queue('crm_channel_id', $user[1], env('U_COOKIE_EXPIRE'));
  38. $this->setUserGlobal($user[0], $user[1]);
  39. }
  40. }
  41. return $next($request);
  42. }
  43. private function setUserGlobal($uid, $channel_id)
  44. {
  45. $user = app()->make('user');
  46. $user->id = $uid;
  47. $user->channel_id = $channel_id;
  48. }
  49. private function auth($param)
  50. {
  51. $param['appid'] = 'wx9d389a73b88bbeae';
  52. $options = [
  53. 'app_id' => 'wx9d389a73b88bbeae',
  54. 'secret' => '2f6594bb595dfa256b5512e43a32a3d3',
  55. 'oauth' => [
  56. 'scopes' => ['snsapi_base'],
  57. 'callback' => env('AUTH_CALLBACK_URL') . '?' . http_build_query($param),
  58. ],
  59. ];
  60. return $options;
  61. }
  62. }