微信消息自動回覆 json版

 1 <?php  2 //芒果數據庫類庫
 3 require_once './mongo/vendor/autoload.php';  4 //調試模式
 5 define("DEBUG",true);  6 //認證
 7 if (isset($_GET['echostr'])) {  8     $nonce = $_GET['nonce'];  9     $token = "qosg123";  10     $timestamp = $_GET['timestamp'];  11     $echostr = $_GET['echostr'];  12     $signature = $_GET['signature'];  13     //造成數組,而後按字典序排序
 14     $array = array();  15     $array = array($nonce, $timestamp, $token);  16     sort($array);  17     //拼接成字符串,sha1加密 ,而後與signature進行校驗
 18     $str = sha1(implode($array));  19     if ($str == $signature && $echostr) {  20         //第一次接入weixin api接口的時候
 21         echo $echostr;  22         exit;  23  }  24 
 25 } else { //消息自動回覆  26  //接受消息
 27     $obj = file_get_contents('php://input');  28     //記錄日誌
 29     writeLog(json_encode($obj),false);  30 
 31     if ($obj) { //消息不爲空
 32         $postSql = json_decode($obj);  33 
 34         $content = empty($postSql->Content) ? '' : $postSql->Content; //內容
 35 
 36         $openid = $postSql->FromUserName; //用戶openID
 37         $MsgId = $postSql->MsgId; //消息ID
 38         if ($postSql->MsgType == 'event'){  //觸發消息 //消息類型
 39             if (!isset($postSql->SessionFrom)) exit();  40             $info = json_decode($postSql->SessionFrom,true);  41             $type = $postSql->MsgType;  42             $data = array(  43                 "touser" => $openid,
 44                 "msgtype" => "link",
 45                 "link" => array(  46                     "title" => '標題',
 47                     "description" => '內容描述',
 48                     "url" => "https://www.baidu.com",
 49                     "thumb_url" => "https://www.baidu.com/icon.png"
 50  )  51  );  52             $postData = [  53                 'user' => $info['openid'],
 54                 'qu'   => $info['serverUrl'],
 55                 'time' => $postSql->CreateTime,
 56                 'data' => json_encode($data),
 57  ];  58             $tb = dns('kefu');  59             if (!$tb->insertOne($postData)->isAcknowledged()){  60                 writeLog('存庫失敗');  61                 $tb->insertOne($postData);  62  }  63 
 64             $sendData = array(  65                 "touser" => $openid,
 66                 "msgtype" => "text",
 67                 "text" => ['content' => '回覆內容'],
 68  );  69             send($sendData);  70  }  71         elseif ($postSql->MsgType == 'text'){  72             if (isset($postSql->Content) && $postSql->Content === '1'){  73                 $tb = dns('kefu');  74                 $data = $tb->findOne(['user'=>$openid],['sort'=>['time'=>-1]]);  75                 if (empty($data) || empty($data['data'])) exit();  76                 send(json_decode($data['data'],true));  77                 if (!$tb->deleteMany(['user'=>$openid]) ) writeLog('刪除失敗');  78  }  79  }  80         echo 'success';  81     } else {  82         // CLog::writeLog('獲取token4',$token);
 83         echo "123";  84         exit;  85  }  86 
 87 }  88 
 89 /**  90  * 日誌記錄  91  * @param $ct string 要記錄的字符串  92  * @return null 無  93  */
 94 function writeLog($ct,$is = true) //是否強行記錄
 95 {  96     if (!DEBUG && !$is) return null;  97     $myfile = fopen("logs.txt", "a+");  98     if (!$myfile) return null;  99     $content = '時間:' . date("Y-m-d H:i:s") . "\r\n------------------------\r\n"; 100     $content .= $ct . "\r\n"; 101     $content .= "================================\r\n\r\n"; 102     fwrite($myfile, $content); 103     fclose($myfile); 104     return null; 105 } 106 
107 /** 108  * 獲取token 109  * @return bool|string 失敗|token 110  */
111 function access_token() 112 { 113     $appid = 'wx0000000000000000'; 114     $secret = '00000000000000000000000000000000'; 115     $tb = dns('token'); 116     $token = $tb->findOne(['_id' => 'all']); 117     if (empty($token) || $token['time'] < time()) { 118         $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret"; //獲取token地址
119         $data = httpGet($url); //發送請求
120         $t = json_decode($data, true); //解析數據
121         if (empty($t)) { 122             writeLog('獲取token失敗' . json_encode($t)); 123             return false; //沒有數據 返回請求失敗
124  } 125         $tb->updateOne(['_id' => 'all'], ['$set' => ['token' => $t['access_token'], 'time' => time() + 7000]], ['upsert' => true])->isAcknowledged(); 126         return $t['access_token']; 127  } 128     return $token['token']; 129 } 130 
131 //get請求
132 function httpGet($url) 133 { 134     return file_get_contents($url); 135 } 136 
137 //post請求
138 function httpPost($url, $data = [], $head = [], $outtime = 30) //請求地址
139 { 140     $ch = curl_init(); 141     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳過證書檢查
142     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);  // 從證書中檢查SSL加密算法是否存在
143     curl_setopt($ch, CURLOPT_URL, $url);  //設置請求地址
144     curl_setopt($ch, CURLOPT_HTTPHEADER, $head); //頭信息
145     curl_setopt($ch, CURLOPT_POST, true); //post請求
146     curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data,JSON_UNESCAPED_UNICODE)); //post請求參數 147 // curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); //post請求參數
148     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 149     curl_setopt($ch, CURLOPT_TIMEOUT, $outtime); //容許 cURL 函數執行的最長秒數
150     return curl_exec($ch); 151 } 152 //發送消息
153 function send($data){ 154     $token = access_token(); 155     if (!$token){ 156         exit('錯誤'); 157  } 158     $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$token}"; 159     $head = ["Content-type: text/html; charset=utf-8"]; 160     $result = httpPost($url, $data, $head); 161     writeLog(json_encode($result)); 162     return null; 163 } 164 //鏈接數據庫
165 function dns($tb){ 166     //鏈接數據庫
167     $dbs  = new MongoDB\Client("mongodb://127.0.0.1:27017"); 168     return $dbs->token->$tb; 169 }

 參考地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140453php

相關文章
相關標籤/搜索