> 백엔드 개발 > PHP 튜토리얼 > 微信公众平台开发(二) 微信公众平台示例代码分析_PHP教程

微信公众平台开发(二) 微信公众平台示例代码分析_PHP教程

WBOY
풀어 주다: 2016-07-20 11:14:05
원래의
1113명이 탐색했습니다.

微信公众平台提供了一个简单的php示例代码,在做进一步开发之前,我们有必要将其详细了解一下。

微信官网:http://mp.weixin.qq.com/mpres/htmledition/res/wx_sample.zip

完整代码如下:

<?<span php
</span><span /*</span><span *
  * wechat php test
  </span><span */</span>

<span //</span><span define your token</span>
<span define</span>("TOKEN", "weixin"<span );
</span><span $wechatObj</span> = <span new</span><span  wechatCallbackapiTest();
</span><span $wechatObj</span>-><span valid();

</span><span class</span><span  wechatCallbackapiTest
{
    </span><span public</span> <span function</span><span  valid()
    {
        </span><span $echoStr</span> = <span $_GET</span>["echostr"<span ];

        </span><span //</span><span valid signature , option</span>
        <span if</span>(<span $this</span>-><span checkSignature()){
            </span><span echo</span> <span $echoStr</span><span ;
            </span><span exit</span><span ;
        }
    }

    </span><span public</span> <span function</span><span  responseMsg()
    {
        </span><span //</span><span get post data, May be due to the different environments</span>
        <span $postStr</span> = <span $GLOBALS</span>["HTTP_RAW_POST_DATA"<span ];

        </span><span //</span><span extract post data</span>
        <span if</span> (!<span empty</span>(<span $postStr</span><span )){
                
                </span><span $postObj</span> = <span simplexml_load_string</span>(<span $postStr</span>, 'SimpleXMLElement',<span  LIBXML_NOCDATA);
                </span><span $fromUsername</span> = <span $postObj</span>-><span FromUserName;
                </span><span $toUsername</span> = <span $postObj</span>-><span ToUserName;
                </span><span $keyword</span> = <span trim</span>(<span $postObj</span>-><span Content);
                </span><span $time</span> = <span time</span><span ();
                </span><span $textTpl</span> = "<span <xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            <FuncFlag>0</FuncFlag>
                            </xml></span>"<span ;             
                </span><span if</span>(!<span empty</span>( <span $keyword</span><span  ))
                {
                    </span><span $msgType</span> = "text"<span ;
                    </span><span $contentStr</span> = "Welcome to wechat world!"<span ;
                    </span><span $resultStr</span> = <span sprintf</span>(<span $textTpl</span>, <span $fromUsername</span>, <span $toUsername</span>, <span $time</span>, <span $msgType</span>, <span $contentStr</span><span );
                    </span><span echo</span> <span $resultStr</span><span ;
                }</span><span else</span><span {
                    </span><span echo</span> "Input something..."<span ;
                }

        }</span><span else</span><span  {
            </span><span echo</span> ""<span ;
            </span><span exit</span><span ;
        }
    }
        
    </span><span private</span> <span function</span><span  checkSignature()
    {
        </span><span $signature</span> = <span $_GET</span>["signature"<span ];
        </span><span $timestamp</span> = <span $_GET</span>["timestamp"<span ];
        </span><span $nonce</span> = <span $_GET</span>["nonce"<span ];    
                
        </span><span $token</span> =<span  TOKEN;
        </span><span $tmpArr</span> = <span array</span>(<span $token</span>, <span $timestamp</span>, <span $nonce</span><span );
        </span><span sort</span>(<span $tmpArr</span><span );
        </span><span $tmpStr</span> = <span implode</span>( <span $tmpArr</span><span  );
        </span><span $tmpStr</span> = <span sha1</span>( <span $tmpStr</span><span  );
        
        </span><span if</span>( <span $tmpStr</span> == <span $signature</span><span  ){
            </span><span return</span> <span true</span><span ;
        }</span><span else</span><span {
            </span><span return</span> <span false</span><span ;
        }
    }
}

</span>?>
로그인 후 복사

3.1 整体分析

原始示例代码大致分为四个部分:

  • 定义TOKEN
  • 声明一个类 wechatCallbackapiTest
  • 创建类wechatCallbackapiTest 的一个实例对象 $wechatObj
  • 调用类的 valid() 方法。

3.2 详细分析

3.2.1 定义TOKEN

3.2.2 声明一个类

<span <span><span><span <strong>responseMsg 函数详解:</strong></span><br /><br /></span></span><span>$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];</span><br />接收微信公众平台发送过来的用户消息,该消息数据结构为XML,不是php默认的识别数据类型,因此这里用了$GLOBALS['HTTP_RAW_POST_DATA']来接收,同时赋值给了$postStr<br /><br />if (!empty($postStr))<br />判断$postStr是否为空,如果不为空(接收到了数据),就继续执行下面的语句;如果为空,则跳转到与之相对应的else语句。<br /><br />$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);<br />使用simplexml_load_string() 函数将接收到的XML消息数据载入对象$postObj中。这个严谨的写法后面还得加个判断是否载入成功的条件语句,不过不写也没事。<br /><br />$fromUsername = $postObj->FromUserName;<br />将对象$postObj中的发送消息用户的OPENID赋值给$fromUsername变量<br /><br />$toUsername = $postObj->ToUserName;<br />将对象$postObj中的公众账号的ID赋值给$toUsername变量<br /><br />$keyword = trim($postObj->Content);<br />trim() 函数从字符串的两端删除空白字符和其他预定义字符,这里就可以得到用户输入的关键词<br /><br />$time = time();<br />time() 函数返回当前时间的 Unix 时间戳,即自从 Unix 纪元(格林威治时间 1970 年 1 月 1 日 00:00:00)到当前时间的秒数。<br /><br />$textTpl = "<xml><br /></span>       <ToUserName><![CDATA[%s]]></ToUserName><br />       <FromUserName><![CDATA[%s]]></FromUserName><br />        <CreateTime>%s</CreateTime><br />       <MsgType><![CDATA[%s]]></MsgType><br />       <Content><![CDATA[%s]]></Content><br />       <FuncFlag>0</FuncFlag><br />       </xml>";<br />存放微信输出内容的模板<br /><br />if(!empty( $keyword ))<br />判断$keyword是否为空,不为空则继续执行下面的语句;如果为空,则跳转到与之相对应的else语句,即 echo "Input something...";<br /><br />$msgType = "text";<br />消息类型是文本类型<br /><br />$contentStr = "Welcome to wechat world!";<br />回复的消息内容<br /><br />$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);<br />使用sprintf() 函数将格式化的数据写入到变量中去;<br />$fromUsername, $toUsername, $time, $msgType, $contentStr 分别顺序替换模板里&ldquo;%s&rdquo;位置,也即是&ldquo;$resultStr&rdquo;这个变量最后实际为:
로그인 후 복사




$time


0 //位0x0001被标志时,星标刚收到的消息。

echo $resultStr; //把回复的消息输出

<span 加密/校验流程:
1. 将token、timestamp、nonce三个参数进行字典序排序
2. 将三个参数字符串拼接成一个字符串进行sha1加密
3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信</span>
로그인 후 복사

3.2.4 调用类方法验证

$wechatObj->valid();

以上是对微信官方示例代码的一个分析,有解释不对的地方,还请高手指出。另外,该代码只是官方给出的简单示例代码,如果要做复杂的开发,还是要求开发者按照严谨的开发模式改写该段代码,会在后续教程中娓娓道来。

微信官方公众平台API文档:http://mp.weixin.qq.com/wiki/index.php

请关注 卓锦苏州 微信公众帐号,卓锦苏州 基于SAE 平台开发,针对于主流的微信功能进行开发测试。

您可以关注 卓锦苏州 公众帐号进行功能测试,以及获取新的应用开发。

1. 登录微信客户端,朋友们 -> 添加朋友 -> 搜号码 -> zhuojinsz,查找并关注。

2. 扫描二维码:

卓锦苏州 功能列表。

 


We Believe, Great People Share Knowledge...

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/440310.htmlTechArticle微信公众平台提供了一个简单的php示例代码,在做进一步开发之前,我们有必要将其详细了解一下。 微信官网:http://mp.weixin.qq.com/mpres/ht...
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿