Home  >  Article  >  WeChat Applet  >  Detailed explanation and examples of the development process of PHP docking WeChat public platform message interface

Detailed explanation and examples of the development process of PHP docking WeChat public platform message interface

高洛峰
高洛峰Original
2018-05-15 14:59:4021904browse

This article mainly introduces the development process of PHP docking WeChat public platform message interface, how to use the PHP version of the interface to operate public platform messages, friends in need can refer to the following

1. Write the interface program

Upload an interface program file on your server with the following content:

The code is as follows:

<?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, &#39;SimpleXMLElement&#39;, 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 = &#39;你好啊,屌丝&#39;;
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }else{
                echo &#39;咋不说哈呢&#39;;
            }
        }else {
            echo &#39;咋不说哈呢&#39;;
            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;
        }
    }
}
?>

2. Configure the WeChat public platform reply interface

Set the reply interface, fill in the URL and Token (the URL is filled in http://www.yourdomain.com/weixin.php above, and the token must be consistent with the Token defined in the above program)

Detailed explanation and examples of the development process of PHP docking WeChat public platform message interface
3. Verification interface

Use your personal WeChat to follow your public account, send a message to this account, and receive the original message The message is returned, indicating that the verification was successful.

4. Start custom reply

Comment out the line $wechatObj->valid(); and remove //$wechatObj->responseMsg() ;Comments for this line.
You can modify the code in the responseMsg function to reply to the user with different content based on the user's message type ('text', 'image', 'location') and message content.
The message interface is ready for use. Let’s try sending a message?

1. Encapsulate weixin.class.php

Since the communication on the WeChat public platform uses XML data in a specific format, it must be done every time it is accepted and replied A lot of data processing.
We will consider making an encapsulation on this basis, weixin.class.php, the code is as follows:

The code is as follows:

<?php
class Weixin
{
    public $token = &#39;&#39;;//token
    public $debug =  false;//是否debug的状态标示,方便我们在调试的时候记录一些中间数据
    public $setFlag = false;
    public $msgtype = &#39;text&#39;;   //(&#39;text&#39;,&#39;image&#39;,&#39;location&#39;)
    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, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA);
            $this->msgtype = strtolower($this->msg[&#39;MsgType&#39;]);
        }
    }
  //回复文本消息
    public function makeText($text=&#39;&#39;)
    {
        $CreateTime = time();
        $FuncFlag = $this->setFlag ? 1 : 0;
        $textTpl = "<xml>
            <ToUserName><![CDATA[{$this->msg[&#39;FromUserName&#39;]}]]></ToUserName>
            <FromUserName><![CDATA[{$this->msg[&#39;ToUserName&#39;]}]]></FromUserName>
            <CreateTime>{$CreateTime}</CreateTime>
            <MsgType><![CDATA
            1  
            ]></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[&#39;FromUserName&#39;]}]]></ToUserName>
            <FromUserName><![CDATA[{$this->msg[&#39;ToUserName&#39;]}]]></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 = &#39;&#39;;
        $itemsCount = count($newsData[&#39;items&#39;]);
        $itemsCount = $itemsCount < 10 ? $itemsCount : 10;//微信公众平台图文回复的消息一次最多10条
        if ($itemsCount) {
            foreach ($newsData[&#39;items&#39;] as $key => $item) {
                if ($key<=9) {
                    $Content .= sprintf($newTplItem,$item[&#39;title&#39;],$item[&#39;description&#39;],$item[&#39;picurl&#39;],$item[&#39;url&#39;]);
                }
            }
        }
        $header = sprintf($newTplHeader,$newsData[&#39;content&#39;],$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[&#39;REQUEST_METHOD&#39;]==&#39;GET&#39; )
            {
                echo $_GET[&#39;echostr&#39;];
                exit;
            }
        }else{
            write_log(&#39;认证失败&#39;);
            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){
        //这里是你记录调试信息的地方  请自行完善   以便中间调试
    }
}
?>

2. Call weixin. class.php

Put your WeChat public platform main interface file and modify the code to:

The code is as follows:

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

3 .Query code

You also need to format the query results in the database into a specific form

The code is as follows:

<?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 详见微信官方的文档描述
                        &#39;title&#39; =>$msg[&#39;title&#39;],
                        &#39;description&#39; =>$msg[&#39;discription&#39;],
                        &#39;picurl&#39; => $msg[&#39;pic_url&#39;],
                        &#39;url&#39; =>$msg[&#39;url&#39;]
                    );
        }
    }
    return $record;
}
?>

The above is the detailed content of Detailed explanation and examples of the development process of PHP docking WeChat public platform message interface. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn