responseMsg();
}else{
$wechatObj->valid();
}
class wechatCallbackapiTest
{
//验证签名
public function valid()
{
$echoStr = $_GET["echostr"];
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$tmpArr = array(TOKEN, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
if($tmpStr == $signature){
// echo $echoStr;
exit;
}
}
//响应消息
public function responseMsg()
{
$timestamp = $_GET['timestamp'];
$nonce = $_GET["nonce"];
$msg_signature = $_GET['msg_signature'];
$encrypt_type = (isset($_GET['encrypt_type']) && ($_GET['encrypt_type'] == 'aes')) ? "aes" : "raw";
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!empty($postStr)){
//解密
if ($encrypt_type == 'aes'){
$pc = new WXBizMsgCrypt(TOKEN, EncodingAESKey, AppID);
$this->logger(" D \r\n".$postStr);
$decryptMsg = ""; //解密后的明文
$errCode = $pc->DecryptMsg($msg_signature, $timestamp, $nonce, $postStr, $decryptMsg);
$postStr = $decryptMsg;
}
$this->logger(" R \r\n".$postStr);
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$RX_TYPE = trim($postObj->MsgType);
$ComponentVerifyTicket = trim($postObj->ComponentVerifyTicket);
$this->logger(" T: \r\n".$ComponentVerifyTicket);
if($ComponentVerifyTicket<>''){//保存即可.
$res=file_put_contents("json/VerifyTicket.json", $ComponentVerifyTicket);
if (ob_get_level() == 0) ob_start();
ob_implicit_flush(true);
ob_clean();
header("Content-type: text/plain");
#log_msg(headers_list());
echo("success");
ob_flush();
flush();
ob_end_flush();
die();
exit();
$data_string='{
"component_appid":"'.AppID.'" ,
"component_appsecret": "'.Appsecret.'",
"component_verify_ticket": "'.$ComponentVerifyTicket.'"
}';
// $bbb = http_post_data("https://api.weixin.qq.com/cgi-bin/component/api_component_token", $data_string);
$this->logger(" B \r\n".$bbb);
// exit;
//echo "sucsess";
}
//消息类型分离
switch ($RX_TYPE)
{
case "event":
$result = $this->receiveEvent($postObj);
break;
case "text":
$result = $this->receiveText($postObj);
break;
}
$this->logger(" Re: \r\n".$RX_TYPE.$result);
//加密
if ($encrypt_type == 'aes'){
$encryptMsg = ''; //加密后的密文
$errCode = $pc->encryptMsg($result, $timeStamp, $nonce, $encryptMsg);
$result = $encryptMsg;
$this->logger(" E \r\n".$result);
}
echo $result;
}else {
echo "";
exit;
}
}
//接收事件消息
private function receiveEvent($object)
{
$content = "";
switch ($object->Event)
{
case "subscribe":
$content = "欢迎关注方倍工作室 ";
break;
}
$result = $this->transmitText($object, $content);
return $result;
}
//接收文本消息
private function receiveText($object)
{
$keyword = trim($object->Content);
if (strstr($keyword, "文本")){
$content = "这是个文本消息";
}else if (strstr($keyword, "单图文")){
$content = array();
$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 = array();
$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 = array("Title"=>"最炫民族风", "Description"=>"歌手:凤凰传奇", "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3", "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3");
}else{
$content = date("Y-m-d H:i:s",time())."\n".$object->FromUserName."\n技术支持 方倍工作室";
}
if(is_array($content)){
if (isset($content[0])){
$result = $this->transmitNews($object, $content);
}else if (isset($content['MusicUrl'])){
$result = $this->transmitMusic($object, $content);
}
}else{
$result = $this->transmitText($object, $content);
}
return $result;
}
//回复文本消息
private function transmitText($object, $content)
{
$xmlTpl = "
%s
";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
return $result;
}
//回复图文消息
private function transmitNews($object, $newsArray)
{
if(!is_array($newsArray)){
return;
}
$itemTpl = " -
";
$item_str = "";
foreach ($newsArray as $item){
$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
}
$xmlTpl = "
%s
%s
$item_str
";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
return $result;
}
//回复音乐消息
private function transmitMusic($object, $musicArray)
{
$itemTpl = "
";
$item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
$xmlTpl = "
%s
$item_str
";
$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
return $result;
}
//日志记录
public 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 = 500000;
$log_filename = "log_wx.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);
}
}
public function getToken($appid,$appsecret,$jsonid){
$file = file_get_contents("json/{$jsonid}_token.json",true);
$result = json_decode($file,true);
if (time() > $result['expires']){
$data = array();
$data['access_token'] = getNewToken($appid,$appsecret);
$data['expires']=time()+7200;
$jsonStr = json_encode($data);
$fp = fopen("json/{$jsonid}_token.json", "w");
fwrite($fp, $jsonStr);
fclose($fp);
return $data['access_token'];
}else{
return $result['access_token'];
}
}
public function getNewToken($appid,$appsecret){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
$access_token_Arr = https_request($url);
return $access_token_Arr['access_token'];
}
public function https_request ($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$out = curl_exec($ch);
curl_close($ch);
return json_decode($out,true);
}
public function http_post_data($url, $data_string) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($data_string))
);
ob_start();
curl_exec($ch);
$return_content = ob_get_contents();
//echo $return_content."
";
ob_end_clean();
$return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// return array($return_code, $return_content);
return $return_content;
}
}
?>