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; } } }