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

简介: 原文: 微信公众平台消息接口PHP版开发教程  一、写好接口程序 在你的服务器上上传好一个接口程序文件,如http://www.yourdomain.
原文: 微信公众平台消息接口PHP版开发教程



一、写好接口程序

在你的服务器上上传好一个接口程序文件,如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
1	 

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

?>






目录
相关文章
|
7月前
|
安全 PHP
PHP 8 新特性实战:提升开发效率的利器
PHP 8 新特性实战:提升开发效率的利器
233 87
|
7月前
|
安全 PHP
PHP 8 新特性实战:提升开发效率的利器
PHP 8 新特性实战:提升开发效率的利器
249 88
|
7月前
|
安全 编译器 PHP
PHP 8 新特性:现代开发的强力引擎
PHP 8 新特性:现代开发的强力引擎
231 89
|
7月前
|
安全 编译器 PHP
PHP 8 新特性:现代化开发的飞跃
PHP 8 新特性:现代化开发的飞跃
327 89
|
7月前
|
安全 大数据 PHP
PHP 7+ 新特性实战指南:提升开发效率
PHP 7+ 新特性实战指南:提升开发效率
236 87
|
5月前
|
算法 iOS开发 CDN
“企业微信iPad协议”第 0x04 天:当朋友圈接口在凌晨 2:14 突然返回 404
新品上线紧急任务:300位经销商朋友圈同步海报。突破官方限制,利用企业微信iPad协议私有接口,自动化上传发布。凌晨遭遇404,迅速定位并修复算法版本问题,最终高效完成推送,点赞超4200。技术在文档之外,也在边界之内。
277 0
|
5月前
|
消息中间件 人工智能 Java
抖音微信爆款小游戏大全:免费休闲/竞技/益智/PHP+Java全筏开源开发
本文基于2025年最新行业数据,深入解析抖音/微信爆款小游戏的开发逻辑,重点讲解PHP+Java双引擎架构实战,涵盖技术选型、架构设计、性能优化与开源生态,提供完整开源工具链,助力开发者从理论到落地打造高留存、高并发的小游戏产品。
|
5月前
|
iOS开发
“企业微信iPad协议”第0x0B次编译:当朋友圈接口在凌晨悄然返回空数组
新品海报发布失败,排查发现企业微信iPad端因本地时间偏差超60秒,导致`ext_ticket`校验失败。NTP校准后恢复正常。问题根源:独立加签逻辑对时间敏感,且错误不提示。精准时间成合规关键。
326 0
|
12月前
|
自然语言处理 搜索推荐 小程序
微信公众号接口:解锁公众号开发的无限可能
微信公众号接口是微信官方提供的API,支持开发者通过编程与公众号交互,实现自动回复、消息管理、用户管理和数据分析等功能。本文深入探讨接口的定义、类型、优势及应用场景,如智能客服、内容分发、电商闭环等,并介绍开发流程和工具,帮助运营者提升用户体验和效率。未来,随着微信生态的发展,公众号接口将带来更多机遇,如小程序融合、AI应用等。
|
11月前
|
JSON 自然语言处理 前端开发
【01】对APP进行语言包功能开发-APP自动识别地区ip后分配对应的语言功能复杂吗?-成熟app项目语言包功能定制开发-前端以uniapp-基于vue.js后端以laravel基于php为例项目实战-优雅草卓伊凡
【01】对APP进行语言包功能开发-APP自动识别地区ip后分配对应的语言功能复杂吗?-成熟app项目语言包功能定制开发-前端以uniapp-基于vue.js后端以laravel基于php为例项目实战-优雅草卓伊凡
598 72
【01】对APP进行语言包功能开发-APP自动识别地区ip后分配对应的语言功能复杂吗?-成熟app项目语言包功能定制开发-前端以uniapp-基于vue.js后端以laravel基于php为例项目实战-优雅草卓伊凡