参考文件

微信公众号官方开发文档
微信Api调试

1、wx_sample.php初始代码

此代码用于验证公众号开发者模式服务器配置

<?php
/**
 * wechat php test
 */

//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();

class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //extract post data
        if (!empty($postStr)){
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
            the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
            $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 = "Welcome to wechat world!";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }else{
                echo "Input something...";
            }

        }else{
            echo "";
            exit;
        }
    }
 
    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
 
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
 
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
 
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}

?>

2、启用调用回复信息(带注释)

wx_sample.php文件中注释掉$wechatObj->valid();,在其下增加一句$wechatObj->responseMsg();

<?php

//定义TOKEN密钥
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
//接口验证(验证成功后关闭
//$wechatObj->valid();
//开启自动回复
$wechatObj->responseMsg();

class wechatCallbackapiTest
{
    public function valid()
    {
        //接收随机字符串
        $echoStr = $_GET["echostr"];

        //进行用户数字签名验证
        if($this->checkSignature()){
            //如果成功,则返回接受到的随机字符串
            echo $echoStr;
            exit;
        }
    }
    
    //定义用户数字签名验证功能
    private function checkSignature()
    {
        //判断TOKEN密钥是否定义
        if (!defined("TOKEN")) {
            //如果没有定义,则抛出异常
            throw new Exception('TOKEN is not defined!');
        }
 
        //接收微信加密签名
        $signature = $_GET["signature"];
        //接收时间戳
        $timestamp = $_GET["timestamp"];
        //接收随机数
        $nonce = $_GET["nonce"];
 
        //把TOKEN常量赋值给$token变量
        $token = TOKEN;
        //把相关参数组装为数组(密钥,时间戳,随机数)
        $tmpArr = array($token, $timestamp, $nonce);
        //通过字典法进行排序
        sort($tmpArr, SORT_STRING);
        //把排序后的数组转化为字符串
        $tmpStr = implode( $tmpArr );
        //通过哈希算法进行加密操作
        $tmpStr = sha1( $tmpStr );
 
        //与加密签名进行对比
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    //定义自动回复功能
    public function responseMsg()
    {
        //接收用户端发送过来的XML数据
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //判断XML数据是否为空
        if (!empty($postStr)){
            libxml_disable_entity_loader(true);
            //通过simplexml进行xml解析
            $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 ))
            {
                //回复类型,如果为"text",代表文本类型
                $msgType = "text";
                //回复内容
                $contentStr = "Welcome to Ricken world!";
                //格式化字符串
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                //把XML数据返回手机端
                echo $resultStr;
            }else{
                echo "Input something...";
            }

        }else{
            echo "";
            exit;
        }
    }
}

?>

3、关键词自动回复和关注回复

$keyword保存着用户微信端发来的文本信息。

关注事件与一般的文本消息有两处不同,一是MsgType值是event,二是增加了Event值是subscribe。由于官方文档(最初的wx_sample.php)没有提取这个参数,需要我们自己提取。在程序中增加两个变量$msgType$event

<?php

//定义TOKEN密钥
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
//接口验证(验证成功后关闭
//$wechatObj->valid();
//开启自动回复
$wechatObj->responseMsg();

class wechatCallbackapiTest
{
    public function valid()
    {
        //接收随机字符串
        $echoStr = $_GET["echostr"];

        //进行用户数字签名验证
        if($this->checkSignature()){
            //如果成功,则返回接受到的随机字符串
            echo $echoStr;
            exit;
        }
    }
    
    //定义用户数字签名验证功能
    private function checkSignature()
    {
        //判断TOKEN密钥是否定义
        if (!defined("TOKEN")) {
            //如果没有定义,则抛出异常
            throw new Exception('TOKEN is not defined!');
        }
 
        //接收微信加密签名
        $signature = $_GET["signature"];
        //接收时间戳
        $timestamp = $_GET["timestamp"];
        //接收随机数
        $nonce = $_GET["nonce"];
 
        //把TOKEN常量赋值给$token变量
        $token = TOKEN;
        //把相关参数组装为数组(密钥,时间戳,随机数)
        $tmpArr = array($token, $timestamp, $nonce);
        //通过字典法进行排序
        sort($tmpArr, SORT_STRING);
        //把排序后的数组转化为字符串
        $tmpStr = implode( $tmpArr );
        //通过哈希算法进行加密操作
        $tmpStr = sha1( $tmpStr );
 
        //与加密签名进行对比
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    //定义自动回复功能
    public function responseMsg()
    {
        //接收用户端发送过来的XML数据
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //判断XML数据是否为空
        if (!empty($postStr)){
            libxml_disable_entity_loader(true);
            //通过simplexml进行xml解析
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            //手机端
            $fromUsername = $postObj->FromUserName;
            //微信的公众平台
            $toUsername = $postObj->ToUserName;
            //接收用户发送的关键词
            $keyword = trim($postObj->Content);
            //消息类型
            $msgType = $postObj->MsgType;
            //时间类型
            $event = $postObj->Event;//时间类型,subscribe(订阅)、unsubscribe(取消订阅)
            //时间戳
            $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>"; 
            
            switch($msgType){
                case "event":
                    if($event == "subscribe"){
                        $contentStr = "谢谢你那么可爱还关注我~~~";
                    }
                case "text":
                    switch($keyword){
                        case "小角落":
                            $contentStr = "<a href=\"https://kk.hackerjk.top\">小角落</a>";
                            break;
                        default:
                            $contentStr = "Welcome to Ricken world!";
                    }
            }

            //回复类型,如果为"text",代表文本类型
            $msgType = "text";
            //格式化字符串
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            //把XML数据返回手机端
            echo $resultStr;

        }else{
            echo "";
            exit;
        }
    }
}

?>
最后修改:2022 年 05 月 19 日
要不?请我吃一下沙县连锁大酒店?