微信接口配置需要用到http开头的域名,然后将自己的api.php路径填写正确 如下
下面是api.php文件的代码
valid();
//开启自动回复功能
$wechatObj->responseMsg();
//定义类文件
class wechatCallbackapiTest
{
//定义checkSignature方法
private function checkSignature(){
// you must define TOKEN by yourself
//判断TOKEN密钥是否定义
if (!defined("TOKEN")) {
//如果没有定义则抛出异常,返回'TOKEN is not defined!'字符串
throw new Exception('TOKEN is not defined!');
}
//接收微信加密签名
$signature = $_GET["signature"];
//接收时间戳信息
$timestamp = $_GET["timestamp"];
//接收随机数
$nonce = $_GET["nonce"];
//把TOKEN常量赋值给$token变量
$token = TOKEN;
//把相关参数组装为数组(密钥文件、时间戳、随机数)
$tmpArr = array($token, $timestamp, $nonce);
// use SORT_STRING rule
//通过字典法进行排序
sort($tmpArr, SORT_STRING);
//把排序后的数组转化为字符串
$tmpStr = implode( $tmpArr );
//通过哈希算法对字符串进行加密操作
$tmpStr = sha1( $tmpStr );
//与加密签名进行对比
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
//实现valid验证方法:实现对接微信公众平台
public function valid()
{
//通过GET请求接收随机字符串
$echoStr = $_GET["echostr"];
//调用checkSignature方法进行用户(开发者)数字签名验证
//valid signature , option
if($this->checkSignature()){
//如果成功,则返回接收到的随机字符串
echo $echoStr;
//并退出
exit;
}
}
//=============================================================================================
/**
* 主要的控制方法
*/
public function responseMsg()
{
//get post data, May be due to the different environments
//接收用户端(客户)发送过来的XML数据
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
//extract post data
//判断XML数据是否为空
if (!empty($postStr)){
/* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
the best way is to check the validity of xml by yourself */
libxml_disable_entity_loader(true);
//通过simplexml进行xml解析 PHP中有两大类可以完成对XML的解析,1.PHP的Dom模型2.通过simplexml模型
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
//发送方帐号(一个OpenID)
$fromUsername = $postObj->FromUserName;
//开发者微信号
$toUsername = $postObj->ToUserName;
//接收用户发送的关键词
$keyword = trim($postObj->Content);
//消息类型
$mysgType = $postObj->MsgType;
//事件类型,subscribe(订阅)、unsubscribe(取消订阅)
$event = $postObj->Event;
//时间戳
$time = time();
switch ($mysgType){
case "event":
if ($event == "subscribe"){//订阅
keyText($fromUsername,$toUsername,$time);//显示菜单
}
if ($event == "location_select") {//发送位置
$label = $postObj->Label;//地理位置的字符串信息
keyText($fromUsername,$toUsername,$time,$label);
}
break;
case "text":
keyText($fromUsername,$toUsername,$time,$keyword);
break;
default:
echo "Input something...";
break;
}
}else {
echo "ERROR:XML数据为空";
exit;
}
}
}
?>
及WeChat_message.php文件代码
%s
0
";
//回复类型,如果为"text",代表文本类型
$msgType = "text";
if($keyword == "?" || $keyword == "?"){
$contentStr = "可操作菜单有\n1.开发人\n?.菜单";
}else if($keyword == "1"){//发送1 回复的内容
$contentStr = "开发人:LRJ 你的openid:".$fromUsername;
}else{
$contentStr = "".$keyword;
}
//格式化字符串(对xml进行格式化操作,把里面相关的变量格式化成字符串)
//文本形式
$resultStr = sprintf($Tpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;//输出
}
配置成功后记得把api.php里的valid()方法注释掉