123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461 |
- <?php
- namespace app\controllers;
- use app\common\components\SiteUrl;
- use app\components\WeiXin\WeiXin;
- use app\modules\admin\models\Config;
- use app\modules\plugins\models\MpReply;
- use app\modules\ucenter\models\UserOpenAuth;
- use app\modules\doc\models\DocReal;
- use app\modules\doc\models\DocDowncode;
- use Yii;
- use yii\web\Controller;
- class WeixinController extends Controller
- {
- public $enableCsrfValidation = false;
- public $mpconfig;
- public $imageconfig;
- public function init()
- {
- parent::init();
- //系统配置的公众号
- $mpconfigResult = Config::find()->where("name='mp'")->one();
- $this->mpconfig = string2array($mpconfigResult->value);
- //图片配置
- $imageconfigResult = Config::find()->where("name='imageconfig'")->one();
- $this->imageconfig = string2array($imageconfigResult->value);
- }
- public function traceHttp()
- {
- $this->logger("QUERY_STRING:".$_SERVER["QUERY_STRING"]);
- }
- public function logger($log_content)
- {
- $max_size = 500000;
- $log_filename = Yii::$app->params['wxPath'].'log.xml';
- if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
- file_put_contents($log_filename, date('Y-m-d H:i:s').$log_content."\r\n", FILE_APPEND);
- }
- //扫码关注登录/注册(因为获取不到昵称头像,暂时弃用)
- public function actionOpenauth()
- {
- $args = array(
- 'appId'=>Yii::$app->params['openauth']['mpAppId'],
- 'appSecret'=>Yii::$app->params['openauth']['mpAppSecret'],
- 'token'=>Yii::$app->params['openauth']['mpToken'],
- );
- $weixin = new WeiXin($args);
- $weixin->init();
- $this->traceHttp();
- $result = $weixin->receiveMsg();
- $this->logger(var_export($result,true));
- if(empty($result))
- {
- ob_clean();
- $weixin->valid();
- }
- else
- {
- $result['eventKey'] = str_replace('qrscene_','',$result['eventKey']);
- //扫码事件处理
- if(!empty($result['eventKey'])&&($result['event']=='SCAN'||$result['event']=='subscribe'))
- {
- $scene_id = $result['eventKey'];
- //扫码关注登录(PC)
- if(strpos($scene_id,'mplogin_')!==false)
- {
- $this->initOpenAuth($weixin,$result,$scene_id);
- }
- }
- }
- }
- //公众号用到的接口
- public function actionMp()
- {
- $args = array(
- 'appId'=>Yii::$app->params['mp']['mpAppId'],
- 'appSecret'=>Yii::$app->params['mp']['mpAppSecret'],
- 'token'=>Yii::$app->params['mp']['mpToken'],
- );
- $weixin = new WeiXin($args);
- $weixin->init();
- $this->traceHttp();
- $result = $weixin->receiveMsg();
- //$this->logger(var_export($result,true));
- if(empty($result))
- {
- ob_clean();
- $weixin->valid();
- }
- else
- {
- //被动回复
- if($result['msgType']!='event'&&!empty($result['content'])&&Yii::$app->params['mp']['autoreply'])
- {
- $reply = MpReply::find()->where("keywords like '%".$result['content']."%'")->orderBy(['list_order'=>SORT_ASC])->one();
- if(empty($reply))//默认没有匹配发送文档搜索入口
- {
- $picurl = $this->_getDowntipImg();
- //回复搜索页
- $url = SiteUrl::searchForWeixin(getSysconfigValue('default_search_model'),$result['content']);
- $articles = array(
- array(
- 'title'=>'"'.$result['content'].'"'.'的搜索结果',
- 'description'=>'点击查看所有内容',
- 'picurl'=>$picurl,
- 'url'=>urldecode($url)
- ),
- );
- $weixin->responseMsg(array('type'=>'news','count'=>'1'),$articles);
- }
- else
- {
- $this->sendReply($weixin,$reply);
- }
- exit;
- }
- $result['eventKey'] = str_replace('qrscene_','',$result['eventKey']);
- //扫码事件处理
- if(!empty($result['eventKey'])&&($result['event']=='SCAN'||$result['event']=='subscribe'))
- {
- $scene_id = $result['eventKey'];
- //$this->logger($scene_id);
- //扫码关注登录(PC)
- if(strpos($scene_id,'mplogin_')!==false)
- {
- //统一到登录注册配置的公众号信息
- $args = array(
- 'appId'=>Yii::$app->params['openauth']['mpAppId'],
- 'appSecret'=>Yii::$app->params['openauth']['mpAppSecret'],
- 'token'=>Yii::$app->params['openauth']['mpToken'],
- );
- $weixin = new WeiXin($args);
- $weixin->init();
- $this->traceHttp();
- $result = $weixin->receiveMsg();
- $openAuth = $this->initOpenAuth($weixin,$result,$scene_id);
- if(!empty($openAuth))
- {
- //判断用户资料是否写入
- $checkUserInfo = string2array(base64_decode($openAuth->user_info));
- if(!$checkUserInfo['nick_name'])
- {
- $picurl = $this->_getDowntipImg('mplogin');
- $newsurl = SiteUrl::mpLogin($scene_id,1);
- $articles = array(
- array(
- 'title'=>'',
- 'description'=>'',
- 'picurl'=>$picurl,
- 'url'=>urldecode($newsurl)
- ),
- array(
- 'title'=>'点击授权登录>>',
- 'description'=>'',
- 'picurl'=>'',
- 'url'=>urldecode($newsurl)
- ),
- );
- $weixin->responseMsg(array('type'=>'news','count'=>'2'),$articles);
- exit;
- }
- else
- {
- $picurl = $this->_getDowntipImg('mpsuccess');
- $newsurl = WAP_URL;
- $articles = array(
- array(
- 'title'=>'',
- 'description'=>'',
- 'picurl'=>$picurl,
- 'url'=>urldecode($newsurl)
- ),
- array(
- 'title'=>'您已在电脑端登录成功!',
- 'description'=>'',
- 'picurl'=>'',
- 'url'=>urldecode($newsurl)
- ),
- );
- //附加其他推送
- $weixin->responseMsg(array('type'=>'news','count'=>'2'),$articles);
- exit;
- }
- }
- }
- //扫码订阅消息通知(PC)
- if(strpos($scene_id,'mpmsg_')!==false&&Yii::$app->params['mp']['openmsg'])
- {
- $this->initMpMsg($weixin,$result,$scene_id);
- }
- //首次关注推送消息
- if(Yii::$app->params['mp']['autoreply']&&$result['event']=='subscribe')
- {
- //自动消息(客服消息)
- $customerMsg = \app\modules\plugins\models\MpReply::find()->where("focus=1")->orderBy(['list_order'=>SORT_ASC])->one();
- if(!empty($customerMsg))
- {
- $data = string2array($customerMsg->data);
- $return = $weixin->sendCustomermsg($customerMsg->msg_type,$result['fromUsername'],$data);
- //$this->logger(var_export($return,true));
- }
- //再增加一条关注回复
- if(strpos($scene_id,'freedowndoc_')===false){
- $reply = \app\modules\plugins\models\MpReply::find()->where("focus=1 and id!='".$customerMsg->id."'")->orderBy(['list_order'=>'SORT_ASC'])->one();
- if(!empty($reply))
- {
- $this->sendReply($weixin,$reply);
- }
- }
- }
- //免费扫码下载
- if(strpos($scene_id,'freedowndoc_')!==false)
- {
- $docId = str_replace("freedowndoc_","",$scene_id);
- $doc = DocReal::findOne($docId);
- $downCode = DocDowncode::find()->where("doc_id=$docId and openid='".$result['fromUsername']."' and user_id=0")->orderBy(['create_time'=>SORT_DESC])->one();
- if(empty($downCode))
- {
- $default_user_group = getDefaultUserGroup(getSysconfigValue('default_user_model'));
- if(empty($default_user_group)){
- $weixin->responseMsg(array('type'=>'text','content'=>'请设置默认用户组'));
- }
- $default_user_group_level = getDefaultUserGroupLevel(getSysconfigValue('default_user_model'));
- if(empty($default_user_group_level))
- {
- $weixin->responseMsg(array('type'=>'text','content'=>'请设置默认用户等级'));
- }
- $userGroupLevel = \app\modules\ucenter\models\UserGroupLevel::findOne($default_user_group_level);
- $groupRights = string2array($userGroupLevel->settings);
- //日期
- $timeList = getTimeList(1);
- $todayStart = $timeList['dayStart'];
- $todayEnd = $timeList['dayEnd'];
- //今日免费下载数量
- $freeDownNumToday = DocDowncode::find()->where("openid='".$result['fromUsername']."' and user_id=0 and (create_time>=".$todayStart." and create_time<=".$todayEnd.")")->groupBy('doc_id')->count();
- //免费总下载数量
- $freeDownNumTotal = DocDowncode::find()->where("openid='".$result['fromUsername']."' and user_id=0")->groupBy('doc_id')->count();
- //所在用户组被禁止下载
- if($groupRights['doc_downnum_day']==-1||$groupRights['doc_downnum_total']==-1)
- {
- $weixin->responseMsg(array('type'=>'text','content'=>'您已被禁止下载'));
- }
- //总数量限制检查
- if($groupRights['doc_freedownload_totalnum']>0&&$freeDownNumTotal>=$groupRights['doc_freedownload_totalnum'])
- {
- $weixin->responseMsg(array('type'=>'text','content'=>'您已达到免费文档下载总量上限('.$groupRights['doc_freedownload_totalnum'].'份),无法继续下载'));
- }
- //每日数量限制检查
- if($groupRights['doc_freedownload_num']>0&&$freeDownNumToday>=$groupRights['doc_freedownload_num'])
- {
- $weixin->responseMsg(array('type'=>'text','content'=>'您已达到今日免费文档下载总量上限('.$groupRights['doc_freedownload_num'].'份/天),无法继续下载'));
- }
- $downCode = new DocDowncode();
- $downCode->doc_id = $doc->id;
- $downCode->openid = strval($result['fromUsername']);
- $downCode->downcode = strval(getDowncode($doc->id));
- $downCode->user_id = 0;
- $downCode->doc_user_id = $doc->user_id;
- $downCode->is_ad = $doc->is_ad;;
- $downCode->type = 1;
- $downCode->create_time = TIMESTAMP;
- $downCode->save();
- }
- //输出回复内容
- $picurl = $this->_getDowntipImg();
- $downloadUrl = SiteUrl::downByLink($downCode->downcode,1);
- $articles = array(
- array(
- 'title'=>$doc->title,
- 'description'=>$doc->description,
- 'picurl'=>$picurl,
- 'url'=>urldecode($downloadUrl)
- ),
- );
- $weixin->responseMsg(array('type'=>'news','count'=>'1'),$articles);
- }
- }
- else if(!empty($result['event'])) //其他事件反馈
- {
- //$this->logger(var_export($result,true));
- //首次关注推送消息
- if(Yii::$app->params['mp']['autoreply']&&$result['event']=='subscribe')
- {
- //自动消息(客服消息)
- $customerMsg = \app\modules\plugins\models\MpReply::find()->where("focus=1")->orderBy(['list_order'=>SORT_ASC])->one();
- if(!empty($customerMsg))
- {
- $data = string2array($customerMsg->data);
- $weixin->sendCustomermsg($customerMsg->msg_type,$result['fromUsername'],$data);
- //$this->logger(var_export($return,true));
- }
- //再增加一条关注回复
- $reply = \app\modules\plugins\models\MpReply::find()->where("focus=1 and id!='".$customerMsg->id."'")->orderBy(['list_order'=>'SORT_ASC'])->one();
- if(!empty($reply))
- {
- $this->sendReply($weixin,$reply);
- }
- }
- }
- }
- }
- //扫码关注公众号二维码登录处理
- public function initOpenAuth($weixin,$result,$scene_id)
- {
- //$this->logger(var_export($result,true));
- //如果开启了unionid
- if(Yii::$app->params['openauth']['openUnionId']==1)
- {
- $userInfo = $weixin->getUserInfo($result['fromUsername']);
- if($userInfo['unionid'])
- {
- $openAuth = UserOpenAuth::find()->where("app_unionname='wx' and app_unionid='".$userInfo['unionid']."'")->orderBy(['id'=>SORT_DESC])->one();
- }
- }
- //$this->logger(var_export($openAuth,true));
- if(empty($openAuth)){
- $openAuth = UserOpenAuth::find()->where("app_uid='".$result['fromUsername']."' and app='mp'")->one();
- }
- if(empty($openAuth))
- {
- if(empty($userInfo)) $userInfo = $weixin->getUserInfo($result['fromUsername']);
- $openAuth = new UserOpenAuth();
- $openAuth->app='mp';
- $openAuth->app_uid = strval($result['fromUsername']);
- $openAuth->scene_id = strval($scene_id);
- $openAuth->user_info = base64_encode(array2string($userInfo));
- $openAuth->bind_time = TIMESTAMP;
- $openAuth->hash = md5($openAuth->app.$openAuth->app_uid);
- $openAuth->app_unionid = $userInfo['unionid']?$userInfo['unionid']:'';
- $openAuth->app_unionname = 'wx';
- if(!$openAuth->save())
- {
- $this->logger($openAuth->returnFirstError());
- }
- }
- else
- {
- $openAuth->app_unionid = $userInfo['unionid']?$userInfo['unionid']:'';
- $openAuth->scene_id = strval($scene_id);
- $openAuth->save();
- if(!$openAuth->save())
- {
- $this->logger($openAuth->returnFirstError());
- }
- }
- return $openAuth;
- }
- //回复消息
- public function sendReply($weixin,$reply)
- {
- $data = string2array($reply->data);
- if($reply->msg_type=='news')
- {
- $articles = array(
- array(
- 'title'=>$data['title'],
- 'description'=>$data['description'],
- 'picurl'=>$data['picurl'],
- 'url'=>$data['url']
- ),
- );
- $weixin->responseMsg(array('type'=>'news','count'=>'1'),$articles);
- }
- if($reply->msg_type=='text')
- {
- $weixin->responseMsg(array('type'=>'text','content'=>$data['content']));
- }
- if($reply->msg_type=='image'||$reply->msg_type=='voice')
- {
- $weixin->responseMsg(array('type'=>$reply->msg_type,'media_id'=>$data['media_id']));
- }
- if($reply->msg_type=='video')
- {
- $weixin->responseMsg(array('type'=>$reply->msg_type,'media_id'=>$data['media_id'],'title'=>$data['title'],
- 'description'=>$data['description']));
- }
- }
- //扫码订阅消息通知
- public function initMpMsg($weixin,$result,$scene_id)
- {
- $openAuth = UserOpenAuth::find()->where("app_uid='".$result['fromUsername']."' and app='mpmsg'")->one();
- if(empty($openAuth))
- {
- $userInfo = $weixin->getUserInfo($result['fromUsername']);
- $openAuth = new UserOpenAuth();
- $openAuth->app = 'mpmsg';
- $openAuth->app_uid = strval($result['fromUsername']);
- $openAuth->scene_id = strval($scene_id);
- $openAuth->user_info = base64_encode(array2string($userInfo));
- $openAuth->bind_time = TIMESTAMP;
- $openAuth->hash = md5($openAuth->app.$openAuth->app_uid);
- $openAuth->app_unionid = $userInfo['unionid']?$userInfo['unionid']:'';
- $openAuth->app_unionname = 'mpmsg';
- if(!$openAuth->save())
- {
- $this->logger($openAuth->returnFirstError());
- }
- }
- else
- {
- $openAuth->scene_id = strval($scene_id);
- $openAuth->save();
- if(!$openAuth->save())
- {
- $this->logger($openAuth->returnFirstError());
- }
- }
- }
- //获取下载引导封面图
- private function _getDowntipImg($type='downtip',$path=0)
- {
- $picPath = BASE_PATH.'web'.DIRECTORY_SEPARATOR.'upload'.DIRECTORY_SEPARATOR.'system'.DIRECTORY_SEPARATOR;
- dir_create($picPath);
- $downtipImg = getFileUrl($this->imageconfig[$type]);
- $picFile = $picPath.basename($downtipImg);
- if(!file_exists($picFile)) file_put_contents($picFile,https_request($downtipImg));
- $picurl = APP_URL.'upload/system/'.basename($downtipImg);
- if($path)
- {
- return $picFile;
- }
- else
- {
- return $picurl;
- }
- }
- }
|