设为首页 收藏本站
查看: 1352|回复: 0

[经验分享] 微信公众平台消息接口开发(2)-封装weixin.class.php

[复制链接]
累计签到:2 天
连续签到:1 天
发表于 2015-8-23 13:13:32 | 显示全部楼层 |阅读模式
  一、封装weixin.class.php
  由于微信公众平台的通信使用的是特定格式的XML数据,每次接受和回复都要去做一大堆的数据处理。
  我们就考虑在这个基础上做一次封装,weixin.class.php,代码如下:



<?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;
}
     //获得用户发过来的消息(消息内容和消息类型  )
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']);
}
}
     //回复文本消息
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);
}
     //根据数组参数回复图文消息
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;
}
}
    private function write_log($log){
       //这里是你记录调试信息的地方  请自行完善   以便中间调试
    }
}
?>

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



include_once('weixin.class.php');//引用刚定义的微信消息处理类
define("TOKEN", "mmhelper");
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']
);
        }
    }
    return $record;
}


  
  -------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  承接微信公众平台消息接口开发、PHP、.NET、javascript、html5程序开发;新浪微博应用、腾讯微博应用等各大开放平台应用开发业务
  联系QQ:1433273389
  关注妈妈助手(账号mmhelper)方法:
  1. 依次进入以下路径:朋友们—>添加朋友—>搜号码,输入mmhelper,不区分大小写,点击查找,然后点击关注。
  2. 扫描二维码:
DSC0000.jpg

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-102990-1-1.html 上篇帖子: 从PHP安全讲DedeCms的安全加固 下篇帖子: 2014年最佳的10款 PHP 开发框架
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表