|
- <?php
- /**
- *
- * ============================================================================
- * * 版权所有 运游通 * *
- * 网站地址: http://www.zhizhuchuxing.com
- * ----------------------------------------------------------------------------
- * 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和
- * 使用;不允许对程序代码以任何形式任何目的的再发布。
- * ============================================================================
- * Author By: 倪宗锋
- * PhpStorm wxInterface.php
- * Create By 2017/1/4 10:55 $
- */
-
-
- namespace WxInterface\Service;
-
-
- use Util\Util\CurlInterface;
- use Util\Util\Util;
- use WxInterface\Model\WxInterfaceModel;
-
- class WxInterface
- {
- //配置参数
- private $request = array();
- private $response = false;
- private $logMsg = '';
- private $token = '';
- private $appid = '';
- private $appsecret = '';
-
- public function __construct()
- {
- $wxConfig = Util::getWxPayConfig();
- $this->token = $wxConfig['token'];
- $this->appid = $wxConfig['appid'];
- $this->appsecret = $wxConfig['appsecret'];
- $this->setLog(date('Y-m-d H:i:s'));
- }
-
- /**
- * Des:接收参数并处理返回值
- * Name: exec
- * @return string
- * @author 倪宗锋
- */
- public function exec()
- {
- $content = $this->getContent();//获取参数并解析
- if ($content['MsgType'] == 'text') {
- $this->response = $this->textMsg($content);
- } elseif ($content['MsgType'] == 'event') {
- $this->response = $this->eventMsg($content);
- }
- return $this->response;
- }
-
- /**
- * Des:用户输入内容处理
- * Name: textMsg
- * @param $content
- * @return bool|string
- * @author 倪宗锋
- */
- public function textMsg($content)
- {
- $word = $content['Content'];
- return $this->send($word, $content, 'text');
- }
-
- /**
- * Des:推送事件处理
- * Name: eventMsg
- * @param $content
- * @return string
- * @author 倪宗锋
- */
- public function eventMsg($content)
- {
- if ($content['Event'] == 'subscribe') {//微信关注事件 发送欢迎语
- $word = 'subscribe';
- if (empty($content['EventKey']) == false ) {
- $EventKey = explode('_',$content['EventKey']);
- $textConfig = require ROOT_PATH . '/data/wxConfig/Wx.event.config.php';
- if (empty($EventKey[1]) == false && empty($textConfig[$EventKey[1]]) == false) {
- $word = $EventKey[1];
- }
- }
- } elseif ($content['Event'] == 'unsubscribe') {//微信关注事件 发送欢迎语
- $word = 'unsubscribe';
- } elseif ($content['Event'] == 'SCAN') {//扫一扫
- $word = 'SCAN';
- if (empty($content['EventKey']) == false ) {
- $textConfig = require ROOT_PATH . '/data/wxConfig/Wx.event.config.php';
- if (empty($textConfig[$content['EventKey']]) == false) {
- $word = $content['EventKey'];
- }
- }
- } else if ($content['Event'] == 'VIEW' || empty($content['EventKey'])) {
- return false;
- } else {
- $word = $content['EventKey'];
- }
- if ($word == 'MSG_LIANXIKEFU') {
- return $this->callCuster($content);
- }
- return $this->send($word, $content, 'event');
-
- }
-
- /**
- * Des: 发送处理
- * Name: send
- * @param $word
- * @param $content
- * @param string $type 触发类型:text 用户输入 event:推送事件
- * @return string
- * @author 倪宗锋
- */
- public function send($word, $content, $type = 'text')
- {
- $textConfig = require ROOT_PATH . '/data/wxConfig/Wx.' . $type . '.config.php';
- if (empty($textConfig[$word]) == false) {//如果 有指定的配置就用指定的配置
- $msgSend = $textConfig[$word];
- } else if ($type == 'text') {//没有指定的配置 且 接收的是用户输入文本信息
- $info = new WxDoFunction();
- $getDoResult = $info->showOrderInfo($word);
- if ($getDoResult == '') {
- //默认联系客服
- $msgSend = $this->callCuster($content);
- return $msgSend;
- } else {
- $msgSend = $getDoResult;
- }
- } else {//没有指定配置 且接收的是按钮或扫一扫则直接返回关注自动回复信息
- $msgSend = $textConfig['subscribe'];
- }
- $this->setLog('sendMsg:' . print_r($msgSend, 1));//日志记录
- Util::setLogs(json_encode($msgSend));
- if (is_array($msgSend) && empty($msgSend['function']) == false) {//当推送事件有方法指定时,则调用该方法
- $wxDoFunction = new WxDoFunction();
- $function = $msgSend['function'];
- $wxDoFunction->$function($content);
- }
- if (isset($msgSend['type']) && $msgSend['type'] == 'news') {//如果是图文类型
- return $this->sendNews($content, $msgSend);
- } elseif (isset($msgSend['type']) && $msgSend['type'] == 'img') {//如果是图片类型
- return $this->sendImage($content, $msgSend['id']);
- } elseif (isset($msgSend['type']) && $msgSend['type'] == 'voice') {//如果是语音类型
- return $this->sendVoice($content, $msgSend['id']);
- } elseif (isset($msgSend['type']) && $msgSend['type'] == 'video') {//如果是视频类型
- return $this->sendVideo($content, $msgSend);
- } else {
- return $this->sendText($content, $msgSend);
- }
- }
-
- /**
- * Des:联系客服
- * Name: sendText
- * @param $content
- * @return string
- * @author 倪宗锋
- */
- private function callCuster($content)
- {
- $textTpl = '' . "
- <xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[transfer_customer_service]]></MsgType>
- </xml>";
- $resultStr = sprintf($textTpl, $content['FromUserName'], $content['ToUserName'], time());
- return $resultStr;
- }
-
- /**
- * Des:发送文字
- * Name: sendText
- * @param $content
- * @param $msgSend
- * @return string
- * @author 倪宗锋
- */
- private function sendText($content, $msgSend)
- {
- $textTpl = '' . "
- <xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[%s]]></MsgType>
- <Content><![CDATA[%s]]></Content>
- </xml>";
- $msgType = "text";
- if (is_array($msgSend)) {
- $msgSend = $msgSend['text'];
- }
- $resultStr = sprintf($textTpl, $content['FromUserName'], $content['ToUserName'], time(), $msgType, $msgSend);
- return $resultStr;
- }
-
- /**
- * Des:发送图文
- * Name: sendNews
- * @param $content array
- * @param $msgSend array
- * @return string
- * @author 倪宗锋
- */
- private function sendNews($content, $msgSend)
- {
- $news = $this->getNewsByMediaId($msgSend);
- return $this->transmitNews($content, $news);
- }
-
- /**
- * Des:发送图片
- * Name: sendImage
- * @param $content
- * @param $mediaId
- * @return string
- * @author 倪宗锋
- */
- private function sendImage($content, $mediaId)
- {
- $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, $content['FromUserName'], $content['ToUserName'], time(), $mediaId);
- return $result;
- }
-
- /**
- * Des:发送语音
- * Name: sendVoice
- * @param $content
- * @param $mediaId
- * @return string
- * @author 倪宗锋
- */
- private function sendVoice($content, $mediaId)
- {
- $xmlTpl = '' . "<xml>
- <ToUserName><![CDATA[%s]]></ToUserName>
- <FromUserName><![CDATA[%s]]></FromUserName>
- <CreateTime>%s</CreateTime>
- <MsgType><![CDATA[voice]]></MsgType>
- <Voice>
- <MediaId><![CDATA[%s]]></MediaId>
- </Voice>
- </xml>";
- $result = sprintf($xmlTpl, $content['FromUserName'], $content['ToUserName'], time(), $mediaId);
- return $result;
- }
-
- /**
- * Des:发送视频
- * Name: sendVideo
- * @param $content
- * @param $sendMsg
- * @return string
- * @author 倪宗锋
- */
- private function sendVideo($content, $sendMsg)
- {
- $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, $content['FromUserName'], $content['ToUserName'], time(), $sendMsg['id'], $sendMsg["title"], $sendMsg["des"]);
- return $result;
- }
-
- /**
- * Des:根据ID获取图文信息
- * Name: getNewsByMediaId
- * @param $msgSend array
- * @return array
- * @author 倪宗锋
- */
- public function getNewsByMediaId($msgSend)
- {
- $data_media_id = '{"media_id":"' . $msgSend['id'] . '"}';
- $url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" . $this->getAccessToken();
- $response = $this->_requestPost($url, $data_media_id);
- $media = json_decode($response, true);
- $mediaArray = $media['news_item'];
- $content = array();
- foreach ($mediaArray as $k => $v) {
- if (isset($msgSend['url'])) {
- $v['url'] = $msgSend['url'];
- $v['content_source_url'] = $msgSend['url'];
- }
- 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']);
- }
- return $content;
- }
-
- /**
- * Des:图文推送数据处理
- * Name: transmitNews
- * @param $content
- * @param $newsArray
- * @return string
- * @author 倪宗锋
- */
- private function transmitNews($content, $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[{$content['FromUserName']}]]></ToUserName>
- <FromUserName><![CDATA[{$content['ToUserName']}]]></FromUserName>
- <CreateTime>" . time() . "</CreateTime>
- <MsgType><![CDATA[news]]></MsgType>
- <ArticleCount>" . count($newsArray) . "</ArticleCount>
- <Articles>$item_str</Articles>
- </xml>";
- // $result = sprintf($xmlTpl, $content['FromUserName'], $content['ToUserName'], time(), count($newsArray));
- return $xmlTpl;
- }
-
- /*************************=========第一次请求校验==========***********************************/
- /**
- * Des:第一次校验
- * Name: valid
- * @return bool
- * @author 倪宗锋
- */
- public function valid()
- {
- $echoStr = $_GET["echostr"];
- if ($this->checkSignature()) {
- $this->response = $echoStr;
- }
- return $this->response;
- }
-
- /**
- * Des:数据校验
- * Name: checkSignature
- * @return bool
- * @author 倪宗锋
- */
- private function checkSignature()
- {
- $token = $this->token;
- $signature = isset($_GET["signature"]) ? $_GET["signature"] : "";
- $timestamp = isset($_GET["timestamp"]) ? $_GET["timestamp"] : "";
- $nonce = isset($_GET["nonce"]) ? $_GET["nonce"] : "";
- $tmpArr = array($token, $timestamp, $nonce);
- $this->setLog('param:' . print_r($tmpArr, 1));
- sort($tmpArr, SORT_STRING);
- $tmpStr = implode($tmpArr);
- $tmpStr = sha1($tmpStr);
- if ($tmpStr == $signature) {
- return true;
- } else {
- return false;
- }
- }
-
-
- /**
- * Des:参数解析
- * Name: getContent
- * @author 倪宗锋
- */
- private function getContent()
- {
- $content = file_get_contents("php://input");
- // $content = "<xml><ToUserName><![CDATA[gh_358ca80fc02a]]></ToUserName>\n<FromUserName><![CDATA[owEylwhtT-zr5klahSms6hPAfK1E]]></FromUserName>\n<CreateTime>1492567969</CreateTime>\n<MsgType><![CDATA[event]]></MsgType>\n<Event><![CDATA[subscribe]]></Event>\n<EventKey><![CDATA[]]></EventKey>\n</xml>";
- $this->setLog('content: ' . print_r($content, 1));
- libxml_disable_entity_loader(true);
- $this->request = (array)simplexml_load_string($content, 'SimpleXMLElement', LIBXML_NOCDATA);
- return $this->request;
- }
-
- /**
- * Des:获取token
- * Name: getAccessToken
- * @return string
- * @author 倪宗锋
- */
- public static function getAccessToken()
- {
- $wxConfig = Util::getWxPayConfig();
- $appid = $wxConfig['appid'];
- $appsecret = $wxConfig['appsecret'];
- $time = time();
- $data['appid'] = $appid;
- $data['appsecret'] = $appsecret;
- $data['time'] = $time;
- $param = [
- 'code' => Util::authCode(http_build_query($data), 'ENCODE'),
- 'time' => $time
- ];
- $curl = new CurlInterface($param, 4);
- $siteConfig = Util::getSiteConfig();
- $return = $curl->execute($siteConfig['wx_get_token'] . '/zzcx/interfaces/fx/get-wx-token', 'POST');
- return $return;
- }
-
- /**
- * Des:发起get请求
- * Name: _requestGet
- * @param $url string
- * @param bool|true $ssl
- * @return bool|mixed
- * @author 倪宗锋
- */
- public static function _requestGet($url, $ssl = true)
- {
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_URL, $url);
- 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) {
- return false;
- }
- return $response;
- }
-
- /**
- * Des:发起post请求
- * Name: _requestPost
- * @param $url
- * @param $data
- * @param bool|true $ssl
- * @return bool|mixed
- * @author 倪宗锋
- */
- public static 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) {
- return false;
- }
- return $response;
- }
-
- /**
- * Des:获取
- * Name: httpRequest
- * @param $url
- * @param null $data
- * @return mixed
- * @author 倪宗锋
- */
- static function httpRequest($url, $data = null)
- {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- if (!empty($data)) {
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- }
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- $output = curl_exec($ch);
- curl_close($ch);
- return $output;
- }
-
-
- public function setLog($logMsg)
- {
- $logMsg = str_replace(PHP_EOL, '', $logMsg);
- $logMsg = preg_replace("/\s(?=\s)/", "\\1", $logMsg);
- $this->logMsg .= $logMsg . PHP_EOL;
- }
-
- /**
- * 项目关闭 写入日志
- */
- public function __destruct()
- {
- $this->setLog(print_r($this->response, 1));//写入返回值
- $fileName = ROOT_PATH . '/data/log/WXLog/wxinterface' . date('Y-m-d') . '.log';
- file_put_contents($fileName, $this->logMsg . PHP_EOL, FILE_APPEND);
- }
- }
|