如何在 MixPHP V2.1 中使用 EasyWeChat

國內(nèi)中小型公司有大量的微信接入需求,EasyWeChat 是一個(gè)非常流行的微信開發(fā)庫,由于該庫是為 FPM 模式的傳統(tǒng)框架而打造,因此很多 Swoole 用戶不知道如何使用,下面詳細(xì)介紹一下 MixPHP v2.1 中如何使用。

Hook Guzzle

首先由于 overtrue/wechat 是基于 GuzzleHttp 開發(fā)的,因?yàn)?GuzzleHttp 無法直接在 Swoole 中使用,所以需要先安裝 Mix Guzzle Hook,該庫能在不修改源碼的情況下讓 GuzzleHttp 協(xié)程化。

Request 類代理

由于 EasyWeChat 中使用的是 Symfony 框架的 Request 類,并且又不完全符合 PSR-7 規(guī)范,因此我們需要?jiǎng)?chuàng)建一個(gè) 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();
    }

}

框架中使用

創(chuàng)建完成后就可在 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;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容