好久就想实现这个功能了,可是一直没心情,好在收到网易实习的offer,于是心情大好,实现了这个功能来和大家共享。大家可以先看效果吧:只要关注微信公众帐号say_magic,
然后打开网址http://www.saymagic.cn/weixin/wall.php,在公众号里回复:上墙+您要说的话,您就会发现您说的话会同步到上面的网址上。
整个流程大概是这样:
公众号的后台接收到消息并将消息存入数据库,而前台呢,则使用js的setTimeout函数进行循环的使用ajax向后台get数据来获取数据库的最新数据,当明白整个原理后,就显得很简单,接下来看一下主要的代码:
wall.php(微信墙页面 )
立即学习“PHP免费学习笔记(深入)”;
微信墙 query($wxQuery); while ($wxRow=mysql_fetch_row($wxResult)) { $lastID or $lastID = $wxRow[0];//0代表数据库中的id,这个要和你自己数据库相对应 $content = $wxRow[4];//4也是一样的 echo "
",$content,"
\n"; } $lastID = (int)$lastID; ?>
mysql操作文件sql.php:
db_host = $db_host;
$this->db_user = $db_user;
$this->db_pwd = $db_pwd;
$this->db_database = $db_database;
$this->conn = $conn;
$this->coding = $coding;
$this->connect();
}
/*数据库连接*/
public function connect() {
if ($this->conn == "pconn") {
//永久链接
$this->conn = mysql_pconnect($this->db_host, $this->db_user, $this->db_pwd);
} else {
//即使链接
$this->conn = mysql_connect($this->db_host, $this->db_user, $this->db_pwd);
}
if (!mysql_select_db($this->db_database, $this->conn)) {
if ($this->show_error) {
$this->show_error("数据库不可用:", $this->db_database);
}
}
//mysql_query("SET NAMES $this->coding");
}
/*数据库执行语句,可执行查询添加修改删除等任何sql语句*/
public function query($sql) {
if ($sql == "") {
$this->show_error("SQL语句错误:", "SQL查询语句为空");
}
$this->sql = $sql;
$result = mysql_query($this->sql, $this->conn);
if (!$result) {
//调试中使用,sql语句出错时会自动打印出来
if ($this->show_error) {
$this->show_error("错误SQL语句:", $this->sql);
}
} else {
$this->result = $result;
}
return $this->result;
}
}
?>
不断从数据库获取最新数据的文件message.php.
1000) {
die("possible deep recursion attack");
}
foreach ($array as $key => $value) {
if (is_array($value)) {
arrayRecursive($array[$key], $function, $apply_to_keys_also);
} else {
$array[$key] = $function($value);
}
if ($apply_to_keys_also && is_string($key)) {
$new_key = $function($key);
if ($new_key != $key) {
$array[$new_key] = $array[$key];
unset($array[$key]);
}
}
}
$recursive_counter--;
}
function JSON($array) {
arrayRecursive($array, "urlencode", true);
$json = json_encode($array);
return urldecode($json);
}
$lastID = (int) $_GET["lastID"];
include_once("sql.php");
$backValue=array();
$wxQuery = "SELECT * FROM wx_note WHERE id > ".$lastID." ORDER BY id LIMIT 3";
$wxResult = $mysql->query($wxQuery);
while ($wxRow=mysql_fetch_row($wxResult)) {
$recordID = $wxRow[0];
$content = $wxRow[4];
//$xml=$content;
$backValue[$recordID ] = $content;
}
echo JSON($backValue);
?>
最后,如果需要的话,还有背景图片:/program/UploadPic/2014-3/2014317135337634.jpg.
当然,这里说的只是后端的部分,在处理微信消息上,你还需要把收到的消息存入数据库,这应该没什么难度,就不放代码了。这里一定要记得和刚才操作的方法中的数据格式相对应,这是最容易出错的了。好的,如果有什么疑问的话,欢迎留言。
转载请注明:我的原博客链接http://blog.saymagic.cn/blog.php?id=58











