<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
public function index(){
$nonce = $_GET['nonce'];
$token = 'weixin';
$timestamp=$_GET['timestamp'];
$echostr = $_GET['echostr'];
$signature = $_GET['signature'];
$array = array($nonce,$timestamp,$token);
sort($array);
$str = sha1(implode($array));
if($str == $signature && $echostr){
//第一次接入weixin api 接口的时候
echo $echostr;
exit;
}
}
}
?>
微信url http://pianyi.echox.net/we/index.php/Home/Index/index
Token weixin
用户关注后给用户实现关注回复
<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
public function index(){
$nonce = $_GET['nonce'];
$token = 'weixin';
$timestamp=$_GET['timestamp'];
$echostr = $_GET['echostr'];
$signature = $_GET['signature'];
$array = array($nonce,$timestamp,$token);
sort($array);
$str = sha1(implode($array));
if($str == $signature && $echostr){ //这次接入是在接入token 时候的
//第一次接入weixin api 接口的时候
echo $echostr;
exit;
}else{
$this->reponseMsg(); //用户关注
}
}
//接收事件推送给并回复
public function reponseMsg(){
//1.当用户关注的时候微信会推出一个xml 获取微信推送过来的数据
$postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
$tmpstr=$postArr;
//查看接受的信息
//2.处理消息类型,并设置回复类型和内容;
/**
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1348831860</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[this is a test]]></Content>
<MsgId>1234567890123456</MsgId>
</xml>
*/
//simplexml_load_string 把xml转化成对象
$postObj = simplexml_load_string($postArr);
// $postObj->ToUsername='';
// $postObj->FromUserName='';
// $postObj->CreateTime='';
// $postObj->MsgType='';
// $postObj->Content='';
//判断该数据包是否是订阅的事件推送
if(strtolower($postObj->MsgType)=='event'){
//如果是关注subscribe事件
if(strtolower($postObj->Event=='subscribe')){
//就回复用户消息
$toUser = $postObj->FromUserName;
$fromUser = $postObj->toUserName;
$time= time();
$Msgtype='text';
$Content = '微信号的openod'.$postObj->FromUserName;
$template="
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
//sprintf 占位符
$info = sprintf($template,$toUser,$fromUser,$time,$Msgtype,$Content);
echo $info;
//回复消息格式
/** <xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserrName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[你好]]></Content>
</xml>
**/
}
}
}
}