加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

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

发布时间:2020-05-25 13:03:10 所属栏目:PHP 来源:互联网
导读:这篇文章主要介绍了php微信公众号开发第三课,php实现简单微信文本通讯,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

public function __construct($token,$debug)
{
$this->token = $token;
$this->debug = $debug;
}
//获得用户发过来的消息(消息内容和消息类型 )
public function getMsg()
{
$postStr = $GLOBALS["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 ? 1 : 0;
$textTpl = "

msg['FromUserName']}]]> msg['ToUserName']}]]> {$CreateTime} %s "; return sprintf($textTpl,$text,$FuncFlag); }

//根据数组参数回复图文消息
public function makeNews($newsData=array())
{
$CreateTime = time();
$FuncFlag = $this->setFlag ? 1 : 0;
$newTplHeader = "

msg['FromUserName']}]]> msg['ToUserName']}]]> {$CreateTime} %s"; $newTplItem = " <![CDATA[%s]]> "; $newTplFoot = " %s "; $Content = ''; $itemsCount = count($newsData['items']); $itemsCount = $itemsCount < 10 ? $itemsCount : 10;//微信公众平台图文回复的消息一次最多10条 if ($itemsCount) { foreach ($newsData['items'] as $key => $item) { if ($key<=9) { $Content .= sprintf($newTplItem,$item['title'],$item['description'],$item['picurl'],$item['url']); } } } $header = sprintf($newTplHeader,$newsData['content'],$itemsCount); $footer = sprintf($newTplFoot,$FuncFlag); return $header . $Content . $footer; } public function reply($data) {

echo $data;
}
public function valid()
{
if ($this->checkSignature()) {
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->token,$timestamp,$nonce);
sort($tmpArr);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );

if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}

}
?>

接着正式开发,使用百度SVN地址,创建weixinapi.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);

这样就实现了一个例子,第一次关注事件回复,非文本回复,以及文本回复,这里文本回复是你输入什么就返回什么。

具体实现功能就写在文本回复里面。

其他的功能暂时不做,具体开发下节再说。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读