tp51+easywechat

安裝

安裝tp51

composer create-project topthink/think=5.1.* tp5

安裝easywechat

composer require overtrue/wechat:~4.0 -vvv

環境要求

  • PHP >= 7.0
  • PHP cURL 擴展
  • PHP OpenSSL 擴展
  • PHP SimpleXML 擴展
  • PHP fileinfo 拓展

申請微信測試號

鏈接: 微信測試號申請


在tp51框架下的config文件夾中加入wechat.php配置文件
return [
    /**
     * Debug 模式,bool 值:true/false
     *
     * 當值爲 false 時,所有的日誌都不會記錄
     */
    'debug'  => true,
    /**
     * 賬號基本信息,請從微信公衆平臺/開放平臺獲取
     */
    'app_id'  => 'your-app-id',         // AppID
    'secret'  => 'your-app-secret',     // AppSecret
    'token'   => 'your-token',          // Token
    'aes_key' => '',                    // EncodingAESKey,安全模式下請一定要填寫!!!
    /**
     * 日誌配置
     *
     * level: 日誌級別, 可選爲:
     *         debug/info/notice/warning/error/critical/alert/emergency
     * permission:日誌文件權限(可選),默認爲null(若爲null值,monolog會取0644)
     * file:日誌文件位置(絕對路徑!!!),要求可寫權限
     */
    'log' => [
        'level'      => 'debug',
        'permission' =>  0777,
        'file'       =>  Env::get('runtime_path').'log/easywechat.log',
    ],
    /**
     * OAuth 配置
     *
     * scopes:公衆平臺(snsapi_userinfo / snsapi_base),開放平臺:snsapi_login
     * callback:OAuth授權完成後的回調頁地址
     */
    'oauth' => [
        'scopes'   => ['snsapi_userinfo'],
        'callback' => '/wx/index/oauthCallback',
    ],
    /**
     * 微信支付
     */
    'payment' => [
        'merchant_id'        => 'your-mch-id',
        'key'                => 'key-for-signature',
        'cert_path'          => 'path/to/your/cert.pem', // XXX: 絕對路徑!!!!
        'key_path'           => 'path/to/your/key',      // XXX: 絕對路徑!!!!
        // 'device_info'     => '013467007045764',
        // 'sub_app_id'      => '',
        // 'sub_merchant_id' => '',
        // ...
    ],
    /**
     * Guzzle 全局設置
     *
     * 更多請參考: http://docs.guzzlephp.org/en/latest/request-options.html
     */
    'guzzle' => [
        'timeout' => 3.0, // 超時時間(秒)
        //'verify' => false, // 關掉 SSL 認證(強烈不建議!!!)
    ],
];

服務器驗證
  1. 建立控制器基類,這裏使用\app\common\controller\BaseController
namespace app\common\controller;

use EasyWeChat\Factory;
use think\facade\Config;
use think\Controller;

class BaseController extends Controller
{
    protected $app = null;

    public function initialize(){
        //將wechat的配置文件讀取出來
        $config = Config::pull('wechat');

        //初始化app實例
        $this->app = Factory::officialAccount($config);
    }
}
  1. 服務器驗證的具體邏輯
namespace app\index\controller;
use app\common\controller\BaseController;
use think\facade\Request;

class Index extends BaseController
{

    public function index(){
        //監測開發者微信服務器
        //$this->checkServer();
        //exit;

        $this->app->server->push(function ($message) {
            switch ($message['MsgType']) {
                case 'event':
                    $messageEvent = $message['Event'];
                    $messageKey = (isset($message['EventKey']) && !empty($message['EventKey'])) ? $message['EventKey'] : '';
                    $returnInfo = $this->eventHandler($messageEvent, $messageKey);
                    return $returnInfo;
                    break;
                case 'text':
                    return str_replace('?', '', $message['Content']) . '!'; // 實現人工智能(*^▽^*)
                    break;
                case 'image':
                    return '收到圖片消息';
                    break;
                case 'voice':
                    return '收到語音消息';
                    break;
                case 'video':
                    return '收到視頻消息';
                    break;
                case 'location':
                    return '收到座標消息';
                    break;
                case 'link':
                    return '收到鏈接消息';
                    break;
                default:
                    return '收到其它消息';
                    break;
            }
        });

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

    }

    /**
     * 檢測開發者服務器
     * @return mixed
     */
    public function checkServer(){
        $response = $this->app->server->serve();
        return $response->send();
    }


    public function setMenu(){
        $buttons = [
            [
                "type" => "click",
                "name" => "menuClick",
                "key"  => "menu_click_test",
            ],
            [
                "name"       => "二級菜單",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => '搜索',
                        "url"  => "http://domain.com/wx/index/test",
                    ],
                    [
                        "type" => "click",
                        "name" => "subMenuClick",
                        "key" => "sub_menu_click_test"
                    ],
                ],
            ],
        ];

        $setRes = $this->app->menu->create($buttons);

        return json_encode($setRes);
    }

    /**
     * 事件處理
     * @param $messageEvent
     * @param $eventKey
     * @return string
     */
    private function eventHandler($messageEvent,$eventKey)
    {
        $messageEvent = strtolower($messageEvent);
        switch ($messageEvent) {
            case 'subscribe': // 訂閱事件
                return '歡迎訂閱';
                break;
            case 'unsubscribe': // 取消訂閱事件
                // TODO 可以添加日誌等其他邏輯
                return '';
                break;
            case 'click': // 處理菜單點擊事件
                return $this->menuClickEventHandler($eventKey);
                break;
            default:
                return "{$messageEvent}, {$eventKey}";
                break;
        }
    }

    /**
     * 菜單欄中type爲click的按鈕纔會發送return的消息回去
     * eventKey是設置菜單時type爲click的key值
     * @param $eventKey
     * @return string
     */
    private function menuClickEventHandler($eventKey){
        switch ($eventKey) {
            case 'menu_click_test':
                return '點擊了一級菜單的 menuClick 按鈕';
                break;
            case 'sub_menu_click_test':
                return '點擊了二級菜單的 subMenuClick 按鈕';
                break;
            default:
                return "嘻嘻";
                break;
        }
    }
}
這裏說明一下:服務器的驗證方法是checkServer,使用easywechat,只用簡單的幾句就完成了驗證。
針對創建菜單,和各種事件做了一個簡單測試,這裏就不贅述,看一下代碼就很清楚了。

網頁授權

具體的網頁邏輯使用了一個新的父類\app\common\controller\WechatBaseController
namespace app\common\controller;


use EasyWeChat\Factory;
use think\facade\Config;
use think\Controller;
use think\facade\Session;

class WechatBaseController extends Controller
{
    protected $app = null;

    public function initialize(){
        //將wechat的配置文件讀取出來
        $config = Config::pull('wechat');
        //初始化app實例
        $this->app = Factory::officialAccount($config);

        if(!$this->hasWechatUser()){
            $this->redirect('/wx/Oauth/profile');
        }else{
            //dump('父類統一獲取');
            //dump(Session::get('wechat_user'));
        }
    }

    /**
     * 是否有wechat_user的session
     * @return bool
     */
    protected function hasWechatUser(){
        if(Session::has('wechat_user')){
            return true;
        }else{
            return false;
        }
    }
}
網頁授權控制器 \app\wx\controller\Oauth
namespace app\wx\controller;


use app\common\controller\WechatBaseController;
use think\facade\Session;

class Oauth extends WechatBaseController
{
    // 開始授權
    public function profile()
    {
        $oauth = $this->app->oauth;
        if (empty(Session::get('wechat_user'))) {
            Session::set('target_url', '/wx/Oauth/profile');
            return $oauth->redirect();
        }
        //$user = Session::get('wechat_user');
    }

    // 授權成功回調
    public function oauthCallback()
    {
        $oauth = $this->app->oauth;
        $user = $oauth->user();
        Session::set('wechat_user', $user);
        $targetUrl = !empty(Session::get('target_url')) ? '/wx/Oauth/oauthSuccess' : Session::get('target_url');
        header('location:' . $targetUrl); // 跳轉到 user/profile
    }

    // 授權成功之後輸出信息
    public function oauthSuccess(){
        $user=Session::get('wechat_user');
        // todo 將用戶的基本信息保存在數據庫中,然後提供下次進行使用
        dump($user);
    }
}
具體業務頁面
namespace app\wx\controller;

use app\common\controller\WechatBaseController;

class Index extends WechatBaseController
{
    // test頁面渲染
    public function test()
    {
        //$users = $this->getUserList();
        //dump($users);
        return $this->view->fetch();
    }

    // 獲取用戶列表
    public function getUserList(){
        $users = $this->app->user->list();
        return $users;
    }



}

目前的測試使用就到這裏,進行了一些微信基本功能的測試,感覺easywechat還是很爽的啊。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章