<?php
/*
方倍工作室 http://www.fangbei.org/
CopyRight 2015 All Rights Reserved
*/
header('Content-type:text');
define("TOKEN", "weixin"); //定义TOKEN=weixin
$wechatObj = new wechatCallbackapiTest(); //新建一个wechatCallbackapiTest类型对象wechatObj
if (!isset($_GET['echostr'])) { //echostr不存在的话去执行wechatObj类中的responseMsg函数
$wechatObj->responseMsg();
}else{
$wechatObj->valid(); //echostr存在的话去执行wechatObj类中的valid函数
}
class wechatCallbackapiTest
{
//验证签名
public function valid()
{
$echoStr = $_GET["echostr"]; //从前台url中取出参数echostr的值再赋值给变量echoStr()
$signature = $_GET["signature"]; //从前台url中取出参数signature的值再赋值给变量signature(签名)
$timestamp = $_GET["timestamp"]; //从前台url中取出参数timestamp的值再赋值给变量timestamp(时间戳)
$nonce = $_GET["nonce"]; //从前台url中取出参数nonce的值再赋值给变量nonce(随机数、临时数)
$token = TOKEN; //将TOKEN赋值给变量token(就是固定值“weixin”)
$tmpArr = array($token, $timestamp, $nonce); //将被赋值的三个变量$token, $timestamp, $nonce组成数组tmpArr
sort($tmpArr, SORT_STRING); //给数组tmpArr中三个元素进行排序
$tmpStr = implode($tmpArr); //将数组tmpArr通过 implode函数解析成字符串并赋值给tmpStr
$tmpStr = sha1($tmpStr); //将字符串tmpStr通过sha1函数进行加密后重新赋值给tmpStr
if($tmpStr == $signature){ //判断签名的字符串signature与新生成的tmpStr字符串相等的话输出echoStr
echo $echoStr;
exit;
}
}
//响应消息
public function responseMsg()
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //取post表单类数据中的所有值并赋值给postStr变量
if (!empty($postStr)){
$this->logger("R \r\n".$postStr); //通过日志函数logger记录日志,. 用在两个字符串之间是连接字符串的意思相当于+号
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); //将字符串变量postStr按SimpleXMLElement格式只取CDATA标签中的值并转化成对象型变量$postObj
$RX_TYPE = trim($postObj->MsgType); //获取对象型变量postObj的MsgType属性值并赋值给RX_TYPE变量
//消息类型分离
switch ($RX_TYPE)
{ //根据前边被赋过值的RX_TYPE变量来判断去执行的不同的函数
case "event":
$result = $this->receiveEvent($postObj);
break;
case "text":
$result = $this->receiveText($postObj);
break;
case "image":
$result = $this->receiveImage($postObj);
break;
case "location":
$result = $this->receiveLocation($postObj);
break;
case "voice":
$result = $this->receiveVoice($postObj);
break;
case "video":
case "shortvideo":
$result = $this->receiveVideo($postObj);
break;
case "link":
$result = $this->receiveLink($postObj);
break;
default:
$result = "unknown msg type: ".$RX_TYPE;
break;
}
$this->logger("T \r\n".$result);
echo $result;
}else {
echo "";
exit;
}
}
//接收事件消息
private function receiveEvent($object)
{
$content = "";
switch ($object->Event)
{
case "subscribe":
$content = "欢迎使用方倍工作室微信开发入门教程Demo\n请回复以下关键字:文本 表情 单图文 多图文 音乐\n请按住说话 或 点击 + 再分别发送以下内容:语音 图片 小视频 我的收藏 位置";
$content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
//str_replace函数将$object->EventKey中所有的qrscene_都替换成空
$content .= "\n\n".'<a href="http://m.cnblogs.com/?u=txw1958">技术支持 方倍工作室</a>';
break;
case "unsubscribe":
$content = "取消关注";
break;
case "CLICK":
switch ($object->EventKey)
{
case "COMPANY":
$content = array();
$content[] = array("Title"=>"方倍工作室", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
break;
default:
$content = "点击菜单:".$object->EventKey;
break;
}
break;
case "VIEW":
$content = "跳转链接 ".$object->EventKey;
break;
case "SCAN":
$content = "扫描场景 ".$object->EventKey;
break;
case "LOCATION":
$content = "上传位置:纬度 ".$object->Latitude.";经度 ".$object->Longitude;
break;
case "scancode_waitmsg":
if ($object->ScanCodeInfo->ScanType == "qrcode"){
$content = "扫码带提示:类型 二维码 结果:".$object->ScanCodeInfo->ScanResult;
}else if ($object->ScanCodeInfo->ScanType == "barcode"){
$codeinfo = explode(",",strval($object->ScanCodeInfo->ScanResult));
//strval函数将$object->ScanCodeInfo->ScanResult转化成字符串;explode将字符串按其中的逗号分隔成若干的元素,最后赋值给数组codeinfo
$codeValue = $codeinfo[1]; //数组中第一个元素的值赋给字符串变量codeValue
$content = "扫码带提示:类型 条形码 结果:".$codeValue;
}else{
$content = "扫码带提示:类型 ".$object->ScanCodeInfo->ScanType." 结果:".$object->ScanCodeInfo->ScanResult;
}
break;
case "scancode_push":
$content = "扫码推事件";
break;
case "pic_sysphoto":
$content = "系统拍照";
break;
case "pic_weixin":
$content = "相册发图:数量 ".$object->SendPicsInfo->Count;
break;
case "pic_photo_or_album":
$content = "拍照或者相册:数量 ".$object->SendPicsInfo->Count;
break;
case "location_select":
$content = "发送位置:标签 ".$object->SendLocationInfo->Label;
break;
default:
$content = "receive a new event: ".$object->Event;
break;
}
if(is_array($content)){
$result = $this->transmitNews($object, $content);
}else{
$result = $this->transmitText($object, $content);
}
return $result;
}
//接收文本消息
private function receiveText($object) //object即前边解析出来的 postObj对象作为参数传递
{
$keyword = trim($object->Content); //将对象object中的Content属性值去掉空格后赋值给变量keyword(trim是去空格函数)
//多客服人工回复模式
if (strstr($keyword, "请问在吗") || strstr($keyword, "在线客服")){ //判断keyword中是否含有 "请问在吗"或 "在线客服"
$result = $this->transmitService($object); //去执行transmitService函数
return $result;
}
//自动回复模式
if (strstr($keyword, "文本")){ //判断keyword中是否包含 "文本"
$content = "这是个文本消息"; //给变量content赋值
}else if (strstr($keyword, "表情")){
$content = "微笑:/::)\n乒乓:/:oo\n中国:".$this->bytes_to_emoji(0x1F1E8).$this->bytes_to_emoji(0x1F1F3)."\n仙人掌:".$this->bytes_to_emoji(0x1F335);
}else if (strstr($keyword, "单图文")){
$content = array(); //定义数组content
$content[] = array("Title"=>"单图文标题", "Description"=>"单图文内容", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
}else if (strstr($keyword, "图文") || strstr($keyword, "多图文")){ //加$content[] 表示二维数组,此二维数组中只有一个元素做为一维
$content = array(); //下边出现几个$content[]就代表此二维数组中的第一维有几个元素,而=>符号是给第二维的元素中指定下标(四个下标分别为Title、Description、PicUrl、Url)
$content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
$content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
$content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
}else if (strstr($keyword, "音乐")){
$content = array(); //后边没有content[]就代表content只是个一维数组
$content = array("Title"=>"最炫民族风", "Description"=>"歌手:凤凰传奇", "MusicUrl"=>"http://mascot-music.stor.sinaapp.com/zxmzf.mp3", "HQMusicUrl"=>"http://mascot-music.stor.sinaapp.com/zxmzf.mp3");
}else{
$content = date("Y-m-d H:i:s",time())."\n\n".'<a href="http://m.cnblogs.com/?u=txw1958">技术支持 方倍工作室</a>';
}
if(is_array($content)){ //判断content是否存在,可能是数组也可能是字符串变量
if (isset($content[0])){ //判断如果是二维数组
$result = $this->transmitNews($object, $content);
}else if (isset($content['MusicUrl'])){ //判断如果是一维数组并且有以MusicUrl为下标的元素
$result = $this->transmitMusic($object, $content);
}
}else{
$result = $this->transmitText($object, $content); //前边已经判断过了数组的情况,只剩下content为文本的情况
}
return $result;
}
//接收图片消息
private function receiveImage($object)
{
$content = array("MediaId"=>$object->MediaId);
$result = $this->transmitImage($object, $content);
return $result;
}
//接收位置消息
private function receiveLocation($object)
{ //如果传过来的object对象是一个位置信息类的对象,其本身就带有Location_Y、Location_X、Scale、Labe等相关属性
$content = "你发送的是位置,经度为:".$object->Location_Y.";纬度为:".$object->Location_X.";缩放级别为:".$object->Scale.";位置为:".$object->Label;
$result = $this->transmitText($object, $content);
return $result;
}
//接收语音消息
private function receiveVoice($object)
{
if (isset($object->Recognition) && !empty($object->Recognition)){
$content = "你刚才说的是:".$object->Recognition;
$result = $this->transmitText($object, $content);
}else{
$content = array("MediaId"=>$object->MediaId);
$result = $this->transmitVoice($object, $content);
}
return $result;
}
//接收视频消息
private function receiveVideo($object)
{
$content = "上传视频类型:".$object->MsgType;
$result = $this->transmitText($object, $content);
return $result;
}
//接收链接消息
private function receiveLink($object)
{
$content = "你发送的是链接,标题为:".$object->Title.";内容为:".$object->Description.";链接地址为:".$object->Url;
$result = $this->transmitText($object, $content);
return $result;
}
//回复文本消息
private function transmitText($object, $content) //contentj是前台传过来的字符串变量,不是数组
{
if (!isset($content) || empty($content)){
return "";
}
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName> //%s是指代字符串,在sprintf格式化字符串里会设置对应的字符串的值
<FromUserName><![CDATA[%s]]></FromUserName> //![CDATA[]]意思是在中间方括号中的内容不让php进行解析,保持其中字符串原样输出
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
//sprintf格式化字符串,第一个参数是要被格式化的字符串,后边参数一一对应指代的字符串%s的内容
return $result;
}
//回复图文消息
private function transmitNews($object, $newsArray) //newsArray用来接收前边传过来的content二维数组(单图文或多图文)
{
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> //<Articles></Articles>等都是微信定义的格式,由微信平台来解析与PHP语法无任何关系
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
return $result;
}
//回复音乐消息
private function transmitMusic($object, $musicArray) //musicArray用来接收前边传过来的content一维数组(音乐)
{
if(!is_array($musicArray)){
return "";
}
$itemTpl = "<Music>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<MusicUrl><![CDATA[%s]]></MusicUrl>
<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";
$item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复图片消息
private function transmitImage($object, $imageArray) //imageArray用来接收前边传过来的content一维数组(图片)
{
$itemTpl = "<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>";
$item_str = sprintf($itemTpl, $imageArray['MediaId']);
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
$item_str //就相当于回复文本消息中的 <Content><![CDATA[%s]]></Content>,实际要显示的内容
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复语音消息
private function transmitVoice($object, $voiceArray)
{
$itemTpl = "<Voice>
<MediaId><![CDATA[%s]]></MediaId>
</Voice>";
$item_str = sprintf($itemTpl, $voiceArray['MediaId']);
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
$item_str
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复视频消息
private function transmitVideo($object, $videoArray)
{
$itemTpl = "<Video>
<MediaId><![CDATA[%s]]></MediaId>
<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
</Video>";
$item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[video]]></MsgType>
$item_str
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复多客服消息
private function transmitService($object)
{
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复第三方接口消息
private function relayPart3($url, $rawData)
{
$headers = array("Content-Type: text/xml; charset=utf-8");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $rawData);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
//字节转Emoji表情
function bytes_to_emoji($cp)
{
if ($cp > 0x10000){ # 4 bytes
return chr(0xF0 | (($cp & 0x1C0000) >> 18)).chr(0x80 | (($cp & 0x3F000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
}else if ($cp > 0x800){ # 3 bytes
return chr(0xE0 | (($cp & 0xF000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
}else if ($cp > 0x80){ # 2 bytes
return chr(0xC0 | (($cp & 0x7C0) >> 6)).chr(0x80 | ($cp & 0x3F));
}else{ # 1 byte
return chr($cp);
}
}
//日志记录
private function logger($log_content)
{
if(isset($_SERVER['HTTP_APPNAME'])){ //SAE
sae_set_display_errors(false);
sae_debug($log_content);
sae_set_display_errors(true);
}else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
$max_size = 1000000;
$log_filename = "log.xml";
if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
file_put_contents($log_filename, date('Y-m-d H:i:s')." ".$log_content."\r\n", FILE_APPEND);
}
}
}
?>
/*
方倍工作室 http://www.fangbei.org/
CopyRight 2015 All Rights Reserved
*/
header('Content-type:text');
define("TOKEN", "weixin"); //定义TOKEN=weixin
$wechatObj = new wechatCallbackapiTest(); //新建一个wechatCallbackapiTest类型对象wechatObj
if (!isset($_GET['echostr'])) { //echostr不存在的话去执行wechatObj类中的responseMsg函数
$wechatObj->responseMsg();
}else{
$wechatObj->valid(); //echostr存在的话去执行wechatObj类中的valid函数
}
class wechatCallbackapiTest
{
//验证签名
public function valid()
{
$echoStr = $_GET["echostr"]; //从前台url中取出参数echostr的值再赋值给变量echoStr()
$signature = $_GET["signature"]; //从前台url中取出参数signature的值再赋值给变量signature(签名)
$timestamp = $_GET["timestamp"]; //从前台url中取出参数timestamp的值再赋值给变量timestamp(时间戳)
$nonce = $_GET["nonce"]; //从前台url中取出参数nonce的值再赋值给变量nonce(随机数、临时数)
$token = TOKEN; //将TOKEN赋值给变量token(就是固定值“weixin”)
$tmpArr = array($token, $timestamp, $nonce); //将被赋值的三个变量$token, $timestamp, $nonce组成数组tmpArr
sort($tmpArr, SORT_STRING); //给数组tmpArr中三个元素进行排序
$tmpStr = implode($tmpArr); //将数组tmpArr通过 implode函数解析成字符串并赋值给tmpStr
$tmpStr = sha1($tmpStr); //将字符串tmpStr通过sha1函数进行加密后重新赋值给tmpStr
if($tmpStr == $signature){ //判断签名的字符串signature与新生成的tmpStr字符串相等的话输出echoStr
echo $echoStr;
exit;
}
}
//响应消息
public function responseMsg()
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //取post表单类数据中的所有值并赋值给postStr变量
if (!empty($postStr)){
$this->logger("R \r\n".$postStr); //通过日志函数logger记录日志,. 用在两个字符串之间是连接字符串的意思相当于+号
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); //将字符串变量postStr按SimpleXMLElement格式只取CDATA标签中的值并转化成对象型变量$postObj
$RX_TYPE = trim($postObj->MsgType); //获取对象型变量postObj的MsgType属性值并赋值给RX_TYPE变量
//消息类型分离
switch ($RX_TYPE)
{ //根据前边被赋过值的RX_TYPE变量来判断去执行的不同的函数
case "event":
$result = $this->receiveEvent($postObj);
break;
case "text":
$result = $this->receiveText($postObj);
break;
case "image":
$result = $this->receiveImage($postObj);
break;
case "location":
$result = $this->receiveLocation($postObj);
break;
case "voice":
$result = $this->receiveVoice($postObj);
break;
case "video":
case "shortvideo":
$result = $this->receiveVideo($postObj);
break;
case "link":
$result = $this->receiveLink($postObj);
break;
default:
$result = "unknown msg type: ".$RX_TYPE;
break;
}
$this->logger("T \r\n".$result);
echo $result;
}else {
echo "";
exit;
}
}
//接收事件消息
private function receiveEvent($object)
{
$content = "";
switch ($object->Event)
{
case "subscribe":
$content = "欢迎使用方倍工作室微信开发入门教程Demo\n请回复以下关键字:文本 表情 单图文 多图文 音乐\n请按住说话 或 点击 + 再分别发送以下内容:语音 图片 小视频 我的收藏 位置";
$content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
//str_replace函数将$object->EventKey中所有的qrscene_都替换成空
$content .= "\n\n".'<a href="http://m.cnblogs.com/?u=txw1958">技术支持 方倍工作室</a>';
break;
case "unsubscribe":
$content = "取消关注";
break;
case "CLICK":
switch ($object->EventKey)
{
case "COMPANY":
$content = array();
$content[] = array("Title"=>"方倍工作室", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
break;
default:
$content = "点击菜单:".$object->EventKey;
break;
}
break;
case "VIEW":
$content = "跳转链接 ".$object->EventKey;
break;
case "SCAN":
$content = "扫描场景 ".$object->EventKey;
break;
case "LOCATION":
$content = "上传位置:纬度 ".$object->Latitude.";经度 ".$object->Longitude;
break;
case "scancode_waitmsg":
if ($object->ScanCodeInfo->ScanType == "qrcode"){
$content = "扫码带提示:类型 二维码 结果:".$object->ScanCodeInfo->ScanResult;
}else if ($object->ScanCodeInfo->ScanType == "barcode"){
$codeinfo = explode(",",strval($object->ScanCodeInfo->ScanResult));
//strval函数将$object->ScanCodeInfo->ScanResult转化成字符串;explode将字符串按其中的逗号分隔成若干的元素,最后赋值给数组codeinfo
$codeValue = $codeinfo[1]; //数组中第一个元素的值赋给字符串变量codeValue
$content = "扫码带提示:类型 条形码 结果:".$codeValue;
}else{
$content = "扫码带提示:类型 ".$object->ScanCodeInfo->ScanType." 结果:".$object->ScanCodeInfo->ScanResult;
}
break;
case "scancode_push":
$content = "扫码推事件";
break;
case "pic_sysphoto":
$content = "系统拍照";
break;
case "pic_weixin":
$content = "相册发图:数量 ".$object->SendPicsInfo->Count;
break;
case "pic_photo_or_album":
$content = "拍照或者相册:数量 ".$object->SendPicsInfo->Count;
break;
case "location_select":
$content = "发送位置:标签 ".$object->SendLocationInfo->Label;
break;
default:
$content = "receive a new event: ".$object->Event;
break;
}
if(is_array($content)){
$result = $this->transmitNews($object, $content);
}else{
$result = $this->transmitText($object, $content);
}
return $result;
}
//接收文本消息
private function receiveText($object) //object即前边解析出来的 postObj对象作为参数传递
{
$keyword = trim($object->Content); //将对象object中的Content属性值去掉空格后赋值给变量keyword(trim是去空格函数)
//多客服人工回复模式
if (strstr($keyword, "请问在吗") || strstr($keyword, "在线客服")){ //判断keyword中是否含有 "请问在吗"或 "在线客服"
$result = $this->transmitService($object); //去执行transmitService函数
return $result;
}
//自动回复模式
if (strstr($keyword, "文本")){ //判断keyword中是否包含 "文本"
$content = "这是个文本消息"; //给变量content赋值
}else if (strstr($keyword, "表情")){
$content = "微笑:/::)\n乒乓:/:oo\n中国:".$this->bytes_to_emoji(0x1F1E8).$this->bytes_to_emoji(0x1F1F3)."\n仙人掌:".$this->bytes_to_emoji(0x1F335);
}else if (strstr($keyword, "单图文")){
$content = array(); //定义数组content
$content[] = array("Title"=>"单图文标题", "Description"=>"单图文内容", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
}else if (strstr($keyword, "图文") || strstr($keyword, "多图文")){ //加$content[] 表示二维数组,此二维数组中只有一个元素做为一维
$content = array(); //下边出现几个$content[]就代表此二维数组中的第一维有几个元素,而=>符号是给第二维的元素中指定下标(四个下标分别为Title、Description、PicUrl、Url)
$content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
$content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
$content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
}else if (strstr($keyword, "音乐")){
$content = array(); //后边没有content[]就代表content只是个一维数组
$content = array("Title"=>"最炫民族风", "Description"=>"歌手:凤凰传奇", "MusicUrl"=>"http://mascot-music.stor.sinaapp.com/zxmzf.mp3", "HQMusicUrl"=>"http://mascot-music.stor.sinaapp.com/zxmzf.mp3");
}else{
$content = date("Y-m-d H:i:s",time())."\n\n".'<a href="http://m.cnblogs.com/?u=txw1958">技术支持 方倍工作室</a>';
}
if(is_array($content)){ //判断content是否存在,可能是数组也可能是字符串变量
if (isset($content[0])){ //判断如果是二维数组
$result = $this->transmitNews($object, $content);
}else if (isset($content['MusicUrl'])){ //判断如果是一维数组并且有以MusicUrl为下标的元素
$result = $this->transmitMusic($object, $content);
}
}else{
$result = $this->transmitText($object, $content); //前边已经判断过了数组的情况,只剩下content为文本的情况
}
return $result;
}
//接收图片消息
private function receiveImage($object)
{
$content = array("MediaId"=>$object->MediaId);
$result = $this->transmitImage($object, $content);
return $result;
}
//接收位置消息
private function receiveLocation($object)
{ //如果传过来的object对象是一个位置信息类的对象,其本身就带有Location_Y、Location_X、Scale、Labe等相关属性
$content = "你发送的是位置,经度为:".$object->Location_Y.";纬度为:".$object->Location_X.";缩放级别为:".$object->Scale.";位置为:".$object->Label;
$result = $this->transmitText($object, $content);
return $result;
}
//接收语音消息
private function receiveVoice($object)
{
if (isset($object->Recognition) && !empty($object->Recognition)){
$content = "你刚才说的是:".$object->Recognition;
$result = $this->transmitText($object, $content);
}else{
$content = array("MediaId"=>$object->MediaId);
$result = $this->transmitVoice($object, $content);
}
return $result;
}
//接收视频消息
private function receiveVideo($object)
{
$content = "上传视频类型:".$object->MsgType;
$result = $this->transmitText($object, $content);
return $result;
}
//接收链接消息
private function receiveLink($object)
{
$content = "你发送的是链接,标题为:".$object->Title.";内容为:".$object->Description.";链接地址为:".$object->Url;
$result = $this->transmitText($object, $content);
return $result;
}
//回复文本消息
private function transmitText($object, $content) //contentj是前台传过来的字符串变量,不是数组
{
if (!isset($content) || empty($content)){
return "";
}
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName> //%s是指代字符串,在sprintf格式化字符串里会设置对应的字符串的值
<FromUserName><![CDATA[%s]]></FromUserName> //![CDATA[]]意思是在中间方括号中的内容不让php进行解析,保持其中字符串原样输出
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
//sprintf格式化字符串,第一个参数是要被格式化的字符串,后边参数一一对应指代的字符串%s的内容
return $result;
}
//回复图文消息
private function transmitNews($object, $newsArray) //newsArray用来接收前边传过来的content二维数组(单图文或多图文)
{
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> //<Articles></Articles>等都是微信定义的格式,由微信平台来解析与PHP语法无任何关系
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
return $result;
}
//回复音乐消息
private function transmitMusic($object, $musicArray) //musicArray用来接收前边传过来的content一维数组(音乐)
{
if(!is_array($musicArray)){
return "";
}
$itemTpl = "<Music>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<MusicUrl><![CDATA[%s]]></MusicUrl>
<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";
$item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复图片消息
private function transmitImage($object, $imageArray) //imageArray用来接收前边传过来的content一维数组(图片)
{
$itemTpl = "<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>";
$item_str = sprintf($itemTpl, $imageArray['MediaId']);
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
$item_str //就相当于回复文本消息中的 <Content><![CDATA[%s]]></Content>,实际要显示的内容
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复语音消息
private function transmitVoice($object, $voiceArray)
{
$itemTpl = "<Voice>
<MediaId><![CDATA[%s]]></MediaId>
</Voice>";
$item_str = sprintf($itemTpl, $voiceArray['MediaId']);
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
$item_str
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复视频消息
private function transmitVideo($object, $videoArray)
{
$itemTpl = "<Video>
<MediaId><![CDATA[%s]]></MediaId>
<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
</Video>";
$item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[video]]></MsgType>
$item_str
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复多客服消息
private function transmitService($object)
{
$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//回复第三方接口消息
private function relayPart3($url, $rawData)
{
$headers = array("Content-Type: text/xml; charset=utf-8");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $rawData);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
//字节转Emoji表情
function bytes_to_emoji($cp)
{
if ($cp > 0x10000){ # 4 bytes
return chr(0xF0 | (($cp & 0x1C0000) >> 18)).chr(0x80 | (($cp & 0x3F000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
}else if ($cp > 0x800){ # 3 bytes
return chr(0xE0 | (($cp & 0xF000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
}else if ($cp > 0x80){ # 2 bytes
return chr(0xC0 | (($cp & 0x7C0) >> 6)).chr(0x80 | ($cp & 0x3F));
}else{ # 1 byte
return chr($cp);
}
}
//日志记录
private function logger($log_content)
{
if(isset($_SERVER['HTTP_APPNAME'])){ //SAE
sae_set_display_errors(false);
sae_debug($log_content);
sae_set_display_errors(true);
}else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
$max_size = 1000000;
$log_filename = "log.xml";
if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
file_put_contents($log_filename, date('Y-m-d H:i:s')." ".$log_content."\r\n", FILE_APPEND);
}
}
}
?>