How to use EasyWeChat in MixPHP V2.1

Small and medium-sized companies in China have a large number of WeChat access requirements. EasyWeChat is a very popular WeChat development library. Since this library is built for the traditional framework of FPM mode, many Swoole users do not know how to use it. The following is a detailed introduction to MixPHP v2 .1 how to use.

Hook Guzzle

First of all, because  overtrue/wechat  is developed based on GuzzleHttp, because GuzzleHttp cannot be used directly in Swoole, you need to install Mix Guzzle Hook first, which can make GuzzleHttp coroutine without modifying the source code.

Request class proxy

Since the Request class of the Symfony framework is used in EasyWeChat, and it is not fully compliant with the   PSR-7 specification, we need to create a Request proxy class:

<?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();
    }

}

used in the frame

After the creation is complete, it can be used in the MixPHP controller as follows:

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;
}
{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324163939&siteId=291194637