微信公众平台-开发php入门demo

[开发者接口][1]

这里实现一个简单的回包功能。 目的在于,可以基于这个,开发出更强大的功能。 修改respMessage 函数,处理用户发来的Content,然后返回相应的数据到Content标签下。

如果接受消息,并不想有任何回复,则可以直接: echo “success”;

返回一个success 字符串,告诉微信,已经成功接收消息

class CWeiXin
{
		private $token="申请的token";
		private $xml=array();
		private $ToUserName;
		private $FromUserName;
		private $CreateTime;
		private $MsgType;
		private $Content;

		public function postMessage($message)
		{
				xml=(array)$xml;
				$this->ToUserName=$this->xml['ToUserName'];
				$this->FromUserName=$this->xml['FromUserName'];
				$this->CreateTime=$this->xml['CreateTime'];
				$this->MsgType=$this->xml['MsgType'];
				$this->Content=$this->xml['Content'];
		}
		public function respMessage()
		{
				$time=time();
				$touser=$this->FromUserName;
				$fromuser=$this->ToUserName;
				$content=$this->Content;
				$msg="
		<xml>
		<ToUserName><![CDATA[$touser]]></ToUserName>
		<FromUserName><![CDATA[$fromuser]]></FromUserName>
		<CreateTime>$time</CreateTime>
		<MsgType><![CDATA[text]]></MsgType>
		<Content><![CDATA[$content]]></Content>
		</xml>";
				echo $msg;
		}
		function checkSignature($token)
		{
				$signature = $_GET["signature"];
				$timestamp = $_GET["timestamp"];
				$nonce = $_GET["nonce"];
				$tmpArr = array($token, $timestamp, $nonce);
				sort($tmpArr, SORT_STRING);
				$tmpStr = implode( $tmpArr );
				$tmpStr = sha1( $tmpStr );
				if($tmpStr == $signature){
						return true;
				}else{
						return false;
				}
		}
		public function process(){
				if(!$this->checkSignature($this->token)){
						echo "error";
						return;
				}
				if($method=="GET"){
						echo $_GET['echostr'];
				}else{
						$body=file_get_contents('php://input');
						$this->postMessage($body);
						$this->respMessage();
				}
		}
};

$method=$_SERVER['REQUEST_METHOD'];

$weixin=new CWeiXin();
$weixin->process();

?>

开通基本流程:
[申请公众号][2]-》等待审核通过-》申请开发者-》填写url和token-》启用服务器




[1]:http://mp.weixin.qq.com/wiki/index.php
[2]:https://mp.weixin.qq.com/
humboldt Written by:

humboldt 的趣味程序园