|
|
本帖最后由 Test 于 2014-1-22 13:53 编辑
要成为微信公众号(订阅号或服务号)的开发者,需要首先验证接口,这个可以在登录微信https://mp.weixin.qq.com后台后设置。但是我嫌麻烦,于是开发个接口类,包含验证函数(还有回复文本信息和图文信息的功能)。其实接口验证在成为开发者之后就没用了。
上代码,微信基类:weixin.class.php
- <?php
- class Weixin
- {
- public $token = '';//token
- public $debug = false;//是否debug的状态标示,方便我们在调试的时候记录一些中间数据
- public $setFlag = false;
- public $msgtype = 'text'; //('text','image','location')
- public $msg = array();
- public function __construct($token,$debug)
- {
- $this->token = $token;
- $this->debug = $debug;
- }
- //获得用户发过来的消息(消息内容和消息类型 )
- public function getMsg()
- {
- $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
- if ($this->debug)
- {
- $this->write_log($postStr);
- }
- if (!empty($postStr))
- {
- $this->msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
- $this->msgtype = strtolower($this->msg['MsgType']);
- }
- }
- //回复文本消息
- public function makeText($text='')
- {
- $CreateTime = time();
- $FuncFlag = $this->setFlag ? 1 : 0;
- $textTpl = "<xml>
- <ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName>
- <FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName>
- <CreateTime>{$CreateTime}</CreateTime>
- <MsgType><![CDATA[text]]></MsgType>
- <Content><![CDATA[%s]]></Content>
- <FuncFlag>%s</FuncFlag>
- </xml>";
- return sprintf($textTpl,$text,$FuncFlag);
- }
- //根据数组参数回复图文消息
- public function makeNews($newsData=array())
- {
- $CreateTime = time();
- $FuncFlag = $this->setFlag ? 1 : 0;
- $newTplHeader = "<xml>
- <ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName>
- <FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName>
- <CreateTime>{$CreateTime}</CreateTime>
- <MsgType><![CDATA[news]]></MsgType>
- <Content><![CDATA[%s]]></Content>
- <ArticleCount>%s</ArticleCount><Articles>";
- $newTplItem = "<item>
- <Title><![CDATA[%s]]></Title>
- <Description><![CDATA[%s]]></Description>
- <PicUrl><![CDATA[%s]]></PicUrl>
- <Url><![CDATA[%s]]></Url>
- </item>";
- $newTplFoot = "</Articles>
- <FuncFlag>%s</FuncFlag>
- </xml>";
- $Content = '';
- $itemsCount = count($newsData);
- $itemsCount = $itemsCount < 10 ? $itemsCount : 10;//微信公众平台图文回复的消息一次最多10条
- if ($itemsCount)
- {
- foreach ($newsData as $key => $item)
- {
- if ($key<=9)
- {
- $Content .= sprintf($newTplItem,$item['Title'],$item['Description'],$item['PicUrl'],$item['Url']);
- }
- }
- }
- $header = sprintf($newTplHeader,$newsData['content'],$itemsCount);
- $footer = sprintf($newTplFoot,$FuncFlag);
- return $header . $Content . $footer;
- }
- public function reply($data)
- {
- if ($this->debug)
- {
- $this->write_log($data);
- }
- echo $data;
- }
- public function valid()
- {
- if ($this->checkSignature())
- {
- //if( $_SERVER['REQUEST_METHOD']=='GET' )
- //{
- echo $_GET['echostr'];
- exit;
- //}
- }
- else
- {
- write_log('认证失败');
- exit;
- }
- }
- private function checkSignature()
- {
- $signature = $_GET["signature"];
- $timestamp = $_GET["timestamp"];
- $nonce = $_GET["nonce"];
- $tmpArr = array($this->token, $timestamp, $nonce);
- sort($tmpArr);
- $tmpStr = implode( $tmpArr );
- $tmpStr = sha1( $tmpStr );
- if( $tmpStr == $signature )
- return true;
- else
- return false;
- }
- private function write_log($log)
- {
- //这里是你记录调试信息的地方 请自行完善 以便中间调试
- }
- }
- ?>
复制代码
微信接口的代码:weixin.php
- <?php
- header("Content-Type: text/html;charset=utf-8");
- include_once('weixin.class.php'); //引用刚定义的微信消息处理类
- define("TOKEN", "itwatch"); //mmhelper
- define('DEBUG', false);
- $weixin = new Weixin(TOKEN, DEBUG); //实例化
- //$weixin->valid();
- $weixin->getMsg();
- $type = $weixin->msgtype; //消息类型
- $username = $weixin->msg['FromUserName']; //哪个用户给你发的消息,这个$username是微信加密之后的,但是每个用户都是一一对应的
- if ($type==='text')
- {
- //if ($weixin->msg['Content']=='Hello2BizUser')
- if ($weixin->msg['Content']=='你好')
- { //微信用户第一次关注你的账号的时候,你的公众账号就会受到一条内容为'Hello2BizUser'的消息
- $reply = $weixin->makeText('欢迎你关注网眼视界威信公众平台');
- }
- else
- { //这里就是用户输入了文本信息
- $keyword = $weixin->msg['Content']; //用户的文本消息内容
- //include_once("chaxun.php"); //文本消息 调用查询程序
- //$chaxun= new chaxun(DEBUG, $keyword, $username);
- //$results['items'] =$chaxun->search(); //查询的代码
- //$reply = $weixin->makeNews($results);
- $arrayCon = array(
- array(
- "Title"=>"电脑学习网",
- "Description"=>"十万个为什么-电脑学习网",
- "PicUrl"=>"<a target="_blank" href="http://www.veryphp.cn/datas/userfiles/8bd108c8a01a892d129c52484ef97a0d/images/website13.jpg">http://www.veryphp.cn/datas/userfiles/8bd108c8a01a892d129c52484ef97a0d/images/website13.jpg</a>",
- "Url"=>"<a target="_blank" href="http://www.why100000.com/">http://www.why100000.com/</a>"
- ),
- array(
- "Title"=>"非常PHP学习网",
- "Description"=>"大型PHP学习分享社区",
- "PicUrl"=>"<a target="_blank" href="http://www.veryphp.cn/datas/userfiles/8bd108c8a01a892d129c52484ef97a0d/images/php01.jpg">http://www.veryphp.cn/datas/userfiles/8bd108c8a01a892d129c52484ef97a0d/images/php01.jpg</a>",
- "Url"=>"<a target="_blank" href="http://www.veryphp.cn/">http://www.veryphp.cn/</a>"
- )
- );
- $results = $arrayCon;
- $reply = $weixin->makeNews($results);
- }
- }
- elseif ($type==='location')
- {
- //用户发送的是位置信息 稍后处理
- }
- elseif ($type==='image')
- {
- //用户发送的是图片 稍后处理
- }elseif ($type==='voice')
- {
- //用户发送的是声音 稍后处理
- }
- //
- $weixin->reply($reply);
- ?>
复制代码
验证微信接口的代码,用 curl 函数完成,需要打开PHP的 curl 扩展。把 weixin.php 文件中的 //$weixin->valid(); 一句的注释去掉即可验证,完了把这句注释掉即可。
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- </head>
- <body>
- <?php
- //header("Content-Type: text/html;charset=utf-8");
- //准备数据
- define('TOKEN', 'itwatch');//自己定义的token 就是个通信的私钥
- $echostr = '返回此数据表明正确。';
- $timestamp = (string)time(); //本身为整数,必须转换为字符串
- $nonce = 'my-nonce';
- $signature = signature(TOKEN, $timestamp, $nonce);
- function signature($token, $timestamp, $nonce)
- {
- $tmpArr = array($token, $timestamp, $nonce);
- sort($tmpArr);
- $tmpStr = implode($tmpArr);
- $tmpStr = sha1($tmpStr);
- return $tmpStr;
- }
- //提交
- $post_data = array(
- "signature=$signature",
- "timestamp=$timestamp",
- "nonce=$nonce",
- "echostr=$echostr"
- );
- $post_data = implode('&',$post_data);
- $url='http://www.veryphp.cn/tools/weixin/weixin.php';
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url.'?'.$post_data); //模拟GET方法
- ob_start();
- curl_exec($ch);
- $result = ob_get_contents();
- ob_end_clean();
- echo $result;
- ?>
复制代码
以上的核心代码是 weixin.class.php 和 weixin.php 两个文件,是我调试成功的,已经部署在我的服务器上了。你要测试的话,用手机微信收听微信号:itwatch,然后输入“你好”,会返回字符串:欢迎你关注网眼视界威信公众平台。随便输入,会打开一个图文消息。
好吧,我承认以上代码写的非常凌乱,因为我十分瞌睡了, 要睡觉了。但以上代码确实是能工作的,是典型的原理实现性测试代码。希望给微信开发者提供个思路,看明白之后可以结合数据库写一个功能完善的微信信息后台管理程序。。
有微信服务号的,可以在此基础上开发个菜单,然后调用仿照以上代码开发的消息回复系统。其实很简单。
这才是真正的网络通信程序,比你写企业站,把数据输进去,再按顺序检索出来分页显示,要有意思的多。
网眼-张庆
2013-12-3
来自圈子: Demo俱乐部 |
|