使用前提条件:拥有一个公网上的HTTP服务器主机空间,具有创建目录、上传文件等权限。推荐新浪的SAE。http://sae.sina.com.cn/

首先请注册微信公众平台的账号,注册地址:http://mp.weixin.qq.com/

本教程主要讲解接口的开发流程。

官方的文档非常简洁:http://mp.weixin.qq.com/cgi-bin/indexpage?t=wxm-callbackapi-doc&lang=zh_CN

事例代码也跑不通。我研究了一番,终于搞定。方法如下:

一、写好接口程序

在你的服务器上上传好一个接口程序文件,如http://www.yourdomain.com/weixin.php  内容如下:

<?php
define("TOKEN", "weixin");//自己定义的token 就是个通信的私钥
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
//$wechatObj->responseMsg();
class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }
    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();
            $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            <FuncFlag>0<FuncFlag>
            </xml>";
            if(!empty( $keyword ))
            {
                $msgType = "text";
                $contentStr = '你好啊,屌丝';
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }else{
                echo '咋不说哈呢';
            }
        }else {
            echo '咋不说哈呢';
            exit;
        }
    }
 
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token =TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
 
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}
?>

二、配置微信公众平台回复接口

设置回复接口,填好URL和Token(url填上面的http://www.yourdomain.com/weixin.php,token必须跟上面程序里面定义的Token一致)

三、验证接口

用自己的个人微信关注下你的公众账号,给这个账号发一条消息过去,收到原样的消息返回,即验证成功了。

四、开始自定义回复

注释掉$wechatObj->valid(); 这行,同时去掉//$wechatObj->responseMsg();这行的注释。

你可以修改responseMsg函数里面的代码,根据用户的消息类型('text','image','location')和消息内容来回复用户不同的内容。

消息接口就可以使用了,发个消息试试看吧?

封装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;
    }<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;
        }
    }
    private function write_log($log){<br>       //这里是你记录调试信息的地方  请自行完善   以便中间调试<br>    }
}
?>

调用weixin.class.php

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

<?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);

?>

查询代码

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

<?php

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;
}

?>

来源:http://www.weste.net/2013/4-27/90846.html

微信公众平台消息接口PHP版的更多相关文章

  1. 微信公众平台消息接口PHP版开发教程

    原文:微信公众平台消息接口PHP版开发教程  一.写好接口程序 在你的服务器上上传好一个接口程序文件,如http://www.yourdomain.com/weixin.php  内容如下: &l ...

  2. 微信公众平台消息接口API指南

    简介 微信公众平台消息接口为开发者提供了一种新的消息处理方式.微信公众平台消息接口为开发者提供与用户进行消息交互的能力.对于成功接入消息接口的微信公众账号,当用户发消息给公众号,微信公众平台服务器会使 ...

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

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

  4. 微信公众平台消息接口开发(12)消息接口Bug

    微信公众平台开发模式 微信公众平台消息接口 微信公众平台API 微信开发模式 Bug 方倍工作室 原文:http://www.cnblogs.com/txw1958/archive/2013/03/1 ...

  5. 微信公众平台消息接口开发(24)图片识别之人脸识别API

    微信公众平台开发模式 微信 公众平台 消息接口 开发模式 企业微信公众平台 图片识别 人脸识别 API 作者:方倍工作室 原文:http://www.cnblogs.com/txw1958/archi ...

  6. 微信公众平台消息接口开发(2)你的服务器没有正确响应Token验证的解决方法

    你的服务器没有正确响应Token验证,请阅读消息接口使用指南 微信 微信公众平台开发模式 平台 消息 接口 启用 URL Token作者:http://txw1958.cnblogs.com/ 本系统 ...

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

    一.封装weixin.class.php 由于微信公众平台的通信使用的是特定格式的XML数据,每次接受和回复都要去做一大堆的数据处理. 我们就考虑在这个基础上做一次封装,weixin.class.ph ...

  8. 微信公众平台消息接口开发(26)从Hello2BizUser文本到subscribe事件

    微信公众平台 微信公众平台开发模式 消息接口 企业微信公众平台 Hello2BizUser subscribe 订阅事件 作者:方倍工作室 原文:http://www.cnblogs.com/txw1 ...

  9. 微信公众平台消息接口开发之微信浏览器HTTP_USER_AGENT判断

    在微信公众平台的开发过程中,我们有时需要开发网页并判断是否是是来自微信浏览器访问,本文介绍如何做出这一判断. 一.$_SERVER数组 $_SERVER 是一个包含了诸如头信息(header).路径( ...

随机推荐

  1. C#中&和&&,|和||区别

    当两者都为逻辑运算符时. 其实没什么差别. &&和||当已经确定结果时,不会对第二个操作数求值.也不知道什么情况会用到这个差别.做个笔记好了. http://blog.csdn.net ...

  2. Shell基础学习(三) 传递参数

    我们可以在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n.n 代表一个数字,1 为执行脚本的第一个参数,2 为执行脚本的第二个参数,以此类推…… 以下实例我们向脚本传递三个参数 ...

  3. SqlServer 2008无法远程连接到服务器

    其他的什么先别说,上来第一点,看看服务器防火墙,是否把SqlServer的端口号例外了.  别弄了半天发现防火墙问题,那就得不偿失了. 用户在使用SQL Server 2008远程链接时,可能会弹出如 ...

  4. VC中__int64的用法

    VCVC6.0的64位整数分别叫做__int64与unsigned __int64,其范围分别是[-2^63, 2^63)与[0,2^64),即-922337203685 4775808~922337 ...

  5. C# 通过HttpWebRequest在后台对WebService进行调用

    通过HttpWebRequest在后台对WebService进行调用 http://www.cnblogs.com/macroxu-1982/archive/2009/12/23/1630415.ht ...

  6. Unity接入谷歌支付

    文章理由 前段时间负责Unity接入Google内购功能,一开始研究别人的技术博客时发现,他们的文章都有些年头了,有些细节的地方已经不像n年前那样了,技术永远是需要更新的,而这篇就作为2016年末的最 ...

  7. 定制NSLog便于打印调试

    定制NSLog便于打印调试 本人之前从事过嵌入式开发,对于打印调试比较在行,现分享定制的NSLog以及教大家如何使用. 源码下载地址  https://github.com/YouXianMing/Y ...

  8. redis中文API

    1.学习文档地址:http://www.redisdoc.com/en/latest/index.html 2.redis中文API REDIS所有的命令 <<ABOUT LIST> ...

  9. [Android Pro] Android系统手机端抓包方法 和 通过File查看应用程序流量

    adb shellcat proc/uid_stat/%uid%/tcp_snd  proc/uid_stat/%uid%/tcp_rcv ------------------------------ ...

  10. ssh免密登录方法不生效?Authentication refused: bad ownership or modes for directory

    机器A通过ssh登录机器B,方法有两种: 1.密码方式 2.密钥方式: 两种方式同时开启的时候,优先使用密钥方式. 密钥登录方式的配置方法是,首先在登录机器B上创建文件authorized_keys( ...