PHP code example of xinqudao / thinkphp5-easywechat4

1. Go to this page and download the library: Download xinqudao/thinkphp5-easywechat4 library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

xinqudao / thinkphp5-easywechat4 example snippets



namespace app\wechatopen\controller;

use think\Controller;
use uctoo\ThinkEasyWeChat\Facade;
use think\Hook;
/**
 * 非第三方平台开发模式微信公众号的交互控制器,中控服务器
 * 主要获取和反馈微信平台的数据,分析用户交互和系统消息分发。
 */
class Official extends Controller {
    
    //行为绑定,需要将标签位的处理逻辑分发到各个行为类的都要在这里绑定行为
    public function _initialize()
    {
        Hook::add('user_enter_tempsession','app\\wechatopen\\behavior\\UserEnterTempsession');
        Hook::add('text_auto_reply','app\\wechatopen\\behavior\\CustomSendAutoReply');
        Hook::add('subscribemsg','app\\wechatopen\\behavior\\CustomSendAutoReply');
    }
        
     /**
     * 开启了开发模式的公众号所有发送到微信公众号的消息都会推送到该操作
     * 所以,微信公众平台后台填写的api地址则为该操作的访问地址
     * 在mp.weixin.qq.com  公众号登录 开发->基本配置-> 服务器地址(URL)填写  https://域名/wechatopen/official/index
     * @return mixed
     */
	public function index() {
	    $config = [
            // AppID
            'app_id' => '',
            // AppSecret
            'secret' => '',
            // Token
            'token' => 'uctoo',
            // EncodingAESKey
            'aes_key' => '',
        ];
        $officialAccount = Facade::officialAccount('',$config);  // 支持传入公众号配置信息
        $officialAccount->server->push(function($message){       //公众号收到消息回复用户
            return 'hello,world';
        });
        $officialAccount->server->serve()->send();
    }
}

use uctoo\ThinkEasyWeChat\Facade;

$officialAccount = Facade::officialAccount();  // 公众号
$work = Facade::work(); // 企业微信
$payment = Facade::payment(); // 微信支付
$openPlatform = Facade::openPlatform(); // 开放平台
$miniProgram = Facade::miniProgram(); // 小程序  

$officialAccount = Facade::officialAccount('test'); // 公众号

$officialAccount = Facade::officialAccount('',$config); // 公众号


namespace app\wechatopen\controller;
use app\wechatopen\service\openPlatform\AuthorizedEventHandler;
use app\wechatopen\service\openPlatform\RegisterEventHandler;
use app\wechatopen\service\openPlatform\UnauthorizedEventHandler;
use app\wechatopen\service\openPlatform\ComponentVerifyTicketEventHandler;
use app\wechatopen\service\openPlatform\UpdateAuthorizedEventHandler;
use EasyWeChat\OpenPlatform\Application;
use EasyWeChat\OpenPlatform\Server\Guard;
use think\Controller;
use uctoo\ThinkEasyWeChat\Facade;

/*
 * 微信开放平台授权事件处理
 * */
class Authevent extends Controller {

    /*
     * 微信第三方平台授权事件接收URL
     * */
      public function index(){
          $auth_code = input('auth_code');  //商户扫码授权后第三方平台redirect回本地址时会有auth_code字段
          $openPlatform = Facade::openPlatform();

          if ($this->request->isGet() && !isset($auth_code)) {  //跳转第三方平台授权页,微信第三方平台接收到的地址 $_SERVER["HTTP_REFERER"] 需要与第三方平台 授权事件接收URL 相同
              $callbackurl = url('wechatopen/authevent/index','','',true);
              $PAurl = $openPlatform->getPreAuthorizationUrl($callbackurl);
              $this->success("跳转第三方平台授权页",$PAurl,'',1);
          }
        try{
            // 授权事件
            $openPlatform->server->push(new ComponentVerifyTicketEventHandler(),Guard::EVENT_COMPONENT_VERIFY_TICKET);
            // 授权事件
            $openPlatform->server->push(new AuthorizedEventHandler(),Guard::EVENT_AUTHORIZED);
            // 更新授权事件
            $openPlatform->server->push(new UpdateAuthorizedEventHandler(),Guard::EVENT_UPDATE_AUTHORIZED);
            // 取消授权事件
            $openPlatform->server->push(new UnauthorizedEventHandler(),Guard::EVENT_UNAUTHORIZED);
            // 小程序快速注册事件
            $openPlatform->server->push(new RegisterEventHandler(),Guard::EVENT_THIRD_FAST_REGISTERED);

            $openPlatform->server->serve()->send();
        }catch (\Exception $e){
            return '404';
         }
    }
}


Hook::add('text_auto_reply','app\\wechatopen\\behavior\\CustomSendAutoReply');


namespace app\wechatopen\behavior;

use uctoo\ThinkEasyWeChat\Facade;

class CustomSendAutoReply
{
    /**
     * 用户进入小程序客服默认发图片
     * @access public
     */
    public function textAutoReply()
    {
    }

    /**
     * 用户关注默认发消息
     * @access public
     */
    public function subscribemsg()
    {
    }
}


use uctoo\ThinkEasyWeChat\Facade;

$app = Facade::officialAccount('',Config::load());   //注意帐号配置信息传第二个参数

 
use uctoo\ThinkEasyWeChat\Facade;

/**
 * 微信接口
 */
class Index extends \think\addons\Controller
{
    public $app = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->app = Facade::officialAccount('',Config::load());  // 公众号
        Hook::add('text_auto_reply','app\\admin\\eventhandler\\wechat\\CustomSendAutoReply');        //注册具体业务处理的模块
        Hook::add('subscribemsg','app\\admin\\eventhandler\\wechat\\CustomSendAutoReply');
    }
    
        /**
         * 微信API对接接口
         */
        public function api()
        {
            //.....
            //自动回复处理
            $res =  Hook::listen("text_auto_reply", $message);         //实现点监听消息,将处理逻辑分发到具体业务实现模块
            $res =  Hook::listen("subscribemsg", $message);
            return $res[0];
        }
}

 
class CustomSendAutoReply
{
    /**
     * 用户进入默认发图片
     * @access public
     */
    public function textAutoReply($message)
    {
        $matches = null;
          $wechatService = new WechatService;
          $unknownMessage = WechatConfig::getValue('default.unknown.message');
          $unknownMessage = $unknownMessage ? $unknownMessage : "";
          //自动回复处理
         if ($message['MsgType'] == 'text') {
              $autoreply = null;
              $autoreplyList = WechatAutoreply::where('status', 'normal')->cache(true)->order('weigh DESC,id DESC')->select();
              foreach ($autoreplyList as $index => $item) {
                  //完全匹配和正则匹配
                  if ($item['text'] == $message['Content'] || (in_array(mb_substr($item['text'], 0, 1), ['#', '~', '/']) && preg_match($item['text'], $message['Content'], $matches))) {
                      $autoreply = $item;
                      break;
                  }
              }
              if ($autoreply) {
                  $wechatResponse = WechatResponse::where(["eventkey" => $autoreply['eventkey'], 'status' => 'normal'])->find();
                  if ($wechatResponse) {
                      $responseContent = (array)json_decode($wechatResponse['content'], true);
                      $wechatContext = WechatContext::where(['openid' => $message['FromUserName']])->order('id', 'desc')->find();
                      $result = $wechatService->response($this, $message['FromUserName'], $message['Content'], $responseContent, $wechatContext, $matches);
                      if ($result) {
                          return $result;
                      }
                  }
              }
          }
          return $unknownMessage;
    }

    /**
     * 用户关注默认发消息
     * @access public
     */
    public function subscribemsg()
    {
    }
}