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

2019-03-02 00:54|来源: 网路

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

 

一、封装weixin.class.php

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
class Weixin
{
    public $token = '' ; //token
    public $debug =  false; //是否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)中,修改代码为:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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 );

 

三、查询代码

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

 

?
1
2
3
4
5
6
7
8
9
10
11
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>

 

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

承接微信公众平台消息接口开发、PHP、.NET、javascript、html5程序开发;新浪微博应用、腾讯微博应用等各大开放平台应用开发业务

联系QQ:1433273389

关注妈妈助手(账号mmhelper)方法:

1. 依次进入以下路径:朋友们—>添加朋友—>搜号码,输入mmhelper,不区分大小写,点击查找,然后点击关注。

2. 扫描二维码:


转自:http://www.cnblogs.com/steven9801/archive/2013/03/22/2974853

相关问答

更多
  • JAVA的WEB开发、数据库开发等,,,,,,,,,,具体要看需求、构架等
  • 能使用的!微信 在安卓手机里可以使用,安装是用java 开发的,所以 可以用java开发
  • JAVA的WEB开发、数据库开发等,,,,,,,,,,具体要看需求、构架等
  • 微信公众平台开发注意事项: 一、微信公众平台开发是指为微信公众号进行业务开发,为移动应用、PC端网站、公众号第三方平台(为各行各业公众号运营者提供服务)的开发,请前往微信开放平台接入。 二、在申请到认证公众号之前,你可以先通过测试号申请系统,快速申请一个接口测试号,立即开始接口测试开发。 三、在开发过程中,可以使用接口调试工具来在线调试某些接口。 四、每个接口都有每日接口调用频次限制,可以在公众平台官网-开发者中心处查看具体频次。 五、在开发出现问题时,可以通过接口调用的返回码,以及报警排查指引(在公众平台 ...
  • 小猪cms还凑合,,有源码的 ,每周更新两三个模板的 ,你可以看下 ,,
  • 登录微信公众平台,点击左下角的 开发者工具,即可看到相关文档。
  • 微网站开发模式教程:   第一步:申请消息接口   在公众平台网站的高级功能 – 开发模式页,点击“成为开发者”按钮,填写URL和Token,其中URL是开发者用来接收微信服务器数据的接口URL。Token可由开发者可以任意填写,用作生成签名。   第二步:验证URL有效性   开发者提交信息后,微信服务器将发送GET请求到填写的URL上,GET请求携带四个参数:   开发者通过检验signature对请求进行校验。若确认此次GET请求来自微信服务器,请原样返回 echostr参数内容,则接入生效,成为开发 ...
  • 不是仿,是直接登录到微信公众平台,但是没有通过他们的登录界面登录进去,而是用程序提交用户名密码登录进去,然后进行相关操作,往相关接口提交数据