No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

886 líneas
40 KiB

  1. <?php
  2. class WeChat
  3. {
  4. private $_appid;
  5. private $_appsecret;
  6. private $_accessToken;
  7. public $debug = DEBUG;
  8. public $MsgType = 'text';
  9. public $msg = array();
  10. /* //QRCode类型
  11. const QRCODE_TYPE_TEMP=1;
  12. const QRCODE_TYPE_LIMIT=2;
  13. const QRCODE_TYPE_LIMIT_STR=3; */
  14. public function __construct($appid, $appsecret)
  15. {
  16. $this->_appid = $appid;
  17. $this->_appsecret = $appsecret;
  18. if (isset($_GET['echostr'])) {
  19. $this->valid();
  20. }
  21. if (ALWAYSCHECK == true) {
  22. $check = $this->checkSignature();
  23. if (!$check) {
  24. $this->writelog("checkSignature()--非法服务器");
  25. exit;
  26. }
  27. }
  28. $this->_accessToken = $this->getAccessToken();
  29. }
  30. public function getAccessToken()
  31. {
  32. // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
  33. $data = json_decode($this->get_php_file("access_token.php"));
  34. if ($data->expire_time < time()) {
  35. // 如果是企业号用以下URL获取access_token
  36. // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
  37. $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->_appid}&secret={$this->_appsecret}";
  38. $res = json_decode($this->_requestGet($url));
  39. $access_token = $res->access_token;
  40. $this->writelog("url获取的token:" . $access_token);
  41. if ($access_token) {
  42. $data->expire_time = time() + 3600;
  43. $data->access_token = $access_token;
  44. $this->set_php_file("access_token.php", json_encode($data));
  45. $this->writelog("生成access_token:" . $access_token);
  46. }
  47. } else {
  48. $access_token = $data->access_token;
  49. $this->writelog("文件中读取的token:" . $access_token);
  50. }
  51. return $access_token;
  52. }
  53. private function get_php_file($filename)
  54. {
  55. $dir = __DIR__ . "/../Log/";
  56. if (!is_dir($dir)) {
  57. mkdir($dir);
  58. }
  59. $token_file = $dir . $filename;
  60. return trim(substr(file_get_contents($token_file), 15));
  61. }
  62. private function set_php_file($filename, $content)
  63. {
  64. $dir = __DIR__ . "/../Log/";
  65. if (!is_dir($dir)) {
  66. mkdir($dir);
  67. }
  68. $token_file = $dir . $filename;
  69. $fp = fopen($token_file, "w");
  70. fwrite($fp, "<?php exit();?>" . $content);
  71. fclose($fp);
  72. }
  73. private function _requestGet($url, $ssl = true)
  74. {
  75. $curl = curl_init();
  76. curl_setopt($curl, CURLOPT_URL, $url);
  77. /* $user_agent=isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'';
  78. curl_setopt($curl, CURLOPT_USERAGENT, $user_agent); */
  79. curl_setopt($curl, CURLOPT_AUTOREFERER, true);
  80. if ($ssl) {
  81. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  82. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
  83. }
  84. curl_setopt($curl, CURLOPT_HEADER, false);
  85. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  86. $response = curl_exec($curl);
  87. if ($response === false) {
  88. $this->writelog('_requestGet()--返回值错误');
  89. return false;
  90. }
  91. return $response;
  92. }
  93. private function _requestPost($url, $data, $ssl = true)
  94. {
  95. $curl = curl_init();
  96. curl_setopt($curl, CURLOPT_URL, $url);
  97. $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
  98. curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);
  99. curl_setopt($curl, CURLOPT_AUTOREFERER, true);
  100. if ($ssl) {
  101. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  102. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
  103. }
  104. curl_setopt($curl, CURLOPT_POST, true);
  105. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  106. curl_setopt($curl, CURLOPT_HEADER, false);
  107. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  108. $response = curl_exec($curl);
  109. if ($response === false) {
  110. $this->writelog('_requestPost()--返回值错误');
  111. return false;
  112. }
  113. //$error=json_decode($response,true);
  114. $this->writelog("url:" . $url);
  115. $this->writelog("curl返回值为" . $response);
  116. return $response;
  117. }
  118. public function valid()
  119. {
  120. $echoStr = $_GET["echostr"];
  121. //valid signature , option
  122. if ($this->checkSignature()) {
  123. $this->writelog("valid()--第一次验证成功");
  124. echo $echoStr;
  125. exit;
  126. } else {
  127. $this->writelog("valid()--第一次验证,非法服务器");
  128. exit();
  129. }
  130. }
  131. private function checkSignature()
  132. {
  133. // you must define TOKEN by yourself
  134. if (!defined("TOKEN")) {
  135. throw new Exception('TOKEN is not defined!');
  136. }
  137. $signature = isset($_GET["signature"]) ? $_GET["signature"] : "";
  138. $timestamp = isset($_GET["timestamp"]) ? $_GET["timestamp"] : "";
  139. $nonce = isset($_GET["nonce"]) ? $_GET["nonce"] : "";
  140. $token = TOKEN;
  141. $tmpArr = array($token, $timestamp, $nonce);
  142. // use SORT_STRING rule
  143. sort($tmpArr, SORT_STRING);
  144. $tmpStr = implode($tmpArr);
  145. $tmpStr = sha1($tmpStr);
  146. if ($tmpStr == $signature) {
  147. return true;
  148. } else {
  149. return false;
  150. }
  151. }
  152. private function writelog($activation)
  153. {
  154. $dir = "./Log";
  155. if (!is_dir($dir)) {
  156. mkdir($dir);
  157. }
  158. $filename = date("Y-m-d") . ".txt";
  159. $open = fopen($dir . "/" . $filename, "a");
  160. fwrite($open, date("Y-m-d H:i:s") . "\t" . $activation . "\r\n");
  161. fclose($open);
  162. }
  163. //获取消息
  164. public function responseMsg()
  165. {
  166. //get post data, May be due to the different environments
  167. //$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
  168. $postStr = file_get_contents("php://input");
  169. if ($this->debug) {
  170. $this->writelog("function:responseMsg--接收到的消息为--" . $postStr);
  171. }
  172. //extract post data
  173. if (!empty($postStr)) {
  174. /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
  175. the best way is to check the validity of xml by yourself */
  176. libxml_disable_entity_loader(true);
  177. $this->msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  178. foreach ($this->msg as $key => $v) {
  179. $this->writelog("function:responseMsg--接收到的消息为--" . $key);
  180. $this->writelog("function:responseMsg--接收到的消息为--" . $v);
  181. }
  182. $this->MsgType = strtolower($this->msg['MsgType']);
  183. return $this->msg;
  184. } else {
  185. $this->writelog("消息为空");
  186. return false;
  187. }
  188. }
  189. public function eventMsg($array)
  190. {
  191. $result = "";
  192. $this->writelog("eventMsg array:" . json_encode($array));
  193. switch ($array['Event']) {
  194. case 'subscribe':
  195. $from_qrcode_id = 0;
  196. if (!empty($array['EventKey'])) {
  197. $from_qrcode_txt = substr($array['EventKey'], 8);
  198. $from_qrcode_id = (int)$from_qrcode_txt;
  199. }
  200. $pdo = conn();
  201. //$sql_update = " INSERT INTO wechat_user(`OPENID`,`IS_REGISTER`) values('{$array['FromUserName']}',1) ON DUPLICATE KEY UPDATE IS_REGISTER = 1 ";
  202. $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} ";
  203. $selectDate = $pdo->exec($sql_update);
  204. /*
  205. $contentStr="Hi,『蜘蛛出行』每天为无数乘客提供便捷的交通出行服务,快来尝试一下吧!
  206. 如果您已经预订了车票,请按以下格式回复“#订单号#预定时预留的手机号”进行订单绑定。
  207. 绑定后可在『更多服务』—『行程』中查看巴士定位、车牌号码和司机电话等信息。
  208. (#号需输入,不可跳过,订单号请查找蜘蛛出行为您发送的手机短信)";
  209. $textTpl="
  210. <xml>
  211. <ToUserName><![CDATA[%s]]></ToUserName>
  212. <FromUserName><![CDATA[%s]]></FromUserName>
  213. <CreateTime>%s</CreateTime>
  214. <MsgType><![CDATA[%s]]></MsgType>
  215. <Content><![CDATA[%s]]></Content>
  216. </xml>";
  217. $msgType="text";
  218. $result= sprintf($textTpl, $array['FromUserName'], $array['ToUserName'], time(), $msgType, $contentStr);
  219. return $result;
  220. */
  221. $data_media_id = '{"media_id":"AuXDjP791-NMcyJajUxBL0jmNmYMjTJ6fTQTEQV8Gh8"}';
  222. $url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" . $this->_accessToken;
  223. $response = $this->_requestPost($url, $data_media_id);
  224. $this->writelog("返回--" . $response);
  225. $media = json_decode($response, true);
  226. $mediaArray = $media['news_item'];
  227. $content = array();
  228. foreach ($mediaArray as $k => $v) {
  229. if ($k == 0 || $k == 1)
  230. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['url']);
  231. elseif ($k == 2) {
  232. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
  233. } else
  234. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
  235. }
  236. $this->writelog("返回--" . json_encode($content));
  237. if (is_array($content)) {
  238. if (isset($content[0]['PicUrl'])) {
  239. $result = $this->transmitNews($array, $content);
  240. $this->writelog(json_encode($result));
  241. return $result;
  242. }
  243. }
  244. if (!empty($array['EventKey'])) {
  245. /*
  246. $id=substr($array['EventKey'],strpos($array['EventKey'],"qrscene_")+8);
  247. $openid=$array['FromUserName'];
  248. $time=date("Y-m-d H:i:s");
  249. $pdo = new PDO("sqlsrv:Server=".HOST.";Database=".DB, USER, PASSWORD);//5.6版本pdo连接sqlsrv
  250. $sql="SELECT id FROM qrcodeDetail WHERE qrcodeId=".$id." AND openId='".$openid."'";
  251. $selectDate=$pdo->query($sql);
  252. $selectRes=$selectDate->fetchAll(PDO::FETCH_ASSOC);
  253. if (empty($selectRes)){
  254. $sql1="INSERT INTO qrcodeDetail values($id,'$openid','subscribe','$time')";
  255. $this->writelog("eventMsg function : subscribe:result id=".$id."--sql1-".$sql1);
  256. $result=$pdo->exec($sql1);
  257. }
  258. $sql2="SELECT media_id,url FROM qrcode WHERE id=".$id;
  259. $selectDate2=$pdo->query($sql2);
  260. $selectRes2=$selectDate2->fetchAll(PDO::FETCH_ASSOC);
  261. if (!empty($selectRes2)){
  262. $media_id= $selectRes2[0]['media_id'];
  263. $Rurl= $selectRes2[0]['url'];
  264. }else {
  265. //$media_id="AuXDjP791-NMcyJajUxBLzhsCmTK5evvwTjASqBwmv8";
  266. $media_id="AuXDjP791-NMcyJajUxBL5N9VCy5YnysR-dDWT2XFWg";
  267. $Rurl="http://wx.zhizhuchuxing.com/bookingHomePage/mdidiDetail.html?prod_code=NSPTSM01";
  268. }*/
  269. $media_id = "AuXDjP791-NMcyJajUxBL0jmNmYMjTJ6fTQTEQV8Gh8";
  270. $data = '{"media_id":"' . $media_id . '"}';
  271. $url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" . $this->_accessToken;
  272. $response = $this->_requestPost($url, $data);
  273. $this->writelog("返回--" . $response);
  274. $media = json_decode($response, true);
  275. $mediaArray = $media['news_item'];
  276. $content = array();
  277. foreach ($mediaArray as $k => $v) {
  278. if ($k == 0 || $k == 1)
  279. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['url']);
  280. else
  281. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
  282. }
  283. $this->writelog("返回--" . json_encode($content));
  284. if (is_array($content)) {
  285. if (isset($content[0]['PicUrl'])) {
  286. $result = $this->transmitNews($array, $content);
  287. return $result;
  288. }
  289. }
  290. } else {
  291. //$data='{"media_id":"AuXDjP791-NMcyJajUxBLw7rLLVx_s0V9I0l_sS92c0"}';
  292. /* $data='{"media_id":"AuXDjP791-NMcyJajUxBL5N9VCy5YnysR-dDWT2XFWg"}';
  293. $url="https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=".$this->_accessToken;
  294. $response=$this->_requestPost($url, $data);
  295. $this->writelog("返回--".$response);
  296. $media=json_decode($response,true);
  297. $mediaArray=$media['news_item'];
  298. $content = array();
  299. foreach ($mediaArray as $k=>$v){
  300. if ($k==0 || $k==1)
  301. $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['url']);
  302. else
  303. $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['content_source_url']);
  304. }
  305. $this->writelog("返回--".json_encode($content));
  306. if(is_array($content)){
  307. if (isset($content[0]['PicUrl'])){
  308. $result = $this->transmitNews($array, $content);
  309. }
  310. } */
  311. $data_media_id = '{"media_id":"AuXDjP791-NMcyJajUxBL0jmNmYMjTJ6fTQTEQV8Gh8"}';
  312. $url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" . $this->_accessToken;
  313. $response = $this->_requestPost($url, $data_media_id);
  314. $this->writelog("返回--" . $response);
  315. $media = json_decode($response, true);
  316. $mediaArray = $media['news_item'];
  317. $content = array();
  318. foreach ($mediaArray as $k => $v) {
  319. if ($k == 0 || $k == 1)
  320. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['url']);
  321. elseif ($k == 2) {
  322. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
  323. } else
  324. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
  325. }
  326. $this->writelog("返回--" . json_encode($content));
  327. if (is_array($content)) {
  328. if (isset($content[0]['PicUrl'])) {
  329. $result = $this->transmitNews($array, $content);
  330. $this->writelog(json_encode($result));
  331. return $result;
  332. }
  333. }
  334. }
  335. break;
  336. case 'SCAN':
  337. if (isset($array['EventKey'])) {
  338. /*
  339. $pdo = new PDO("sqlsrv:Server=".HOST.";Database=".DB, USER, PASSWORD);//5.6版本pdo连接sqlsrv
  340. $id=$array['EventKey'];
  341. $openid=$array['FromUserName'];
  342. $time=date("Y-m-d H:i:s");
  343. $sql="SELECT id FROM qrcodeDetail WHERE qrcodeId=".$id." AND openId='".$openid."'";
  344. $selectDate=$pdo->query($sql);
  345. $selectRes=$selectDate->fetchAll(PDO::FETCH_ASSOC);
  346. if (empty($selectRes)){
  347. $sql1="INSERT INTO qrcodeDetail values($id,'$openid','SCAN','$time')";
  348. $this->writelog("eventMsg function : SCAN:result id=".$id."--sql1-".$sql1);
  349. $result=$pdo->exec($sql1);
  350. }*/
  351. /* $this->writelog("eventMsg function : SCAN:result id=".$id."---".json_encode($result));
  352. $errinfo=$pdo->errorInfo();
  353. if ($errinfo[0] !='00000')
  354. $this->writelog("eventMsg function : SCAN:error id=".$id."---".$errinfo[2]);
  355. else{
  356. $res=$result->fetchAll(PDO::FETCH_ASSOC);
  357. $this->writelog("eventMsg function : SCAN:res id=".$id."---".json_encode($res));
  358. $headUrl=$res[0]['url'];
  359. $this->writelog("eventMsg function : SCAN:headUrl id=".$id."---".$headUrl);
  360. header("Location: $headUrl");exit;
  361. } */
  362. // $data='{"media_id":"AuXDjP791-NMcyJajUxBLw7rLLVx_s0V9I0l_sS92c0"}';
  363. /*
  364. $sql2="SELECT media_id,url FROM qrcode WHERE id=".$id;
  365. $selectDate2=$pdo->query($sql2);
  366. $selectRes2=$selectDate2->fetchAll(PDO::FETCH_ASSOC);
  367. if (!empty($selectRes2)){
  368. $media_id= $selectRes2[0]['media_id'];
  369. $Rurl= $selectRes2[0]['url'];
  370. }else {
  371. //$media_id="AuXDjP791-NMcyJajUxBLzhsCmTK5evvwTjASqBwmv8";
  372. $media_id="AuXDjP791-NMcyJajUxBL5N9VCy5YnysR-dDWT2XFWg";
  373. $Rurl="http://wx.zhizhuchuxing.com/bookingHomePage/mdidiDetail.html?prod_code=NSPTSM01";
  374. }*/
  375. /*
  376. $pdo=conn();
  377. $sql_update = " INSERT INTO wechat_user(`OPENID`,`IS_REGISTER`) values('{$array['FromUserName']}',1) ON DUPLICATE KEY UPDATE IS_REGISTER = 1 ";
  378. $selectDate = $pdo->exec($sql_update);
  379. $contentStr="Hi,『蜘蛛出行』每天为无数乘客提供便捷的交通出行服务,快来尝试一下吧!
  380. 如果您已经预订了车票,请按以下格式回复“#订单号#预定时预留的手机号”进行订单绑定。
  381. 绑定后可在『更多服务』—『行程』中查看巴士定位、车牌号码和司机电话等信息。
  382. (#号需输入,不可跳过,订单号请查找蜘蛛出行为您发送的手机短信)";
  383. $textTpl="
  384. <xml>
  385. <ToUserName><![CDATA[%s]]></ToUserName>
  386. <FromUserName><![CDATA[%s]]></FromUserName>
  387. <CreateTime>%s</CreateTime>
  388. <MsgType><![CDATA[%s]]></MsgType>
  389. <Content><![CDATA[%s]]></Content>
  390. </xml>";
  391. $msgType="text";
  392. $result= sprintf($textTpl, $array['FromUserName'], $array['ToUserName'], time(), $msgType, $contentStr);
  393. return $result;
  394. */
  395. $from_qrcode_id = 0;
  396. if (!empty($array['EventKey'])) {
  397. $from_qrcode_txt = substr($array['EventKey'], 8);
  398. $from_qrcode_id = (int)$from_qrcode_txt;
  399. }
  400. $this->writelog("SCAN CODE:" . json_encode($array));
  401. $pdo = conn();
  402. $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} ";
  403. $selectDate = $pdo->exec($sql_update);
  404. if ($from_qrcode_id != 0) {
  405. //发送微信红包
  406. $this->sendWxRedPack($array['FromUserName']);
  407. }
  408. $data_media_id = '{"media_id":"AuXDjP791-NMcyJajUxBL0jmNmYMjTJ6fTQTEQV8Gh8"}';
  409. $url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" . $this->_accessToken;
  410. $response = $this->_requestPost($url, $data_media_id);
  411. $this->writelog("返回--" . $response);
  412. $media = json_decode($response, true);
  413. $mediaArray = $media['news_item'];
  414. $content = array();
  415. foreach ($mediaArray as $k => $v) {
  416. if ($k == 0 || $k == 1)
  417. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['url']);
  418. elseif ($k == 2) {
  419. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
  420. } else
  421. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
  422. }
  423. $this->writelog("返回--" . json_encode($content));
  424. if (is_array($content)) {
  425. if (isset($content[0]['PicUrl'])) {
  426. $result = $this->transmitNews($array, $content);
  427. $this->writelog(json_encode($result));
  428. return $result;
  429. }
  430. }
  431. /*
  432. $data='{"media_id":"'.$media_id.'"}';
  433. $url="https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=".$this->_accessToken;
  434. $response=$this->_requestPost($url, $data);
  435. $this->writelog("返回--".$response);
  436. $media=json_decode($response,true);
  437. $mediaArray=$media['news_item'];
  438. $content = array();
  439. foreach ($mediaArray as $k=>$v){
  440. if ($k==0 || $k==1)
  441. $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['url']);
  442. elseif($k==2){
  443. $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['content_source_url']);
  444. }
  445. else
  446. $content[] = array("Title"=>$v['title'], "Description"=>$v['digest'], "PicUrl"=>$v['thumb_url'], "Url" =>$v['content_source_url']);
  447. }
  448. $this->writelog("返回--".json_encode($content));
  449. if(is_array($content)){
  450. if (isset($content[0]['PicUrl'])){
  451. $result = $this->transmitNews($array, $content);
  452. }
  453. }*/
  454. }
  455. break;
  456. case 'CLICK':
  457. $pdo = conn();
  458. $contantConfig = require dirname(dirname(__DIR__)) . '/config/moduleConfig/module/site.contants.config.php';
  459. $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 ";
  460. $selectDate = $pdo->exec($sql_update);
  461. /*
  462. $contentStr="Hi,『蜘蛛出行』每天为无数乘客提供便捷的交通出行服务,快来尝试一下吧!
  463. 如果您已经预订了车票,请按以下格式回复“#订单号#预定时预留的手机号”进行订单绑定。
  464. 绑定后可在『更多服务』—『行程』中查看巴士定位、车牌号码和司机电话等信息。
  465. (#号需输入,不可跳过,订单号请查找蜘蛛出行为您发送的手机短信)";
  466. $textTpl="
  467. <xml>
  468. <ToUserName><![CDATA[%s]]></ToUserName>
  469. <FromUserName><![CDATA[%s]]></FromUserName>
  470. <CreateTime>%s</CreateTime>
  471. <MsgType><![CDATA[%s]]></MsgType>
  472. <Content><![CDATA[%s]]></Content>
  473. </xml>";
  474. $msgType="text";
  475. $result= sprintf($textTpl, $array['FromUserName'], $array['ToUserName'], time(), $msgType, $contentStr);
  476. return $result;
  477. */
  478. if (isset($array['EventKey']) && $array['EventKey'] == 'Push-Photo-List') {
  479. $data = '{"media_id":"AuXDjP791-NMcyJajUxBL0jmNmYMjTJ6fTQTEQV8Gh8"}';
  480. $url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" . $this->_accessToken;
  481. $response = $this->_requestPost($url, $data);
  482. $this->writelog("CLICK返回response--" . $response);
  483. $media = json_decode($response, true);
  484. $mediaArray = $media['news_item'];
  485. $content = array();
  486. foreach ($mediaArray as $k => $v) {
  487. if ($k == 0 || $k == 1)
  488. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['url']);
  489. else
  490. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
  491. }
  492. $this->writelog("CLICK返回content--" . json_encode($content));
  493. if (is_array($content)) {
  494. if (isset($content[0]['PicUrl'])) {
  495. $result = $this->transmitNews($array, $content);
  496. }
  497. }
  498. } elseif (isset($array['EventKey']) && $array['EventKey'] == 'MSG_LIANXIKEFU') {
  499. $textTpl = '' . "
  500. <xml>
  501. <ToUserName><![CDATA[%s]]></ToUserName>
  502. <FromUserName><![CDATA[%s]]></FromUserName>
  503. <CreateTime>%s</CreateTime>
  504. <MsgType><![CDATA[transfer_customer_service]]></MsgType>
  505. </xml>";
  506. $result = sprintf($textTpl, $array['FromUserName'], $array['ToUserName'], time());
  507. }
  508. }
  509. /*
  510. $data='{"type":"news","offset":0,"count":20}';
  511. $url="https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=".$this->_accessToken;
  512. $response=$this->_requestPost($url, $data);
  513. $this->writelog("返回--".$response); */
  514. $this->writelog("回复用户event--" . json_encode($result));
  515. return $result;
  516. }
  517. /**
  518. * Function Description:发送微信红包
  519. * Function Name: sendWxRedPack
  520. * @param $openId
  521. *
  522. * @return bool
  523. *
  524. * @author 倪宗锋
  525. */
  526. public function sendWxRedPack($openId)
  527. {
  528. $path = dirname(dirname(__DIR__));
  529. $config = require $path . "/config/wxpay.config.php";
  530. //准备数据
  531. $params = array(
  532. 'openid' => $openId,
  533. 'act_id' => 1
  534. );
  535. $params['sign'] = $this->getSign($params, $config['key']);//安全机制 秘钥签名
  536. $url = 'http://' . $_SERVER['HTTP_HOST'] . '/module/activity/redpack/sendRedPack?';
  537. $url .= http_build_query($params);
  538. //调用接口
  539. $curl = curl_init();
  540. curl_setopt($curl, CURLOPT_URL, $url);
  541. curl_setopt($curl, CURLOPT_AUTOREFERER, true);
  542. curl_setopt($curl, CURLOPT_POST, true);
  543. curl_setopt($curl, CURLOPT_POSTFIELDS, array());
  544. curl_setopt($curl, CURLOPT_HEADER, false);
  545. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  546. //1秒超时 不等待
  547. curl_setopt($curl, CURLOPT_TIMEOUT, 1);
  548. curl_exec($curl);
  549. return true;
  550. }
  551. /**
  552. * Function Description:获取签名
  553. * Function Name: getSign
  554. * @param $params
  555. * @param $key string 配置类型
  556. *
  557. * @return string
  558. *
  559. * @author 倪宗锋
  560. */
  561. public static function getSign($params, $key)
  562. {
  563. if (isset($params['sign'])) {
  564. unset($params['sign']);
  565. }
  566. //签名步骤一:按字典序排序参数
  567. ksort($params);
  568. $string = self::ToUrlParams($params);
  569. //签名步骤二:在string后加入KEY
  570. $string = $string . "&key=" . $key;
  571. //签名步骤三:MD5加密
  572. $string = md5($string);
  573. //签名步骤四:所有字符转为大写
  574. $result = strtoupper($string);
  575. return $result;
  576. }
  577. /**
  578. * Function Description:格式化参数 格式化成url参数
  579. * Function Name: ToUrlParams
  580. * @param $params
  581. *
  582. * @return string
  583. *
  584. * @author 倪宗锋
  585. */
  586. public static function ToUrlParams($params)
  587. {
  588. $buff = "";
  589. foreach ($params as $k => $v) {
  590. if ($k != "sign" && $v != "" && !is_array($v)) {
  591. $buff .= $k . "=" . $v . "&";
  592. }
  593. }
  594. $buff = trim($buff, "&");
  595. return $buff;
  596. }
  597. //把openid存入数据库
  598. public function insertOpenid($data, $type)
  599. {
  600. $openid = $data['FromUserName'];
  601. if ($type == 'subscribe') {
  602. $sql = "insert into wx_user(openid) values('{$openid}')";
  603. } else if ($type == 'unsubscribe') {
  604. $sql = "delete from wx_user where openid='{$openid}'";
  605. }
  606. $result = '';
  607. try {
  608. $pdo = new PDO("sqlsrv:Server=" . HOST . ";Database=" . DB, USER, PASSWORD);//5.6版本pdo连接sqlsrv
  609. //$pdo=new PDO("mysql:host=".HOST.";dbname=".DB,USER,PASSWORD); //7.0版本pdo连接mysql
  610. $result = $pdo->exec($sql);
  611. $errinfo = $pdo->errorInfo();
  612. if ($errinfo[0] != '00000')
  613. $this->writelog($errinfo[2]);
  614. } catch (PDOException $e) {
  615. $this->writelog($e->getMessage());
  616. }
  617. if ($result) {
  618. return true;
  619. } else {
  620. return false;
  621. }
  622. }
  623. //有用户关注的时候推送多图文消息
  624. private function transmitNews($array, $newsArray)
  625. {
  626. if (!is_array($newsArray)) {
  627. return;
  628. }
  629. $itemTpl = "<item>
  630. <Title><![CDATA[%s]]></Title>
  631. <Description><![CDATA[%s]]></Description>
  632. <PicUrl><![CDATA[%s]]></PicUrl>
  633. <Url><![CDATA[%s]]></Url>
  634. </item>";
  635. $item_str = "";
  636. foreach ($newsArray as $item) {
  637. $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
  638. }
  639. $xmlTpl = "<xml>
  640. <ToUserName><![CDATA[%s]]></ToUserName>
  641. <FromUserName><![CDATA[%s]]></FromUserName>
  642. <CreateTime>%s</CreateTime>
  643. <MsgType><![CDATA[news]]></MsgType>
  644. <ArticleCount>%s</ArticleCount>
  645. <Articles>
  646. $item_str</Articles>
  647. </xml>";
  648. $result = sprintf($xmlTpl, $array['FromUserName'], $array['ToUserName'], time(), count($newsArray));
  649. return $result;
  650. }
  651. private function transmitImage($array)
  652. {
  653. $xmlTpl = "<xml>
  654. <ToUserName><![CDATA[%s]]></ToUserName>
  655. <FromUserName><![CDATA[%s]]></FromUserName>
  656. <CreateTime>%s</CreateTime>
  657. <MsgType><![CDATA[image]]></MsgType>
  658. <Image>
  659. <MediaId><![CDATA[%s]]></MediaId>
  660. </Image>
  661. </xml>";
  662. $result = sprintf($xmlTpl, $array['FromUserName'], $array['ToUserName'], time(), $array['media_id']);
  663. return $result;
  664. }
  665. private function transmitVoice($array)
  666. {
  667. $xmlTpl = "<xml>
  668. <ToUserName><![CDATA[%s]]></ToUserName>
  669. <FromUserName><![CDATA[%s]]></FromUserName>
  670. <CreateTime>%s</CreateTime>
  671. <MsgType><![CDATA[voice]]></MsgType>
  672. <Image>
  673. <MediaId><![CDATA[%s]]></MediaId>
  674. </Image>
  675. </xml>";
  676. $result = sprintf($xmlTpl, $array['FromUserName'], $array['ToUserName'], time(), $array['media_id']);
  677. return $result;
  678. }
  679. private function transmitVideo($array)
  680. {
  681. $xmlTpl = "<xml>
  682. <ToUserName><![CDATA[%s]]></ToUserName>
  683. <FromUserName><![CDATA[%s]]></FromUserName>
  684. <CreateTime>%s</CreateTime>
  685. <MsgType><![CDATA[video]]></MsgType>
  686. <Video>
  687. <MediaId><![CDATA[%s]]></MediaId>
  688. <Title><![CDATA[%s]]></Title>
  689. <Description><![CDATA[%s]]></Description>
  690. </Video>
  691. </xml>";
  692. $result = sprintf($xmlTpl, $array['FromUserName'], $array['ToUserName'], time(), $array['media_id'], $array["title"], $array["description"]);
  693. return $result;
  694. }
  695. //获取文本
  696. public function textMsg($data)
  697. {
  698. $Content = trim($data['Content']);
  699. $textTpl = "
  700. <xml>
  701. <ToUserName><![CDATA[%s]]></ToUserName>
  702. <FromUserName><![CDATA[%s]]></FromUserName>
  703. <CreateTime>%s</CreateTime>
  704. <MsgType><![CDATA[%s]]></MsgType>
  705. <Content><![CDATA[%s]]></Content>
  706. </xml>";
  707. $msgType = "text";
  708. $word = $data['Content'];
  709. if ($word == '寻路') {
  710. $this->writelog("textMsg有调用:关键字是面试");
  711. $data_media_id = '{"media_id":"AuXDjP791-NMcyJajUxBL8LcnGB8gKQTImk6XJK53uU"}';
  712. $url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" . $this->_accessToken;
  713. $response = $this->_requestPost($url, $data_media_id);
  714. $this->writelog("返回--" . $response);
  715. $media = json_decode($response, true);
  716. $mediaArray = $media['news_item'];
  717. $content = array();
  718. foreach ($mediaArray as $k => $v) {
  719. if ($k == 0 || $k == 1)
  720. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['url']);
  721. elseif ($k == 2) {
  722. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
  723. } else
  724. $content[] = array("Title" => $v['title'], "Description" => $v['digest'], "PicUrl" => $v['thumb_url'], "Url" => $v['content_source_url']);
  725. }
  726. $this->writelog("返回--" . json_encode($content));
  727. if (is_array($content)) {
  728. if (isset($content[0]['PicUrl'])) {
  729. $result = $this->transmitNews($data, $content);
  730. $this->writelog(json_encode($result));
  731. return $result;
  732. }
  733. }
  734. } else if ($word == '活动') {
  735. $data["media_id"] = "AuXDjP791-NMcyJajUxBL2MpGN_djcS5OUH-Y5njOMA";
  736. $result = $this->transmitImage($data);
  737. $this->writelog(json_encode($result));
  738. return $result;
  739. } else if ($word == '测试定制巴士') {
  740. $contentStr = "http://wx.zhizhuchuxing.com/ZZDZ/dzbs_login.php";
  741. $resultStr = sprintf($textTpl, $data['FromUserName'], $data['ToUserName'], time(), $msgType, $contentStr);
  742. return $resultStr;
  743. } else if ($word == '订单绑定' || $word == '绑定订单' || $word == '绑定' || $word == '绑订单') {
  744. $contentStr = "Hi,『蜘蛛出行』每天为无数乘客提供便捷的交通出行服务,快来尝试我们为您准备的新功能吧!
  745. 如果您已经预订了车票,请按以下格式回复“#订单号#预定时预留的手机号”进行订单绑定,绑定后可在『更多服务』—『行程』中查看巴士定位、车牌号码和司机电话等信息。
  746. (#号需输入,不可跳过,订单号请查找蜘蛛出行为您发送的手机短信)
  747. 如果您还没有预订车票,请戳左下角『出行预订』!";
  748. $resultStr = sprintf($textTpl, $data['FromUserName'], $data['ToUserName'], time(), $msgType, $contentStr);
  749. $this->writelog($resultStr);
  750. return $resultStr;
  751. } else if (substr($word, 0, 1) == '#') {
  752. $word = substr($word, 1);
  753. $wordArr = explode("#", $word);
  754. if (count($wordArr) != 2 || $wordArr[0] == '' || $wordArr[1] == '') {
  755. $contentStr = "输入格式错误";
  756. } else if (!is_numeric($wordArr[0]) || !is_numeric($wordArr[1])) {
  757. $contentStr = "订单号和手机号必须整数";
  758. } else {
  759. $pdo = conn();
  760. $sql = "CALL DRIVER_WEICHAT_BOND(" . $wordArr[0] . "," . $wordArr[1] . ",'" . $data['FromUserName'] . "')";
  761. $this->writelog("订单绑定" . $sql);
  762. $result = $pdo->query($sql);
  763. $rowset = $result->fetchAll(PDO::FETCH_ASSOC);
  764. $result->closeCursor();
  765. $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]}";
  766. $pdo_update = conn();
  767. $pdo_update->exec($update_sql);
  768. if ($rowset[0]['code'] == 0) {
  769. $contentStr = "绑定成功";
  770. } else {
  771. $contentStr = $rowset[0]['info'];
  772. }
  773. }
  774. $resultStr = sprintf($textTpl, $data['FromUserName'], $data['ToUserName'], time(), $msgType, $contentStr);
  775. $this->writelog($resultStr);
  776. return $resultStr;
  777. } /*else{
  778. $contentStr="Hi,『蜘蛛出行』每天为无数乘客提供便捷的交通出行服务,快来尝试我们为您准备的新功能吧!
  779. 如果您已经预订了车票,请按以下格式回复“#订单号#预定时预留的手机号”进行订单绑定,绑定后可在『更多服务』—『行程』中查看巴士定位、车牌号码和司机电话等信息。
  780. (#号需输入,不可跳过,订单号请查找蜘蛛出行为您发送的手机短信)
  781. 如果您还没有预订车票,请戳左下角『出行预订』!";
  782. $resultStr = sprintf($textTpl, $data['FromUserName'], $data['ToUserName'], time(), $msgType, $contentStr);
  783. return $resultStr;
  784. }*/
  785. //$contentStr=$this->simsimiHttp($Content);
  786. else {
  787. $textTpl = '' . "
  788. <xml>
  789. <ToUserName><![CDATA[%s]]></ToUserName>
  790. <FromUserName><![CDATA[%s]]></FromUserName>
  791. <CreateTime>%s</CreateTime>
  792. <MsgType><![CDATA[transfer_customer_service]]></MsgType>
  793. </xml>";
  794. $resultStr = sprintf($textTpl, $data['FromUserName'], $data['ToUserName'], time());
  795. return $resultStr;
  796. }
  797. }
  798. private function simsimiHttp($msg)
  799. {
  800. $url = "http://www.xiaodoubi.com/simsimiapi.php?msg=" . $msg;
  801. $res = file_get_contents($url);
  802. file_put_contents("./demo.txt", date("Y-m-d H:i:s") . " " . $res . PHP_EOL, FILE_APPEND);
  803. if (strpos($res, "xiaodouqqcom") !== false) {
  804. $res = "无法回答,请不要发一下奇怪的问题或字符😒";
  805. }
  806. if (strpos($msg, "主人") !== false) {
  807. $res = "我的主人就是你呀";
  808. }
  809. return $res;
  810. }
  811. private function checkAccessToken($check)
  812. {
  813. if (isset($check['errcode']) && $check['errcode'] == 40001) {
  814. $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->_appid}&secret={$this->_appsecret}";
  815. $result = $this->_requestGet($url);
  816. if (!$result) {
  817. $this->writelog("获取token出错");
  818. return false;
  819. }
  820. $result_obj = json_decode($result);
  821. file_put_contents($token_file, $result_obj->access_token);
  822. $this->writelog("url获取的token:" . $result_obj->access_token);
  823. return $result_obj->access_token;
  824. }
  825. }
  826. }
  827. ?>