Laravel EasyWechat 全网发布

Laravel + overtrue/wechat 开发微信第三方平台

说明

本文使用的是 overtrue/wechat 的开发版本(即最新的4.0版本)

开始之前

集成到Laravel中

1.安装 overture/wechat

composer require "overtrue/wechat:dev-master"

2.安装 overtrue/laravel-wechat

composer require "overtrue/laravel-wechat:dev-master"

3.发布配置文件

php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider"

4.修改配置文件
file

全网发布

本文中使用的 域名为 wx.test.com,实际使用中请替换成自己的域名。
第三方管理平台,假设有如下配置

授权事件接收URL   http://wx.test.com/openPlatform/serve
公众号消息与事件接收URL  http://wx.test.com/api/wx/openPlatform/officialAccount/events?appid=/$APPID$

微信全网发布验证

  • 组件Ticket正确接收

  • 生成预授权码

    • 无需实现
  • 获取授权code

    • 无需实现
  • 授权

    • 无需实现
  • 返回Api文本消息

    • 自己实现
  • 返回普通文本消息

    • 自己实现
  • 发送事件消息

    • 自己实现
  • 取消授权

    • 无需实现

本文中有如下类 OpenPlatformAPIController 用于处理相关请求,代码如下

    /**
     * 公众号消息与事件接收
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|mixed|\Symfony\Component\HttpFoundation\Response
     */
    public function officialAccountEvents(Request $request)
    {

        /** @var \EasyWeChat\OpenPlatform\Application $open_platform */
        $open_platform = EasyWeChat::openPlatform();
        $authorizer_appid = substr($request->get('appid'), 1);

        /**
         * 全网发布
         */
        if ($authorizer_appid == 'wx570bc396a51b8ff8') {
            return $this->releaseToNetWork($open_platform, $authorizer_appid);
        }

        /**
         * 正常业务,根据实际需求自己实现
         */
        $official_account = WeChatAuthorizer::where('authorizer_appid', '=', $authorizer_appid)->first();
        if (empty($official_account)) {
            return $this->sendResponse(null, 'official account not authorization');
        }

        $official_account_client = $open_platform->officialAccount($official_account->authorizer_appid, $official_account->authorizer_refresh_token);

        $server = $official_account_client->server;
        /**
         * 简单的处理 文本消息和事件
         */
        $server->push(TextMessageHandler::class, Message::TEXT);
        $server->push(EventMessageHandler::class, Message::EVENT);

        $response = $server->serve();
        return $response;
    }

全网发布需要自己实现的部分

    /**
     * 处理全网发布相关逻辑
     * @param \EasyWeChat\OpenPlatform\Application $open_platform
     * @param $authorizer_appid
     * @return mixed
     */
    private function releaseToNetWork($open_platform, $authorizer_appid)
    {
        $message = $open_platform->server->getMessage();

        //返回API文本消息
        if ($message['MsgType'] == 'text' && strpos($message['Content'], "QUERY_AUTH_CODE:") !== false) {
            $auth_code = str_replace("QUERY_AUTH_CODE:", "", $message['Content']);
            $authorization = $open_platform->handleAuthorize($auth_code);
            $official_account_client = $open_platform->officialAccount($authorizer_appid, $authorization['authorization_info']['authorizer_refresh_token']);
            $content = $auth_code . '_from_api';
            $official_account_client['customer_service']->send([
                'touser' => $message['FromUserName'],
                'msgtype' => 'text',
                'text' => [
                    'content' => $content
                ]
            ]);

            //返回普通文本消息
        } elseif ($message['MsgType'] == 'text' && $message['Content'] == 'TESTCOMPONENT_MSG_TYPE_TEXT') {
            $official_account_client = $open_platform->officialAccount($authorizer_appid);
            $official_account_client->server->push(function ($message) {
                return $message['Content'] . "_callback";
            });
            //发送事件消息
        } elseif ($message['MsgType'] == 'event') {
            $official_account_client = $open_platform->officialAccount($authorizer_appid);
            $official_account_client->server->push(function ($message) {
                return $message['Event'] . 'from_callback';
            });
        }
        $response = $official_account_client->server->serve();
        return $response;
    }
本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由 Summer 于 6年前 加精
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 5

有后台管理吗?例如我要管理哪些授权过哪些取消过的,以及当前授权赋予的权限?

6年前 评论

@大师兄 我自己看错了,我以为是基于laravel-wechat的二次开发

6年前 评论

我觉得写复杂了
处理公众号事件的URL的action:

/**
     * 处理公众号相关事件
     * @param $appid
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function appid($appid)
    {
        $officialAccount = $this->openPlatform->officialAccount($appid);
        $server = $officialAccount->server;

        if($appid == self::FULL_PUBLIC_APPID) { //你的第三方appid
            $server->push(FullPublicMessageHandler::class);
        } else {
            /**
             * 传实例主要用于构造时传参,传类名就单纯对message的内容处理
             * 由于第三方平台是要传进appid来处理相关消息,所以传实例
             */
            //$server->push(LogMessageHandler::class);
            $server->push(TextMessageHandler::class, Message::TEXT); //接入智能闲聊
            $server->push(new ImageMessageHandler($appid, true), Message::IMAGE); //接入人脸融合
            $server->push(new VoiceMessageHandler($appid, true), Message::VOICE); //接入语音翻译
        }

        return $server->serve();
    }

FullPublicMessageHandler的代码,即全网发布逻辑代码:

<?php
namespace App\Handler\Platform;

use EasyWeChat\Kernel\Contracts\EventHandlerInterface;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Factory;

class FullPublicMessageHandler implements  EventHandlerInterface
{
    const
        FULL_PUBLIC_APPID = 'wx570bc396asfsfsdfdf'; //填上你的第三方appid

    protected
        $openPlatform;

    public function __construct()
    {
        $config = config('wechat.open_platform');
        $this->openPlatform = Factory::openPlatform($config);
    }

    public function handle(array $message = [])
    {
        switch($message['MsgType']) {
            case 'event': //1. 事件
                return new Text($message['Event'].'from_callback');
                break;
            case 'text': // 2. 文本
                if($message['Content'] == 'TESTCOMPONENT_MSG_TYPE_TEXT') {
                    return new Text('TESTCOMPONENT_MSG_TYPE_TEXT_callback');
                } else { //3. 授权发送客服消息
                    $query_auth_code = str_replace('QUERY_AUTH_CODE:', '',$message['Content']);
                    //取授权公众号信息拿refresh_access_token
                    $authInfo = $this->openPlatform->handleAuthorize($query_auth_code);

                    $auth_refresh_access_token = $authInfo['authorization_info']['authorizer_refresh_token'] ?? '';
                    //初始化公众号app
                    $app = $this->openPlatform->officialAccount(self::FULL_PUBLIC_APPID, $auth_refresh_access_token);
                    // 发送客服消息
                    $app->customer_service->message(new Text("{$query_auth_code}_from_api"))->to($message['FromUserName'])->send();
                }
                break;

        }
    }
}
6年前 评论
waney 4年前
EthanYep

借鉴了,很好的解决了我遇到的全网发布的问题

4年前 评论

按照这个方法操作,全网发布时提示返回普通文本检测失败,看了下都是正常回复的,有遇见过这种问题的吗

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!