## EasyWeChat 接入
國內中小型公司有大量的微信接入需求,[EasyWeChat](https://www.easywechat.com/) 是一個非常流行的微信開發庫,由于該庫是為 FPM 模式的傳統框架而打造,因此很多 Swoole 用戶不知道如何使用,下面詳細介紹一下 [MixPHP v2.1](https://github.com/mix-php/mix) 中如何使用。
## Hook Guzzle
首先由于?[overtrue/wechat](https://github.com/overtrue/wechat)?是基于 GuzzleHttp 開發的,因為 GuzzleHttp 無法直接在 Swoole 中使用,所以需要先安裝 Mix Guzzle Hook,該庫能在不修改源碼的情況下讓 GuzzleHttp 協程化。
* [https://github.com/mix-php/guzzle-hook](https://github.com/mix-php/guzzle-hook)
## Request 類代理
由于 EasyWeChat 中使用的是 Symfony 框架的 Request 類,并且又不完全符合 ?[PSR-7](https://www.php-fig.org/psr/psr-7/) 規范,因此我們需要創建一個 Request 代理類:
```
<?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;
}
```
- 歡迎使用 MixPHP
- 安裝說明
- 全棧安裝
- Phar 開發安裝
- 新手教程
- 命令行常識
- 進程管理
- 熱更新
- 全局變量
- 入門須知
- 命名空間
- 自動加載
- 入口文件
- 增改應用
- 核心功能
- 配置 (manifest.php)
- 協程
- 什么是協程
- 開啟協程
- PHP Stream Hook
- xgo + Channel
- WaitGroup + xdefer
- 連接池
- 協程池
- 定時器
- 依賴注入
- 事件調度
- 命令行
- 簡介
- Application
- 創建命令
- 命令參數
- 打印與顏色
- 守護進程
- 后臺運行
- Web/API 應用
- 簡介
- 服務器
- 路由
- 中間件
- 請求
- 文件上傳
- 響應
- 控制器
- 視圖
- Auth
- Session
- 客戶端
- GuzzleHttp
- 調試與錯誤
- 安全建議
- WebSocket 應用
- 簡介
- 服務器
- 客戶端
- JavaScript
- Swoole
- nginx代理
- 60s無消息斷線
- TCP 應用
- 簡介
- 服務器
- 客戶端
- Telnet
- PHP
- Swoole
- UDP 應用
- 簡介
- 服務器
- 客戶端
- NC
- Swoole
- Sync Invoke 同步調用
- 簡介
- 服務器
- 客戶端
- 公共組件
- 驗證器
- 驗證器定義
- 驗證規則
- 靜態調用
- 日志
- 緩存
- 數據庫
- Database
- ConnectionPool
- Connection
- QueryBuilder
- ExecutedEvent
- Redis
- ConnectionPool
- Connection
- CalledEvent
- 常見問題
- 如何利用CPU多核
- 連接多個數據庫
- 使用主從數據庫
- 如何設置跨域
- form-data 上傳文件失敗
- 輸出大于2M的文件失敗 (xlsx)
- 如何接入EasyWeChat
- 升級指導
- 不兼容修改-001
- 不兼容修改-002
- 不兼容修改-003