PHP前端开发

php微信公众号开发(3)php实现简单微信文本通讯

百变鹏仔 5小时前 #前端问答
文章标签 公众

微信开发前,需要设置token,这个是微信设置的,可以任意设置,用来实现微信通讯。这里有一个别人写的微信类,功能还比较不错。weixin.class.php代码如下

<?php class Weixin{ public $token = &#39;&#39;;//token public $debug = false;//是否debug的状态标示,方便我们在调试的时候记录一些中间数据 public $setFlag = false; public $msgtype = &#39;text&#39;; //(&#39;text&#39;,&#39;image&#39;,&#39;location&#39;) public $msg = array();  public function __construct($token,$debug) { $this->token = $token; $this-&gt;debug = $debug; }//获得用户发过来的消息(消息内容和消息类型 ) public function getMsg() { $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];  if (!empty($postStr)) {  $this-&gt;msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);  $this-&gt;msgtype = strtolower($this-&gt;msg['MsgType']); } }//回复文本消息 public function makeText($text='') { $CreateTime = time(); $FuncFlag = $this-&gt;setFlag ? 1 : 0; $textTpl = "<xml>  <tousername>msg['FromUserName']}]]&gt;</tousername>  <fromusername>msg['ToUserName']}]]&gt;</fromusername>  <createtime>{$CreateTime}</createtime>  <msgtype></msgtype>  <content></content>  <funcflag>%s</funcflag>  </xml>"; return sprintf($textTpl,$text,$FuncFlag); } //根据数组参数回复图文消息 public function makeNews($newsData=array()) { $CreateTime = time(); $FuncFlag = $this-&gt;setFlag ? 1 : 0; $newTplHeader = "<xml>  <tousername>msg['FromUserName']}]]&gt;</tousername>  <fromusername>msg['ToUserName']}]]&gt;</fromusername>  <createtime>{$CreateTime}</createtime>  <msgtype></msgtype>  <content></content>  <articlecount>%s</articlecount><articles>"; $newTplItem = "<item>  <title></title>  <description></description>  <picurl></picurl>  <url></url>  </item>"; $newTplFoot = "</articles>  <funcflag>%s</funcflag>  </xml>"; $Content = ''; $itemsCount = count($newsData['items']); $itemsCount = $itemsCount  $item) {  if ($keycheckSignature()) {  if( $_SERVER['REQUEST_METHOD']=='GET' )  {  echo $_GET['echostr'];  exit;  } }else{    exit; } } private function checkSignature() { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"];  $tmpArr = array($this-&gt;token, $timestamp, $nonce); sort($tmpArr); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr );  if( $tmpStr == $signature ){  return true; }else{  return false; } } }?&gt;

接着正式开发,使用百度SVN地址,创建weixinapi.php文件,这个根据你后台设置名称。

<?php define("TOKEN", "");define(&#39;DEBUG&#39;, false);include_once(&#39;weixin.class.php&#39;);require_once("db.php");  $weixin = new Weixin(TOKEN,DEBUG);//实例化$weixin->getMsg();$type = $weixin-&gt;msgtype;//消息类型$keyword = $weixin-&gt;msg['Content'];//获取的文本if ($type==='text') {$reply = $weixin-&gt;makeText($key);}elseif($type==='event'){//第一次关注推送事件 $reply = $weixin-&gt;makeText("欢迎关注");}else{//其他类型$reply = $weixin-&gt;makeText("暂时没有图片,声音,地理位置等功能,后续开发会增加,感谢你关注");}$weixin-&gt;reply($reply);

这样就实现了一个例子,第一次关注事件回复,非文本回复,以及文本回复,这里文本回复是你输入什么就返回什么。
具体实现功能就写在文本回复里面。
其他的功能暂时不做,具体开发下节再说。