接收微信服务器发送的消息与被动回复消息

<?php
//第三方服务器与微信服务器进行消息接入,
// https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html

// 接收微信服务器发送的四个验证参数
//加密签名
        $signature = $_GET["signature"];
//时间戳
        $timestamp = $_GET["timestamp"];
//随机数
        $nonce = $_GET["nonce"];
//随机字符串
        $echostr = $_GET["echostr"];
// TOKEN
        define('TOKEN','weixin');

//1.进行字典序排序
        $tmpArr = array(TOKEN, $timestamp, $nonce);
    sort($tmpArr, SORT_STRING);
//2.将三个参数字符串拼接成一个字符串进行sha1加密 
        $tmpStr = implode( $tmpArr );
    $tmpStr = sha1( $tmpStr );
//3.开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
        if( $tmpStr == $signature ){
            echo "$echostr";
        }else{
            return false;
        }



//服务器接收微信POST发送的xml格式原生数据
    // $postStr  = $GLOBALS['HTTP_RAW_POST_DATA'];
        $postStr = file_get_contents("php://input");

    if (!$postStr) {
        echo "post data error";
        exit;
    }

//将xml格式转对象形式输出  LIBXML_NOCDATA - 将 CDATA 设置为文本节点
$postObj = simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);
 //判断消息类型  被动回复消息    严格来说,发送被动响应消息其实并不是一种接口,而是对微信服务器发过来消息的一次回复。
 $MsgType = $postObj->MsgType;
 switch ($MsgType) {
     case 'text':

        $Content = $postObj->Content;
        switch ($Content) {
          case 'binbin':
            $xml = '<xml>
                  <ToUserName><![CDATA[%s]]></ToUserName>
                  <FromUserName><![CDATA[%s]]></FromUserName>
                  <CreateTime>%d</CreateTime>
                  <MsgType><![CDATA[text]]></MsgType>
                  <Content><![CDATA[%s]]></Content>
                </xml>';
                echo sprintf($xml,$postObj->FromUserName,$postObj->ToUserName,time(),'binbin is girl');
            break;
          
          default:
             $xml = '<xml>
                  <ToUserName><![CDATA[%s]]></ToUserName>
                  <FromUserName><![CDATA[%s]]></FromUserName>
                  <CreateTime>%d</CreateTime>
                  <MsgType><![CDATA[text]]></MsgType>
                  <Content><![CDATA[%s]]></Content>
                </xml>';
               echo sprintf($xml,$postObj->FromUserName,$postObj->ToUserName,time(),$postObj->Content);
            break;
        }
         
     
     default:
        
 }


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值