PHP微信公众平台开发(二) 公众平台示例代码分
【PHP微信公众平台开发系列】
01.配置微信接口
02.公众平台示例代码分析
本文地址:http://www.phpchina.com/archives/view-43358-1.html
本系列由PHPChina特邀作者@David_Tang供稿,转载请注明作者信息与本文地址。
一、摘要
微信公众平台提供了一个简单的php示例代码,在做进一步开发之前,我们有必要将其详细了解一下。
二、获取代码
微信官网:http://mp.weixin.qq.com/mpres/htmledition/res/wx_sample.zip
三、分析代码
完整代码如下:
<?php /** * wechat php test */ //define your token define("TOKEN", "weixin"); $wechatObj = new wechatCallbackapiTest(); $wechatObj->valid(); class wechatCallbackapiTest { public function valid() { $echoStr = $_GET["echostr"]; //valid signature , option if($this->checkSignature()){ echo $echoStr; exit; } } public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //extract post data if (!empty($postStr)){ $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml>"; if(!empty( $keyword )) { $msgType = "text"; $contentStr = "Welcome to wechat world!"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; }else{ echo "Input something..."; } }else { echo ""; exit; } } private function checkSignature() { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } } } ?>
3.1 整体分析
原始示例代码大致分为四个部分:
- 定义TOKEN
- 声明一个类 wechatCallbackapiTest
- 创建类wechatCallbackapiTest 的一个实例对象 $wechatObj
- 调用类的 valid() 方法。
3.2 详细分析
3.2.1 定义TOKEN
define("TOKEN", "weixin");
define 是用来给常量赋值的函数,这句话的意思是赋予“TOKEN”这个常量值为“weixin”。
TOKEN 是用来进行交互安全认证的,开发者可以随意定义,要和公众平台里设置的一样。
3.2.2 声明一个类
class wechatCallbackapiTest{
}
声明一个类 wechatCallbackapiTest,该类中包含有三个方法(函数)。
a. public function valid()
用于申请 成为开发者 时向微信发送验证信息。
b. public function responseMsg()
处理并回复用户发送过来的消息,也是用的最多的一个函数,几乎所有的功能都在这里实现。
<strong>responseMsg 函数详解:</strong> $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; 接收微信公众平台发送过来的用户消息,该消息数据结构为XML,不是php默认的识别数据类型,因此这里用了$GLOBALS['HTTP_RAW_POST_DATA']来接收,同时赋值给了$postStr if (!empty($postStr)) 判断$postStr是否为空,如果不为空(接收到了数据),就继续执行下面的语句;如果为空,则跳转到与之相对应的else语句。 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); 使用simplexml_load_string() 函数将接收到的XML消息数据载入对象$postObj中。这个严谨的写法后面还得加个判断是否载入成功的条件语句,不过不写也没事。 $fromUsername = $postObj->FromUserName; 将对象$postObj中的发送消息用户的OPENID赋值给$fromUsername变量 $toUsername = $postObj->ToUserName; 将对象$postObj中的公众账号的ID赋值给$toUsername变量 $keyword = trim($postObj->Content); trim() 函数从字符串的两端删除空白字符和其他预定义字符,这里就可以得到用户输入的关键词 $time = time(); time() 函数返回当前时间的 Unix 时间戳,即自从 Unix 纪元(格林威治时间 1970 年 1 月 1 日 00:00:00)到当前时间的秒数。 $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml>"; 存放微信输出内容的模板 if(!empty( $keyword )) 判断$keyword是否为空,不为空则继续执行下面的语句;如果为空,则跳转到与之相对应的else语句,即 echo "Input something..."; $msgType = "text"; 消息类型是文本类型 $contentStr = "Welcome to wechat world!"; 回复的消息内容 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); 使用sprintf() 函数将格式化的数据写入到变量中去; $fromUsername, $toUsername, $time, $msgType, $contentStr 分别顺序替换模板里“%s”位置,也即是“$resultStr”这个变量最后实际为:
echo $resultStr; //把回复的消息输出
c. private function checkSignature()
开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请求原样返回echostr参数内容,则接入生效,否则接入失败。
signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
加密/校验流程: 1. 将token、timestamp、nonce三个参数进行字典序排序 2. 将三个参数字符串拼接成一个字符串进行sha1加密 3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
3.2.3 创建实例对象
$wechatObj = new wechatCallbackapiTest();
3.2.4 调用类方法验证
$wechatObj->valid();
调用类的valid()方法执行接口验证,接口设置成功后将其注释掉。
四、总结
以上是对微信官方示例代码的一个分析,有解释不对的地方,还请高手指出。另外,该代码只是官方给出的简单示例代码,如果要做复杂的开发,还是要求开发者按照严谨的开发模式改写该段代码,会在后续教程中娓娓道来。
五、参考
微信官方公众平台API文档:http://mp.weixin.qq.com/wiki/index.php

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

Strict types in PHP are enabled by adding declare(strict_types=1); at the top of the file. 1) It forces type checking of function parameters and return values to prevent implicit type conversion. 2) Using strict types can improve the reliability and predictability of the code, reduce bugs, and improve maintainability and readability.

Compatibility issues and troubleshooting methods for company security software and application. Many companies will install security software in order to ensure intranet security. However, security software sometimes...
