浏览量 1
定义TOKEN,开发启用时用到; 定义一个wechatCallbackapiTest()的类; 验证消息确实来自微信服务器; 接受原始的xml数据包; 封装你想发送的xml数据返回给用户;
代码语言:javascript复制<?php
define("TOKEN", "kantm");
$wechatObj = new wechatCallbackapiTest();
if (isset($_GET['echostr'])) {
$wechatObj->valid();
}else{
$wechatObj->responseMsg();
}
class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];
if($this->checkSignature()){
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);//将token、timestamp、nonce三个参数进行字典序排序
$tmpStr = implode( $tmpArr );//将数组转换成字符串
$tmpStr = sha1( $tmpStr );//sha1加密
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
//具体功能实现
public function responseMsg()
{
//接受post过来的原始数据
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!empty($postStr)){
//数据载入对象中
//对象名为SimpleXMLElement
$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)
{
$msgType = "text";
$contentStr = date("Y-m-d H:i:s",time());
//封装xml并返回给用户
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}
}else{
echo "";
exit;
}
}
}
?>