由於在easywechat中沒有提及在thinkphp中的使用,后來我在http://www.thinkphp.cn/topic/45416.html中找到了有人已經封裝了一下,我把自己使用的過程寫下來與大家共勉
在thinkphp中安裝easywechat
1.使用composer下載
使用命令行進入thinkphp根目錄
然后運行下面的命令:
- composer require hooklife/thinkphp5-wechat
然后發布配置文件到項目根目錄
- php think wechat:config
然后你會看到application目錄下多了一個extra文件夾,里面有一個wechat.php,如果報錯了,請參考 https://www.ailoli.org/archives/72/,這樣就算是引入成功了
然后
填寫配置文件需要填寫的項
示例:
'debug' => true,
/**
* 賬號基本信息,請從微信公眾平台/開放平台獲取
*/
'app_id' => '......', // AppID
'secret' => '......', // AppSecret
'token' => '......', // Token
'aes_key' => '',
'oauth' => [
'scopes' => ['snsapi_userinfo'],
'callback' => '回調地址',
],
然后,在原代碼基礎上創建一個控制器(與微信相關):Wechat1.php,
在里面定義一個變量app
$options = Config::get('wechat');
$app = new Application($options);
這樣就能夠使用app變量了,其他的用法參照文檔https://www.easywechat.com/docs即可
配置和原來類似,我是在Wechat1.php中定義一個serve方法
public function serve(){
$server = self::$app->server;
$server->setMessageHandler(function ($message) {
return '你好';
});
$server->serve()->send();
}
在微信公眾號后台驗證token的url寫能夠訪問到這個serve方法的鏈接即可驗證成功
下面重點說明我使用easywechat進行網頁授權過程
在需要授權的控制器Personal.php中的寫了
static $app;
public function _initialize()
{
if (empty(session('id'))){
self::$app = Wechat1::return_app();
$oauth = self::$app->oauth;
session('target_url',$_SERVER['PATH_INFO']);
if (empty(session('wechat_user'))){
$oauth->redirect()->send();
}else{
$user = session('wechat_user');
$open_id = $user['original']['openid'];
//查詢數據庫中用戶的賬號的openid中是否有值,有值說明用戶的微信與賬號綁定
$student_no = self::check_login($open_id);
if ($student_no!=0){
session('id',$student_no);
$this->redirect(session('target_url'));
}else{
$this->redirect('index/Index/login');
}
}
}
}
然后在Wechat1.php中寫了一個授權回調的方法
public function oauth(){
$oauth = self::$app->oauth;
$user = $oauth->user();
session('wechat_user',$user->toArray());
$targetUrl = session('target_url');
$this->redirect($targetUrl);
}
注:上面的配置文件中的回調函數就寫能夠找到oauth方法的地址即可
這樣就能夠完成微信網頁授權,授權過的微信的用戶信息存在session中,之后用到該用戶信息的時候,只需要從session中取即可
### 注:現在官方網站上面支持thinkphp了,可以使用官方支持的擴展包,應該會更方便一些!!!thinkphp-wechat地址