更新内核

增加自定义表单(未完成)
This commit is contained in:
2017-07-04 12:13:24 +08:00
parent 8af311aa07
commit aef819d417
82 changed files with 12328 additions and 59 deletions

View File

@@ -0,0 +1,93 @@
<?php
namespace Wechat\Lib;
use Wechat\Loader;
/**
* 微信SDK基础缓存类
*
* @author Anyon <zoujingli@qq.com>
* @date 2016-08-20 17:50
*/
class Cache {
/**
* 缓存位置
* @var string
*/
static public $cachepath;
/**
* 设置缓存
* @param string $name
* @param string $value
* @param int $expired
* @return mixed
*/
static public function set($name, $value, $expired = 0) {
if (isset(Loader::$callback['CacheSet'])) {
return call_user_func_array(Loader::$callback['CacheSet'], func_get_args());
}
$data = serialize(array('value' => $value, 'expired' => $expired > 0 ? time() + $expired : 0));
return self::check() && file_put_contents(self::$cachepath . $name, $data);
}
/**
* 读取缓存
* @param string $name
* @return mixed
*/
static public function get($name) {
if (isset(Loader::$callback['CacheGet'])) {
return call_user_func_array(Loader::$callback['CacheGet'], func_get_args());
}
if (self::check() && ($file = self::$cachepath . $name) && file_exists($file) && ($data = file_get_contents($file)) && !empty($data)) {
$data = unserialize($data);
if (isset($data['expired']) && ($data['expired'] > time() || $data['expired'] === 0)) {
return isset($data['value']) ? $data['value'] : null;
}
}
return null;
}
/**
* 删除缓存
* @param string $name
* @return mixed
*/
static public function del($name) {
if (isset(Loader::$callback['CacheDel'])) {
return call_user_func_array(Loader::$callback['CacheDel'], func_get_args());
}
return self::check() && @unlink(self::$cachepath . $name);
}
/**
* 输出内容到日志
* @param string $line
* @param string $filename
* @return mixed
*/
static public function put($line, $filename = '') {
if (isset(Loader::$callback['CachePut'])) {
return call_user_func_array(Loader::$callback['CachePut'], func_get_args());
}
empty($filename) && $filename = date('Ymd') . '.log';
return self::check() && file_put_contents(self::$cachepath . $filename, '[' . date('Y/m/d H:i:s') . "] {$line}\n", FILE_APPEND);
}
/**
* 检查缓存目录
* @return bool
*/
static protected function check() {
empty(self::$cachepath) && self::$cachepath = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Cache' . DIRECTORY_SEPARATOR;
self::$cachepath = rtrim(self::$cachepath, '/\\') . DIRECTORY_SEPARATOR;
if (!is_dir(self::$cachepath) && !mkdir(self::$cachepath, 0755, TRUE)) {
return FALSE;
}
return TRUE;
}
}

View File

@@ -0,0 +1,179 @@
<?php
namespace Wechat\Lib;
use Prpcrypt;
use Wechat\Loader;
/**
* 微信SDK基础类
*
* @category WechatSDK
* @subpackage library
* @author Anyon <zoujingli@qq.com>
* @date 2016/05/28 11:55
*/
class Common {
/** API接口URL需要使用此前缀 */
const API_BASE_URL_PREFIX = 'https://api.weixin.qq.com';
const API_URL_PREFIX = 'https://api.weixin.qq.com/cgi-bin';
const GET_TICKET_URL = '/ticket/getticket?';
const AUTH_URL = '/token?grant_type=client_credential&';
public $token;
public $encodingAesKey;
public $encrypt_type;
public $appid;
public $appsecret;
public $access_token;
public $postxml;
public $_msg;
public $errCode = 0;
public $errMsg = "";
public $config = array();
private $_retry = FALSE;
/**
* 构造方法
* @param array $options
*/
public function __construct($options = array()) {
$config = Loader::config($options);
$this->token = isset($config['token']) ? $config['token'] : '';
$this->appid = isset($config['appid']) ? $config['appid'] : '';
$this->appsecret = isset($config['appsecret']) ? $config['appsecret'] : '';
$this->encodingAesKey = isset($config['encodingaeskey']) ? $config['encodingaeskey'] : '';
$this->config = $config;
}
/**
* 接口验证
* @return bool
*/
public function valid() {
$encryptStr = "";
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$postStr = file_get_contents("php://input");
$array = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$this->encrypt_type = isset($_GET["encrypt_type"]) ? $_GET["encrypt_type"] : '';
if ($this->encrypt_type == 'aes') {
$encryptStr = $array['Encrypt'];
!class_exists('Prpcrypt', FALSE) && require __DIR__ . '/Prpcrypt.php';
$pc = new Prpcrypt($this->encodingAesKey);
$array = $pc->decrypt($encryptStr, $this->appid);
if (!isset($array[0]) || intval($array[0]) > 0) {
$this->errCode = $array[0];
$this->errMsg = $array[1];
Tools::log("Interface Authentication Failed. {$this->errMsg}[{$this->errCode}]", 'ERR');
return false;
}
$this->postxml = $array[1];
empty($this->appid) && $this->appid = $array[2];
} else {
$this->postxml = $postStr;
}
} elseif (isset($_GET["echostr"])) {
if ($this->checkSignature()) {
exit($_GET["echostr"]);
} else {
return false;
}
}
if (!$this->checkSignature($encryptStr)) {
$this->errMsg = 'Interface authentication failed, please use the correct method to call.';
return false;
}
return true;
}
/**
* 验证来自微信服务器
* @param string $str
* @return bool
*/
private function checkSignature($str = '') {
// 如果存在加密验证则用加密验证段
$signature = isset($_GET["msg_signature"]) ? $_GET["msg_signature"] : (isset($_GET["signature"]) ? $_GET["signature"] : '');
$timestamp = isset($_GET["timestamp"]) ? $_GET["timestamp"] : '';
$nonce = isset($_GET["nonce"]) ? $_GET["nonce"] : '';
$tmpArr = array($this->token, $timestamp, $nonce, $str);
sort($tmpArr, SORT_STRING);
if (sha1(implode($tmpArr)) == $signature) {
return true;
} else {
return false;
}
}
/**
* 获取公众号访问 access_token
* @param string $appid 如在类初始化时已提供,则可为空
* @param string $appsecret 如在类初始化时已提供,则可为空
* @param string $token 手动指定access_token非必要情况不建议用
* @return bool|string
*/
public function getAccessToken($appid = '', $appsecret = '', $token = '') {
if (!$appid || !$appsecret) {
$appid = $this->appid;
$appsecret = $this->appsecret;
}
if ($token) {
return $this->access_token = $token;
}
$cache = 'wechat_access_token_' . $appid;
if (($access_token = Tools::getCache($cache)) && !empty($access_token)) {
return $this->access_token = $access_token;
}
# 检测事件注册
if (isset(Loader::$callback[__FUNCTION__])) {
return $this->access_token = call_user_func_array(Loader::$callback[__FUNCTION__], array(&$this, &$cache));
}
$result = Tools::httpGet(self::API_URL_PREFIX . self::AUTH_URL . 'appid=' . $appid . '&secret=' . $appsecret);
if ($result) {
$json = json_decode($result, true);
if (!$json || isset($json['errcode'])) {
$this->errCode = $json['errcode'];
$this->errMsg = $json['errmsg'];
Tools::log("Get New AccessToken Error. {$this->errMsg}[{$this->errCode}]", 'ERR');
return false;
}
$this->access_token = $json['access_token'];
Tools::log("Get New AccessToken Success.");
Tools::setCache($cache, $this->access_token, 5000);
return $this->access_token;
}
return false;
}
/**
* 接口失败重试
* @param $method SDK方法名称
* @param array $arguments SDK方法参数
* @return bool|mixed
*/
protected function checkRetry($method, $arguments = array()) {
if (!$this->_retry && in_array($this->errCode, array('40014', '40001', '41001', '42001'))) {
Tools::log("Run {$method} Faild. {$this->errMsg}[{$this->errCode}]", 'ERR');
($this->_retry = true) && $this->resetAuth();
$this->errCode = 40001;
$this->errMsg = 'no access';
Tools::log("Retry Run {$method} ...");
return call_user_func_array(array($this, $method), $arguments);
}
return false;
}
/**
* 删除验证数据
* @param string $appid 如在类初始化时已提供,则可为空
* @return bool
*/
public function resetAuth($appid = '') {
$authname = 'wechat_access_token_' . (empty($appid) ? $this->appid : $appid);
Tools::log("Reset Auth And Remove Old AccessToken.");
$this->access_token = '';
Tools::removeCache($authname);
return true;
}
}

View File

@@ -0,0 +1,176 @@
<?php
/**
* PKCS7算法 加解密
* @category WechatSDK
* @subpackage library
* @date 2016/06/28 11:59
*/
class PKCS7Encoder {
public static $block_size = 32;
/**
* 对需要加密的明文进行填充补位
* @param string $text 需要进行填充补位操作的明文
* @return string 补齐明文字符串
*/
function encode($text) {
$amount_to_pad = PKCS7Encoder::$block_size - (strlen($text) % PKCS7Encoder::$block_size);
if ($amount_to_pad == 0) {
$amount_to_pad = PKCS7Encoder::$block_size;
}
$pad_chr = chr($amount_to_pad);
$tmp = "";
for ($index = 0; $index < $amount_to_pad; $index++) {
$tmp .= $pad_chr;
}
return $text . $tmp;
}
/**
* 对解密后的明文进行补位删除
* @param string $text 解密后的明文
* @return string 删除填充补位后的明文
*/
function decode($text) {
$pad = ord(substr($text, -1));
if ($pad < 1 || $pad > PKCS7Encoder::$block_size) {
$pad = 0;
}
return substr($text, 0, (strlen($text) - $pad));
}
}
/**
* 接收和推送给公众平台消息的加解密
* @category WechatSDK
* @subpackage library
* @date 2016/06/28 11:59
*/
class Prpcrypt {
public $key;
function __construct($k) {
$this->key = base64_decode($k . "=");
}
/**
* 对明文进行加密
* @param string $text 需要加密的明文
* @param string $appid 公众号APPID
* @return string 加密后的密文
*/
public function encrypt($text, $appid) {
try {
//获得16位随机字符串填充到明文之前
$random = $this->getRandomStr();//"aaaabbbbccccdddd";
$text = $random . pack("N", strlen($text)) . $text . $appid;
$iv = substr($this->key, 0, 16);
$pkc_encoder = new PKCS7Encoder;
$text = $pkc_encoder->encode($text);
$encrypted = openssl_encrypt($text, 'AES-256-CBC', substr($this->key, 0, 32), OPENSSL_ZERO_PADDING, $iv);
return array(ErrorCode::$OK, $encrypted);
} catch (Exception $e) {
return array(ErrorCode::$EncryptAESError, null);
}
}
/**
* 对密文进行解密
* @param string $encrypted 需要解密的密文
* @param string $appid 公众号APPID
* @return string 解密得到的明文
*/
public function decrypt($encrypted, $appid) {
try {
$iv = substr($this->key, 0, 16);
$decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', substr($this->key, 0, 32), OPENSSL_ZERO_PADDING, $iv);
} catch (Exception $e) {
return array(ErrorCode::$DecryptAESError, null);
}
try {
$pkc_encoder = new PKCS7Encoder;
$result = $pkc_encoder->decode($decrypted);
if (strlen($result) < 16) {
return "";
}
$content = substr($result, 16, strlen($result));
$len_list = unpack("N", substr($content, 0, 4));
$xml_len = $len_list[1];
$xml_content = substr($content, 4, $xml_len);
$from_appid = substr($content, $xml_len + 4);
if (!$appid) {
$appid = $from_appid;
}
} catch (Exception $e) {
return array(ErrorCode::$IllegalBuffer, null);
}
return array(0, $xml_content, $from_appid);
}
/**
* 随机生成16位字符串
* @return string 生成的字符串
*/
function getRandomStr() {
$str = "";
$str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
$max = strlen($str_pol) - 1;
for ($i = 0; $i < 16; $i++) {
$str .= $str_pol[mt_rand(0, $max)];
}
return $str;
}
}
/**
* 仅用作类内部使用
* 不用于官方API接口的errCode码
* Class ErrorCode
*/
class ErrorCode {
public static $OK = 0;
public static $ValidateSignatureError = 40001;
public static $ParseXmlError = 40002;
public static $ComputeSignatureError = 40003;
public static $IllegalAesKey = 40004;
public static $ValidateAppidError = 40005;
public static $EncryptAESError = 40006;
public static $DecryptAESError = 40007;
public static $IllegalBuffer = 40008;
public static $EncodeBase64Error = 40009;
public static $DecodeBase64Error = 40010;
public static $GenReturnXmlError = 40011;
public static $errCode = array(
'0' => '处理成功',
'40001' => '校验签名失败',
'40002' => '解析xml失败',
'40003' => '计算签名失败',
'40004' => '不合法的AESKey',
'40005' => '校验AppID失败',
'40006' => 'AES加密失败',
'40007' => 'AES解密失败',
'40008' => '公众平台发送的xml不合法',
'40009' => 'Base64编码失败',
'40010' => 'Base64解码失败',
'40011' => '公众帐号生成回包xml失败'
);
/**
* 获取错误消息内容
* @param string $err
* @return bool
*/
public static function getErrText($err) {
if (isset(self::$errCode[$err])) {
return self::$errCode[$err];
}
return false;
}
}

View File

@@ -0,0 +1,268 @@
<?php
namespace Wechat\Lib;
use CURLFile;
/**
* 微信接口通用类
*
* @category WechatSDK
* @subpackage library
* @author Anyon <zoujingli@qq.com>
* @date 2016/05/28 11:55
*/
class Tools {
/**
* 产生随机字符串
* @param int $length
* @param string $str
* @return string
*/
static public function createNoncestr($length = 32, $str = "") {
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
/**
* 获取签名
* @param array $arrdata 签名数组
* @param string $method 签名方法
* @return bool|string 签名值
*/
static public function getSignature($arrdata, $method = "sha1") {
if (!function_exists($method)) {
return false;
}
ksort($arrdata);
$params = array();
foreach ($arrdata as $key => $value) {
$params[] = "{$key}={$value}";
}
return $method(join('&', $params));
}
/**
* 生成支付签名
* @param array $option
* @param string $partnerKey
* @return string
*/
static public function getPaySign($option, $partnerKey) {
ksort($option);
$buff = '';
foreach ($option as $k => $v) {
$buff .= "{$k}={$v}&";
}
return strtoupper(md5("{$buff}key={$partnerKey}"));
}
/**
* XML编码
* @param mixed $data 数据
* @param string $root 根节点名
* @param string $item 数字索引的子节点名
* @param string $id 数字索引子节点key转换的属性名
* @return string
*/
static public function arr2xml($data, $root = 'xml', $item = 'item', $id = 'id') {
return "<{$root}>" . self::_data_to_xml($data, $item, $id) . "</{$root}>";
}
static private function _data_to_xml($data, $item = 'item', $id = 'id', $content = '') {
foreach ($data as $key => $val) {
is_numeric($key) && $key = "{$item} {$id}=\"{$key}\"";
$content .= "<{$key}>";
if (is_array($val) || is_object($val)) {
$content .= self::_data_to_xml($val);
} elseif (is_numeric($val)) {
$content .= $val;
} else {
$content .= '<![CDATA[' . preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/", '', $val) . ']]>';
}
list($_key,) = explode(' ', $key . ' ');
$content .= "</$_key>";
}
return $content;
}
/**
* 将xml转为array
* @param string $xml
* @return array
*/
static public function xml2arr($xml) {
return json_decode(Tools::json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
}
/**
* 生成安全JSON数据
* @param array $array
* @return string
*/
static public function json_encode($array) {
return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', create_function('$matches', 'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'), json_encode($array));
}
/**
* 以get方式提交请求
* @param $url
* @return bool|mixed
*/
static public function httpGet($url) {
$oCurl = curl_init();
if (stripos($url, "https://") !== FALSE) {
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($oCurl, CURLOPT_SSLVERSION, 1);
}
curl_setopt($oCurl, CURLOPT_URL, $url);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
$sContent = curl_exec($oCurl);
$aStatus = curl_getinfo($oCurl);
curl_close($oCurl);
if (intval($aStatus["http_code"]) == 200) {
return $sContent;
} else {
return false;
}
}
/**
* 以post方式提交请求
* @param string $url
* @param array|string $data
* @return bool|mixed
*/
static public function httpPost($url, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
if (is_array($data)) {
foreach ($data as &$value) {
if (is_string($value) && stripos($value, '@') === 0 && class_exists('CURLFile', FALSE)) {
$value = new CURLFile(realpath(trim($value, '@')));
}
}
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$data = curl_exec($ch);
curl_close($ch);
if ($data) {
return $data;
}
return false;
}
/**
* 使用证书以post方式提交xml到对应的接口url
* @param string $url POST提交的内容
* @param array $postdata 请求的地址
* @param string $ssl_cer 证书Cer路径 | 证书内容
* @param string $ssl_key 证书Key路径 | 证书内容
* @param int $second 设置请求超时时间
* @return bool|mixed
*/
static public function httpsPost($url, $postdata, $ssl_cer = null, $ssl_key = null, $second = 30) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
/* 要求结果为字符串且输出到屏幕上 */
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
/* 设置证书 */
if (!is_null($ssl_cer) && file_exists($ssl_cer) && is_file($ssl_cer)) {
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
curl_setopt($ch, CURLOPT_SSLCERT, $ssl_cer);
}
if (!is_null($ssl_key) && file_exists($ssl_key) && is_file($ssl_key)) {
curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
curl_setopt($ch, CURLOPT_SSLKEY, $ssl_key);
}
curl_setopt($ch, CURLOPT_POST, true);
if (is_array($postdata)) {
foreach ($postdata as &$data) {
if (is_string($data) && stripos($data, '@') === 0 && class_exists('CURLFile', FALSE)) {
$data = new CURLFile(realpath(trim($data, '@')));
}
}
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($ch);
curl_close($ch);
if ($result) {
return $result;
} else {
return false;
}
}
/**
* 读取微信客户端IP
* @return null|string
*/
static public function getAddress() {
foreach (array('HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP', 'REMOTE_ADDR') as $header) {
if (!isset($_SERVER[$header]) || ($spoof = $_SERVER[$header]) === NULL) {
continue;
}
sscanf($spoof, '%[^,]', $spoof);
if (!filter_var($spoof, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$spoof = NULL;
} else {
return $spoof;
}
}
return '0.0.0.0';
}
/**
* 设置缓存,按需重载
* @param string $cachename
* @param mixed $value
* @param int $expired
* @return bool
*/
static public function setCache($cachename, $value, $expired = 0) {
return Cache::set($cachename, $value, $expired);
}
/**
* 获取缓存,按需重载
* @param string $cachename
* @return mixed
*/
static public function getCache($cachename) {
return Cache::get($cachename);
}
/**
* 清除缓存,按需重载
* @param string $cachename
* @return bool
*/
static public function removeCache($cachename) {
return Cache::del($cachename);
}
/**
* SDK日志处理方法
* @param string $msg 日志行内容
* @param string $type 日志级别
*/
static public function log($msg, $type = 'MSG') {
Cache::put($type . ' - ' . $msg);
}
}