國內中小型公司有大量的微信接入需求,EasyWeChat 是一個很是流行的微信開發庫,因爲該庫是爲 FPM 模式的傳統框架而打造,所以不少 Swoole 用戶不知道如何使用,下面詳細介紹一下 MixPHP v2.1 中如何使用。php
Hook Guzzle
首先因爲 overtrue/wechat 是基於 GuzzleHttp 開發的,由於 GuzzleHttp 沒法直接在 Swoole 中使用,因此須要先安裝 Mix Guzzle Hook,該庫能在不修改源碼的狀況下讓 GuzzleHttp 協程化。git
Request 類代理
因爲 EasyWeChat 中使用的是 Symfony 框架的 Request 類,而且又不徹底符合 PSR-7 規範,所以咱們須要建立一個 Request 代理類:github
<?php namespace App\Http\EasyWeChat; class Request { /** * @var \Mix\Http\Message\ServerRequest */ public $request; public function __construct(\Mix\Http\Message\ServerRequest $request) { $this->request = $request; } public function get($key) { return $this->request->getAttribute($key); } public function getContent() { return $this->request->getBody()->getContents(); } public function getContentType() { return $this->request->getHeaderLine('Content-Type'); } public function getUri() { return $this->request->getUri()->__toString(); } public function getMethod() { return $this->request->getMethod(); } }
框架中使用
建立完成後就可在 MixPHP 的控制器中按以下代碼使用:微信
public function index(ServerRequest $request, Response $response) { $config = [ 'app_id' => 'wx3cf0f39249eb0xxx', 'secret' => 'f1c242f4f28f735d4687abb469072xxx', 'token' => 'TestToken', 'response_type' => 'array', //... ]; $app = \EasyWeChat\Factory::officialAccount($config); $app->request = new \App\Http\EasyWeChat\Request($request); $wechatResponse = $app->server->serve(); $body = (new StreamFactory())->createStream($wechatResponse->getContent()); $code = $wechatResponse->getStatusCode(); $response->withBody($body) ->withStatus($code); return $response; }