代码演示:
<?php
//如果配置失败,可能是编码问题,加上这一句
header("Content-Type:text/plain;charset=utf-8");
//这里填写你的 token
$token="c75d4wfa98ce5986f2928962b771ehad";
define("TOKEN",$token);
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
class wechatCallbackapiTest
{
/**验证*/
public function valid() {
$echoStr = $_GET["echostr"];
if($this->checkSignature()) {
echo $echoStr;exit;
}
}
/**响应消息*/
public function responseMsg() {
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!empty($postStr)) {
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);
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ) {
return true;
}else {
return false;
}
}
}
如果有需要帮助请联系作者:微信:Q360164460;