当前位置: 首页 > 后端技术 > PHP

如何在MixPHPV2.1中使用EasyWeChat

时间:2023-03-30 01:16:32 PHP

国内中小公司有大量的微信接入需求。EasyWeChat是一个非常流行的微信开发库。由于该库是为FPM模型的传统框架搭建的,很多Swoole用户并不知道如何使用,下面就来详细介绍下如何在MixPHPv2.1中使用。HookGuzzleFirst,因为overtrue/wechat是基于GuzzleHttp开发的,由于GuzzleHttp在Swoole中不能直接使用,所以需要先安装MixGuzzleHook。这个库可以在不修改源码的情况下制作GuzzleHttp协程。https://github.com/mix-php/guzzle-hookRequest类代理由于EasyWeChat使用了Symfony框架的Request类,并不完全符合PSR-7规范,所以我们需要创建一个Request代理类:request=$request;}publicfunctionget($key){return$this->request->getAttribute($key);}publicfunctiongetContent(){return$this->request->getBody()->getContents();}publicfunctiongetContentType(){return$this->request->getHeaderLine('Content-Type');}publicfunctiongetUri(){return$this->request->getUri()->__toString();}publicfunctiongetMethod(){return$this->request->getMethod();}}在框架中使用创建完成后,可以在MixPHP控制器中使用,代码如下:publicfunctionindex(ServerRequest$请求,响应$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=(newStreamFactory())->createStream($wechatResponse->getContent());$code=$wechatResponse->getStatusCode();$response->withBody($body)->withStatus($code);返回$响应;}