前提:有一个工作账号,调为编辑模式,有服务器(虚拟机什么的都可以),百度地图key
<?php
/**
* wechat php test
*/
//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid();
$wechatObj -> responseMsg();
class wechatCallbackapiTest {
public function valid() {
$echoStr = $_GET["echostr"];
//valid signature , option
if ($this -> checkSignature()) {
echo $echoStr;
exit ;
}
}
public function responseMsg() {
//get post data, May be due to the different environments
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
//接收发送过来的数据
//extract post data
if (!empty($postStr)) {
//php中接卸xml的函数
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj -> FromUserName;
//用户的openID
$toUsername = $postObj -> ToUserName;
//公众号的id
$keyword = trim($postObj -> Content);
$latitude=$postObj->Location_X;
$longtitude=$postObj->Location_Y;
$type=$postObj->MsgType;
//发Geocoding接口
//$geourl="http://api.map.baidu.com/telematics/v3/reverseGeocoding?location={$longtitude},{$latitude}&coord_type=gcj02&ak=uUu8NvbFGUjbYtINhz5CNRmN";
$geourl="http://api.map.baidu.com/telematics/v3/distance?waypoints=113.65000,34.76667;{$longtitude},{$latitude}&ak=uUu8NvbFGUjbYtINhz5CNRmN";
//读取地址
$apiStr=file_get_contents($geourl);
$apiObj=simplexml_load_string($apiStr);
$distance=$apiObj->results->distance;
//$addstr=$apiObj->results->result[0]->name;
$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 = "你是:" . $fromUsername . "\n发给:" . $toUsername."\n距离--".$distance."米";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
// } else {
echo "Input something...";
//}
} else {
echo "空数据";
exit ;
}
}
private function checkSignature() {
$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;
}
}
}
?>