public function boot()
 {
     $this->publishes([__DIR__ . '/../Config/config.php' => config_path('wechat.php')], 'config');
     if (config('wechat.debug')) {
         error_reporting(E_ALL);
     }
     Log::setLogger(app('log'));
 }
Пример #2
0
 /**
  * @param $message
  * @return mixed|null
  */
 protected function handleTestMessage($message)
 {
     $handler = $this->testMessageHandler;
     if (!is_callable($handler)) {
         Log::debug('No handler enabled.');
         return null;
     }
     Log::debug('Test Message detail:', $message);
     $message = new Collection($message);
     return call_user_func_array($handler, [$message]);
 }
 public function getToken($forceRefresh = false)
 {
     $cacheKey = $this->prefix . $this->appId;
     $cached = $this->getCache()->fetch($cacheKey);
     if ($forceRefresh || empty($cached)) {
         $token = $this->getTokenFromServer();
         // XXX: T_T... 7200 - 1500
         $this->getCache()->save($cacheKey, $token[$this->getQueryName()], $token['expires_in'] - 1500);
         Log::debug('服务器获取到component_access_token' . $token[$this->getQueryName()]);
         return $token[$this->getQueryName()];
     }
     Log::debug('缓存获取到component_access_token' . $cached);
     return $cached;
 }
 /**
  * 获取授权公众号的令牌
  *
  * @return string
  */
 public function getToken()
 {
     $cacheKey = sprintf($this->cacheKey, $this->authorizerAppId);
     $this->token = $this->getCache()->fetch($cacheKey);
     if (!$this->token) {
         $params = array('component_appid' => $this->componentAppId, 'authorizer_appid' => $this->authorizerAppId, 'authorizer_refresh_token' => $this->authorizerRefreshToken);
         $http = new ComponentHttp(new ComponentAccessToken($this->componentAppId, $this->componentAppSecret, $this->cache));
         $response = $http->json(self::API_AUTHORIZER_TOKEN, $params);
         Log::debug(is_array($response) ? json_encode($response) : $response);
         // 设置token
         $token = $response['authorizer_access_token'];
         // 把token缓存起来
         $this->setToken($response['authorizer_access_token'], $response['authorizer_refresh_token']);
         return $token;
     }
     return $this->token;
 }
 /**
  * Registers services on the given container.
  *
  * This method should only be used to configure services and parameters.
  * It should not get services.
  *
  * @param Container $pimple A container instance
  */
 public function register(Container $pimple)
 {
     $pimple['encryptor'] = function ($pimple) {
         return new Encryptor($pimple['config']['component_app_id'], $pimple['config']['component_token'], $pimple['config']['component_aes_key']);
     };
     $pimple['component'] = function ($pimple) {
         return new Component($pimple['config']['component_app_id'], $pimple['config']['component_app_secret'], $pimple['cache']);
     };
     $pimple['auth_server'] = function ($pimple) {
         $server = new AuthGuard($pimple['config']['component_token']);
         $server->debug($pimple['config']['debug']);
         $server->setEncryptor($pimple['encryptor']);
         //处理verifyTicket
         $server->setVerifyTicketHandler(function ($message) use($pimple) {
             Log::info('接收到ticket事件' . $message);
             $componentVerifyTicket = new ComponentVerifyTicket($pimple['cache']);
             $componentVerifyTicket->setComponentVerifyTicket($message->ComponentVerifyTicket);
         });
         return $server;
     };
 }
Пример #6
0
 /**
  * @param \Psr\Http\Message\ResponseInterface|string $body
  *
  * @return mixed
  *
  * @throws \EasyWeChat\Core\Exceptions\HttpException
  */
 public function parseJSON($body)
 {
     if ($body instanceof ResponseInterface) {
         $body = $body->getBody();
     }
     // XXX: json maybe contains special chars. So, let's F**K the WeChat API developers ...
     $body = $this->fuckTheWeChatInvalidJSON($body);
     if (empty($body)) {
         return false;
     }
     $contents = json_decode($body, true);
     Log::debug('API response decoded:', compact('contents'));
     if (JSON_ERROR_NONE !== json_last_error()) {
         throw new HttpException('Failed to parse JSON: ' . json_last_error_msg());
     }
     return $contents;
 }
Пример #7
0
 /**
  * Handle message.
  *
  * @param array $message
  *
  * @return mixed
  */
 protected function handleMessage($message)
 {
     $handler = $this->messageHandler;
     if (!is_callable($handler)) {
         Log::debug('No handler enabled.');
         return;
     }
     Log::debug('Message detail:', $message);
     $message = new Collection($message);
     $type = $this->messageTypeMapping[$message->get('MsgType')];
     $response = null;
     if ($this->messageFilter & $type) {
         $response = call_user_func_array($handler, [$message]);
     }
     return $response;
 }
Пример #8
0
 /**
  * Initialize logger.
  */
 private function initializeLogger()
 {
     $logger = new Logger('easywechat');
     if (!$this['config']['debug'] || defined('PHPUNIT_RUNNING')) {
         $logger->pushHandler(new NullHandler());
     } elseif ($logFile = $this['config']['log.file']) {
         $logger->pushHandler(new StreamHandler($logFile, $this['config']->get('log.level', Logger::WARNING)));
     }
     Log::setLogger($logger);
 }
Пример #9
0
 /**
  * Return retry middleware.
  *
  * @return \GuzzleHttp\RetryMiddleware
  */
 protected function retryMiddleware()
 {
     return Middleware::retry(function ($retries, RequestInterface $request, ResponseInterface $response = null, RequestException $exception = null) {
         // Limit the number of retries to 2
         if ($retries <= 2 && $response && ($body = $response->getBody())) {
             // Retry on server errors
             if (stripos($body, 'errcode') && (stripos($body, '40001') || stripos($body, '42001'))) {
                 $field = $this->accessToken->getQueryName();
                 $token = $this->accessToken->getToken();
                 $request = $request->withUri($newUri = Uri::withQueryValue($request->getUri(), $field, $token));
                 Log::debug("Retry with Request Token: {$token}");
                 Log::debug("Retry with Request Uri: {$newUri}");
                 return true;
             }
         }
         return false;
     });
 }
Пример #10
0
 /**
  * Set request access_token query.
  */
 protected function attachAccessToken()
 {
     if (!$this->accessToken) {
         return;
     }
     // log
     $this->getHttp()->addMiddleware(function (callable $handler) {
         return function (RequestInterface $request, array $options) use($handler) {
             $field = $this->accessToken->getQueryName();
             $token = $this->accessToken->getToken();
             $request = $request->withUri(Uri::withQueryValue($request->getUri(), $field, $token));
             Log::debug("Request Token: {$token}");
             Log::debug('Request Uri: ' . $request->getUri());
             return $handler($request, $options);
         };
     });
     // retry
     $this->getHttp()->addMiddleware(Middleware::retry(function ($retries, RequestInterface $request, ResponseInterface $response = null, RequestException $exception = null) {
         // Limit the number of retries to 2
         if ($retries <= 2 && $response && ($body = $response->getBody())) {
             // Retry on server errors
             if (stripos($body, 'errcode') && (stripos($body, '40001') || stripos($body, '42001'))) {
                 return true;
             }
         }
         return false;
     }));
 }
Пример #11
0
 /**
  * 处理授权
  * @param callable $callable
  */
 public function setAuthCallback(callable $callable)
 {
     $this->forgetPreAuthCode(null);
     $request = Request::createFromGlobals();
     $authInfo = $this->queryAuth($request->get('auth_code'));
     Log::debug('处理授权同步回调' . $request->getContent());
     //保存信息
     $authirizerAccessToken = new AuthorizerAccessToken($authInfo['authorization_info']['authorizer_appid'], $authInfo['authorization_info']['authorizer_refresh_token'], $this->componentAppId, $this->componentAppSecret, $this->cache);
     $authInfoDetails = $this->getAuthorizerInfo($authInfo['authorization_info']['authorizer_appid']);
     $authirizerAccessToken->setToken($authInfo['authorization_info']['authorizer_access_token'], $authInfo['authorization_info']['authorizer_refresh_token']);
     $callable(array_merge($authInfo, $authInfoDetails));
     return;
 }
Пример #12
0
 /**
  * Handle message.
  *
  * @param array $message
  *
  * @return mixed
  */
 protected function handleMessage($message)
 {
     $handler = $this->messageHandler;
     $verifyHandler = $this->verifyHandler;
     if (!is_callable($handler)) {
         Log::debug('No handler enabled.');
         return;
     }
     Log::debug('Message detail:', $message);
     $message = new Collection($message);
     //处理verifyTicket
     if ($message->get('InfoType') == 'component_verify_ticket') {
         call_user_func_array($verifyHandler, [$message]);
     }
     $type = $this->messageTypeMapping[$message->get('InfoType')];
     $response = null;
     if ($this->messageFilter & $type) {
         $response = call_user_func_array($handler, [$message]);
     }
     return $response;
 }