微信关注 自动回复 关注消息 php

<?php
header("Content-type: text/html; charset=utf-8"); 
$nonce = $_GET['nonce'];
$token = 'winxin';
$timestamp = $_GET['timestamp'];
if (isset($_GET['echostr'])) {
    if (bindServerCheck()) {
        echo $_GET['echostr'];
    }
    exit();
}
responseMsg();


 //消息回复
function responseMsg() {
    //1.获取到微信推送过来post数据(xml格式)
    $postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
    //2.处理消息类型,并设置回复类型和内容
    $postObj = simplexml_load_string($postArr, 'SimpleXMLElement', LIBXML_NOCDATA);
    //判断该数据包是否是订阅de事件推送
    if (strtolower($postObj->MsgType) == 'event') {
        //如果是关注 subscribe事件
        if (strtolower($postObj->Event) == 'subscribe') {
            $toUser = $postObj->FromUserName;
            $fromUser = $postObj->ToUserName;
            $time = time();
            $msgType = 'text';
            $content = '欢迎关注我的微信公众号 test 123';



 
             //修改为
              if (is_utf8($content)) {
                $content = $content;
              } else {
               $content = iconv('gb2312', 'UTF-8//IGNORE', $content);
              }

            $template = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            </xml>";
            $info = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
            echo $info;
        }
    }
}


// 开发者模式绑定校验
function bindServerCheck($token) {
    $signature = $_GET["signature"];
    $timestamp = $_GET["timestamp"];
    $nonce = $_GET["nonce"];
    $tmpArr = array(
        $token,
        $timestamp,
        $nonce
    );
    sort($tmpArr);
    $tmpStr = implode($tmpArr);
    $tmpStr = sha1($tmpStr);
    if ($tmpStr == $signature) {
        return true;
    } else {
        return false;
    }
}




  function to_utf8($in) 

        if (is_array($in)) { 
            foreach ($in as $key => $value) { 
                $out[to_utf8($key)] = to_utf8($value); 
            } 
        } elseif(is_string($in)) { 
            if(mb_detect_encoding($in) != "UTF-8") 
                return utf8_encode($in); 
            else 
                return $in; 
        } else { 
            return $in; 
        } 
        return $out; 





 function is_utf8($str)
{
  return preg_match('//u', $str);
}




?>

猜你喜欢

转载自blog.csdn.net/fkedwgwy/article/details/80237060