1.开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。加密/校验流程如下:
1)将token、timestamp、nonce三个参数进行字典序排序 2)将三个参数字符串拼接成一个字符串进行sha1加密 3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信 public function index(){ //获得参数 signature nonce token timestamp echostr $nonce = $_GET['nonce']; $token = 'weixin'; $timestamp = $_GET['timestamp']; $echostr = $_GET['echostr']; $signature = $_GET['signature']; //形成数组,然后按字典序排序 $array = array(); $array = array($nonce, $timestamp, $token); sort($array); //拼接成字符串,sha1加密 ,然后与signature进行校验 $str = sha1( implode( $array ) ); if( $str == $signature && $echostr ){ //第一次接入weixin api接口的时候 echo $echostr; exit; }else{ $this->reponseMsg(); } } 2.接受事件并回复: //1.获取到微信推送过来post数据(xml格式) $postArr = $GLOBALS['HTTP_RAW_POST_DATA']; //2.处理消息类型,并设置回复类型和内容 $postObj = simplexml_load_string( $postArr ); //判断是否订阅并回复多图文消息 if( strtolower( $postObj->MsgType) == 'event'){ //如果是关注 subscribe 事件 if( strtolower($postObj->Event == 'subscribe') ){ //回复用户消息(纯文本格式) $arr = array( array( 'title'=>'imooc', 'description'=>"欢迎来到慕课网---用户id:".$postObj->FromUserName, 'picUrl'=>'http://114.215.80.202/weixin/Public/head.jpg', 'url'=>'http://www.imooc.com', ) ); $indexModel = D('Index'); $indexModel->responseSubscribe($postObj,$arr); } } //回复多图文 public function responseMSG($postObj,$arr){ //return 1; $toUser = $postObj->FromUserName; $fromUser = $postObj->ToUserName; $template = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <ArticleCount>".count($arr)."</ArticleCount> <Articles>"; foreach($arr as $k=>$v){ $template .="<item> <Title><![CDATA[".$v['title']."]]></Title> <Description><![CDATA[".$v['description']."]]></Description> <PicUrl><![CDATA[".$v['picUrl']."]]></PicUrl> <Url><![CDATA[".$v['url']."]]></Url> </item>"; } $template .="</Articles></xml> "; echo sprintf($template, $toUser, $fromUser, time(), 'news'); } //回复文本 public function responseText($postObj,$content){ $template = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> </xml>"; //注意模板中的中括号 不能少 也不能多 $fromUser = $postObj->ToUserName; $toUser = $postObj->FromUserName; $time = time(); // $content = '18723180099'; $msgType = 'text'; echo sprintf($template, $toUser, $fromUser, $time, $msgType, $content); } |