Update wechat.lib.php注释

src
p9x75mskn 2 months ago
parent c1eb3c2b85
commit 38d9717a6c

@ -1,62 +1,93 @@
<?php
// 定义命名空间,用于组织代码
namespace LaneWeChat\Core;
// Wechat类定义用于处理微信相关功能
class Wechat{
// 私有属性,用于调试模式和请求数据
private $debug;
private $request;
// 构造函数用于初始化Wechat对象
public function __construct($token, $debug = FALSE) {
// 检查是否是微信服务器的验证请求,并验证签名
if ($this->isValid() && $this->validateSignature($token)) {
// 如果验证通过返回echostr给微信服务器
return $_GET['echostr'];
}
// 设置调试模式
$this->debug = $debug;
// 解析微信发送的XML数据
$xml = (array) simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA'], 'SimpleXMLElement', LIBXML_NOCDATA);
// 将XML数据转换为数组并转换所有键为小写
$this->request = array_change_key_case($xml, CASE_LOWER);
}
// 私有方法isValid用于检查是否是微信服务器的验证请求
private function isValid() {
// 检查是否存在echostr参数该参数在微信服务器验证时存在
return isset($_GET['echostr']);
}
// 私有方法validateSignature用于验证签名
private function validateSignature($token) {
// 获取微信服务器发送的signature、timestamp、nonce参数
$signature = $_GET['signature'];
$timestamp = $_GET['timestamp'];
$nonce = $_GET['nonce'];
// 将token、timestamp、nonce组合并排序
$signatureArray = array($token, $timestamp, $nonce);
sort($signatureArray, SORT_STRING);
// 计算签名并比较
return sha1(implode($signatureArray)) == $signature;
}
// 受保护的方法getRequest用于获取请求参数
protected function getRequest($param = FALSE) {
// 如果没有指定参数,则返回所有请求参数
if ($param === FALSE) {
return $this->request;
}
// 将参数名转为小写
$param = strtolower($param);
// 如果请求参数存在,则返回该参数的值
if (isset($this->request[$param])) {
return $this->request[$param];
}
// 如果请求参数不存在则返回NULL
return NULL;
}
// 公共方法run用于处理微信请求
public function run() {
// 根据请求类型分发处理
return WechatRequest::switchType($this->request);
}
// 公共方法checkSignature用于检查签名
public function checkSignature()
{
// 获取微信服务器发送的signature、timestamp、nonce参数
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
// 获取配置中的token
$token = WECHAT_TOKEN;
// 将token、timestamp、nonce组合并排序
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
// 将组合后的字符串转为sha1签名
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
// 比较计算出的签名和微信服务器发送的签名
if( $tmpStr == $signature ){
// 如果签名匹配返回echostr给微信服务器
echo $_GET['echostr'];
return true;
}else{
// 如果签名不匹配返回false
return false;
}
}

Loading…
Cancel
Save