有人遇到过 Swoft 接入 EasyWechat 扩展,微信验证服务端 token 失败问题吗?

新手上路,请多包涵

我用的环境

  • PHP 版本:7.2
  • overtrue/wechat 版本:4.1
  • Swoole版本:4.4.3
  • Swoole框架名称: Swoft2.0.5

问题及现象

微信公众号监听用户关注事件,微信公众号后台需要验证服务器端token
swoft 框架不能使用 exit ,文档中说 $response->send() 直接输出(echo)了,请问用swoft 的方式怎么去做

WeChatController

$config=[
    ....
];
$app = Factory::officialAccount($config);
$response = $app->server->serve();
return \context()->getResponse()
->withContentType('text/xml')
->withContent($response->getContent());

有人使用过Swoft 接入EasyWechat扩展,服务端验证微信token失败问题吗

求助中

阅读 3.1k
1 个回答

我也接了easywechat,是这样写的

<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link     https://swoft.org
 * @document https://swoft.org/docs
 * @contact  group@swoft.org
 * @license  https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Http\Controller;

use App\Common\EasyWeChat\MessageFactory;
use Swoft;
use Swoft\Exception\SwoftException;
use Swoft\Http\Server\Annotation\Mapping\{Controller,RequestMapping};
use EasyWeChat\Factory;

/**
 * Class HomeController
 * @Controller(prefix="/wechat")
 */
class EasyWeChatController
{
    /**
     * 公众号应用实例
     * @var \EasyWeChat\OfficialAccount\Application
     */
    public $app;

    /**
     * 微信配置信息
     * @var mixed
     */
    public $config;

    /**
     * 响应对象
     * @var
     */
    public $response;

    public function __construct()
    {
        $this->config = config('wechat');

        $this->app = Factory::officialAccount($this->config);
    }

    /**
     * @RequestMapping(route="verify")
     */
    public function serviceRoute()
    {
        $this->activeInit();

        $this->app->server->push(function ($message) {
            return MessageFactory::handleMessage($message);
        });

        $this->response = $this->app->server->serve();

        return \context()->getResponse()
            ->withContentType('text/xml')
            ->withContent($this->response->getContent());
    }

    /**
     * 主动初始化接收方法
     * @throws SwoftException
     */
    private function activeInit()
    {
        $get = \context()->getRequest()->get() ?? [];
        $post= \context()->getRequest()->post() ?? [];
        $attr = [];
        $cookies = \context()->getRequest()->cookie() ?? [];
        $files = \context()->getRequest()->file() ?? [];
        $server = \context()->getRequest()->server() ?? [];
        $raw = \context()->getRequest()->raw() ?? [];
        $this->app->request->initialize($get, $post, $attr, $cookies, $files, $server, $raw);
    }

}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题