微信图文消息回复

1.开发者只能回复1条图文消息;其余场景最多可回复8条图文消息
2.foreach()遍历拼接
index.php

<?php
include './common.php';
//因为define的常量是全局的,所以放在该文件也是可以的
define('TOKEN','weixin');
$wechat = new weChat();

//如果echostr 存在则需要验证第三方服务器的真实性
if($_GET["echostr"]){
	$wechat->valid();
}else{
	$wechat->responseMeg();
}

common.php 这里重点看replyNews()方法

<?php

class weChat
{
	//验证消息,检验签名是否成功
	public function valid()
	{
		$echostr = $_GET["echostr"];
		if($this->checkSignature()){
			echo "$echostr";
		}else{
			echo 'error';
			exit;
		}
	}

	//检验签名
	public function checkSignature()
	{
		//第三方服务器与微信服务器进行消息接入,
		// https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html

		// 接收微信服务器发送的四个验证参数
		//加密签名
		        $signature = $_GET["signature"];
		//时间戳
		        $timestamp = $_GET["timestamp"];
		//随机数
		        $nonce = $_GET["nonce"];
		//随机字符串
		        $echostr = $_GET["echostr"];
		// TOKEN
		        // define('TOKEN','weixin');

		//1.进行字典序排序
		        $tmpArr = array(TOKEN, $timestamp, $nonce);
		    sort($tmpArr, SORT_STRING);
		//2.将三个参数字符串拼接成一个字符串进行sha1加密 
		        $tmpStr = implode( $tmpArr );
		    $tmpStr = sha1( $tmpStr );
		//3.开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
		        if( $tmpStr == $signature ){
		            // echo "$echostr";
		            return true;
		        }else{
		            return false;
		        }

	}


	//处理用户请求消息
	public function responseMeg()
	{
		//服务器接收微信POST发送的xml格式原生数据
	    // $postStr  = $GLOBALS['HTTP_RAW_POST_DATA'];
	        $postStr = file_get_contents("php://input");

	    if (!$postStr) {
	        echo "post data error";
	        exit;
	    }

		//将xml格式转对象形式输出  LIBXML_NOCDATA - 将 CDATA 设置为文本节点
		$postObj = simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);
		//处理消息的类型
		$MsgType = $postObj->MsgType;
		//根据xml对象与消息类型处理
		$this->checkMsgType($postObj,$MsgType);
	}

	//处理消息类型
	public function checkMsgType($postObj,$MsgType)
	{
		switch ($MsgType) {
			case 'text':
				//处理文本消息
				$this->receiveText($postObj);
				break;
			case 'image':
				//处理图片消息
				$this->receiveImage($postObj);
				break;
			default:
				
				break;
		}
	}

	//处理文本消息
	public function receiveText($postObj)
	{
		$Content = $postObj->Content;
		switch ($Content) {
			case '点歌':
				$str = "欢迎来到点歌系统\n";
				//遍历文件
				$files = scandir('music');
				$i = 1;
				foreach ($files as $key => $value) {
					if ($value !='.' && $value !='..') {
						$str .=$i.'-'.$value."\n";
						$i++;
					}
				
				}
				$str .="请输入对应的编号试听歌曲\n";
				$this->replyText($postObj,$str);
				break;
			case '笑话':
				$this->replyText($postObj,$str);
				break;
			case '新闻':
				$data=array(
					array(
						'Title'=>'3000万的故事',
						'Description'=>'3000万的颠沛流离',
						'PicUrl'=>'https://www.liuyuanshan.top/wechat/img/1.jpg',
						'Url'=>'http://www.baidu.com',
						),
					array(
						'Title'=>'3001万的故事',
						'Description'=>'3000万的颠沛流离',
						'PicUrl'=>'https://www.liuyuanshan.top/wechat/img/2.jpg',
						'Url'=>'http://www.baidu.com',
						),
					array(
						'Title'=>'3002万的故事',
						'Description'=>'3000万的颠沛流离',
						'PicUrl'=>'https://www.liuyuanshan.top/wechat/img/3.jpg',
						'Url'=>'http://www.baidu.com',
						),
					);
				$this->replyNews($postObj,$data);
				break;
			default:
				//正则匹配输入选择歌曲的数字
				if(preg_match('/^\d{1,2}$/',$Content)){
					//遍历文件
					$files = scandir('music');
					$i = 1;
					foreach ($files as $key => $value) {
						if ($value !='.' && $value !='..') {
							if($Content==$i){
								$data = array(
									'Title' => $value, 
									'Description'=>$value,
									'MusicUrl'=>'https://www.liuyuanshan.top/wechat/music/'.$value,
									'HQMusicUrl'=>'https://www.liuyuanshan.top/wechat/music/'.$value
								);
								$this->replyMusic($postObj,$data);

							}
							$i++;
						}
					
					}
				}
				break;
		}
	}

	//处理图片消息
	public function receiveImage($postObj)
	{
		$MediaId = $postObj->MediaId;
		$this->replyImage($postObj,$MediaId);
	}

	//回复文本消息
	public function replyText($postObj,$Content)
	{
		$xml = '<xml>
                  <ToUserName><![CDATA[%s]]></ToUserName>
                  <FromUserName><![CDATA[%s]]></FromUserName>
                  <CreateTime>%d</CreateTime>
                  <MsgType><![CDATA[text]]></MsgType>
                  <Content><![CDATA[%s]]></Content>
                </xml>';
        echo sprintf($xml,$postObj->FromUserName,$postObj->ToUserName,time(),$Content);
	}

	//回复图片消息
	public function replyImage($postObj,$MediaId)
	{	
		$xml = '<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%d</CreateTime>
                    <MsgType><![CDATA[image]]></MsgType>
                    <Image>
                      <MediaId><![CDATA[%s]]></MediaId>
                    </Image>
                  </xml>';
        echo sprintf($xml,$postObj->FromUserName,$postObj->ToUserName,time(),$MediaId);
	}

	//回复音乐消息
	public function replyMusic($postObj,$data)
	{
		$xml = '<xml>
				  <ToUserName><![CDATA[%s]]></ToUserName>
				  <FromUserName><![CDATA[%s]]></FromUserName>
				  <CreateTime>%d</CreateTime>
				  <MsgType><![CDATA[music]]></MsgType>
				  <Music>
				    <Title><![CDATA[%s]]></Title>
				    <Description><![CDATA[%s]]></Description>
				    <MusicUrl><![CDATA[%s]]></MusicUrl>
				    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
				  </Music>
				</xml>';
		echo sprintf($xml,$postObj->FromUserName,$postObj->ToUserName,time(),$data['Title'],$data['Description'],$data['MusicUrl'],$data['HQMusicUrl']);
	}

	//回复图文消息  这里似乎开者只能回复一条消息,其他场景最多可回复8条
	public function replyNews($postObj,$data)
	{
		//遍历拼接三遍
		foreach ($data as $key => $value) {
		    $str.="<item>
		              <Title><![CDATA[".$value["Title"]."]]></Title>
		              <Description><![CDATA[".$value["Description"]."]]></Description>
		              <PicUrl><![CDATA[".$value["PicUrl"]."]]></PicUrl>
		              <Url><![CDATA[".$value["Url"]."]]></Url>
		            </item>";
		}

		$xml = '<xml>
				  <ToUserName><![CDATA[%s]]></ToUserName>
				  <FromUserName><![CDATA[%s]]></FromUserName>
				  <CreateTime>%d</CreateTime>
				  <MsgType><![CDATA[news]]></MsgType>
				  <ArticleCount>'.count($data).'</ArticleCount>
				  <Articles>
				    '.$str.'
				  </Articles>
				</xml>';
			echo sprintf($xml,$postObj->FromUserName,$postObj->ToUserName,time());
	}
}

显示结果页
在这里插入图片描述

发布了161 篇原创文章 · 获赞 0 · 访问量 7415

猜你喜欢

转载自blog.csdn.net/weixin_39218464/article/details/105038899
今日推荐