php版微信自定义回复功能示例

时间:2022-09-18 15:49:36

本文实例讲述了php微信自定义回复功能。分享给大家供大家参考,具体如下:

php版微信自定义回复功能示例

配置好服务器之后,就可以用php实现自动回复了。

index.php中的代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
define("token", "weixin");
$wechatobj = new wechatcallbackapitest();
if (isset($_get['echostr'])) {
  $wechatobj->valid();
}else{
  $wechatobj->responsemsg();
}
class wechatcallbackapitest
{
  public function valid()
  {
    $echostr = $_get["echostr"];
    if($this->checksignature()){
      header('content-type:text');
      echo $echostr;
      exit;
    }
  }
  private function checksignature()
  {
    $signature = $_get["signature"];
    $timestamp = $_get["timestamp"];
    $nonce = $_get["nonce"];
    $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()
  {
    $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($keyword == "?" || $keyword == "?") //获取用户信息
      {
        $msgtype = "text";
        $contentstr = date("y-m-d h:i:s",time()); // 回复的内容
        $resultstr = sprintf($texttpl, $fromusername, $tousername, $time, $msgtype, $contentstr);
        echo $resultstr;
      }
    }else{
      echo "";
      exit;
    }
  }
}
?>

效果:

当用户输入?或者?就会获取当前时间

php版微信自定义回复功能示例

希望本文所述对大家php程序设计有所帮助。