|
- <?php
-
- class WeChat
- {
- private $_appid;
- private $_appsecret;
- private $_accessToken;
- public $debug = DEBUG;
- public $MsgType = 'text';
- public $msg = array();
-
- /* //QRCode类型
- const QRCODE_TYPE_TEMP=1;
- const QRCODE_TYPE_LIMIT=2;
- const QRCODE_TYPE_LIMIT_STR=3; */
- public function __construct($appid, $appsecret)
- {
-
- $this->_appid = $appid;
- $this->_appsecret = $appsecret;
- if (isset($_GET['echostr'])) {
- $this->valid();
- }
- if (ALWAYSCHECK == true) {
- $check = $this->checkSignature();
- if (!$check) {
- $this->writelog("checkSignature()--非法服务器");
- exit;
- }
- }
- $this->_accessToken = $this->getAccessToken();
- }
-
- public function getAccessToken()
- {
-
- // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
- $data = json_decode($this->get_php_file("access_token.php"));
- if ($data->expire_time < time()) {
- // 如果是企业号用以下URL获取access_token
- // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
- $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->_appid}&secret={$this->_appsecret}";
- $res = json_decode($this->_requestGet($url));
- $access_token = $res->access_token;
- $this->writelog("url获取的token:" . $access_token);
- if ($access_token) {
- $data->expire_time = time() + 3600;
- $data->access_token = $access_token;
- $this->set_php_file("access_token.php", json_encode($data));
- $this->writelog("生成access_token:" . $access_token);
- }
- } else {
- $access_token = $data->access_token;
- $this->writelog("文件中读取的token:" . $access_token);
- }
- return $access_token;
- }
-
- private function get_php_file($filename)
- {
- $dir = __DIR__ . "/../Log/";
- if (!is_dir($dir)) {
- mkdir($dir);
- }
- $token_file = $dir . $filename;
- return trim(substr(file_get_contents($token_file), 15));
- }
-
- private function set_php_file($filename, $content)
- {
- $dir = __DIR__ . "/../Log/";
- if (!is_dir($dir)) {
- mkdir($dir);
- }
- $token_file = $dir . $filename;
- $fp = fopen($token_file, "w");
- fwrite($fp, "<?php exit();?>" . $content);
- fclose($fp);
- }
-
- private function _requestGet($url, $ssl = true)
- {
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_URL, $url);
- /* $user_agent=isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'';
- curl_setopt($curl, CURLOPT_USERAGENT, $user_agent); */
- curl_setopt($curl, CURLOPT_AUTOREFERER, true);
- if ($ssl) {
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
- }
- curl_setopt($curl, CURLOPT_HEADER, false);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- $response = curl_exec($curl);
- if ($response === false) {
- $this->writelog('_requestGet()--返回值错误');
- return false;
- }
- return $response;
- }
-
- private function _requestPost($url, $data, $ssl = true)
- {
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_URL, $url);
- $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
- curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);
- curl_setopt($curl, CURLOPT_AUTOREFERER, true);
- if ($ssl) {
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
- }
- curl_setopt($curl, CURLOPT_POST, true);
- curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
- curl_setopt($curl, CURLOPT_HEADER, false);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- $response = curl_exec($curl);
- if ($response === false) {
- $this->writelog('_requestPost()--返回值错误');
- return false;
- }
- //$error=json_decode($response,true);
- $this->writelog("url:" . $url);
- $this->writelog("curl返回值为" . $response);
-
- return $response;
- }
-
- public function valid()
- {
- $echoStr = $_GET["echostr"];
- //valid signature , option
- if ($this->checkSignature()) {
- $this->writelog("valid()--第一次验证成功");
- echo $echoStr;
- exit;
- } else {
- $this->writelog("valid()--第一次验证,非法服务器");
- exit();
- }
- }
-
- private function checkSignature()
- {
- // you must define TOKEN by yourself
- if (!defined("TOKEN")) {
- throw new Exception('TOKEN is not defined!');
- }
-
- $signature = isset($_GET["signature"]) ? $_GET["signature"] : "";
- $timestamp = isset($_GET["timestamp"]) ? $_GET["timestamp"] : "";
- $nonce = isset($_GET["nonce"]) ? $_GET["nonce"] : "";
-
- $token = TOKEN;
- $tmpArr = array($token, $timestamp, $nonce);
- // use SORT_STRING rule
- sort($tmpArr, SORT_STRING);
- $tmpStr = implode($tmpArr);
- $tmpStr = sha1($tmpStr);
-
- if ($tmpStr == $signature) {
- return true;
- } else {
- return false;
- }
- }
-
- private function writelog($activation)
- {
- $dir = "./Log";
- if (!is_dir($dir)) {
- mkdir($dir);
- }
- $filename = date("Y-m-d") . ".txt";
- $open = fopen($dir . "/" . $filename, "a");
- fwrite($open, date("Y-m-d H:i:s") . "\t" . $activation . "\r\n");
- fclose($open);
- }
-
- //获取消息
- public function responseMsg()
- {
- //get post data, May be due to the different environments
- //$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
- $postStr = file_get_contents("php://input");
-
- if ($this->debug) {
- $this->writelog("function:responseMsg--接收到的消息为--" . $postStr);
- }
- //extract post data
- if (!empty($postStr)) {
- /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
- the best way is to check the validity of xml by yourself */
- libxml_disable_entity_loader(true);
- $this->msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
- foreach ($this->msg as $key => $v) {
- $this->writelog("function:responseMsg--接收到的消息为--" . $key);
- $this->writelog("function:responseMsg--接收到的消息为--" . $v);
- }
- $this->MsgType = strtolower($this->msg['MsgType']);
- return $this->msg;
- } else {
- $this->writelog("消息为空");
- return false;
- }
- }
-
- public function eventMsg($array)
- {
- $result = "";
- $this->writelog("eventMsg array:" . json_encode($array));
- switch ($array['Event']) {
- case 'subscribe':
- $from_qrcode_id = 0;
- if (!empty($array['EventKey'])) {
- $from_qrcode_txt = substr($array['EventKey'], 8);
- $from_qrcode_id = (int)$from_qrcode_txt;
- }
- $pdo = conn();
- //$sql_update = " INSERT INTO wechat_user(`OPENID`,`IS_REGISTER`) values('{$array['FromUserName']}',1) ON DUPLICATE KEY UPDATE IS_REGISTER = 1 ";
- $sql_update = " INSERT INTO wechat_user(`OPENID`,`IS_REGISTER`,`FROM_QRCODE_ID`) values('{$array['FromUserName']}',1,{$from_qrcode_id}) ON DUPLICATE KEY UPDATE IS_REGISTER = 1,FROM_QRCODE_ID={$from_qrcode_id} ";
- $selectDate = $pdo->exec($sql_update);
- /*
- $contentStr="Hi,『蜘蛛出行』每天为无数乘客提供便捷的交通出行服务,快来尝试一下吧!
- 如果您已经预订了车票,请按以下格式回复“#订单号#预定时预留的手机号”进行订单绑定。
- 绑定后可在『更多服务』—『行程』中查看巴士定位、车牌号码和司机电话等信息。
- (#号需输入,不可跳过,订单号请查找蜘蛛出行为您发送的手机短信)";
- $textTpl="
- <xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[%s]]></MsgType>
- <Content><![CDATA[%s]]></Content>
- </xml>";
- $msgType="text";
- $result= sprintf($textTpl, $array['FromUserName'], $array['ToUserName'], time(), $msgType, $contentStr);
- return $result;
- */
-
- $data_media_id = '{"media_id":"AuXDjP791-NMcyJajUxBL0jmNmYMjTJ6fTQTEQV8Gh8"}';
- $url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" . $this->_accessToken;
- $response = $this->_requestPost($url, $data_media_id);
- $this->writelog("返回--" . $response);
- $media = json_decode($response, true);
- $mediaArray = $media['news_item'];
- $content = array();
- foreach ($mediaArray as $k => $v) {
- if ($k == 0 || $k == 1)
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['url']);
- elseif ($k == 2) {
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
- } else
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
- }
- $this->writelog("返回--" . json_encode($content));
- if (is_array($content)) {
- if (isset($content[0]['PicUrl'])) {
- $result = $this->transmitNews($array, $content);
- $this->writelog(json_encode($result));
- return $result;
- }
- }
- if (!empty($array['EventKey'])) {
- /*
- $id=substr($array['EventKey'],strpos($array['EventKey'],"qrscene_")+8);
- $openid=$array['FromUserName'];
- $time=date("Y-m-d H:i:s");
- $pdo = new PDO("sqlsrv:Server=".HOST.";Database=".DB, USER, PASSWORD);//5.6版本pdo连接sqlsrv
- $sql="SELECT id FROM qrcodeDetail WHERE qrcodeId=".$id." AND openId='".$openid."'";
- $selectDate=$pdo->query($sql);
- $selectRes=$selectDate->fetchAll(PDO::FETCH_ASSOC);
- if (empty($selectRes)){
- $sql1="INSERT INTO qrcodeDetail values($id,'$openid','subscribe','$time')";
- $this->writelog("eventMsg function : subscribe:result id=".$id."--sql1-".$sql1);
- $result=$pdo->exec($sql1);
- }
-
- $sql2="SELECT media_id,url FROM qrcode WHERE id=".$id;
- $selectDate2=$pdo->query($sql2);
- $selectRes2=$selectDate2->fetchAll(PDO::FETCH_ASSOC);
- if (!empty($selectRes2)){
- $media_id= $selectRes2[0]['media_id'];
- $Rurl= $selectRes2[0]['url'];
- }else {
- //$media_id="AuXDjP791-NMcyJajUxBLzhsCmTK5evvwTjASqBwmv8";
- $media_id="AuXDjP791-NMcyJajUxBL5N9VCy5YnysR-dDWT2XFWg";
- $Rurl="http://wx.zhizhuchuxing.com/bookingHomePage/mdidiDetail.html?prod_code=NSPTSM01";
- }*/
-
-
- $media_id = "AuXDjP791-NMcyJajUxBL0jmNmYMjTJ6fTQTEQV8Gh8";
- $data = '{"media_id":"' . $media_id . '"}';
- $url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" . $this->_accessToken;
- $response = $this->_requestPost($url, $data);
- $this->writelog("返回--" . $response);
- $media = json_decode($response, true);
-
- $mediaArray = $media['news_item'];
- $content = array();
- foreach ($mediaArray as $k => $v) {
- if ($k == 0 || $k == 1)
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['url']);
- else
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
- }
- $this->writelog("返回--" . json_encode($content));
- if (is_array($content)) {
- if (isset($content[0]['PicUrl'])) {
- $result = $this->transmitNews($array, $content);
- return $result;
- }
- }
- } else {
-
- //$data='{"media_id":"AuXDjP791-NMcyJajUxBLw7rLLVx_s0V9I0l_sS92c0"}';
- /* $data='{"media_id":"AuXDjP791-NMcyJajUxBL5N9VCy5YnysR-dDWT2XFWg"}';
- $url="https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=".$this->_accessToken;
- $response=$this->_requestPost($url, $data);
- $this->writelog("返回--".$response);
- $media=json_decode($response,true);
- $mediaArray=$media['news_item'];
- $content = array();
- foreach ($mediaArray as $k=>$v){
- if ($k==0 || $k==1)
- $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['url']);
- else
- $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['content_source_url']);
- }
- $this->writelog("返回--".json_encode($content));
- if(is_array($content)){
- if (isset($content[0]['PicUrl'])){
- $result = $this->transmitNews($array, $content);
- }
- } */
-
- $data_media_id = '{"media_id":"AuXDjP791-NMcyJajUxBL0jmNmYMjTJ6fTQTEQV8Gh8"}';
- $url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" . $this->_accessToken;
- $response = $this->_requestPost($url, $data_media_id);
- $this->writelog("返回--" . $response);
- $media = json_decode($response, true);
- $mediaArray = $media['news_item'];
- $content = array();
- foreach ($mediaArray as $k => $v) {
- if ($k == 0 || $k == 1)
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['url']);
- elseif ($k == 2) {
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
- } else
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
- }
- $this->writelog("返回--" . json_encode($content));
- if (is_array($content)) {
- if (isset($content[0]['PicUrl'])) {
- $result = $this->transmitNews($array, $content);
- $this->writelog(json_encode($result));
- return $result;
- }
- }
-
- }
-
- break;
- case 'SCAN':
- if (isset($array['EventKey'])) {
- /*
- $pdo = new PDO("sqlsrv:Server=".HOST.";Database=".DB, USER, PASSWORD);//5.6版本pdo连接sqlsrv
- $id=$array['EventKey'];
- $openid=$array['FromUserName'];
- $time=date("Y-m-d H:i:s");
- $sql="SELECT id FROM qrcodeDetail WHERE qrcodeId=".$id." AND openId='".$openid."'";
- $selectDate=$pdo->query($sql);
- $selectRes=$selectDate->fetchAll(PDO::FETCH_ASSOC);
- if (empty($selectRes)){
- $sql1="INSERT INTO qrcodeDetail values($id,'$openid','SCAN','$time')";
- $this->writelog("eventMsg function : SCAN:result id=".$id."--sql1-".$sql1);
- $result=$pdo->exec($sql1);
- }*/
-
- /* $this->writelog("eventMsg function : SCAN:result id=".$id."---".json_encode($result));
- $errinfo=$pdo->errorInfo();
- if ($errinfo[0] !='00000')
- $this->writelog("eventMsg function : SCAN:error id=".$id."---".$errinfo[2]);
- else{
- $res=$result->fetchAll(PDO::FETCH_ASSOC);
- $this->writelog("eventMsg function : SCAN:res id=".$id."---".json_encode($res));
- $headUrl=$res[0]['url'];
- $this->writelog("eventMsg function : SCAN:headUrl id=".$id."---".$headUrl);
-
- header("Location: $headUrl");exit;
- } */
- // $data='{"media_id":"AuXDjP791-NMcyJajUxBLw7rLLVx_s0V9I0l_sS92c0"}';
- /*
- $sql2="SELECT media_id,url FROM qrcode WHERE id=".$id;
- $selectDate2=$pdo->query($sql2);
- $selectRes2=$selectDate2->fetchAll(PDO::FETCH_ASSOC);
- if (!empty($selectRes2)){
- $media_id= $selectRes2[0]['media_id'];
- $Rurl= $selectRes2[0]['url'];
- }else {
- //$media_id="AuXDjP791-NMcyJajUxBLzhsCmTK5evvwTjASqBwmv8";
- $media_id="AuXDjP791-NMcyJajUxBL5N9VCy5YnysR-dDWT2XFWg";
- $Rurl="http://wx.zhizhuchuxing.com/bookingHomePage/mdidiDetail.html?prod_code=NSPTSM01";
- }*/
-
- /*
- $pdo=conn();
- $sql_update = " INSERT INTO wechat_user(`OPENID`,`IS_REGISTER`) values('{$array['FromUserName']}',1) ON DUPLICATE KEY UPDATE IS_REGISTER = 1 ";
- $selectDate = $pdo->exec($sql_update);
-
- $contentStr="Hi,『蜘蛛出行』每天为无数乘客提供便捷的交通出行服务,快来尝试一下吧!
- 如果您已经预订了车票,请按以下格式回复“#订单号#预定时预留的手机号”进行订单绑定。
- 绑定后可在『更多服务』—『行程』中查看巴士定位、车牌号码和司机电话等信息。
- (#号需输入,不可跳过,订单号请查找蜘蛛出行为您发送的手机短信)";
- $textTpl="
- <xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[%s]]></MsgType>
- <Content><![CDATA[%s]]></Content>
- </xml>";
- $msgType="text";
- $result= sprintf($textTpl, $array['FromUserName'], $array['ToUserName'], time(), $msgType, $contentStr);
- return $result;
- */
- $from_qrcode_id = 0;
- if (!empty($array['EventKey'])) {
- $from_qrcode_txt = substr($array['EventKey'], 8);
- $from_qrcode_id = (int)$from_qrcode_txt;
- }
- $this->writelog("SCAN CODE:" . json_encode($array));
- $pdo = conn();
- $sql_update = " INSERT INTO wechat_user(`OPENID`,`IS_REGISTER`,`FROM_QRCODE_ID`) values('{$array['FromUserName']}',1,{$from_qrcode_id}) ON DUPLICATE KEY UPDATE IS_REGISTER = 1,FROM_QRCODE_ID={$from_qrcode_id} ";
- $selectDate = $pdo->exec($sql_update);
- if ($from_qrcode_id != 0) {
- //发送微信红包
- $this->sendWxRedPack($array['FromUserName']);
- }
- $data_media_id = '{"media_id":"AuXDjP791-NMcyJajUxBL0jmNmYMjTJ6fTQTEQV8Gh8"}';
- $url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" . $this->_accessToken;
- $response = $this->_requestPost($url, $data_media_id);
- $this->writelog("返回--" . $response);
- $media = json_decode($response, true);
- $mediaArray = $media['news_item'];
- $content = array();
- foreach ($mediaArray as $k => $v) {
- if ($k == 0 || $k == 1)
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['url']);
- elseif ($k == 2) {
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
- } else
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
- }
- $this->writelog("返回--" . json_encode($content));
- if (is_array($content)) {
- if (isset($content[0]['PicUrl'])) {
- $result = $this->transmitNews($array, $content);
- $this->writelog(json_encode($result));
- return $result;
- }
- }
-
- /*
- $data='{"media_id":"'.$media_id.'"}';
- $url="https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=".$this->_accessToken;
- $response=$this->_requestPost($url, $data);
- $this->writelog("返回--".$response);
- $media=json_decode($response,true);
- $mediaArray=$media['news_item'];
- $content = array();
- foreach ($mediaArray as $k=>$v){
- if ($k==0 || $k==1)
- $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['url']);
- elseif($k==2){
- $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['content_source_url']);
- }
- else
- $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['content_source_url']);
- }
- $this->writelog("返回--".json_encode($content));
- if(is_array($content)){
- if (isset($content[0]['PicUrl'])){
- $result = $this->transmitNews($array, $content);
- }
- }*/
- }
- break;
- case 'CLICK':
- $pdo = conn();
- $contantConfig = require dirname(dirname(__DIR__)) . '/config/moduleConfig/module/site.contants.config.php';
- $sql_update = " INSERT INTO wechat_user(`OPENID`,`IS_REGISTER`,`from_source`) values('{$array['FromUserName']}',1,{$contantConfig['org_id']}) ON DUPLICATE KEY UPDATE IS_REGISTER = 1 ";
- $selectDate = $pdo->exec($sql_update);
- /*
- $contentStr="Hi,『蜘蛛出行』每天为无数乘客提供便捷的交通出行服务,快来尝试一下吧!
- 如果您已经预订了车票,请按以下格式回复“#订单号#预定时预留的手机号”进行订单绑定。
- 绑定后可在『更多服务』—『行程』中查看巴士定位、车牌号码和司机电话等信息。
- (#号需输入,不可跳过,订单号请查找蜘蛛出行为您发送的手机短信)";
- $textTpl="
- <xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[%s]]></MsgType>
- <Content><![CDATA[%s]]></Content>
- </xml>";
- $msgType="text";
- $result= sprintf($textTpl, $array['FromUserName'], $array['ToUserName'], time(), $msgType, $contentStr);
- return $result;
- */
- if (isset($array['EventKey']) && $array['EventKey'] == 'Push-Photo-List') {
-
- $data = '{"media_id":"AuXDjP791-NMcyJajUxBL0jmNmYMjTJ6fTQTEQV8Gh8"}';
- $url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" . $this->_accessToken;
- $response = $this->_requestPost($url, $data);
- $this->writelog("CLICK返回response--" . $response);
- $media = json_decode($response, true);
- $mediaArray = $media['news_item'];
- $content = array();
- foreach ($mediaArray as $k => $v) {
- if ($k == 0 || $k == 1)
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['url']);
- else
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
- }
- $this->writelog("CLICK返回content--" . json_encode($content));
- if (is_array($content)) {
- if (isset($content[0]['PicUrl'])) {
- $result = $this->transmitNews($array, $content);
- }
- }
- } elseif (isset($array['EventKey']) && $array['EventKey'] == 'MSG_LIANXIKEFU') {
- $textTpl = '' . "
- <xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[transfer_customer_service]]></MsgType>
- </xml>";
- $result = sprintf($textTpl, $array['FromUserName'], $array['ToUserName'], time());
- }
-
- }
- /*
- $data='{"type":"news","offset":0,"count":20}';
- $url="https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=".$this->_accessToken;
- $response=$this->_requestPost($url, $data);
- $this->writelog("返回--".$response); */
- $this->writelog("回复用户event--" . json_encode($result));
- return $result;
-
- }
-
- /**
- * Function Description:发送微信红包
- * Function Name: sendWxRedPack
- * @param $openId
- *
- * @return bool
- *
- * @author 倪宗锋
- */
- public function sendWxRedPack($openId)
- {
- $path = dirname(dirname(__DIR__));
- $config = require $path . "/config/wxpay.config.php";
- //准备数据
- $params = array(
- 'openid' => $openId,
- 'act_id' => 1
- );
- $params['sign'] = $this->getSign($params, $config['key']);//安全机制 秘钥签名
- $url = 'http://' . $_SERVER['HTTP_HOST'] . '/module/activity/redpack/sendRedPack?';
- $url .= http_build_query($params);
- //调用接口
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_AUTOREFERER, true);
- curl_setopt($curl, CURLOPT_POST, true);
- curl_setopt($curl, CURLOPT_POSTFIELDS, array());
- curl_setopt($curl, CURLOPT_HEADER, false);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- //1秒超时 不等待
- curl_setopt($curl, CURLOPT_TIMEOUT, 1);
- curl_exec($curl);
- return true;
- }
-
- /**
- * Function Description:获取签名
- * Function Name: getSign
- * @param $params
- * @param $key string 配置类型
- *
- * @return string
- *
- * @author 倪宗锋
- */
- public static function getSign($params, $key)
- {
- if (isset($params['sign'])) {
- unset($params['sign']);
- }
- //签名步骤一:按字典序排序参数
- ksort($params);
- $string = self::ToUrlParams($params);
- //签名步骤二:在string后加入KEY
- $string = $string . "&key=" . $key;
- //签名步骤三:MD5加密
- $string = md5($string);
- //签名步骤四:所有字符转为大写
- $result = strtoupper($string);
- return $result;
-
- }
-
- /**
- * Function Description:格式化参数 格式化成url参数
- * Function Name: ToUrlParams
- * @param $params
- *
- * @return string
- *
- * @author 倪宗锋
- */
- public static function ToUrlParams($params)
- {
- $buff = "";
- foreach ($params as $k => $v) {
- if ($k != "sign" && $v != "" && !is_array($v)) {
- $buff .= $k . "=" . $v . "&";
- }
- }
- $buff = trim($buff, "&");
- return $buff;
- }
-
- //把openid存入数据库
- public function insertOpenid($data, $type)
- {
- $openid = $data['FromUserName'];
- if ($type == 'subscribe') {
- $sql = "insert into wx_user(openid) values('{$openid}')";
- } else if ($type == 'unsubscribe') {
- $sql = "delete from wx_user where openid='{$openid}'";
- }
- $result = '';
- try {
- $pdo = new PDO("sqlsrv:Server=" . HOST . ";Database=" . DB, USER, PASSWORD);//5.6版本pdo连接sqlsrv
- //$pdo=new PDO("mysql:host=".HOST.";dbname=".DB,USER,PASSWORD); //7.0版本pdo连接mysql
- $result = $pdo->exec($sql);
- $errinfo = $pdo->errorInfo();
- if ($errinfo[0] != '00000')
- $this->writelog($errinfo[2]);
- } catch (PDOException $e) {
- $this->writelog($e->getMessage());
- }
- if ($result) {
- return true;
- } else {
- return false;
- }
- }
-
- //有用户关注的时候推送多图文消息
- private function transmitNews($array, $newsArray)
- {
- if (!is_array($newsArray)) {
- return;
- }
- $itemTpl = "<item>
- <Title><![CDATA[%s]]></Title>
- <Description><![CDATA[%s]]></Description>
- <PicUrl><![CDATA[%s]]></PicUrl>
- <Url><![CDATA[%s]]></Url>
- </item>";
- $item_str = "";
- foreach ($newsArray as $item) {
- $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
- }
- $xmlTpl = "<xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[news]]></MsgType>
- <ArticleCount>%s</ArticleCount>
- <Articles>
- $item_str</Articles>
- </xml>";
-
- $result = sprintf($xmlTpl, $array['FromUserName'], $array['ToUserName'], time(), count($newsArray));
- return $result;
- }
-
- private function transmitImage($array)
- {
- $xmlTpl = "<xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[image]]></MsgType>
- <Image>
- <MediaId><![CDATA[%s]]></MediaId>
- </Image>
- </xml>";
- $result = sprintf($xmlTpl, $array['FromUserName'], $array['ToUserName'], time(), $array['media_id']);
- return $result;
- }
-
- private function transmitVoice($array)
- {
- $xmlTpl = "<xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[voice]]></MsgType>
- <Image>
- <MediaId><![CDATA[%s]]></MediaId>
- </Image>
- </xml>";
- $result = sprintf($xmlTpl, $array['FromUserName'], $array['ToUserName'], time(), $array['media_id']);
- return $result;
- }
-
- private function transmitVideo($array)
- {
- $xmlTpl = "<xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[video]]></MsgType>
- <Video>
- <MediaId><![CDATA[%s]]></MediaId>
- <Title><![CDATA[%s]]></Title>
- <Description><![CDATA[%s]]></Description>
- </Video>
- </xml>";
- $result = sprintf($xmlTpl, $array['FromUserName'], $array['ToUserName'], time(), $array['media_id'], $array["title"], $array["description"]);
- return $result;
- }
-
- //获取文本
- public function textMsg($data)
- {
-
- $Content = trim($data['Content']);
- $textTpl = "
- <xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[%s]]></MsgType>
- <Content><![CDATA[%s]]></Content>
- </xml>";
- $msgType = "text";
- $word = $data['Content'];
-
- if ($word == '寻路') {
- $this->writelog("textMsg有调用:关键字是面试");
- $data_media_id = '{"media_id":"AuXDjP791-NMcyJajUxBL8LcnGB8gKQTImk6XJK53uU"}';
- $url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" . $this->_accessToken;
- $response = $this->_requestPost($url, $data_media_id);
- $this->writelog("返回--" . $response);
- $media = json_decode($response, true);
- $mediaArray = $media['news_item'];
- $content = array();
- foreach ($mediaArray as $k => $v) {
- if ($k == 0 || $k == 1)
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['url']);
- elseif ($k == 2) {
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
- } else
- $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
- }
- $this->writelog("返回--" . json_encode($content));
- if (is_array($content)) {
- if (isset($content[0]['PicUrl'])) {
- $result = $this->transmitNews($data, $content);
- $this->writelog(json_encode($result));
- return $result;
- }
- }
- } else if ($word == '活动') {
- $data["media_id"] = "AuXDjP791-NMcyJajUxBL2MpGN_djcS5OUH-Y5njOMA";
- $result = $this->transmitImage($data);
- $this->writelog(json_encode($result));
- return $result;
- } else if ($word == '测试定制巴士') {
- $contentStr = "http://wx.zhizhuchuxing.com/ZZDZ/dzbs_login.php";
- $resultStr = sprintf($textTpl, $data['FromUserName'], $data['ToUserName'], time(), $msgType, $contentStr);
- return $resultStr;
- } else if ($word == '订单绑定' || $word == '绑定订单' || $word == '绑定' || $word == '绑订单') {
- $contentStr = "Hi,『蜘蛛出行』每天为无数乘客提供便捷的交通出行服务,快来尝试我们为您准备的新功能吧!
- 如果您已经预订了车票,请按以下格式回复“#订单号#预定时预留的手机号”进行订单绑定,绑定后可在『更多服务』—『行程』中查看巴士定位、车牌号码和司机电话等信息。
- (#号需输入,不可跳过,订单号请查找蜘蛛出行为您发送的手机短信)
- 如果您还没有预订车票,请戳左下角『出行预订』!";
- $resultStr = sprintf($textTpl, $data['FromUserName'], $data['ToUserName'], time(), $msgType, $contentStr);
- $this->writelog($resultStr);
- return $resultStr;
- } else if (substr($word, 0, 1) == '#') {
- $word = substr($word, 1);
- $wordArr = explode("#", $word);
- if (count($wordArr) != 2 || $wordArr[0] == '' || $wordArr[1] == '') {
- $contentStr = "输入格式错误";
- } else if (!is_numeric($wordArr[0]) || !is_numeric($wordArr[1])) {
- $contentStr = "订单号和手机号必须整数";
- } else {
- $pdo = conn();
- $sql = "CALL DRIVER_WEICHAT_BOND(" . $wordArr[0] . "," . $wordArr[1] . ",'" . $data['FromUserName'] . "')";
- $this->writelog("订单绑定" . $sql);
- $result = $pdo->query($sql);
- $rowset = $result->fetchAll(PDO::FETCH_ASSOC);
- $result->closeCursor();
- $update_sql = "UPDATE order_main SET MEMBER_ID = (SELECT id FROM wechat_user WHERE OPENID = '{$data['FromUserName']}' ) WHERE order_id = {$wordArr[0]} OR parent_order_id = {$wordArr[0]}";
- $pdo_update = conn();
- $pdo_update->exec($update_sql);
- if ($rowset[0]['code'] == 0) {
- $contentStr = "绑定成功";
- } else {
- $contentStr = $rowset[0]['info'];
- }
-
- }
- $resultStr = sprintf($textTpl, $data['FromUserName'], $data['ToUserName'], time(), $msgType, $contentStr);
- $this->writelog($resultStr);
- return $resultStr;
-
-
- } /*else{
- $contentStr="Hi,『蜘蛛出行』每天为无数乘客提供便捷的交通出行服务,快来尝试我们为您准备的新功能吧!
- 如果您已经预订了车票,请按以下格式回复“#订单号#预定时预留的手机号”进行订单绑定,绑定后可在『更多服务』—『行程』中查看巴士定位、车牌号码和司机电话等信息。
- (#号需输入,不可跳过,订单号请查找蜘蛛出行为您发送的手机短信)
- 如果您还没有预订车票,请戳左下角『出行预订』!";
- $resultStr = sprintf($textTpl, $data['FromUserName'], $data['ToUserName'], time(), $msgType, $contentStr);
- return $resultStr;
- }*/
-
-
- //$contentStr=$this->simsimiHttp($Content);
- else {
- $textTpl = '' . "
- <xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[transfer_customer_service]]></MsgType>
- </xml>";
- $resultStr = sprintf($textTpl, $data['FromUserName'], $data['ToUserName'], time());
- return $resultStr;
- }
-
- }
-
- private function simsimiHttp($msg)
- {
- $url = "http://www.xiaodoubi.com/simsimiapi.php?msg=" . $msg;
- $res = file_get_contents($url);
- file_put_contents("./demo.txt", date("Y-m-d H:i:s") . " " . $res . PHP_EOL, FILE_APPEND);
- if (strpos($res, "xiaodouqqcom") !== false) {
- $res = "无法回答,请不要发一下奇怪的问题或字符😒";
- }
- if (strpos($msg, "主人") !== false) {
- $res = "我的主人就是你呀";
- }
- return $res;
- }
-
- private function checkAccessToken($check)
- {
- if (isset($check['errcode']) && $check['errcode'] == 40001) {
- $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->_appid}&secret={$this->_appsecret}";
- $result = $this->_requestGet($url);
- if (!$result) {
- $this->writelog("获取token出错");
- return false;
- }
- $result_obj = json_decode($result);
-
- file_put_contents($token_file, $result_obj->access_token);
- $this->writelog("url获取的token:" . $result_obj->access_token);
- return $result_obj->access_token;
- }
- }
- }
-
- ?>
|