accountM = db('weixin_account'); $this->encodingAesKey = open_encodingAesKey;//公众号消息加解密Key $this->token = open_token; //公众号消息校验Token $this->appId = open_appId; //开放平台的appid $this->appSecret = open_appSecret; $this->redirect_uri = curHostURL().'/index.php/index/weixin/get_authorization_code/'; $this->redirect_foreign = curHostURL();//本地 } //发起授权页的体验URL public function login() { $get_pre_auth_code = $this->get_pre_auth_code();//正式 //临时用 return "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" . $this->appId . "&pre_auth_code=$get_pre_auth_code&redirect_uri=".$this->redirect_uri."stoid/".I('stoid/d',0); } //公众号消息与事件接收URL public function test($appid) { $msg_signature = $_REQUEST['msg_signature']; if ($msg_signature) { $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $toUsername = $postObj->ToUserName; if ($toUsername) { mlog(json_encode($postObj), "weixints/".$toUsername); } if ($toUsername == 'gh_3c884a361561') { $this->encrypt($postStr); }else{ $this->encrypt($postStr); } } else { return; } } /* 解密 */ public function encrypt($encyptdata) { $encodingAesKey = $this->encodingAesKey; $token = $this->token; $appId = $this->appId; $timeStamp = empty($_GET['timestamp']) ? "" : trim($_GET['timestamp']); $nonce = empty($_GET['nonce']) ? "" : trim($_GET['nonce']); $msg_sign = empty($_GET['msg_signature']) ? "" : trim($_GET['msg_signature']); $pc = new WXBizMsgCrypt($token, $encodingAesKey, $appId); $xml_tree = new \DomDocument(); $xml_tree->loadXML($encyptdata); $array_e = $xml_tree->getElementsByTagName('Encrypt'); $encrypt = $array_e->item(0)->nodeValue; $format = ""; $from_xml = sprintf($format, $encrypt); //第三方收到公众号平台发送的消息 $msg = ''; $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg); if ($errCode == 0) { $msgObj = json_decode(json_encode(simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA))); file_put_contents(dirname(__FILE__)."/static/recmsg/cccchenzhiqmsgObj.txt",json_encode($msgObj)); // {"ToUserName":"gh_3c884a361561","FromUserName":"ozy4qt1eDxSxzCr0aNT0mXCWfrDE","CreateTime":"1446104321","MsgType":"event","Event":"LOCATION","Latitude":"111.000000","Longitude":"222.000000","Precision":"333.000000"} mlog(json_encode($msgObj),"encrypt"); switch ($msgObj->MsgType) { case "event": $this->replyEventMessage($timeStamp, $nonce, $msg_sign, $msgObj, $msgObj->ToUserName, $msgObj->FromUserName); break; case "text": $this->processTextMessage($timeStamp, $nonce, $msg_sign, $msgObj->Content, $msgObj->ToUserName, $msgObj->FromUserName); break; case "image": exit('success'); // $this->processImageMessage($timeStamp, $nonce, $msg_sign, $msgObj->MediaId, $msgObj->ToUserName, $msgObj->FromUserName); break; case "voice": $this->processVoiceMessage($timeStamp, $nonce, $msg_sign, $msgObj->MediaId, $msgObj->ToUserName, $msgObj->FromUserName); break; default: break; } } else { file_put_contents(dirname(__FILE__)."/static/recmsg/cccxmlerr.txt", json_encode($errCode) . date('Y-m-d H:i:s', time()) . "/n", FILE_APPEND); } } //处理语音回复 public function processVoiceMessage($timeStamp, $nonce, $msg_sign, $Content, $toUserName, $fromUserName) { $pc = new WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->appId); $encryptMsg = ''; $time = time(); $text = "" . $timeStamp . ""; file_put_contents(dirname(__FILE__)."/static/recmsg/cccvoice.txt", $text); $errCode = $pc->encryptMsg($text, $time, $nonce, $encryptMsg); if ($errCode == 0) { file_put_contents(dirname(__FILE__)."/static/recmsg/cccencryptMsgvoice.txt", $encryptMsg); exit($encryptMsg); } else { file_put_contents(dirname(__FILE__)."/static/recmsg/cccerrCodevoice.txt", $errCode); exit($errCode); } } //处理图片回复 public function processImageMessage($timeStamp, $nonce, $msg_sign, $Content, $toUserName, $fromUserName) { $pc = new WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->appId); $encryptMsg = ''; $time = time(); $text = "" . $timeStamp . ""; // // // // 12345678 // // // // // file_put_contents(dirname(__FILE__)."/static/recmsg/cccimage.txt", $text); $errCode = $pc->encryptMsg($text, $time, $nonce, $encryptMsg); if ($errCode == 0) { file_put_contents(dirname(__FILE__)."/static/recmsg/cccencryptMsgimage.txt", $encryptMsg); exit($encryptMsg); } else { file_put_contents(dirname(__FILE__)."/static/recmsg/cccerrCodeimage.txt", $errCode); exit($errCode); } } //处理文本回复 public function processTextMessage($timeStamp, $nonce, $msg_sign, $Content, $toUserName, $fromUserName) { mlog("001","processTextMessage"); if ('TESTCOMPONENT_MSG_TYPE_TEXT' == $Content) { $text = $Content . '_callback'; mlog($text,"processTextMessage"); file_put_contents(dirname(__FILE__)."/static/recmsg/cccTESTCOMPONENT_MSG_TYPE_TEXT.txt", $Content); $this->replyTextMessage($timeStamp, $nonce, $msg_sign, $text, $toUserName, $fromUserName); } elseif (stristr($Content, "QUERY_AUTH_CODE")) { $textArray = explode(':', $Content); file_put_contents(dirname(__FILE__)."/static/recmsg/cccQUERY_AUTH_CODE.txt", $Content); $this->replyApiTextMessage($timeStamp, $nonce, $msg_sign, $textArray[1], $toUserName, $fromUserName); }else{ $this->replyTextMessage($timeStamp, $nonce, $msg_sign, $Content, $toUserName, $fromUserName,1); } } public function replyApiTextMessage($timeStamp, $nonce, $msg_sign, $query_auth_code, $toUserName, $fromUserName) { $url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token='.$this->get_Access_token(); $data = json_encode(array( 'component_appid' => $this->appId, 'authorization_code' => $query_auth_code )); $getreplyApiTextMessage = json_decode($this->curl_get_post($url, $data)); file_put_contents(dirname(__FILE__)."/static/recmsg/ccccgetreplyApiTextMessage.txt", json_encode($getreplyApiTextMessage)); $text = $query_auth_code . '_from_api'; $sfromUserName = $getreplyApiTextMessage->authorization_info->authorizer_appid; $authorizer_access_token = $getreplyApiTextMessage->authorization_info->authorizer_access_token; $authorization = $this->get_authorization($sfromUserName, 'customer_service', '1'); file_put_contents(dirname(__FILE__)."/static/recmsg/cccauthorization.txt", 'ok'); // if ($authorization == 'ok') { // file_put_contents(dirname(__FILE__)."/static/recmsg/ccccget_authorization.txt", 'ok'); $this->processWechatTextMessage($text, $fromUserName, $authorizer_access_token); // } } /* *推送客服回复信息 */ function processWechatTextMessage($text, $fromUserName, $authorizer_access_token) { //$auth_token=get_authorizer_access_token(); $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $authorizer_access_token; $data = json_encode(array( 'touser' => $fromUserName, 'msgtype' => 'text', 'text' => array( 'content' => $text ) )); file_put_contents(dirname(__FILE__)."/static/recmsg/ccccprocessWechatTextMessagedata.txt", $data); $getreplyApiTextMessage = json_decode($this->curl_get_post($url, $data)); file_put_contents(dirname(__FILE__)."/static/recmsg/ccccprocessWechatTextMessage.txt", json_encode($getreplyApiTextMessage)); } /* 获取授权 location_report(地理位置上报选项) 0无上报 1进入会话时上报 2每5s上报 voice_recognize(语音识别开关选项)0关 1开 customer_service(客服开关选项)0关 1开 */ function get_authorization($authorizer_appid, $option_name, $option_value = '1') { $arraydata = array( 'location_report', 'voice_recognize', 'customer_service' ); if (in_array($option_name, $arraydata)) { $url = 'https://api.weixin.qq.com/cgi-bin/component/api_set_authorizer_option?component_access_token=' . $this->get_Access_token(); $data = json_encode(array( 'component_appid' => $this->appId, 'authorizer_appid' => $authorizer_appid, 'option_name' => $option_name, 'option_value' => $option_value )); $query_authorization = json_decode($this->curl_get_post($url, $data)); if ($query_authorization->errmsg == 'ok') { return 'ok'; } else { return 'error'; } } else { return 'error'; } } public function replyEventMessage($timeStamp, $nonce, $msg_sign, $msgObj, $toUserName, $fromUserName) { mlog("回复值: ".json_encode($msgObj),'replyEventMessage'); switch ($msgObj->Event) { case 'CLICK': $content = $msgObj->EventKey; break; case 'subscribe': mlog('是否执行关注openid:'.$fromUserName,'subscribe'); //更新openid是否关注状态 //qrscene_123123 关注取参数值 $subscribekey=$msgObj->EventKey; $subscribekey=json_encode($subscribekey); if ($subscribekey=="{}") { $subscribekey=""; } else { $subscribekey=json_decode($subscribekey,true); $subscribekey = str_replace("qrscene_", "", $subscribekey); } // $url = $this->redirect_foreign.'/Admin/Wechat/get_subscribe_key';//取关注关键字接口 $data = json_encode(array( 'wxid' => $toUserName, 'wxopenid' => $fromUserName, 'subscribekey' => $subscribekey, )); mlog($data,'subscribe'); $res = http_post_json($url, $data,true); mlog('关注内容'.json_encode($res),'subscribe'); $res=json_decode($res[0],true); $content = $res['id'];//用户关注该公众号时触发的关键字 mlog('关注关键字:'.$content,'subscribe'); break; case 'unsubscribe': mlog('取消关注:'.$fromUserName,'unsubscribe'); $url = $this->redirect_foreign.'/Admin/Wechat/unsubscribe';//取消关注关键字接口 $data = json_encode(array( 'wxid' => $toUserName, 'wxopenid' => $fromUserName, )); mlog($data,'unsubscribe'); $res = http_post_json($url, $data); break; default: $content = $msgObj->Event . "from_callback"; break; } // $content = $event . "from_callback"; $this->replyTextMessage($timeStamp, $nonce, $msg_sign, $content, $toUserName, $fromUserName); } public function replyTextMessage($timeStamp, $nonce, $msg_sign, $content, $toUserName, $fromUserName,$inputtype='') { mlog("002".$content,"replyTextMessage/".$toUserName); $pc = new WXBizMsgCrypt($this->token, $this->encodingAesKey, $this->appId); $encryptMsg = ''; $time = time(); if ($toUserName == 'gh_3c884a361561') { $text = " " . $timeStamp . " "; }else{ //发送消息回复 if (!empty($content)) { $url = $this->redirect_foreign . '/Admin/Wechat/reply'; mlog($url, "replyTextMessage"); $data = json_encode(array( 'key' => $content, 'wxid' => $toUserName, 'inputtype'=>$inputtype, )); mlog($data, "replyTextMessage/".$toUserName); $res = json_decode($this->curl_get_post($url, $data)); mlog("返回值:".json_encode($res), "replyTextMessage/".$toUserName); if ($res ) { switch ($res->type) { case 1: //文本格式 $text = " " . $timeStamp . " content . "]]> "; break; case 2: //单图文 $text = " " . $timeStamp . " content]]> "; break; case 3: //多图文 $text = " " . $timeStamp . " " . $res->content->piccount . " "; for ($i = 0; $i < $res->content->piccount;$i++) { $text .= " <![CDATA[" . $res->content->piclist[$i]->logintitle . "]]> content->piclist[$i]->loginremark . "]]> content->piclist[$i]->loginimgurl. "]]> content->piclist[$i]->weburl . "]]> "; } $text .= " "; break; case 4: //多客服 $text = " " . $timeStamp . " "; break; default: exit(); break; } } } } mlog("回复值:".$text,"replyTextMessage/".$toUserName); $errCode = $pc->encryptMsg($text, $time, $nonce, $encryptMsg); if ($errCode == 0) { mlog("返回值 :".$encryptMsg,"replyTextMessage/".$toUserName); // file_put_contents(dirname(__FILE__)."/static/recmsg/cccencryptMsg.txt", $encryptMsg); exit($encryptMsg); } else { mlog("返回值 :".$errCode,"replyTextMessage/".$toUserName); // file_put_contents(dirname(__FILE__)."/static/recmsg/cccerrCode.txt", $errCode); exit($errCode); } } //授权事件接收URL public function acceptc() { // 第三方发送消息给公众平台 $encodingAesKey = $this->encodingAesKey; //echo $encodingAesKey; $token = $this->token; $appId = $this->appId; $timeStamp = empty($_GET['timestamp']) ? "" : trim($_GET['timestamp']); $nonce = empty($_GET['nonce']) ? "" : trim($_GET['nonce']); $msg_sign = empty($_GET['msg_signature']) ? "" : trim($_GET['msg_signature']); $encryptMsg = file_get_contents('php://input'); $pc = new WXBizMsgCrypt($token, $encodingAesKey, $appId); $xml_tree = new \DOMDocument(); $xml_tree->loadXML($encryptMsg); $array_e = $xml_tree->getElementsByTagName('Encrypt'); $encrypt = $array_e->item(0)->nodeValue; mlog("回复值:".$encrypt,"acceptc"); file_put_contents(dirname(__FILE__)."/static/encrypt.txt", $encrypt); //echo $encrypt; $format = ""; $from_xml = sprintf($format, $encrypt); //第三方收到公众号平台发送的消息 $msg = ''; $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg); file_put_contents(dirname(__FILE__)."/static/errCode.txt", $errCode); //echo $errCode; if ($errCode == 0) { $msgObj = json_decode(json_encode(simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA))); switch ($msgObj->InfoType) { case "unauthorized": mlog("执行到","unauthorized"); $AuthorizerAppid = $msgObj->AuthorizerAppid; $AuthorizerAppid=$AuthorizerAppid; $resdata = json_encode(array( 'appid' => $AuthorizerAppid, )); $res = http_post_json($this->redirect_foreign . "/Admin/Wechat/unauthorized", $resdata); mlog($res); break; case "component_verify_ticket": $component_verify_ticket = $msgObj->ComponentVerifyTicket; F("component_verify_ticket",$component_verify_ticket); file_put_contents(dirname(__FILE__)."/static/component_verify_ticket.txt", $component_verify_ticket); break; default: break; } } else { file_put_contents(dirname(__FILE__)."/static/errCode.txt", json_encode($errCode) . date('Y-m-d H:i:s', time()) . "/n", FILE_APPEND); } exit('success'); } public function get_authorizer_access_token() { $authorizer_appid = file_get_contents(dirname(__FILE__)."/static/authorizer_appid.txt"); $authorizer_access_token = file_get_contents(dirname(__FILE__)."/static/authorizer_access_token.txt"); $url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=' . $this->get_Access_token(); $data = '{"component_appid":"' . $this->appId . '","authorizer_appid":"' . $authorizer_appid . '","authorizer_refresh_token":"' . $authorizer_refresh_token . '"}'; $authorization_code_data = json_decode($this->curl_get_post($url, $data)); file_put_contents(dirname(__FILE__)."/static/authorization_code_data.txt", $authorization_code_data); //print_r($authorization_code_data); return $authorization_code_data; } //使用授权码换取公众号的授权信息第一次 public function get_authorization_code($auth_code) { $auth_code = $_REQUEST['auth_code']; $stoid =I('stoid/d',0); if ($auth_code) { $get_Access_token = $this->get_Access_token(); $url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=' . $get_Access_token; $data = array( "component_appid" => $this->appId, "authorization_code" => $auth_code ); $authorization_code_data = json_decode($this->curl_get_post($url, json_encode($data))); // $authorization_code_data = "{\"authorization_info\":{\"authorizer_appid\":\"wx4239d5a73dce686d\",\"authorizer_access_token\":\"SvokI2_mdwR6xlF74DIhYCRo-Xjwtw-dudOW5_Y8Ja36NRHec78ntKF40g9p1fQN3uZWwrleJU9GIVtpSs6cksFUSPrnkVE6zZ9-tTl35dEZhq_Hi5fA_G6Fe_tDmrkQCYCcAFDOKO\",\"expires_in\":7200,\"authorizer_refresh_token\":\"refreshtoken@@@r5ivAUcuv4OnNOcFdHEBmNw8rywurx12AByIz4o1Rgk\",\"func_info\":[{\"funcscope_category\":{\"id\":1}},{\"funcscope_category\":{\"id\":15}},{\"funcscope_category\":{\"id\":4}},{\"funcscope_category\":{\"id\":7}},{\"funcscope_category\":{\"id\":2}},{\"funcscope_category\":{\"id\":3}},{\"funcscope_category\":{\"id\":11}},{\"funcscope_category\":{\"id\":6}},{\"funcscope_category\":{\"id\":5}},{\"funcscope_category\":{\"id\":8}},{\"funcscope_category\":{\"id\":13}},{\"funcscope_category\":{\"id\":9}},{\"funcscope_category\":{\"id\":10}},{\"funcscope_category\":{\"id\":12}},{\"funcscope_category\":{\"id\":22}}]}}"; // $authorization_code_data=json_decode($authorization_code_data); $authorizer_appid = $authorization_code_data->authorization_info->authorizer_appid; $authorizer_info = $this->authorizer_info($authorizer_appid); $resdata = json_encode(array( 'authorization_data' => $authorization_code_data, 'authorizer_info_data' => $authorizer_info, 'stoid' => $stoid )); mlog($resdata, "get_authorization_code"); $res = http_post_json($this->redirect_foreign . "/Admin/Wechat/updatecall", $resdata); $res=json_encode($res); if ($res->STATE==1) { $this->redirect($this->redirect_foreign."/Admin/Wechat/call?appid=".$authorizer_appid,302); }else { $this->redirect($this->redirect_foreign . "/Admin/Wechat/wxsq", 302); } return; } else { return false; } } //获取授权方的账户信息(第一次) public function authorizer_info($authorizer_appid) { $url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=' . $this->get_Access_token(); $data = json_encode(array( 'component_appid' => $this->appId, 'authorizer_appid' => $authorizer_appid )); $authorizer_info = json_decode($this->curl_get_post($url, $data)); // $w['nick_name'] = $authorizer_info->authorizer_info->nick_name; //公众号名称 // $w['original_id'] = $authorizer_info->authorizer_info->user_name; //原始id 发送接收事件必不可少的 // $w['headpic'] = $authorizer_info->authorizer_info->qrcode_url; //公众号二维码 return $authorizer_info; //return ; } public function get_Access_token() { return getcomponent_access_token(); // $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token'; // $component_verify_ticket = file_get_contents(dirname(__FILE__)."/static/component_verify_ticket.txt");//正式 // // $data_string = '{"component_appid":"' . $this->appId . '" ,"component_appsecret": "' . $this->appSecret . '", "component_verify_ticket": "' . $component_verify_ticket . '" }'; // mlog("004000W:".$data_string,"getcomponent_access_token"); // $getAccessToken = json_decode($this->curl_get_post($url, $data_string)); // // $component_access_token = $getAccessToken->component_access_token; // $data['accessToken'] = $component_access_token; // $data['accessTokenTime'] = time() + 7100; // file_put_contents(dirname(__FILE__) . "/static/accessToken.txt", $data['accessToken']); // file_put_contents(dirname(__FILE__) . "/static/accessTokenTime.txt", $data['accessTokenTime']); // // return $component_access_token; } public function get_pre_auth_code() { // $preAuthCodeTime = file_get_contents(dirname(__FILE__)."/static/preAuthCodeTime.txt"); // if ($preAuthCodeTime > time()) { // $get_pre_auth_code = file_get_contents(dirname(__FILE__)."/static/preAuthCode.txt"); // } else { $get_Access_token = $this->get_Access_token(); $url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=$get_Access_token"; $data_string = '{"component_appid":"' . $this->appId . '"}'; $get_pre_auth_code_data = json_decode($this->curl_get_post($url, $data_string)); mlog(json_encode($get_pre_auth_code_data),"weixin"); $get_pre_auth_code = $get_pre_auth_code_data->pre_auth_code; $data['preAuthCode'] = $get_pre_auth_code; $data['preAuthCodeTime'] = time() + 1100; file_put_contents(dirname(__FILE__)."/static/preAuthCode.txt", $data['preAuthCode']); file_put_contents(dirname(__FILE__)."/static/preAuthCodeTime.txt", $data['preAuthCodeTime']); // } return $get_pre_auth_code; } public function getWXtxt($type='component_verify_ticket') { $component_verify_ticket = file_get_contents(dirname(__FILE__)."/static/".$type.".txt"); return $component_verify_ticket; } public function gettest() { // $AuthorizerAppid="wx4239d5a73dce686d"; // $resdata = json_encode(array( // 'appid' => $AuthorizerAppid, // )); // $res = http_post_json($this->redirect_foreign . "/Admin/Wechat/unauthorized", $resdata); // var_dump($res); } private function curl_get_post($url, $data = '', $request = 'GET') { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl, CURLOPT_AUTOREFERER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); curl_setopt($curl, CURLOPT_TIMEOUT, 30); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $tmpInfo = curl_exec($curl); if (curl_errno($curl)) { echo 'Errno' . curl_error($curl); } curl_close($curl); return $tmpInfo; } }