找回密码
 注册

QQ登录

只需一步,快速开始

查看: 196|回复: 0

模拟测试微信接口暨微信开发试验代码

[复制链接]
发表于 2014-1-22 13:49:47 | 显示全部楼层 |阅读模式
本帖最后由 Test 于 2014-1-22 13:53 编辑

要成为微信公众号(订阅号或服务号)的开发者,需要首先验证接口,这个可以在登录微信https://mp.weixin.qq.com后台后设置。但是我嫌麻烦,于是开发个接口类,包含验证函数(还有回复文本信息和图文信息的功能)。其实接口验证在成为开发者之后就没用了。
上代码,微信基类:weixin.class.php
  1. <?php
  2. class Weixin
  3. {
  4.   public $token = '';//token
  5.   public $debug =  false;//是否debug的状态标示,方便我们在调试的时候记录一些中间数据
  6.   public $setFlag = false;
  7.   public $msgtype = 'text';   //('text','image','location')
  8.   public $msg = array();
  9.   public function __construct($token,$debug)
  10.   {
  11.   $this->token = $token;
  12.   $this->debug = $debug;
  13.   }
  14.   //获得用户发过来的消息(消息内容和消息类型  )
  15.   public function getMsg()
  16.   {
  17.     $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
  18.     if ($this->debug)
  19.     {
  20.       $this->write_log($postStr);
  21.     }
  22.     if (!empty($postStr))
  23.     {
  24.       $this->msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  25.       $this->msgtype = strtolower($this->msg['MsgType']);
  26.     }
  27.   }
  28.   //回复文本消息
  29.   public function makeText($text='')
  30.   {
  31.     $CreateTime = time();
  32.     $FuncFlag = $this->setFlag ? 1 : 0;
  33.     $textTpl = "<xml>
  34.       <ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName>
  35.       <FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName>
  36.       <CreateTime>{$CreateTime}</CreateTime>
  37.       <MsgType><![CDATA[text]]></MsgType>
  38.       <Content><![CDATA[%s]]></Content>
  39.       <FuncFlag>%s</FuncFlag>
  40.       </xml>";
  41.     return sprintf($textTpl,$text,$FuncFlag);
  42.   }
  43.   //根据数组参数回复图文消息
  44.   public function makeNews($newsData=array())
  45.   {
  46.     $CreateTime = time();
  47.     $FuncFlag = $this->setFlag ? 1 : 0;
  48.     $newTplHeader = "<xml>
  49.       <ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName>
  50.       <FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName>
  51.       <CreateTime>{$CreateTime}</CreateTime>
  52.       <MsgType><![CDATA[news]]></MsgType>
  53.       <Content><![CDATA[%s]]></Content>
  54.       <ArticleCount>%s</ArticleCount><Articles>";
  55.     $newTplItem = "<item>
  56.       <Title><![CDATA[%s]]></Title>
  57.       <Description><![CDATA[%s]]></Description>
  58.       <PicUrl><![CDATA[%s]]></PicUrl>
  59.       <Url><![CDATA[%s]]></Url>
  60.       </item>";
  61.     $newTplFoot = "</Articles>
  62.       <FuncFlag>%s</FuncFlag>
  63.       </xml>";
  64.     $Content = '';
  65.     $itemsCount = count($newsData);
  66.     $itemsCount = $itemsCount < 10 ? $itemsCount : 10;//微信公众平台图文回复的消息一次最多10条
  67.     if ($itemsCount)
  68.     {
  69.       foreach ($newsData as $key => $item)
  70.       {
  71.         if ($key<=9)
  72.         {
  73.           $Content .= sprintf($newTplItem,$item['Title'],$item['Description'],$item['PicUrl'],$item['Url']);
  74.         }
  75.       }
  76.     }
  77.     $header = sprintf($newTplHeader,$newsData['content'],$itemsCount);
  78.     $footer = sprintf($newTplFoot,$FuncFlag);
  79.     return $header . $Content . $footer;
  80.   }
  81.   public function reply($data)
  82.   {
  83.     if ($this->debug)
  84.     {
  85.       $this->write_log($data);
  86.     }
  87.     echo $data;
  88.   }
  89.   public function valid()
  90.   {
  91.     if ($this->checkSignature())
  92.     {
  93.       //if( $_SERVER['REQUEST_METHOD']=='GET' )
  94.       //{
  95.         echo $_GET['echostr'];
  96.         exit;
  97.       //}
  98.     }
  99.     else
  100.     {
  101.       write_log('认证失败');
  102.       exit;
  103.     }
  104.   }
  105.   private function checkSignature()
  106.   {
  107.     $signature = $_GET["signature"];
  108.     $timestamp = $_GET["timestamp"];
  109.     $nonce = $_GET["nonce"];
  110.     $tmpArr = array($this->token, $timestamp, $nonce);
  111.     sort($tmpArr);
  112.     $tmpStr = implode( $tmpArr );
  113.     $tmpStr = sha1( $tmpStr );
  114.     if( $tmpStr == $signature )
  115.       return true;
  116.     else
  117.       return false;
  118.   }
  119.   private function write_log($log)
  120.   {
  121.     //这里是你记录调试信息的地方  请自行完善   以便中间调试
  122.   }
  123. }
  124. ?>
复制代码

微信接口的代码:weixin.php
  1. <?php
  2.   header("Content-Type: text/html;charset=utf-8");
  3.   include_once('weixin.class.php');  //引用刚定义的微信消息处理类
  4.   define("TOKEN", "itwatch");  //mmhelper
  5.   define('DEBUG', false);
  6.   $weixin = new Weixin(TOKEN, DEBUG);  //实例化
  7.   //$weixin->valid();
  8.   $weixin->getMsg();
  9.   $type = $weixin->msgtype;  //消息类型
  10.   $username = $weixin->msg['FromUserName']; //哪个用户给你发的消息,这个$username是微信加密之后的,但是每个用户都是一一对应的
  11.   if ($type==='text')
  12.   {
  13.     //if ($weixin->msg['Content']=='Hello2BizUser')
  14.     if ($weixin->msg['Content']=='你好')
  15.     { //微信用户第一次关注你的账号的时候,你的公众账号就会受到一条内容为'Hello2BizUser'的消息
  16.       $reply = $weixin->makeText('欢迎你关注网眼视界威信公众平台');
  17.     }
  18.     else
  19.     {  //这里就是用户输入了文本信息
  20.       $keyword = $weixin->msg['Content'];   //用户的文本消息内容
  21.       //include_once("chaxun.php");  //文本消息 调用查询程序
  22.       //$chaxun= new chaxun(DEBUG, $keyword, $username);
  23.       //$results['items'] =$chaxun->search();  //查询的代码
  24.       //$reply = $weixin->makeNews($results);
  25.       $arrayCon = array(
  26.         array(
  27.           "Title"=>"电脑学习网",
  28.           "Description"=>"十万个为什么-电脑学习网",
  29.           "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>",
  30.           "Url"=>"<a target="_blank" href="http://www.why100000.com/">http://www.why100000.com/</a>"
  31.         ),
  32.         array(
  33.           "Title"=>"非常PHP学习网",
  34.           "Description"=>"大型PHP学习分享社区",
  35.           "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>",
  36.           "Url"=>"<a target="_blank" href="http://www.veryphp.cn/">http://www.veryphp.cn/</a>"
  37.         )
  38.       );
  39.       $results  = $arrayCon;
  40.       $reply = $weixin->makeNews($results);
  41.     }
  42.   }
  43.   elseif ($type==='location')
  44.   {
  45.     //用户发送的是位置信息 稍后处理
  46.   }
  47.   elseif ($type==='image')
  48.   {
  49.     //用户发送的是图片 稍后处理
  50.   }elseif ($type==='voice')
  51.   {
  52.     //用户发送的是声音 稍后处理
  53.   }
  54.   //
  55.   $weixin->reply($reply);
  56. ?>
复制代码


验证微信接口的代码,用 curl 函数完成,需要打开PHP的 curl 扩展。把 weixin.php 文件中的   //$weixin->valid(); 一句的注释去掉即可验证,完了把这句注释掉即可。
  1. <html>
  2. <head>
  3.   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  4. </head>
  5. <body>
  6. <?php
  7.   //header("Content-Type: text/html;charset=utf-8");
  8.   //准备数据
  9.   define('TOKEN', 'itwatch');//自己定义的token 就是个通信的私钥
  10.   $echostr = '返回此数据表明正确。';
  11.   $timestamp = (string)time();  //本身为整数,必须转换为字符串
  12.   $nonce = 'my-nonce';
  13.   $signature = signature(TOKEN, $timestamp, $nonce);

  14.   function signature($token, $timestamp, $nonce)
  15.   {
  16.     $tmpArr = array($token, $timestamp, $nonce);
  17.     sort($tmpArr);
  18.     $tmpStr = implode($tmpArr);
  19.     $tmpStr = sha1($tmpStr);
  20.     return $tmpStr;
  21.   }
  22.   //提交
  23.   $post_data = array(
  24.       "signature=$signature",
  25.       "timestamp=$timestamp",
  26.       "nonce=$nonce",
  27.       "echostr=$echostr"
  28.     );
  29.   $post_data = implode('&',$post_data);
  30.   $url='http://www.veryphp.cn/tools/weixin/weixin.php';
  31.   $ch = curl_init();
  32.   curl_setopt($ch, CURLOPT_URL, $url.'?'.$post_data); //模拟GET方法
  33.   ob_start();
  34.   curl_exec($ch);
  35.   $result = ob_get_contents();
  36.   ob_end_clean();
  37.   echo $result;
  38. ?>
复制代码


以上的核心代码是 weixin.class.php 和 weixin.php 两个文件,是我调试成功的,已经部署在我的服务器上了。你要测试的话,用手机微信收听微信号:itwatch,然后输入“你好”,会返回字符串:欢迎你关注网眼视界威信公众平台。随便输入,会打开一个图文消息。
   
好吧,我承认以上代码写的非常凌乱,因为我十分瞌睡了, 要睡觉了。但以上代码确实是能工作的,是典型的原理实现性测试代码。希望给微信开发者提供个思路,看明白之后可以结合数据库写一个功能完善的微信信息后台管理程序。。
有微信服务号的,可以在此基础上开发个菜单,然后调用仿照以上代码开发的消息回复系统。其实很简单。
这才是真正的网络通信程序,比你写企业站,把数据输进去,再按顺序检索出来分页显示,要有意思的多。

网眼-张庆
2013-12-3
来自圈子: Demo俱乐部
您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )

GMT-8, 2026-6-16 11:01 , Processed in 0.025493 second(s), 16 queries .

Supported by Weloment Group X3.5

© 2008-2026 Best Deal Online

快速回复 返回顶部 返回列表