easyswoole和mixphp_如何在 MixPHP V2.1 中使用 EasyWeChat

国内中小型公司有大量的微信接入需求,EasyWeChat 是一个非常流行的微信开发库,由于该库是为 FPM 模式的传统框架而打造,因此很多 Swoole 用户不知道如何使用,下面详细介绍一下 MixPHP v2.1 中如何使用。

Hook Guzzle

首先由于 overtrue/wechat 是基于 GuzzleHttp 开发的,因为 GuzzleHttp 无法直接在 Swoole 中使用,所以需要先安装 Mix Guzzle Hook,该库能在不修改源码的情况下让 GuzzleHttp 协程化。

Request 类代理

由于 EasyWeChat 中使用的是 Symfony 框架的 Request 类,并且又不完全符合  PSR-7 规范,因此我们需要创建一个 Request 代理类:

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值