微信公众平台消息接口开发-封装weixin.class.php

简介: 原文:微信公众平台消息接口开发-封装weixin.class.php一、封装weixin.class.php 由于微信公众平台的通信使用的是特定格式的XML数据,每次接受和回复都要去做一大堆的数据处理。
原文: 微信公众平台消息接口开发-封装weixin.class.php

一、封装weixin.class.php

由于微信公众平台的通信使用的是特定格式的XML数据,每次接受和回复都要去做一大堆的数据处理。

我们就考虑在这个基础上做一次封装,weixin.class.php,代码如下:

<?php
class Weixin
{
    public $token = '';//token
    public $debugfalse;//是否debug的状态标示,方便我们在调试的时候记录一些中间数据
    public $setFlag = false;
    public $msgtype = 'text';   //('text','image','location')
    public $msg = array();
 
    public function __construct($token,$debug)
    {
        $this->token = $token;
        $this->debug = $debug;
    }<br>     //获得用户发过来的消息(消息内容和消息类型  )
    public function getMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if ($this->debug) {
                        $this->write_log($postStr);
        }
        if (!empty($postStr)) {
            $this->msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $this->msgtype = strtolower($this->msg['MsgType']);
        }
    }<br>     //回复文本消息
    public function makeText($text='')
    {
        $CreateTime = time();
        $FuncFlag = $this->setFlag ? 1 : 0;
        $textTpl = "<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);
    }<br>     //根据数组参数回复图文消息
    public function makeNews($newsData=array())
    {
        $CreateTime = time();
        $FuncFlag = $this->setFlag ? 1 : 0;
        $newTplHeader = "<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 ? $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)
    {
        if ($this->debug) {
                    $this->write_log($data);
        }
        echo $data;
    }
    public function valid()
    {
        if ($this->checkSignature()) {
            if( $_SERVER['REQUEST_METHOD']=='GET' )
            {
                echo $_GET['echostr'];
                exit;
            }
        }else{
            write_log('认证失败');
            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;
        }
    }<br>    private function write_log($log){<br>       //这里是你记录调试信息的地方  请自行完善   以便中间调试<br>    }
}
?>

二、调用weixin.class.php

把你的微信公众平台主接口文件(如前面定义的http://www.yourdomain.com/weixin.php)中,修改代码为:

include_once('weixin.class.php');//引用刚定义的微信消息处理类<br>define("TOKEN", "mmhelper");<br>define('DEBUG', true);
$weixin = new Weixin(TOKEN,DEBUG);//实例化
$weixin->getMsg();
$type = $weixin->msgtype;//消息类型
$username = $weixin->msg['FromUserName'];//哪个用户给你发的消息,这个$username是微信加密之后的,但是每个用户都是一一对应的
if ($type==='text') {
    if ($weixin->msg['Content']=='Hello2BizUser') {//微信用户第一次关注你的账号的时候,你的公众账号就会受到一条内容为'Hello2BizUser'的消息
        $reply = $weixin->makeText('欢迎你关注妈妈助手哦,屌丝');
    }else{//这里就是用户输入了文本信息
        $keyword = $weixin->msg['Content'];   //用户的文本消息内容
                include_once("chaxun.php");//文本消息 调用查询程序  
                $chaxun= new chaxun(DEBUG,$keyword,$username);
                $results['items'] =$chaxun->search();//查询的代码
             
                $reply = $weixin->makeNews($results);
    }
}elseif ($type==='location') {
      //用户发送的是位置信息  稍后的文章中会处理                  
}elseif ($type==='image') {
      //用户发送的是图片 稍后的文章中会处理
}elseif ($type==='voice') {     
      //用户发送的是声音 稍后的文章中会处理
}
$weixin->reply($reply);

 三、查询代码

还需要将数据库里面的查询结果格式化为特定的形式

public function search(){
       $record=array();  //定义返回结果的数组
       $list = $this->search($this->keyword);//普通的根据关键词查询数据库的操作  代码就不用分享了
    if(is_array($list)&&!empty($list)){                 
               foreach($list as $msg){ 
                $record[]=array(//以下代码,将数据库中查询返回的数组格式化为微信返回消息能接收的数组形式,即title、description、picurl、url 详见微信官方的文档描述
                    'title' =>$msg['title'],
                    'description' =>$msg['discription'],
                    'picurl' => $msg['pic_url'],
                    'url' =>$msg['url']
                );<br>        }<br>    }<br>    return $record;<br>}<br>

 

目录
相关文章
|
8月前
|
存储 算法 JavaScript
微信支付-Native下单API支付封装+签名流程解读
微信支付-Native下单API支付封装+签名流程解读
88 0
|
9月前
|
前端开发 小程序 JavaScript
微信小程序 - DZMDrawingBoard - (Canvas封装的画板、手写签名、生成图片、保存相册...库)
微信小程序 - DZMDrawingBoard - (Canvas封装的画板、手写签名、生成图片、保存相册...库)
135 0
|
10月前
|
JSON 小程序 前端开发
微信小程序学习实录2(下拉刷新、下拉加载更多、小程序事件、PHP后端代码、刷新无数据解决方案)
微信小程序学习实录2(下拉刷新、下拉加载更多、小程序事件、PHP后端代码、刷新无数据解决方案)
309 0
|
10月前
|
数据采集 前端开发 数据可视化
漏刻有时数据可视化大屏数据采集工具(1):调用微信jsAPI扫描条形码或二维码ajax返回传参PHP源代码
漏刻有时数据可视化大屏数据采集工具(1):调用微信jsAPI扫描条形码或二维码ajax返回传参PHP源代码
74 0
|
小程序 JavaScript 前端开发
微信小程序:阿里云OSS直传实践-PHP实现服务端签名
微信小程序:阿里云OSS直传实践-PHP实现服务端签名
621 0
微信小程序:阿里云OSS直传实践-PHP实现服务端签名
|
缓存 小程序 JavaScript
黯然微信小程序杂记(一):从服务器获取数据 后端语言php
黯然微信小程序杂记(一):从服务器获取数据 后端语言ph
252 0
|
前端开发 PHP
微信支付基于PHP
微信支付基于PHP
123 0
微信支付基于PHP
|
PHP
微信开发之消息模板推送 + php
微信开发之消息模板推送 + php
148 0
|
小程序 JavaScript
微信小程序请求封装(http请求详解)
微信小程序请求封装(http请求详解)
|
JSON 小程序 JavaScript
微信小程序head组件的封装与使用
微信小程序的head是可以进行默认配置head或者自定义封装head组件的,本文将从这两个方面开始进行使用讲解。
305 0
微信小程序head组件的封装与使用