如何在MixPHPV2.1中使用EasyWeChat
Hook Guzzle
首先由于 overtrue/wechat 是基于 GuzzleHttp 开发的,因为 GuzzleHttp 无法直接在 Swoole 中使用,所以需要先安装 Mix Guzzle Hook,该库能在不修改源码的情况下让 GuzzleHttp 协程化。
- https://github.com/mix-php/guzzle-hook
Request 类代理
由于 EasyWeChat 中使用的是 Symfony 框架的 Request 类,并且又不完全符合 PSR-7 规范,因此我们需要创建一个 Request 代理类:
<?phpnamespace AppHttpEasyWeChat;
class Request
{
/**
* @var MixHttpMessageServerRequest
*/
public $request;
public function __construct(MixHttpMessageServerRequest $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 = EasyWeChatFactory::officialAccount($config);
$app->request = new AppHttpEasyWeChatRequest($request);
$wechatResponse = $app->server->serve();
$body = (new StreamFactory())->createStream($wechatResponse->getContent());
$code = $wechatResponse->getStatusCode();
$response->withBody($body)
->withStatus($code);
return $response;
}
以上是 如何在MixPHPV2.1中使用EasyWeChat 的全部内容, 来源链接: utcz.com/z/512876.html