初始化项目

This commit is contained in:
2026-09-01 22:15:50 +08:00
commit b5a26a8848
11217 changed files with 1710987 additions and 0 deletions
@@ -0,0 +1,89 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library;
use app\common\exception\BaseException;
class Download
{
/**
* 获取网络图片到临时目录
* @param int $storeId
* @param string $url
* @param string $prefix
* @return string
* @throws \cores\exception\BaseException
*/
public function saveTempImage(int $storeId, string $url, string $prefix = 'temp'): string
{
$savePath = $this->getSavePath($storeId, $prefix, $url);
if (!file_exists($savePath)) {
$result = $this->curl($url);
empty($result) && throwError('获取到的图片内容为空 url: ' . $url);
$this->fwrite($savePath, $result);
}
return $savePath;
}
/**
* 写入文件
* @param string $savePath
* @param string $result
*/
private function fwrite(string $savePath, string $result)
{
$fp = fopen($savePath, 'w');
fwrite($fp, $result);
fclose($fp);
}
/**
* 请求网络文件
* @param string $url
* @return bool|string
*/
private function curl(string $url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
/**
* 文件保存的路径
* @param int $storeId
* @param string $prefix
* @param string $url
* @return string
*/
private function getSavePath(int $storeId, string $prefix, string $url): string
{
$dirPath = $this->getDirPath($storeId);
return $dirPath . '/' . $prefix . '_' . md5($url) . '.png';
}
/**
* 文件保存的目录
* @param int $storeId
* @return string
*/
private function getDirPath(int $storeId): string
{
$dirPath = runtime_root_path() . "image/{$storeId}";
!is_dir($dirPath) && mkdir($dirPath, 0755, true);
return $dirPath;
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library;
/**
* 文件阻塞锁
* 用于并发情况下保持数据的原子性, 仅适用于轻量并发场景,如果是高并发场景请使用redis
* Class Lock
* @package app\common\library
*/
class Lock
{
// 文件锁资源树
static $resource = [];
/**
* 加锁
* @param string $uniqueId
* @return bool
*/
public static function lockUp(string $uniqueId): bool
{
clearstatcache();
static::$resource[$uniqueId] = fopen(static::getFilePath($uniqueId), 'w+');
return flock(static::$resource[$uniqueId], LOCK_EX);
}
/**
* 解锁
* @param string $uniqueId
* @return bool
*/
public static function unLock(string $uniqueId): bool
{
clearstatcache();
if (!isset(static::$resource[$uniqueId])) return false;
flock(static::$resource[$uniqueId], LOCK_UN);
fclose(static::$resource[$uniqueId]);
return static::deleteFile($uniqueId);
}
/**
* 获取锁文件的路径
* @param string $uniqueId
* @return string
*/
private static function getFilePath(string $uniqueId): string
{
clearstatcache();
$dirPath = runtime_root_path() . 'lock/';
!is_dir($dirPath) && mkdir($dirPath, 0755, true);
return $dirPath . md5($uniqueId) . '.lock';
}
/**
* 删除锁文件
* @param string $uniqueId
* @return bool
*/
private static function deleteFile(string $uniqueId): bool
{
clearstatcache();
$filePath = static::getFilePath($uniqueId);
return file_exists($filePath) && unlink($filePath);
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library;
use think\facade\Log as LogFacade;
class Log
{
// 日志内容
private static $data = [];
/**
* 写入日志
* @param mixed $value
* @param string $type
*/
public static function record($value, string $type = 'info')
{
$content = is_string($value) ? $value : print_r($value, true);
LogFacade::record($content, $type);
}
/**
* 写入日志 (使用追加的方式, 索引值是name)
* @param string $name 日志记录名
* @param array $data 记录内容
*/
public static function append(string $name, array $data)
{
$merge = array_merge(compact('name'), $data);
if (isset(static::$data[$name])) {
$merge = array_merge(static::$data[$name], $merge);
}
static::$data[$name] = $merge;
}
/**
* 在应用结束时将追加的日志数据写入到文件
*/
public static function end()
{
foreach (static::$data as $name => $item) {
static::record(array_merge(['name' => $name], $item));
}
}
}
@@ -0,0 +1,99 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\express;
use think\facade\Cache;
use cores\traits\ErrorTrait;
use app\common\library\helper;
/**
* 快递100API模块
* Class Kuaidi100
* @package app\common\library\express
*/
class Kuaidi100
{
use ErrorTrait;
// 物流跟踪查询API地址
const QUERY_URL = 'http://poll.kuaidi100.com/poll/query.do';
// 微信支付配置
/* @var array $config */
private $config;
/**
* 构造方法
* WxPay constructor.
* @param $config
*/
public function __construct($config)
{
$this->config = $config;
}
/**
* 执行查询
* @param string $code
* @param string $expressNo
* @return string|bool
*/
public function query(string $code, string $expressNo)
{
// 缓存索引
$cacheIndex = "express_{$code}_$expressNo";
if ($cacheData = Cache::get($cacheIndex)) {
return $cacheData;
}
// 参数设置
$postData = [
'customer' => $this->config['customer'],
'param' => helper::jsonEncode([
'resultv2' => '1',
'com' => $code,
'num' => $expressNo
])
];
$postData['sign'] = strtoupper(md5($postData['param'] . $this->config['key'] . $postData['customer']));
// 请求快递100 api
$result = $this->curlGet(self::QUERY_URL, $postData);
$express = helper::jsonDecode($result);
// 记录错误信息
if (isset($express['returnCode']) || !isset($express['data'])) {
$this->error = $express['message'] ?? '查询失败';
return false;
}
// 记录缓存, 时效30分钟
Cache::set($cacheIndex, $express['data'], 3000);
return $express['data'];
}
/**
* curl请求指定url (post)
* @param $url
* @param array $data
* @return bool|string
*/
private function curlGet($url, array $data = [])
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
+267
View File
@@ -0,0 +1,267 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
namespace app\common\library;
/**
* 工具类
* Class helper
* @package app\common\library
*/
class helper
{
/**
* 从object中选取属性
* @param $source
* @param array $columns
* @return array
*/
public static function pick($source, array $columns): array
{
$dataset = [];
foreach ($source as $key => $item) {
in_array($key, $columns) && $dataset[$key] = $item;
}
return $dataset;
}
/**
* 获取数组中指定的列
* @param $source
* @param $column
* @return array
*/
public static function getArrayColumn($source, $column): array
{
$columnArr = [];
foreach ($source as $item) {
isset($item[$column]) && $columnArr[] = $item[$column];
}
return $columnArr;
}
/**
* 获取数组中指定的列 [支持多列]
* @param $source
* @param $columns
* @return array
*/
public static function getArrayColumns($source, $columns): array
{
$columnArr = [];
foreach ($source as $item) {
$temp = [];
foreach ($columns as $index) {
$temp[$index] = $item[$index];
}
$columnArr[] = $temp;
}
return $columnArr;
}
/**
* 把二维数组中某列设置为key返回
* @param $source
* @param $index
* @return array
*/
public static function arrayColumn2Key($source, $index): array
{
$data = [];
foreach ($source as $item) {
$data[$item[$index]] = $item;
}
return $data;
}
/**
* 格式化价格显示
* @param mixed $number
* @param bool $isMinimum 是否存在最小值
* @param float $minimum
* @return string
*/
public static function number2($number, bool $isMinimum = false, float $minimum = 0.01): string
{
$isMinimum && $number = max($minimum, $number);
return sprintf('%.2f', $number);
}
public static function getArrayItemByColumn($array, $column, $value)
{
foreach ($array as $item) {
if ($item[$column] == $value) {
return $item;
}
}
return false;
}
/**
* 获取二维数组中指定字段的和
* @param $array
* @param $column
* @return float|int
*/
public static function getArrayColumnSum($array, $column)
{
$sum = 0;
foreach ($array as $item) {
$sum = self::bcadd($sum, $item[$column]);
}
return $sum;
}
/**
* 在二维数组中查找指定值
* @param array $array 二维数组
* @param string $searchIdx 查找的索引
* @param mixed $searchVal 查找的值
* @return bool|mixed
*/
public static function arraySearch(array $array, string $searchIdx, $searchVal)
{
foreach ($array as $item) {
if ($item[$searchIdx] == $searchVal) {
return $item;
}
}
return false;
}
public static function setDataAttribute(&$source, $defaultData, $isArray = false)
{
if (!$isArray) $dataSource = [&$source]; else $dataSource = &$source;
foreach ($dataSource as &$item) {
foreach ($defaultData as $key => $value) {
$item[$key] = $value;
}
}
return $source;
}
public static function bcsub($leftOperand, $rightOperand, $scale = 2): string
{
return \bcsub($leftOperand, $rightOperand, $scale);
}
public static function bcadd($leftOperand, $rightOperand, $scale = 2): string
{
return \bcadd($leftOperand, $rightOperand, $scale);
}
public static function bcmul($leftOperand, $rightOperand, $scale = 2): string
{
return \bcmul($leftOperand, $rightOperand, $scale);
}
public static function bcdiv($leftOperand, $rightOperand, int $scale = 2): ?string
{
return \bcdiv($leftOperand, $rightOperand, $scale);
}
/**
* 浮点数比较
* 若二个字符串一样大则返回 0;若左边的数字字符串 (left operand) 比右边 (right operand) 的大则返回 +1;若左边的数字字符串比右边的小则返回 -1
* @param $leftOperand
* @param $rightOperand
* @param int $scale
* @return int
*/
public static function bccomp($leftOperand, $rightOperand, int $scale = 2): int
{
return \bccomp($leftOperand, $rightOperand, $scale);
}
/**
* 比较两个数值是否相等
* @param $leftOperand
* @param $rightOperand
* @param int $scale
* @return bool
*/
public static function bcequal($leftOperand, $rightOperand, int $scale = 2): bool
{
return self::bccomp($leftOperand, $rightOperand, $scale) === 0;
}
/**
* 数组转为json
* @param $data
* @param int $options
* @return false|string
*/
public static function jsonEncode($data, int $options = JSON_UNESCAPED_UNICODE)
{
return json_encode($data, $options);
}
/**
* json转义为数组
* @param $json
* @return array|mixed
*/
public static function jsonDecode($json)
{
return json_decode($json, true);
}
/**
* 检查目录是否可写
* @param $path
* @return bool
*/
public static function checkWriteable($path): bool
{
try {
!is_dir($path) && mkdir($path, 0755);
if (!is_dir($path))
return false;
$fileName = $path . '/_test_write.txt';
if ($fp = fopen($fileName, 'w')) {
return fclose($fp) && unlink($fileName);
}
} catch (\Exception $e) {
}
return false;
}
/**
* 记录info日志
* @param string $name
* @param array $content
*/
public static function logInfo(string $name, array $content)
{
$content['name'] = $name;
log_record($content, 'info');
}
/**
* 将字符串转换为字节
* @param string $from
* @return int|null
*/
public static function convertToBytes(string $from): ?int
{
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
$number = substr($from, 0, -2);
$suffix = strtoupper(substr($from, -2));
// B or no suffix
if (is_numeric(substr($suffix, 0, 1))) {
return preg_replace('/[^\d]/', '', $from);
}
$exponent = array_flip($units)[$suffix] ?? null;
if ($exponent === null) {
return null;
}
return $number * (1024 ** $exponent);
}
}
@@ -0,0 +1,33 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\leshua;
/**
* error code 说明.
* <ul>
* <li>-41001: encodingAesKey 非法</li>
* <li>-41003: aes 解密失败</li>
* <li>-41004: 解密后得到的buffer非法</li>
* <li>-41005: base64加密失败</li>
* <li>-41016: base64解密失败</li>
* </ul>
*/
class ErrorCode
{
public static $OK = 0;
public static $IllegalAesKey = -41001;
public static $IllegalIv = -41002;
public static $IllegalBuffer = -41003;
public static $DecodeBase64Error = -41004;
}
@@ -0,0 +1,65 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\leshua;
class LSBizDataCrypt
{
private $appid;
private $sessionKey;
/**
* 构造函数
* @param string $appid string 小程序的appid
* @param string $sessionKey string 用户在小程序登录后获取的会话密钥
*/
public function __construct(string $appid, string $sessionKey)
{
$this->sessionKey = $sessionKey;
$this->appid = $appid;
}
/**
* 检验数据的真实性,并且获取解密后的明文.
* @param string $encryptedData 加密的用户数据
* @param string $iv 与用户数据一同返回的初始向量
* @param mixed $content 解密后的原文
* @return int 成功0,失败返回对应的错误码
*/
public function decryptData(string $encryptedData, string $iv, &$content): int
{
if (strlen($this->sessionKey) != 24) {
return ErrorCode::$IllegalAesKey;
}
if (strlen($iv) != 24) {
return ErrorCode::$IllegalIv;
}
$aesKey = base64_decode($this->sessionKey);
$aesIV = base64_decode($iv);
$aesCipher = base64_decode($encryptedData);
$result = openssl_decrypt($aesCipher, 'AES-128-CBC', $aesKey, 1, $aesIV);
if (empty($result)) {
return ErrorCode::$IllegalBuffer;
}
$resultArr = json_decode($result, true);
if (empty($resultArr)) {
return ErrorCode::$IllegalBuffer;
}
if ($resultArr['watermark']['appid'] != $this->appid) {
return ErrorCode::$IllegalBuffer;
}
$content = $resultArr;
return ErrorCode::$OK;
}
}
@@ -0,0 +1,187 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\leshua;
use think\facade\Cache;
use cores\traits\ErrorTrait;
use app\common\library\helper;
use app\common\exception\BaseException;
/**
* 乐刷api基类
* Class leshua
* @package app\library
*/
class LsBase
{
use ErrorTrait;
protected $appId;
protected $appSecret;
/**
* 构造函数
* WxBase constructor.
* @param $appId
* @param $appSecret
*/
public function __construct($appId = null, $appSecret = null)
{
$this->setConfig($appId, $appSecret);
}
protected function setConfig($appId = null, $appSecret = null)
{
!empty($appId) && $this->appId = $appId;
!empty($appSecret) && $this->appSecret = $appSecret;
}
/**
* 获取access_token
* @return mixed
* @throws \cores\exception\BaseException
*/
protected function getAccessToken()
{
$cacheKey = $this->appId . '@access_token';
if (!Cache::get($cacheKey)) {
// 请求API获取 access_token
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
$result = $this->get($url);
$response = $this->jsonDecode($result);
if (array_key_exists('errcode', $response)) {
throwError("access_token获取失败,错误信息:{$result}");
}
// 记录日志
log_record([
'name' => '获取access_token',
'url' => $url,
'appId' => $this->appId,
'result' => $result
]);
// 写入缓存
Cache::set($cacheKey, $response['access_token'], 6000);
}
return Cache::get($cacheKey);
}
/**
* 模拟GET请求 HTTPS的页面
* @param string $url 请求地址
* @param array $data
* @return string $result
* @throws \cores\exception\BaseException
*/
protected function get(string $url, array $data = [])
{
// 处理query参数
if (!empty($data)) {
$url = $url . '?' . http_build_query($data);
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
$result = curl_exec($curl);
if ($result === false) {
throwError(curl_error($curl));
}
curl_close($curl);
return $result;
}
/**
* 模拟POST请求
* @param string $url 请求地址
* @param mixed $data 请求数据
* @param false $useCert 是否引入微信支付证书
* @param array $sslCert 证书路径
* @return mixed|bool|string
* @throws \cores\exception\BaseException
*/
protected function post(string $url, $data = [], bool $useCert = false, array $sslCert = [])
{
$header = [
'Content-type: application/json;'
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
if ($useCert == true) {
// 设置证书:cert 与 key 分别属于两个.pem文件
curl_setopt($curl, CURLOPT_SSLCERTTYPE, 'PEM');
curl_setopt($curl, CURLOPT_SSLCERT, $sslCert['certPem']);
curl_setopt($curl, CURLOPT_SSLKEYTYPE, 'PEM');
curl_setopt($curl, CURLOPT_SSLKEY, $sslCert['keyPem']);
}
$result = curl_exec($curl);
if ($result === false) {
throwError(curl_error($curl));
}
curl_close($curl);
return $result;
}
/**
* 模拟POST请求 [第二种方式, 用于兼容微信api]
* @param $url
* @param array $data
* @return mixed
* @throws \cores\exception\BaseException
*/
protected function post2($url, array $data = [])
{
$header = [
'Content-Type: application/x-www-form-urlencoded'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
$result = curl_exec($ch);
if ($result === false) {
throwError(curl_error($ch));
}
curl_close($ch);
return $result;
}
/**
* 数组转json
* @param $data
* @return string
*/
protected function jsonEncode($data): string
{
return helper::jsonEncode($data, JSON_UNESCAPED_UNICODE);
}
/**
* json转数组
* @param $json
* @return mixed
*/
protected function jsonDecode($json)
{
return helper::jsonDecode($json);
}
}
@@ -0,0 +1,360 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
namespace app\common\library\leshua;
use app\common\model\wxapp\Setting as WxappSettingModel;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\order\PayType as OrderPayTypeEnum;
use app\common\library\helper;
use app\common\exception\BaseException;
/**
* 乐刷支付
* Class LsPay
* @package app\common\library\leshua
*/
class LsPay extends LsBase
{
// 乐刷支付配置
private $config;
// 当前商城ID
private $storeId;
// 订单模型
private $modelClass = [
OrderTypeEnum::ORDER => \app\api\service\order\PaySuccess::class,
OrderTypeEnum::RECHARGE => \app\api\service\recharge\PaySuccess::class,
];
/**
* 构造函数
* @param array $config
* @param int|null $storeId
*/
public function __construct(array $config = [], ?int $storeId = null)
{
parent::__construct();
$this->config = $config;
$this->storeId = $storeId;
if (!empty($this->config)) {
$this->setConfig($this->config['app_id'], $this->config['app_secret']);
}
}
/**
* 统一下单API
* @param $orderNo
* @param $openid
* @param $totalFee
* @param int $orderType 订单类型
* @return array
* @throws \cores\exception\BaseException
*/
public function unifiedorder($orderNo, $openid, $totalFee, int $orderType = OrderTypeEnum::ORDER): array
{
// 当前时间
$time = time();
// 生成随机字符串
$nonceStr = md5($time . $openid);
// API参数
$params = [
'service' => 'get_tdcode',
'pay_way' => 'WXZF',
'merchant_id' => $this->config['mchid'],
'third_order_id' => $orderNo,
'amount' => (int)helper::bcmul($totalFee, 100), // 价格:单位分
'jspay_flag' => 3,
'appid' => $this->appId,
'sub_openid' => $openid,
'notify_url' => base_url() . 'leshua.php', // 异步通知地址
'body' => $orderNo,
'attach' => helper::jsonEncode(['order_type' => $orderType]),
'nonce_str' => $nonceStr,
//'spbill_create_ip' => \request()->ip(),
'order_expiration' => 60,
];
// 生成签名
$params['sign'] = $this->makeSign($params);
// 请求API
$url = 'https://paygate.leshuazf.com/cgi-bin/lepos_pay_gateway.cgi';
$result = $this->post($url, $params);
$prepay = $this->fromXml($result);
// 请求失败
if ($prepay['resp_code'] != '0') {
$errMsg = "乐刷支付api:{$prepay['resp_msg']}";
throwError($errMsg, null, ['errorCode' => 'LESHUA_PAY', 'isCreated' => true]);
}
if ($prepay['result_code'] != '0') {
$errMsg = "乐刷支付api:{$prepay['error_msg']}";
throwError($errMsg, null, ['errorCode' => 'LESHUA_PAY', 'isCreated' => true]);
}
$jspayInfo = helper::jsonDecode($prepay['jspay_info']);
$prepayId = explode('=', $jspayInfo['package'])[1];
// 生成 nonce_str 供前端使用
// $paySign = $this->makePaySign($params['nonce_str'], $prepayId, $time);
return [
'prepay_id' => $prepayId,
'nonceStr' => $nonceStr,
'timeStamp' => (string)$time,
'paySign' => $jspayInfo['paySign']
];
}
/**
* 支付成功异步通知
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function notify()
{
if (!$xml = file_get_contents('php://input')) {
$this->returnCode(false, 'Not found DATA');
}
// 将服务器返回的XML数据转化为数组
$data = $this->fromXml($xml);
// 记录日志
log_record($xml);
log_record($data);
// 实例化订单模型
$model = $this->getOrderModel($data['third_order_id'], $data['attach']);
// 订单信息
$order = $model->getOrderInfo();
empty($order) && $this->returnCode(false, '订单不存在');
// 小程序配置信息
$wxConfig = WxappSettingModel::getWxappConfig($order['store_id']);
// 设置支付秘钥
$this->config['apikey'] = $wxConfig['apikey'];
// 保存微信服务器返回的签名sign
$dataSign = $data['sign'];
// sign不参与签名算法
unset($data['sign']);
// 生成签名
$sign = $this->makeSign($data);
// 判断签名是否正确 判断支付状态
if (
($sign !== $dataSign)
|| ($data['return_code'] !== 'SUCCESS')
|| ($data['result_code'] !== 'SUCCESS')
) {
$this->returnCode(false, '签名失败');
}
// 订单支付成功业务处理
$status = $model->onPaySuccess(OrderPayTypeEnum::WECHAT, $data);
if ($status == false) {
$this->returnCode(false, $model->getError());
}
// 返回状态
$this->returnCode(true, 'OK');
}
/**
* 申请退款API
* @param string $transactionId 微信支付交易流水号
* @param string $totalFee 订单总金额
* @param string $refundFee 退款金额
* @return bool
* @throws BaseException
* @throws \cores\exception\BaseException
*/
public function refund(string $transactionId, string $totalFee, string $refundFee): bool
{
// 当前时间
$time = time();
// 生成随机字符串
$nonceStr = md5($time . $transactionId . $totalFee . $refundFee);
// API参数
$params = [
'appid' => $this->appId,
'mch_id' => $this->config['mchid'],
'nonce_str' => $nonceStr,
'transaction_id' => $transactionId,
'out_refund_no' => $time,
'total_fee' => (int)helper::bcmul($totalFee,100),
'refund_fee' => (int)helper::bcmul($refundFee,100),
];
// 生成签名
$params['sign'] = $this->makeSign($params);
// 请求API
$url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
$result = $this->post($url, $this->toXml($params), true, $this->getCertPem());
// 请求失败
if (empty($result)) {
throwError('微信退款api请求失败');
}
// 格式化返回结果
$prepay = $this->fromXml($result);
// 记录日志
log_record(['name' => '微信退款API', [
'params' => $params,
'result' => $result,
'prepay' => $prepay
]]);
// 请求失败
if ($prepay['return_code'] === 'FAIL') {
throwError("return_msg: {$prepay['return_msg']}");
}
if ($prepay['result_code'] === 'FAIL') {
throwError("err_code_des: {$prepay['err_code_des']}");
}
return true;
}
/**
* 获取cert证书文件
* @return string[]
* @throws \cores\exception\BaseException
*/
private function getCertPem(): array
{
if (empty($this->config['cert_pem']) || empty($this->config['key_pem'])) {
throwError('请先到后台小程序设置填写微信支付证书文件');
}
// cert目录
$filePath = __DIR__ . "/cert/{$this->storeId}/";
return [
'certPem' => $filePath . 'cert.pem',
'keyPem' => $filePath . 'key.pem'
];
}
/**
* 实例化订单模型 (根据attach判断)
* @param $orderNo
* @param null $attach
* @return mixed
*/
private function getOrderModel($orderNo, $attach = null)
{
$attach = helper::jsonDecode($attach);
// 判断订单类型返回对应的订单模型
$model = $this->modelClass[$attach['order_type']];
return new $model($orderNo);
}
/**
* 返回状态给微信服务器
* @param boolean $returnCode
* @param string|null $msg
*/
private function returnCode(bool $returnCode = true, string $msg = null)
{
// 返回状态
$return = [
'return_code' => $returnCode ? 'SUCCESS' : 'FAIL',
'return_msg' => $msg ?: 'OK',
];
// 记录日志
log_record([
'name' => '返回微信支付状态',
'data' => $return
]);
die($this->toXml($return));
}
/**
* 生成paySign
* @param string $nonceStr
* @param string $prepayId
* @param int $timeStamp
* @return string
*/
private function makePaySign(string $nonceStr, string $prepayId, int $timeStamp): string
{
$data = [
'appId' => $this->appId,
'nonceStr' => $nonceStr,
'package' => 'prepay_id=' . $prepayId,
'signType' => 'MD5',
'timeStamp' => $timeStamp,
];
// 签名步骤一:按字典序排序参数
ksort($data);
$string = $this->toUrlParams($data);
// 签名步骤二:在string后加入KEY
$string = $string . '&key=' . $this->config['apikey'];
// 签名步骤三:MD5加密
$string = md5($string);
// 签名步骤四:所有字符转为大写
return strtoupper($string);
}
/**
* 将xml转为array
* @param string $xml
* @return mixed
*/
private function fromXml(string $xml)
{
// 禁止引用外部xml实体
libxml_disable_entity_loader(true);
return helper::jsonDecode(helper::jsonEncode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)));
}
/**
* 生成签名
* @param array $values
* @return string 本函数不覆盖sign成员变量,如要设置签名需要调用SetSign方法赋值
*/
private function makeSign(array $values): string
{
//签名步骤一:按字典序排序参数
ksort($values);
$string = $this->toUrlParams($values);
//签名步骤二:在string后加入KEY
$string = $string . '&key=' . $this->config['apikey'];
//签名步骤三:MD5加密
$string = md5($string);
//签名步骤四:所有字符转为大写
return strtoupper($string);
}
/**
* 格式化参数格式化成url参数
* @param array $values
* @return string
*/
private function toUrlParams(array $values): string
{
$buff = '';
foreach ($values as $k => $v) {
if ($k != 'sign' && $v != '' && !is_array($v)) {
$buff .= $k . '=' . $v . '&';
}
}
return trim($buff, '&');
}
/**
* 输出xml字符
* @param array $values
* @return bool|string
*/
private function toXml(array $values)
{
if (!is_array($values)
|| count($values) <= 0
) {
return false;
}
$xml = "<xml>";
foreach ($values as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
} else {
$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
}
}
$xml .= "</xml>";
return $xml;
}
}
@@ -0,0 +1,61 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
namespace app\common\library\sms;
use Overtrue\EasySms\Strategies\OrderStrategy;
/**
* EasySms配置类
* Class Config
* @package app\common\library\sms
*/
class Config
{
/**
* 生成EasySms的配置项
* @param array $smsConfig
* @return array
*/
public static function getEasySmsConfig(array $smsConfig): array
{
return [
// HTTP 请求的超时时间(秒)
'timeout' => 5.0,
// 默认发送配置
'default' => [
// 网关调用策略,默认:顺序调用
'strategy' => OrderStrategy::class,
// 默认可用的发送网关
'gateways' => [$smsConfig['default']],
],
// 可用的网关配置
'gateways' => [
'aliyun' => [
'access_key_id' => $smsConfig['engine']['aliyun']['AccessKeyId'],
'access_key_secret' => $smsConfig['engine']['aliyun']['AccessKeySecret'],
'sign_name' => $smsConfig['engine']['aliyun']['sign'],
],
'qcloud' => [
'sdk_app_id' => $smsConfig['engine']['qcloud']['SdkAppID'],
'secret_id' => $smsConfig['engine']['qcloud']['AccessKeyId'],
'secret_key' => $smsConfig['engine']['qcloud']['AccessKeySecret'],
'sign_name' => $smsConfig['engine']['qcloud']['sign'],
],
'qiniu' => [
'access_key' => $smsConfig['engine']['qiniu']['AccessKey'],
'secret_key' => $smsConfig['engine']['qiniu']['SecretKey'],
],
]
];
}
}
@@ -0,0 +1,149 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\sms;
use app\common\library\helper;
use cores\traits\ErrorTrait;
use cores\exception\BaseException;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\InvalidArgumentException;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
/**
* 短信通知模块驱动
* Class Driver
* @package app\common\library\sms
*/
class Driver
{
use ErrorTrait;
// 后台短信配置信息
private $smsConfig;
// 当前短信平台 (后台设置)
private $gateway;
/**
* 构造方法
* Driver constructor.
* @param array $smsConfig
*/
public function __construct(array $smsConfig)
{
// 配置信息
$this->smsConfig = $smsConfig;
// 当前短信平台
$this->gateway = $this->smsConfig['default'];
}
/**
* 发送短信通知
* @param string $acceptPhone 接收的手机号
* @param string $templateCode 短信模板ID
* @param array $templateParams 短信模板参数
* @return bool
* @throws BaseException
* @throws InvalidArgumentException
*/
public function sendSms(string $acceptPhone, string $templateCode, array $templateParams): bool
{
// 实例化EasySms
$easySmsConfig = Config::getEasySmsConfig($this->smsConfig);
$easySms = new EasySms($easySmsConfig);
try {
// 执行发送短信
$result = $easySms->send($acceptPhone, [
'template' => $templateCode,
'data' => $this->getSmsTemplateData($templateParams),
]);
// 短信发送成功的错误处理
$sendStatus = $this->resultHandle($result);
} catch (NoGatewayAvailableException $e) {
// 短信发送异常的错误处理
$sendStatus = false;
$this->exceptionHandle($e);
}
// 记录日志
helper::logInfo('发送短信', [
'gateway' => $this->smsConfig['default'],
'acceptPhone' => $acceptPhone,
'templateCode' => $templateCode,
'templateParams' => $templateParams,
'sendStatus' => $sendStatus ? 'true' : 'false',
'sendErrMsg' => $this->getError(),
]);
// 存在异常时抛错
$sendStatus === false && throwError($this->getError());
return $sendStatus;
}
/**
* 短信发送成功的错误处理
* @param array $result
* @return bool
*/
private function resultHandle(array $result): bool
{
// 腾讯云短信错误: 模板ID不正确
if ($this->gateway === 'qcloud') {
$response = $result[$this->gateway]['result']['Response']['SendStatusSet'];
if (isset($response[0]) && isset($response[0]['Code']) && $response[0]['Code'] !== 'Ok') {
$this->error = '请检查后台短信平台参数和模板ID是否正确';
return false;
}
}
return true;
}
/**
* 短信发送异常的错误处理
* @param NoGatewayAvailableException $e
*/
private function exceptionHandle(NoGatewayAvailableException $e)
{
// 短信发送失败
$err = $e->getLastException();
if ($err instanceof \GuzzleHttp\Exception\ClientException) {
$body = (string)$err->getResponse()->getBody();
$result = helper::jsonDecode($body);
if (isset($result['Message'])) {
// $errMsg = $result['Message'];
$this->error = '请检查后台短信平台的参数设置';
return;
}
if (isset($result['message'])) {
$this->error = $result['message'];
return;
}
}
// if ($err instanceof \Overtrue\EasySms\Exceptions\GatewayErrorException) {
// $this->error = $err->getMessage();
// return;
// }
$this->error = $err->getMessage();
}
/**
* 生成短信模板数据
* @param array $templateParams
* @return array
*/
private function getSmsTemplateData(array $templateParams): array
{
if ($this->gateway === 'qcloud') {
$templateParams = array_values($templateParams);
}
return $templateParams;
}
}
@@ -0,0 +1,98 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\sms\engine;
use app\common\library\helper;
use app\common\library\sms\package\aliyun\SignatureHelper;
/**
* 阿里云短信模块引擎
* Class Aliyun
* @package app\common\library\sms\engine
*/
class Aliyun extends Server
{
private $config;
/**
* 构造方法
* Qiniu constructor.
* @param $config
*/
public function __construct($config)
{
$this->config = $config;
}
/**
* 发送短信通知
* @param array $sceneConfig 场景配置
* @param array $templateParams 短信模板参数
* @return bool
*/
public function sendSms(array $sceneConfig, array $templateParams)
{
$params = [];
// *** 需用户填写部分 ***
// 必填: 短信接收号码
$params["PhoneNumbers"] = $sceneConfig['acceptPhone'];
// 必填: 短信签名,应严格按"签名名称"填写,请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
$params["SignName"] = $this->config['sign'];
// 必填: 短信模板Code,应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
$params["TemplateCode"] = $sceneConfig['templateCode'];
// 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
$params['TemplateParam'] = $templateParams;
// 可选: 设置发送短信流水号
// $params['OutId'] = "12345";
// 可选: 上行短信扩展码, 扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段
// $params['SmsUpExtendCode'] = "1234567";
// *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
if (!empty($params['TemplateParam'])) {
$params['TemplateParam'] = helper::jsonEncode($params['TemplateParam']);
}
// 初始化SignatureHelper实例用于设置参数,签名以及发送请求
$helper = new SignatureHelper;
// 此处可能会抛出异常,注意catch
$response = $helper->request(
$this->config['AccessKeyId']
, $this->config['AccessKeySecret']
, "dysmsapi.aliyuncs.com"
, array_merge($params, [
"RegionId" => "cn-hangzhou",
"Action" => "SendSms",
"Version" => "2017-05-25",
])
// 选填: 启用https
, true
);
// 记录日志
log_record([
'name' => '发送短信',
'config' => $this->config,
'params' => $params
]);
log_record($response);
$this->error = $response->Message;
return $response->Code === 'OK';
}
}
@@ -0,0 +1,29 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\sms\engine;
abstract class Server
{
protected $error;
/**
* 返回错误信息
* @return mixed
*/
public function getError()
{
return $this->error;
}
}
@@ -0,0 +1,88 @@
<?php
namespace app\common\library\sms\package\aliyun;
/**
* 签名助手 2017/11/19
*
* Class SignatureHelper
*/
class SignatureHelper
{
/**
* 生成签名并发起请求
*
* @param $accessKeyId string AccessKeyId (https://ak-console.aliyun.com/)
* @param $accessKeySecret string AccessKeySecret
* @param $domain string API接口所在域名
* @param $params array API具体参数
* @param $security boolean 使用https
* @return bool|\stdClass 返回API接口调用结果,当发生错误时返回false
*/
public function request($accessKeyId, $accessKeySecret, $domain, $params, $security = false)
{
$apiParams = array_merge(array(
"SignatureMethod" => "HMAC-SHA1",
"SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
"SignatureVersion" => "1.0",
"AccessKeyId" => $accessKeyId,
"Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
"Format" => "JSON",
), $params);
ksort($apiParams);
$sortedQueryStringTmp = "";
foreach ($apiParams as $key => $value) {
$sortedQueryStringTmp .= "&" . $this->encode($key) . "=" . $this->encode($value);
}
$stringToSign = "GET&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1));
$sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&", true));
$signature = $this->encode($sign);
$url = ($security ? 'https' : 'http') . "://{$domain}/?Signature={$signature}{$sortedQueryStringTmp}";
try {
$content = $this->fetchContent($url);
return json_decode($content);
} catch (\Exception $e) {
return false;
}
}
private function encode($str)
{
$res = urlencode($str);
$res = preg_replace("/\+/", "%20", $res);
$res = preg_replace("/\*/", "%2A", $res);
$res = preg_replace("/%7E/", "~", $res);
return $res;
}
private function fetchContent($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"x-sdk-client" => "php/2.0.0"
));
if (substr($url, 0, 5) == 'https') {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
$rtn = curl_exec($ch);
if ($rtn === false) {
trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
}
curl_close($ch);
return $rtn;
}
}
@@ -0,0 +1,147 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\storage;
use think\Exception;
use app\common\library\storage\engine\Aliyun;
use app\common\library\storage\engine\Local;
use app\common\library\storage\engine\Qcloud;
use app\common\library\storage\engine\Qiniu;
use app\common\enum\file\Storage as StorageEnum;
/**
* 存储模块驱动
* Class driver
* @package app\common\library\storage
*/
class Driver
{
private $config; // upload 配置
private $engine; // 当前存储引擎类
/**
* 存储引擎类列表
*/
const ENGINE_CLASS_LIST = [
StorageEnum::LOCAL => Local::class,
StorageEnum::QINIU => QINIU::class,
StorageEnum::ALIYUN => Aliyun::class,
StorageEnum::QCLOUD => Qcloud::class
];
/**
* 构造方法
* Driver constructor.
* @param $config
* @param string|null $storage 指定存储方式,如不指定则为系统默认
* @throws Exception
*/
public function __construct($config, string $storage = null)
{
$this->config = $config;
// 实例化当前存储引擎
$this->engine = $this->getEngineClass($storage);
}
/**
* 设置上传的文件信息
* @param string $name
* @return mixed
*/
public function setUploadFile(string $name = 'iFile')
{
return $this->engine->setUploadFile($name);
}
/**
* 设置上传的文件信息
* @param string $filePath
* @return mixed
*/
public function setUploadFileByReal(string $filePath)
{
return $this->engine->setUploadFileByReal($filePath);
}
/**
* 设置上传的文件信息
* @param string $name
* @return mixed
*/
public function setRootName(string $name = '')
{
return $this->engine->setRootName($name);
}
/**
* 设置上传文件的验证规则
* @param array $rules
* @return mixed
*/
public function setValidationScene(array $rules = [])
{
return $this->engine->setValidationScene($rules);
}
/**
* 执行文件上传
*/
public function upload()
{
return $this->engine->upload();
}
/**
* 执行文件删除
* @param string $filePath
* @return mixed
*/
public function delete(string $filePath)
{
return $this->engine->delete($filePath);
}
/**
* 获取错误信息
* @return mixed
*/
public function getError()
{
return $this->engine->getError();
}
/**
* 返回保存的文件信息
* @return mixed
*/
public function getSaveFileInfo()
{
return $this->engine->getSaveFileInfo();
}
/**
* 获取当前的存储引擎
* @param string|null $storage 指定存储方式,如不指定则为系统默认
* @return mixed
* @throws Exception
*/
private function getEngineClass(string $storage = null)
{
$storage = is_null($storage) ? $this->config['default'] : $storage;
if (!isset(self::ENGINE_CLASS_LIST[$storage])) {
throw new Exception("未找到存储引擎类: {$storage}");
}
$class = self::ENGINE_CLASS_LIST[$storage];
return new $class($storage, $this->config['engine'][$storage]);
}
}
@@ -0,0 +1,46 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\storage;
/**
* 文件上传验证类
* Class FileValidate
* @package app\common\library\storage
*/
class FileValidate extends \think\Validate
{
// 验证规则
protected $rule = [
// 图片文件: jpg,jpeg,png,bmp,gif
// 文件大小: 2MB = (1024 * 1024 * 2) = 2097152 字节
'image' => 'filesize:2097152|fileExt:jpg,jpeg,png,bmp,gif',
// 视频文件: mp4
// 文件大小: 20MB = (1024 * 1024 * 20) = 20971520 字节
'video' => 'filesize:10485760|fileExt:mp4',
];
// 错误提示信息
protected $message = [
'image.filesize' => '图片文件大小不能超出2MB',
'image.fileExt' => '图片文件扩展名有误',
'video.filesize' => '视频文件大小不能超出10MB',
'video.fileExt' => '视频文件扩展名有误',
];
// 验证场景
protected $scene = [
'image' => ['image'],
'video' => ['video'],
];
}
@@ -0,0 +1,72 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\storage\engine;
use OSS\OssClient;
use OSS\Core\OssException;
/**
* 阿里云存储引擎 (OSS)
* Class Aliyun
* @package app\common\library\storage\engine
*/
class Aliyun extends Basics
{
/**
* 执行上传
* @return bool
*/
public function upload(): bool
{
try {
$ossClient = new OssClient(
$this->config['access_key_id'],
$this->config['access_key_secret'],
$this->config['domain'],
true
);
$result = $ossClient->uploadFile(
$this->config['bucket'],
$this->getSaveFileInfo()['file_path'],
$this->getRealPath()
);
} catch (OssException $e) {
$this->error = $e->getMessage();
return false;
}
return true;
}
/**
* 删除文件
* @param string $filePath
* @return bool
*/
public function delete(string $filePath): bool
{
try {
$ossClient = new OssClient(
$this->config['access_key_id'],
$this->config['access_key_secret'],
$this->config['domain'],
true
);
$ossClient->deleteObject($this->config['bucket'], $filePath);
} catch (OssException $e) {
$this->error = $e->getMessage();
return false;
}
return true;
}
}
@@ -0,0 +1,239 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\storage\engine;
use Exception;
use think\facade\Request;
use think\file\UploadedFile;
use cores\traits\ErrorTrait;
use app\common\exception\BaseException;
/**
* 存储引擎抽象类
* Class Basics
* @package app\common\library\storage\drivers
*/
abstract class Basics
{
use ErrorTrait;
// 当前存储引擎
protected $storage;
// 存储配置
protected $config;
// file对象句柄
/* @var $file UploadedFile */
protected $file;
// 验证规则
protected $validateRuleScene;
// 磁盘配置
protected $disk = 'public';
// 保存的根文件夹名称
protected $rootDirName;
/**
* 构造函数
* Server constructor.
* @param string $storage 存储方式
* @param array|null $config 存储配置
*/
public function __construct(string $storage, array $config = null)
{
$this->storage = $storage;
$this->config = $config;
}
/**
* 设置上传的文件信息 (外部用户上传)
* @param string $name
* @return $this
* @throws \cores\exception\BaseException
*/
public function setUploadFile(string $name): Basics
{
// 接收上传的文件
try {
$this->file = Request::file($name);
} catch (Exception $e) {
$this->throwFileError($e);
}
empty($this->file) && throwError('未找到上传文件的信息');
return $this;
}
/**
* 文件异常处理
* @param Exception $e
* @throws \cores\exception\BaseException
*/
private function throwFileError(Exception $e)
{
$maxSize = ini_get('upload_max_filesize');
$myMsg = $e->getCode() === 1 ? "上传的文件超出了服务器最大限制: {$maxSize};可修改php.ini文件中upload_max_filesize项调整" : false;
throwError($myMsg ?: $e->getMessage());
}
/**
* 设置上传的文件信息 (系统内部上传)
* @param string $filePath 文件路径
* @return $this
* @throws \cores\exception\BaseException
*/
public function setUploadFileByReal(string $filePath): Basics
{
// 接收上传的文件
$this->file = new UploadedFile($filePath, basename($filePath));
if (empty($this->file)) {
throwError('未找到上传文件的信息');
}
return $this;
}
/**
* 设置上传文件的验证规则
* @param string $scene
* @return Basics
*/
public function setValidationScene(string $scene = ''): Basics
{
$this->validateRuleScene = $scene;
return $this;
}
/**
* 设置磁盘配置
* @param string $disk
* @return $this
*/
public function setDisk(string $disk): Basics
{
$this->disk = $disk;
return $this;
}
/**
* 设置上传的文件根目录名称
* [通常是商城的id, 例如: 10001]
* @param string $name
* @return $this
*/
public function setRootDirName(string $name): Basics
{
$this->rootDirName = $name;
return $this;
}
/**
* 文件上传
* @return mixed
*/
abstract protected function upload();
/**
* 文件删除
* @param string $filePath
* @return mixed
*/
abstract protected function delete(string $filePath);
/**
* 临时文件的绝对路径
* @return mixed
*/
protected function getRealPath(): string
{
return $this->file->getRealPath();
}
/**
* 返回错误信息
* @return mixed
*/
public function getError(): string
{
return $this->error;
}
/**
* 生成保存的文件信息
* @return array
*/
public function getSaveFileInfo(): array
{
// 自动生成的文件名称
//$hashName = $this->file->hashName(null);
$hashName = $this->hashName();
// 存储目录
$filePath = $this->getFilePath($hashName);
// 文件名称
// 去除扩展名的写法 stristr($this->file->getOriginalName(), '.', true)
$fileName = $this->file->getOriginalName();
// 文件扩展名
$fileExt = strtolower($this->file->extension());
return [
'storage' => $this->storage, // 存储方式
'domain' => $this->config['domain'] ?? '', // 存储域名
'file_path' => $filePath, // 文件路径
'file_name' => $fileName, // 文件名称
'file_size' => $this->file->getSize(), // 文件大小(字节)
'file_ext' => $fileExt, // 文件扩展名
];
}
/**
* 自动生成文件名
* @return string
*/
private function hashName(): string
{
return $this->file->hashName(function () {
return date('Ymd') . DIRECTORY_SEPARATOR . md5(uniqid((string)mt_rand(), true));
});
}
/**
* 获取hashName的路径
* @param string $hashName
* @return string
*/
private function getFilePath(string $hashName): string
{
$filePath = empty($this->rootDirName) ? "{$hashName}" : "{$this->rootDirName}/{$hashName}";
return convert_left_slash($filePath);
}
/**
* 获取hashName的文件名
* @param string $filePath
* @return string
*/
protected function getFileHashName(string $filePath): string
{
return basename($filePath);
}
/**
* 获取hashName的文件目录
* @param string $filePath
* @return string
*/
protected function getFileHashRoute(string $filePath): string
{
return dirname($filePath);
}
}
@@ -0,0 +1,75 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\storage\engine;
use think\facade\Filesystem;
use app\common\library\storage\FileValidate;
/**
* 本地文件驱动
* Class Local
* @package app\common\library\storage\drivers
*/
class Local extends Basics
{
/**
* 上传图片文件
* @return bool
*/
public function upload(): bool
{
// 验证文件类型
if (!$this->validate()) {
return false;
}
try {
$filePath = $this->getSaveFileInfo()['file_path'];
// 上传到本地服务器
$sts = Filesystem::disk($this->disk)->putFileAs(
$this->getFileHashRoute($filePath),
$this->file,
$this->getFileHashName($filePath)
);
return (bool)$sts;
} catch (\Exception $e) {
$this->error = $e->getMessage();
return false;
}
}
/**
* 验证上传的文件
* @return bool
*/
private function validate(): bool
{
$FileValidate = new FileValidate;
if (!$FileValidate->check([$this->validateRuleScene => $this->file])) {
$this->error = $FileValidate->getError();
return false;
}
return true;
}
/**
* 删除文件
* @param string $filePath
* @return bool
*/
public function delete(string $filePath): bool
{
// 文件所在目录
$realPath = realpath(web_path() . "uploads/{$filePath}");
return $realPath === false || unlink($realPath);
}
}
@@ -0,0 +1,93 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\storage\engine;
use Qcloud\Cos\Client;
/**
* 腾讯云存储引擎 (COS)
* Class Qcloud
* @package app\common\library\storage\engine
*/
class Qcloud extends Basics
{
// Qcloud类
private $cosClient;
/**
* 构造方法
* Qcloud constructor.
* @param string $storage 存储方式
* @param array|null $config 存储配置
*/
public function __construct(string $storage, array $config = null)
{
parent::__construct($storage, $config);
// 创建Qcloud类
$this->createCosClient();
}
/**
* 创建COS控制类
*/
private function createCosClient()
{
$this->cosClient = new Client([
'region' => $this->config['region'],
'credentials' => [
'secretId' => $this->config['secret_id'],
'secretKey' => $this->config['secret_key'],
],
]);
}
/**
* 执行上传
* @return bool
*/
public function upload(): bool
{
// 上传文件
// putObject(上传接口,最大支持上传5G文件)
try {
$result = $this->cosClient->putObject([
'Bucket' => $this->config['bucket'],
'Key' => $this->getSaveFileInfo()['file_path'],
'Body' => fopen($this->getRealPath(), 'rb')
]);
return true;
} catch (\Exception $e) {
$this->error = $e->getMessage();
return false;
}
}
/**
* 删除文件
* @param string $filePath
* @return bool
*/
public function delete(string $filePath): bool
{
try {
$result = $this->cosClient->deleteObject(array(
'Bucket' => $this->config['bucket'],
'Key' => $filePath
));
return true;
} catch (\Exception $e) {
$this->error = $e->getMessage();
return false;
}
}
}
@@ -0,0 +1,71 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\storage\engine;
use Qiniu\Auth;
use Qiniu\Http\Error;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;
/**
* 七牛云存储引擎
* Class Qiniu
* @package app\common\library\storage\engine
*/
class Qiniu extends Basics
{
/**
* 执行上传
* @return bool|mixed
* @throws \Exception
*/
public function upload()
{
// 要上传图片的本地路径
$realPath = $this->getRealPath();
// 构建鉴权对象
$auth = new Auth($this->config['access_key'], $this->config['secret_key']);
// 要上传的空间
$token = $auth->uploadToken($this->config['bucket']);
// 初始化 UploadManager 对象并进行文件的上传
$uploadMgr = new UploadManager();
// 调用 UploadManager 的 putFile 方法进行文件的上传
list(, $error) = $uploadMgr->putFile($token, $this->getSaveFileInfo()['file_path'], $realPath);
/* @var $error Error */
if ($error !== null) {
$this->error = $error->message();
return false;
}
return true;
}
/**
* 删除文件
* @param string $filePath
* @return bool
*/
public function delete(string $filePath): bool
{
// 构建鉴权对象
$auth = new Auth($this->config['access_key'], $this->config['secret_key']);
// 初始化 UploadManager 对象并进行文件的上传
$bucketMgr = new BucketManager($auth);
/* @var $error Error */
list(, $error) = $bucketMgr->delete($this->config['bucket'], $filePath);
if ($error !== null) {
$this->error = $error->message();
return false;
}
return true;
}
}
@@ -0,0 +1,33 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\wechat;
/**
* error code 说明.
* <ul>
* <li>-41001: encodingAesKey 非法</li>
* <li>-41003: aes 解密失败</li>
* <li>-41004: 解密后得到的buffer非法</li>
* <li>-41005: base64加密失败</li>
* <li>-41016: base64解密失败</li>
* </ul>
*/
class ErrorCode
{
public static $OK = 0;
public static $IllegalAesKey = -41001;
public static $IllegalIv = -41002;
public static $IllegalBuffer = -41003;
public static $DecodeBase64Error = -41004;
}
@@ -0,0 +1,60 @@
<?php
// +----------------------------------------------------------------------
// | 商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www..com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 科技 <admin@.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\wechat;
use app\common\library\helper;
use cores\exception\BaseException;
/**
* 小程序二维码
* Class Qrcode
* @package app\common\library\wechat
*/
class Qrcode extends WxBase
{
/**
* 获取小程序码
* API文档地址:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html
* @param string $scene 场景值 (例如: uid:10001)
* @param string|null $page 页面地址
* @param int $width 二维码宽度
* @return mixed
* @throws BaseException
*/
public function getQrcode(string $scene, string $page = null, int $width = 430)
{
// 微信接口url
$accessToken = $this->getAccessToken();
$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
// 构建请求
$data = compact('scene', 'width');
!is_null($page) && $data['page'] = $page;
// 返回结果
$result = $this->post($url, helper::jsonEncode($data));
// 记录日志
log_record([
'name' => '获取小程序码',
'params' => $data,
'result' => !strpos($result, 'errcode') ? 'true' : $result
]);
if (!strpos($result, 'errcode')) {
return $result;
}
$data = helper::jsonDecode($result);
$error = '小程序码获取失败 ' . $data['errmsg'];
if ($data['errcode'] == 41030) {
$error = '小程序页面不存在,请先发布上线后再生成';
}
throwError($error);
}
}
@@ -0,0 +1,65 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\wechat;
class WXBizDataCrypt
{
private $appid;
private $sessionKey;
/**
* 构造函数
* @param string $appid string 小程序的appid
* @param string $sessionKey string 用户在小程序登录后获取的会话密钥
*/
public function __construct(string $appid, string $sessionKey)
{
$this->sessionKey = $sessionKey;
$this->appid = $appid;
}
/**
* 检验数据的真实性,并且获取解密后的明文.
* @param string $encryptedData 加密的用户数据
* @param string $iv 与用户数据一同返回的初始向量
* @param mixed $content 解密后的原文
* @return int 成功0,失败返回对应的错误码
*/
public function decryptData(string $encryptedData, string $iv, &$content): int
{
if (strlen($this->sessionKey) != 24) {
return ErrorCode::$IllegalAesKey;
}
if (strlen($iv) != 24) {
return ErrorCode::$IllegalIv;
}
$aesKey = base64_decode($this->sessionKey);
$aesIV = base64_decode($iv);
$aesCipher = base64_decode($encryptedData);
$result = openssl_decrypt($aesCipher, 'AES-128-CBC', $aesKey, 1, $aesIV);
if (empty($result)) {
return ErrorCode::$IllegalBuffer;
}
$resultArr = json_decode($result, true);
if (empty($resultArr)) {
return ErrorCode::$IllegalBuffer;
}
if ($resultArr['watermark']['appid'] != $this->appid) {
return ErrorCode::$IllegalBuffer;
}
$content = $resultArr;
return ErrorCode::$OK;
}
}
@@ -0,0 +1,187 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\wechat;
use think\facade\Cache;
use cores\traits\ErrorTrait;
use app\common\library\helper;
use app\common\exception\BaseException;
/**
* 微信api基类
* Class wechat
* @package app\library
*/
class WxBase
{
use ErrorTrait;
protected $appId;
protected $appSecret;
/**
* 构造函数
* WxBase constructor.
* @param $appId
* @param $appSecret
*/
public function __construct($appId = null, $appSecret = null)
{
$this->setConfig($appId, $appSecret);
}
protected function setConfig($appId = null, $appSecret = null)
{
!empty($appId) && $this->appId = $appId;
!empty($appSecret) && $this->appSecret = $appSecret;
}
/**
* 获取access_token
* @return mixed
* @throws \cores\exception\BaseException
*/
protected function getAccessToken()
{
$cacheKey = $this->appId . '@access_token';
if (!Cache::get($cacheKey)) {
// 请求API获取 access_token
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
$result = $this->get($url);
$response = $this->jsonDecode($result);
if (array_key_exists('errcode', $response)) {
throwError("access_token获取失败,错误信息:{$result}");
}
// 记录日志
log_record([
'name' => '获取access_token',
'url' => $url,
'appId' => $this->appId,
'result' => $result
]);
// 写入缓存
Cache::set($cacheKey, $response['access_token'], 6000);
}
return Cache::get($cacheKey);
}
/**
* 模拟GET请求 HTTPS的页面
* @param string $url 请求地址
* @param array $data
* @return string $result
* @throws \cores\exception\BaseException
*/
protected function get(string $url, array $data = [])
{
// 处理query参数
if (!empty($data)) {
$url = $url . '?' . http_build_query($data);
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
$result = curl_exec($curl);
if ($result === false) {
throwError(curl_error($curl));
}
curl_close($curl);
return $result;
}
/**
* 模拟POST请求
* @param string $url 请求地址
* @param mixed $data 请求数据
* @param false $useCert 是否引入微信支付证书
* @param array $sslCert 证书路径
* @return mixed|bool|string
* @throws \cores\exception\BaseException
*/
protected function post(string $url, $data = [], bool $useCert = false, array $sslCert = [])
{
$header = [
'Content-type: application/json;'
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
if ($useCert == true) {
// 设置证书:cert 与 key 分别属于两个.pem文件
curl_setopt($curl, CURLOPT_SSLCERTTYPE, 'PEM');
curl_setopt($curl, CURLOPT_SSLCERT, $sslCert['certPem']);
curl_setopt($curl, CURLOPT_SSLKEYTYPE, 'PEM');
curl_setopt($curl, CURLOPT_SSLKEY, $sslCert['keyPem']);
}
$result = curl_exec($curl);
if ($result === false) {
throwError(curl_error($curl));
}
curl_close($curl);
return $result;
}
/**
* 模拟POST请求 [第二种方式, 用于兼容微信api]
* @param $url
* @param array $data
* @return mixed
* @throws \cores\exception\BaseException
*/
protected function post2($url, array $data = [])
{
$header = [
'Content-Type: application/x-www-form-urlencoded'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
$result = curl_exec($ch);
if ($result === false) {
throwError(curl_error($ch));
}
curl_close($ch);
return $result;
}
/**
* 数组转json
* @param $data
* @return string
*/
protected function jsonEncode($data): string
{
return helper::jsonEncode($data, JSON_UNESCAPED_UNICODE);
}
/**
* json转数组
* @param $json
* @return mixed
*/
protected function jsonDecode($json)
{
return helper::jsonDecode($json);
}
}
@@ -0,0 +1,408 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
namespace app\common\library\wechat;
use app\common\model\wxapp\Setting as WxappSettingModel;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\order\PayType as OrderPayTypeEnum;
use app\common\library\helper;
use cores\exception\BaseException;
/**
* 微信支付
* Class WxPay
* @package app\common\library\wechat
*/
class WxPay extends WxBase
{
// 微信支付配置
private $config;
// 当前商城ID
private $storeId;
// 订单模型
private $modelClass = [
OrderTypeEnum::ORDER => \app\api\service\order\PaySuccess::class,
OrderTypeEnum::RECHARGE => \app\api\service\recharge\PaySuccess::class,
];
/**
* 构造函数
* @param array $config
* @param int|null $storeId
*/
public function __construct(array $config = [], ?int $storeId = null)
{
parent::__construct();
$this->config = $config;
$this->storeId = $storeId;
if (!empty($this->config)) {
$this->setConfig($this->config['app_id'], $this->config['app_secret']);
}
}
/**
* 统一下单API
* @param $orderNo
* @param $openid
* @param $totalFee
* @param int $orderType 订单类型
* @return array
* @throws \cores\exception\BaseException
*/
public function unifiedorder($orderNo, $openid, $totalFee, int $orderType = OrderTypeEnum::ORDER): array
{
// 当前时间
$time = time();
// 生成随机字符串
$nonceStr = md5($time . $openid);
// API参数
$params = [
'appid' => $this->appId,
'attach' => helper::jsonEncode(['order_type' => $orderType]),
'body' => $orderNo,
'mch_id' => $this->config['mchid'],
'nonce_str' => $nonceStr,
'notify_url' => base_url() . 'notice.php', // 异步通知地址
'openid' => $openid,
'out_trade_no' => $orderNo,
'spbill_create_ip' => \request()->ip(),
'total_fee' => (int)helper::bcmul($totalFee, 100), // 价格:单位分
'trade_type' => 'JSAPI',
];
// 生成签名
$params['sign'] = $this->makeSign($params);
// 请求API
$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
$result = $this->post($url, $this->toXml($params));
$prepay = $this->fromXml($result);
// 请求失败
if ($prepay['return_code'] === 'FAIL') {
$errMsg = "微信支付api:{$prepay['return_msg']}";
throwError($errMsg, null, ['errorCode' => 'WECHAT_PAY', 'isCreated' => true]);
}
if ($prepay['result_code'] === 'FAIL') {
$errMsg = "微信支付api:{$prepay['err_code_des']}";
throwError($errMsg, null, ['errorCode' => 'WECHAT_PAY', 'isCreated' => true]);
}
// 生成 nonce_str 供前端使用
$paySign = $this->makePaySign($params['nonce_str'], $prepay['prepay_id'], $time);
return [
'prepay_id' => $prepay['prepay_id'],
'nonceStr' => $nonceStr,
'timeStamp' => (string)$time,
'paySign' => $paySign
];
}
/**
* 支付成功异步通知
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function notify()
{
if (!$xml = file_get_contents('php://input')) {
$this->returnCode(false, 'Not found DATA');
}
// 将服务器返回的XML数据转化为数组
$data = $this->fromXml($xml);
// 记录日志
log_record($xml);
log_record($data);
// 实例化订单模型
$model = $this->getOrderModel($data['out_trade_no'], $data['attach']);
// 订单信息
$order = $model->getOrderInfo();
empty($order) && $this->returnCode(false, '订单不存在');
// 小程序配置信息
$wxConfig = WxappSettingModel::getWxappConfig($order['store_id']);
// 设置支付秘钥
$this->config['apikey'] = $wxConfig['apikey'];
// 保存微信服务器返回的签名sign
$dataSign = $data['sign'];
// sign不参与签名算法
unset($data['sign']);
// 生成签名
$sign = $this->makeSign($data);
// 判断签名是否正确 判断支付状态
if (
($sign !== $dataSign)
|| ($data['return_code'] !== 'SUCCESS')
|| ($data['result_code'] !== 'SUCCESS')
) {
$this->returnCode(false, '签名失败');
}
// 订单支付成功业务处理
$status = $model->onPaySuccess(OrderPayTypeEnum::WECHAT, $data);
if ($status == false) {
$this->returnCode(false, $model->getError());
}
// 返回状态
$this->returnCode(true, 'OK');
}
/**
* 申请退款API
* @param string $transactionId 微信支付交易流水号
* @param string $totalFee 订单总金额
* @param string $refundFee 退款金额
* @return bool
* @throws BaseException
* @throws \cores\exception\BaseException
*/
public function refund(string $transactionId, string $totalFee, string $refundFee): bool
{
// 当前时间
$time = time();
// 生成随机字符串
$nonceStr = md5($time . $transactionId . $totalFee . $refundFee);
// API参数
$params = [
'appid' => $this->appId,
'mch_id' => $this->config['mchid'],
'nonce_str' => $nonceStr,
'transaction_id' => $transactionId,
'out_refund_no' => $time,
'total_fee' => (int)helper::bcmul($totalFee,100),
'refund_fee' => (int)helper::bcmul($refundFee,100),
];
// 生成签名
$params['sign'] = $this->makeSign($params);
// 请求API
$url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
$result = $this->post($url, $this->toXml($params), true, $this->getCertPem());
// 请求失败
if (empty($result)) {
throwError('微信退款api请求失败');
}
// 格式化返回结果
$prepay = $this->fromXml($result);
// 记录日志
log_record(['name' => '微信退款API', [
'params' => $params,
'result' => $result,
'prepay' => $prepay
]]);
// 请求失败
if ($prepay['return_code'] === 'FAIL') {
throwError("return_msg: {$prepay['return_msg']}");
}
if ($prepay['result_code'] === 'FAIL') {
throwError("err_code_des: {$prepay['err_code_des']}");
}
return true;
}
/**
* 获取cert证书文件
* @return string[]
* @throws \cores\exception\BaseException
*/
private function getCertPem(): array
{
if (empty($this->config['cert_pem']) || empty($this->config['key_pem'])) {
throwError('请先到后台小程序设置填写微信支付证书文件');
}
// cert目录
$filePath = __DIR__ . "/cert/{$this->storeId}/";
return [
'certPem' => $filePath . 'cert.pem',
'keyPem' => $filePath . 'key.pem'
];
}
/**
* 实例化订单模型 (根据attach判断)
* @param $orderNo
* @param null $attach
* @return mixed
*/
private function getOrderModel($orderNo, $attach = null)
{
$attach = helper::jsonDecode($attach);
// 判断订单类型返回对应的订单模型
$model = $this->modelClass[$attach['order_type']];
return new $model($orderNo);
}
/**
* 返回状态给微信服务器
* @param boolean $returnCode
* @param string|null $msg
*/
private function returnCode(bool $returnCode = true, string $msg = null)
{
// 返回状态
$return = [
'return_code' => $returnCode ? 'SUCCESS' : 'FAIL',
'return_msg' => $msg ?: 'OK',
];
// 记录日志
log_record([
'name' => '返回微信支付状态',
'data' => $return
]);
die($this->toXml($return));
}
/**
* 生成paySign
* @param string $nonceStr
* @param string $prepayId
* @param int $timeStamp
* @return string
*/
private function makePaySign(string $nonceStr, string $prepayId, int $timeStamp): string
{
$data = [
'appId' => $this->appId,
'nonceStr' => $nonceStr,
'package' => 'prepay_id=' . $prepayId,
'signType' => 'MD5',
'timeStamp' => $timeStamp,
];
// 签名步骤一:按字典序排序参数
ksort($data);
$string = $this->toUrlParams($data);
// 签名步骤二:在string后加入KEY
$string = $string . '&key=' . $this->config['apikey'];
// 签名步骤三:MD5加密
$string = md5($string);
// 签名步骤四:所有字符转为大写
return strtoupper($string);
}
/**
* 将xml转为array
* @param string $xml
* @return mixed
*/
private function fromXml(string $xml)
{
// 禁止引用外部xml实体
libxml_disable_entity_loader(true);
return helper::jsonDecode(helper::jsonEncode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)));
}
/**
* 生成签名
* @param array $values
* @return string 本函数不覆盖sign成员变量,如要设置签名需要调用SetSign方法赋值
*/
private function makeSign(array $values): string
{
//签名步骤一:按字典序排序参数
ksort($values);
$string = $this->toUrlParams($values);
//签名步骤二:在string后加入KEY
$string = $string . '&key=' . $this->config['apikey'];
//签名步骤三:MD5加密
$string = md5($string);
//签名步骤四:所有字符转为大写
return strtoupper($string);
}
/**
* 格式化参数格式化成url参数
* @param array $values
* @return string
*/
private function toUrlParams(array $values): string
{
$buff = '';
foreach ($values as $k => $v) {
if ($k != 'sign' && $v != '' && !is_array($v)) {
$buff .= $k . '=' . $v . '&';
}
}
return trim($buff, '&');
}
/**
* 输出xml字符
* @param array $values
* @return bool|string
*/
private function toXml(array $values)
{
if (!is_array($values)
|| count($values) <= 0
) {
return false;
}
$xml = "<xml>";
foreach ($values as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
} else {
$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
}
}
$xml .= "</xml>";
return $xml;
}
/**
* 发货
* API文档地址:https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/order-shipping/order-shipping.html
* @param string $transaction_id 微信支付交易id
* @param string $desc 商品描述
* @param string $openid 用户openid
* @return mixed
* @throws BaseException
*/
public function uploadShipping(string $transaction_id, string $desc, string $openid)
{
// 微信接口url
$accessToken = $this->getAccessToken();
$url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token={$accessToken}";
$dt = new \DateTime('now', new \DateTimeZone('Asia/Shanghai'));
$upload_time = $dt->format('Y-m-d\TH:i:s.vP');
// 构建请求
$data = [
'order_key' => [
'order_number_type' => 2,
'transaction_id' => $transaction_id,
],
'logistics_type' => 3,
'delivery_mode' => 1,
'shipping_list' => [
[
'item_desc' => $desc,
]
],
'upload_time' => $upload_time,
'payer' => [
'openid' => $openid
]
];
// 返回结果
$result = $this->post($url, helper::jsonEncode($data));
// 记录日志
log_record([
'name' => '微信支付自动发货',
'params' => $data,
'result' => !strpos($result, 'errcode') ? 'true' : $result
]);
$data = helper::jsonDecode($result);
if ($data['errcode'] == 0) {
return $result;
}
$error = '微信支付自动发货 ' . $data['errmsg'];
/*if ($data['errcode'] == 41030) {
$error = '小程序页面不存在,请先发布上线后再生成';
}*/
// throwError($error);
}
}
@@ -0,0 +1,50 @@
<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace app\common\library\wechat;
use app\common\library\helper;
/**
* 微信小程序用户管理类
* Class WxUser
* @package app\common\library\wechat
*/
class WxUser extends WxBase
{
/**
* 获取session_key
* @param string $code
* @return array|mixed
*/
public function jscode2session(string $code)
{
/**
* code 换取 session_key
* 这是一个 HTTPS 接口,开发者服务器使用登录凭证 code 获取 session_key 和 openid。
* 其中 session_key 是对用户数据进行加密签名的密钥。为了自身应用安全,session_key 不应该在网络上传输。
*/
$url = 'https://api.weixin.qq.com/sns/jscode2session';
$result = helper::jsonDecode($this->get($url, [
'appid' => $this->appId,
'secret' => $this->appSecret,
'grant_type' => 'authorization_code',
'js_code' => $code
]));
if (isset($result['errcode'])) {
$this->error = $result['errmsg'];
return false;
}
return $result;
}
}
@@ -0,0 +1,2 @@
*
!.gitignore