php微信公众号开发(3)php实现简单微信文本通讯
(编辑:jimmy 日期: 2025/10/24 浏览:3 次 )
微信开发前,需要设置token,这个是微信设置的,可以任意设置,用来实现微信通讯。这里有一个别人写的微信类,功能还比较不错。weixin.class.php代码如下
<"HTTP_RAW_POST_DATA"];
if (!empty($postStr)) {
$this->msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$this->msgtype = strtolower($this->msg['MsgType']);
}
}
//回复文本消息
public function makeText($text='')
{
$CreateTime = time();
$FuncFlag = $this->setFlag "<xml>
<ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName>
<FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName>
<CreateTime>{$CreateTime}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>%s</FuncFlag>
</xml>";
return sprintf($textTpl,$text,$FuncFlag);
}
//根据数组参数回复图文消息
public function makeNews($newsData=array())
{
$CreateTime = time();
$FuncFlag = $this->setFlag "<xml>
<ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName>
<FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName>
<CreateTime>{$CreateTime}</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[%s]]></Content>
<ArticleCount>%s</ArticleCount><Articles>";
$newTplItem = "<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>";
$newTplFoot = "</Articles>
<FuncFlag>%s</FuncFlag>
</xml>";
$Content = '';
$itemsCount = count($newsData['items']);
$itemsCount = $itemsCount < 10 "signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$tmpArr = array($this->token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}
"htmlcode">
<"TOKEN", "");
define('DEBUG', false);
include_once('weixin.class.php');
require_once("db.php");
$weixin = new Weixin(TOKEN,DEBUG);//实例化
$weixin->getMsg();
$type = $weixin->msgtype;//消息类型
$keyword = $weixin->msg['Content'];//获取的文本
if ($type==='text') {
$reply = $weixin->makeText($key);
}elseif($type==='event'){//第一次关注推送事件
$reply = $weixin->makeText("欢迎关注");
}else{//其他类型
$reply = $weixin->makeText("暂时没有图片,声音,地理位置等功能,后续开发会增加,感谢你关注");
}
$weixin->reply($reply);
这样就实现了一个例子,第一次关注事件回复,非文本回复,以及文本回复,这里文本回复是你输入什么就返回什么。
具体实现功能就写在文本回复里面。
其他的功能暂时不做,具体开发下节再说。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇:php微信公众号开发(2)百度BAE搭建和数据库使用