參考文檔:https://github.com/overtrue/wechat/wiki/%E4%BA%8C%E7%BB%B4%E7%A0%81
<?php namespace App\Http\Controllers\home;
use App\Http\Models\home\Users;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Overtrue\Wechat\Server;
use Overtrue\Wechat\User as WxUser;
use Overtrue\Wechat\QRCode;
class WxController extends Controller {
public function index()
{
//$encodingAESKey 可以爲空
$server =new Server(env('WX_APPID'),env('WX_TOKEN'));
// 只監聽指定類型事件
$server->on('event', 'subscribe',[$this,'guanzhu']);
//取消關注
$server->on('event', 'unsubscribe',[$this,'qxgz']);
//
return $server->serve();
}
//@關注方法。
public function guanzhu($event)
{
$wxuser=new WxUser(env('WX_APPID'),env('WX_SEC'));
$wx_res=$wxuser->get($event->FromUserName);
//寫入數據庫
$user=new Users();
$user->openid=$event->FromUserName;
$user->name=$wx_res->nickname;
$user->subtime=time();
$user->save();
//二維碼操作
$this->qr($user->uid);
//返回信息
return '感謝您的關注。';
}
//@二維碼操作
public function qr($uid){
//file_get_contents https的網址,allow_url_include 要爲 on
ini_set('allow_url_include','on');
//開始生成場景二維碼
$qrcode = new QRCode(env('WX_APPID'),env('WX_SEC'));
$result = $qrcode->forever($uid);
$ticket = $result->ticket;
//下載二維碼
$_path=$this->mkd().'/'.'qr_'.$uid.'.jpg';
$qrcode->download($ticket,$_path);
}
//@創建保存二維碼目錄
protected function mkd(){
$path=public_path().date('/Y/md');
if(!file_exists($path)){
mkdir($path,0777,true);
}
return $path;
}
//@取消關注
public function qxgz($event)
{
//獲得取消用戶的 openid
$open_id=$event->FromUserName;
//取得用戶信息
$user_one=Users::where('openid',$open_id)->first();
//拼接關注時的二維碼路徑
$_path=str_replace('\\','/',public_path()).date('/Y/md').'/'.'qr_'.$user_one->uid.'.jpg';
//判斷並刪除
if(file_exists($_path)){
unlink($_path);
}
//清空信息變量
unset($user_one);
//刪除對應用戶信息
Users::where('openid',$open_id)->delete();
}
}