EasyWechat

EasyWeChat 是一个开源的微信 SDK (非微信官方 SDK)。

如果您使用了 Swoole 4.7.0 及以上版本,并且开启了 native curl 选项,则可以不按照此文档进行操作。

因为组件默认使用 Curl,所以我们需要修改对应的 GuzzleClient 为协程客户端,或者修改常量 SWOOLE_HOOK_FLAGS

替换 Handler

以下以公众号为例,

  1. <?php
  2. use Hyperf\Utils\ApplicationContext;
  3. use EasyWeChat\Factory;
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\HandlerStack;
  6. use Hyperf\Guzzle\CoroutineHandler;
  7. $container = ApplicationContext::getContainer();
  8. $app = Factory::officialAccount($config);
  9. $handler = new CoroutineHandler();
  10. // 设置 HttpClient,部分接口直接使用了 http_client。
  11. $config = $app['config']->get('http', []);
  12. $config['handler'] = $stack = HandlerStack::create($handler);
  13. $app->rebind('http_client', new Client($config));
  14. // 部分接口在请求数据时,会根据 guzzle_handler 重置 Handler
  15. $app['guzzle_handler'] = $handler;
  16. // 如果使用的是 OfficialAccount,则还需要设置以下参数
  17. $app->oauth->setGuzzleOptions([
  18. 'http_errors' => false,
  19. 'handler' => $stack,
  20. ]);

修改 SWOOLE_HOOK_FLAGS

参考 SWOOLE_HOOK_FLAGS

如何使用 EasyWeChat

EasyWeChat 是为 PHP-FPM 架构设计的,所以在某些地方需要修改下才能在 Hyperf 下使用。下面我们以支付回调为例进行讲解。

  1. EasyWeChat 中自带了 XML 解析,所以我们获取到原始 XML 即可。
  1. $xml = $this->request->getBody()->getContents();
  1. 将 XML 数据放到 EasyWeChatRequest 中。
  1. <?php
  2. use Symfony\Component\HttpFoundation\HeaderBag;
  3. use Symfony\Component\HttpFoundation\Request;
  4. $get = $this->request->getQueryParams();
  5. $post = $this->request->getParsedBody();
  6. $cookie = $this->request->getCookieParams();
  7. $uploadFiles = $this->request->getUploadedFiles() ?? [];
  8. $server = $this->request->getServerParams();
  9. $xml = $this->request->getBody()->getContents();
  10. $files = [];
  11. /** @var \Hyperf\HttpMessage\Upload\UploadedFile $v */
  12. foreach ($uploadFiles as $k => $v) {
  13. $files[$k] = $v->toArray();
  14. }
  15. $request = new Request($get, $post, [], $cookie, $files, $server, $xml);
  16. $request->headers = new HeaderBag($this->request->getHeaders());
  17. $app->rebind('request', $request);
  18. // Do something...
  1. 服务器配置

如果需要使用微信公众平台的服务器配置功能,可以使用以下代码。

以下 $responseSymfony\Component\HttpFoundation\Response 并非 Hyperf\HttpMessage\Server\Response 所以只需将 Body 内容直接返回,即可通过微信验证。

  1. $response = $app->server->serve();
  2. return $response->getContent();

如何替换缓存

EasyWeChat 默认使用 文件缓存,而现实场景是 Redis 缓存居多,所以这里可以替换成 Hyperf 提供的 hyperf/cache 缓存组件,如您当前没有安装该组件,请执行 composer require hyperf/cache 引入,使用示例如下:

  1. <?php
  2. use Psr\SimpleCache\CacheInterface;
  3. use Hyperf\Utils\ApplicationContext;
  4. use EasyWeChat\Factory;
  5. $app = Factory::miniProgram([]);
  6. $app['cache'] = ApplicationContext::getContainer()->get(CacheInterface::class);