first commit

This commit is contained in:
2025-07-14 14:55:25 +08:00
commit ace33d202f
473 changed files with 117431 additions and 0 deletions
+521
View File
@@ -0,0 +1,521 @@
<?php
/**
* 商业使用授权协议
*
* Copyright (c) 2025 [云泽网]. 保留所有权利.
*
* 本软件仅供评估使用。任何商业用途必须获得书面授权许可。
* 未经授权商业使用本软件属于侵权行为,将承担法律责任。
*
* 授权购买请联系: 357099073@qq.com
* 官方网站: https://www.yunzer.cn
*
* 评估用户须知:
* 1. 禁止移除版权声明
* 2. 禁止用于生产环境
* 3. 禁止转售或分发
*/
/**
* 文章控制器
*/
namespace app\index\controller;
use app\index\controller\BaseController;
use app\index\model\Users;
use think\facade\Db;
use think\facade\View;
use think\facade\Request;
use app\index\model\Articles\Articles;
use app\index\model\Articles\ArticlesCategory;
use app\index\model\Authors\Authors;
use app\index\model\Resources\Resources;
class ArticlesController extends BaseController
{
//文章中心
public function index()
{
// 获取前端传来的分类ID
$cateid = input('cateid/d', 0); // 使用input助手函数获取参数,并转换为整数
$page = input('page/d', 1);
$limit = input('limit/d', 10);
// 获取所有顶级分类
$categories = ArticlesCategory::where('cid', 0)
->where('delete_time', null)
->where('status', 1)
->select()
->toArray();
// 获取顶级分类信息
$category = null;
if ($cateid > 0) {
$category = ArticlesCategory::where('id', $cateid)
->where('delete_time', null)
->where('status', 1)
->find();
}
// 获取所有子分类
$subCategories = [];
if ($cateid > 0) {
$subCategories = ArticlesCategory::where('cid', $cateid)
->where('delete_time', null)
->where('status', 1)
->select()
->toArray();
}
// 获取所有子分类ID
$subCategoryIds = array_column($subCategories, 'id');
if ($cateid > 0) {
$subCategoryIds[] = $cateid;
}
// 构建文章查询条件
$where = [
['delete_time', '=', null],
['status', '=', 2]
];
if (!empty($subCategoryIds)) {
$where[] = ['cate', 'in', $subCategoryIds];
}
// 查询文章
$articles = Articles::where($where)
->order('id DESC')
->page($page, $limit)
->select()
->toArray();
// 按子分类分组文章
$groupedArticles = [];
foreach ($subCategories as $subCategory) {
$groupedArticles[$subCategory['id']] = [
'id' => $subCategory['id'],
'name' => $subCategory['name'],
'desc' => $subCategory['desc'],
'image' => $subCategory['image'],
'list' => []
];
}
// 将文章分配到对应的子分类
foreach ($articles as $article) {
if (isset($groupedArticles[$article['cate']])) {
// 如果文章图片为空,使用分类图片
if (empty($article['image'])) {
$article['image'] = $groupedArticles[$article['cate']]['image'];
}
$groupedArticles[$article['cate']]['list'][] = $article;
}
}
// 获取总数
$total = Articles::where($where)->count();
// 准备返回数据
$data = [
'cate' => [
'id' => $cateid,
'name' => $category ? $category['name'] : '',
'desc' => $category ? $category['desc'] : '',
'image' => $category ? $category['image'] : '',
'subCategories' => array_values($groupedArticles),
'total' => $total,
'page' => $page,
'limit' => $limit
]
];
// 根据请求方式返回不同的输出
if (request()->isPost()) {
return json([
'code' => 1,
'msg' => '获取成功',
'data' => $data
]);
} else {
// 为视图准备数据
$viewData = [
'categories' => $categories,
'cate' => $data['cate']
];
return view('index', $viewData);
}
}
// 文章列表页
public function list()
{
// 获取分类ID
$cateId = Request::param('cate/d', 0);
// 构建查询条件
$where = [
['a.delete_time', '=', null],
['a.status', '=', 2]
];
if ($cateId > 0) {
$where[] = ['a.cate', '=', $cateId];
}
// 获取文章列表
$articles = Articles::alias('a')
->join('articles_category c', 'a.cate = c.id')
->where($where)
->field([
'a.*',
'IF(a.image IS NULL OR a.image = "", c.image, a.image) as image'
])
->order('a.id DESC')
->paginate([
'list_rows' => 10,
'query' => Request::instance()->param()
]);
// 获取分类信息
$category = null;
if ($cateId > 0) {
$category = ArticlesCategory::where('id', $cateId)
->where('delete_time', null)
->where('status', 3)
->find();
}
// 获取所有分类
$categories = ArticlesCategory::where('delete_time', null)
->where('status', 3)
->select()
->toArray();
// 根据请求方式返回不同的输出
if (request()->isPost()) {
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'articles' => $articles->items(),
'category' => $category,
'categories' => $categories,
'total' => $articles->total(),
'current_page' => $articles->currentPage(),
'per_page' => $articles->listRows()
]
]);
} else {
// 将变量传递给视图
View::assign([
'articles' => $articles,
'category' => $category,
'categories' => $categories
]);
return view('list');
}
}
// 文章详情页
public function detail()
{
$id = Request::param('id/d', 0);
$article = Articles::where('id', $id)->find();
if (!$article) {
return json(['code' => 0, 'msg' => '文章不存在或已被删除']);
}
// 获取分类名称
$cateName = ArticlesCategory::where('id', $article['cate'])
->value('name');
// 获取作者信息
$authorInfo = Users::where('name', $article['author'])->find();
if ($authorInfo) {
// 统计作者的文章数
$articleCount = Articles::where('author', $article['author'])->count();
// 统计作者的资源数
$resourceCount = Resources::where('uploader', $article['author'])->count();
$authorData = [
'avatar' => $authorInfo['avatar'] ?: '/static/images/avatar.png',
'name' => $authorInfo['name'],
'resource_count' => $resourceCount,
'article_count' => $articleCount
];
} else {
$authorData = [
'avatar' => '/static/images/avatar.png',
'name' => $article['author'],
'resource_count' => 0,
'article_count' => 0
];
}
// 获取上一篇和下一篇文章
$prevArticle = Articles::where('id', '<', $id)
->where('delete_time', null)
->where('status', '<>', 3)
->where('cate', $article['cate'])
->field(['id', 'title'])
->order('id DESC')
->find();
$nextArticle = Articles::where('id', '>', $id)
->where('delete_time', null)
->where('status', '<>', 3)
->where('cate', $article['cate'])
->field(['id', 'title'])
->order('id ASC')
->find();
// 获取相关文章(同分类的其他文章)
$relatedArticles = Articles::alias('a')
->join('articles_category c', 'a.cate = c.id')
->where('a.cate', $article['cate'])
->where('a.id', '<>', $id)
->where('a.delete_time', null)
->where('a.status', '=', 2)
->field([
'a.id',
'a.title',
'IF(a.image IS NULL OR a.image = "", c.image, a.image) as image'
])
->order('a.id DESC')
->limit(3)
->select()
->toArray();
// 如果是 POST 请求,返回 JSON 数据
if (Request::isPost()) {
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'authorInfo' => $authorData,
'article' => $article,
'cateName' => $cateName,
'prevArticle' => $prevArticle,
'nextArticle' => $nextArticle,
'relatedArticles' => $relatedArticles
]
]);
}
// GET 请求返回视图
View::assign([
'authorInfo' => $authorData,
'article' => $article,
'cateName' => $cateName,
'prevArticle' => $prevArticle,
'nextArticle' => $nextArticle,
'relatedArticles' => $relatedArticles
]);
return view('detail');
}
// 文章点赞
public function like()
{
if (!Request::isAjax()) {
return json(['code' => 0, 'msg' => '非法请求']);
}
$id = Request::param('id/d', 0);
// 检查文章是否存在
$article = Articles::where('id', $id)
->where('delete_time', null)
->where('status', 2)
->find();
if (!$article) {
return json(['code' => 0, 'msg' => '文章不存在或已被删除']);
}
// 更新点赞数
$result = Articles::where('id', $id)
->where('delete_time', null)
->inc('likes', 1)
->update();
if ($result) {
// 返回更新后的点赞数
$newLikes = $article['likes'] + 1;
return json([
'code' => 1,
'msg' => '点赞成功',
'data' => [
'likes' => $newLikes
]
]);
} else {
return json(['code' => 0, 'msg' => '点赞失败']);
}
}
// 提交评论
public function comment()
{
if (!Request::isAjax() || !Request::isPost()) {
return json(['code' => 0, 'msg' => '非法请求']);
}
$articleId = Request::param('article_id/d', 0);
$content = Request::param('content/s', '');
$parentId = Request::param('parent_id/d', 0);
if (empty($content)) {
return json(['code' => 0, 'msg' => '评论内容不能为空']);
}
// 检查文章是否存在
$article = Articles::where('id', $articleId)
->where('delete_time', null)
->where('status', 3)
->find();
if (!$article) {
return json(['code' => 0, 'msg' => '文章不存在或已被删除']);
}
// 添加评论
// $data = [
// 'article_id' => $articleId,
// 'content' => $content,
// 'parent_id' => $parentId,
// 'user_id' => $this->getUserId(),
// 'user_name' => $this->getUserName(),
// 'status' => 1,
// 'create_time' => time()
// ];
// $result = Db::table('yz_article_comment')->insert($data);
// if ($result) {
// return json(['code' => 1, 'msg' => '评论成功']);
// } else {
// return json(['code' => 0, 'msg' => '评论失败']);
// }
}
// 获取当前用户ID(示例方法,实际应根据您的用户系统实现)
private function getUserId()
{
// 这里应该返回当前登录用户的ID
return 1; // 示例返回值
}
// 获取当前用户名(示例方法,实际应根据您的用户系统实现)
private function getUserName()
{
// 这里应该返回当前登录用户的用户名
return '游客'; // 示例返回值
}
// 获取访问统计
public function viewStats()
{
$id = Request::param('id/d', 0);
// 获取总访问量
$totalViews = Articles::where('id', $id)
->value('views');
return json([
'code' => 1,
'data' => [
'total' => $totalViews
]
]);
}
/**
* 更新文章访问次数
*/
public function updateViews()
{
if (!Request::isPost()) {
return json(['code' => 0, 'msg' => '非法请求']);
}
$id = Request::post('id');
if (!$id) {
return json(['code' => 0, 'msg' => '参数错误']);
}
try {
// 更新访问次数
$article = Articles::where('id', $id)->find();
if (!$article) {
return json(['code' => 0, 'msg' => '文章不存在']);
}
// 更新访问次数
Articles::where('id', $id)->inc('views')->update();
// 获取更新后的访问次数
$newViews = Articles::where('id', $id)->value('views');
return json(['code' => 1, 'msg' => '更新成功', 'data' => ['views' => $newViews]]);
} catch (\Exception $e) {
return json(['code' => 0, 'msg' => '更新失败:' . $e->getMessage()]);
}
}
//获取作者信息
public function getAuthorInfo()
{
if (!Request::isPost()) {
return json(['code' => 0, 'msg' => '非法请求']);
}
$authorName = Request::post('name');
if (empty($authorName)) {
return json(['code' => 0, 'msg' => '作者名称不能为空']);
}
try {
// 获取作者基本信息
$author = Db::name('users')
->where('name', $authorName)
->field('id, name, avatar')
->find();
if (!$author) {
return json(['code' => 0, 'msg' => '作者不存在']);
}
// 获取作者发布的资源数量
$resourceCount = Db::name('resources')
->where('user_id', $author['id'])
->where('delete_time', null)
->where('status', 2) // 假设2是已发布状态
->count();
// 获取作者发布的文章数量
$articleCount = Db::name('articles')
->where('author', $authorName)
->where('delete_time', null)
->where('status', 2) // 假设2是已发布状态
->count();
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'avatar' => $author['avatar'],
'name' => $author['name'],
'resource_count' => $resourceCount,
'article_count' => $articleCount
]
]);
} catch (\Exception $e) {
return json(['code' => 0, 'msg' => '获取作者信息失败:' . $e->getMessage()]);
}
}
}
+144
View File
@@ -0,0 +1,144 @@
<?php
/**
* 商业使用授权协议
*
* Copyright (c) 2025 [云泽网]. 保留所有权利.
*
* 本软件仅供评估使用。任何商业用途必须获得书面授权许可。
* 未经授权商业使用本软件属于侵权行为,将承担法律责任。
*
* 授权购买请联系: 357099073@qq.com
* 官方网站: https://www.yunzer.cn
*
* 评估用户须知:
* 1. 禁止移除版权声明
* 2. 禁止用于生产环境
* 3. 禁止转售或分发
*/
/**
* 前台系统-基础控制器
*/
namespace app\index\controller;
use app\AppApi;
use think\facade\Db;
use think\facade\View;
use think\facade\Cookie;
use think\facade\Config;
use think\exception\HttpResponseException;
use think\facade\Request;
use app\index\model\User;
class Base
{
public $config = [];
public $userId = null;
public $user = [];
public function __construct()
{
date_default_timezone_set('PRC');
# 获取配置
$this->config = Db::table('yz_admin_config')->select()->toArray();
// 将配置数据转换为键值对形式
$configData = [];
foreach ($this->config as $item) {
// 使用正确的字段名 config_name 和 config_value
if (isset($item['config_name']) && isset($item['config_value'])) {
$configData[$item['config_name']] = $item['config_value'];
}
}
$this->config = $configData;
# 获取用户信息
$this->userId = Cookie::get('user_id');
if (!empty($this->userId)) {
$this->user = User::where('uid', $this->userId)->find();
}
View::assign([
'user' => $this->user,
'config' => $this->config
]);
}
/**
* 返回json对象
*/
protected function returnCode($code, $data = [], $count = 10)
{
header('Content-type:application/json');
if ($code == 0) {
$arr = array(
'code' => $code,
'msg' => '成功',
'count' => $count,
'data' => $data
);
} else if ($code >= 1 && $code <= 100) {
$arr = array(
'code' => $code,
'msg' => $data
);
} else {
$appapi = new AppApi();
$arr = array(
'code' => $code,
'msg' => $appapi::errorTip($code)
);
}
echo json_encode($arr);
if ($code != 0) {
exit;
}
}
/**
* 操作成功跳转的快捷方法
* @access protected
* @param mixed $msg 提示信息
* @return void
*/
protected function success($msg = '')
{
$result = [
'code' => 1,
'msg' => $msg
];
$type = $this->getResponseType();
if ($type == 'html') {
$response = view(Config::get('app.dispatch_success_tmpl'), $result);
} else if ($type == 'json') {
$response = json($result);
}
throw new HttpResponseException($response);
}
/**
* 操作错误跳转的快捷方法
* @access protected
* @param mixed $msg 提示信息
* @return void
*/
protected function error($msg = '')
{
$result = [
'code' => 0,
'msg' => $msg
];
$response = view(Config::get('app.dispatch_error_tmpl'), $result);
throw new HttpResponseException($response);
}
/**
* 获取当前的response 输出类型
* @access protected
* @return string
*/
protected function getResponseType()
{
return Request::isJson() || Request::isAjax() ? 'json' : 'html';
}
}
+264
View File
@@ -0,0 +1,264 @@
<?php
/**
* 商业使用授权协议
*
* Copyright (c) 2025 [云泽网]. 保留所有权利.
*
* 本软件仅供评估使用。任何商业用途必须获得书面授权许可。
* 未经授权商业使用本软件属于侵权行为,将承担法律责任。
*
* 授权购买请联系: 357099073@qq.com
* 官方网站: https://www.yunzer.cn
*
* 评估用户须知:
* 1. 禁止移除版权声明
* 2. 禁止用于生产环境
* 3. 禁止转售或分发
*/
declare(strict_types=1);
namespace app\index\controller;
use think\App;
use think\facade\View;
use think\facade\Request;
use think\facade\Db;
use app\service\VisitStatsService;
use PHPMailer\PHPMailer\PHPMailer;
use app\index\model\MailConfig;
use app\index\model\AdminConfig;
use app\index\model\Users;
/**
* 前台控制器基础类
*/
abstract class BaseController
{
/**
* Request实例
* @var \think\Request
*/
protected $request;
protected $visitStats;
/**
* 应用实例
* @var \think\App
*/
protected $app;
/**
* 构造方法
* @access public
* @param App $app 应用对象
*/
public function __construct(App $app)
{
$this->app = $app;
$this->request = $this->app->request;
$this->visitStats = new VisitStatsService();
// 控制器初始化
$this->initialize();
}
/**
* 初始化
*/
protected function initialize()
{
// 记录访问
$this->visitStats->recordVisit($this->getControllerName());
// 获取配置
$configList = AdminConfig::where('config_status', 1)
->order('config_sort DESC')
->select()
->toArray();
// 将配置数据转换为键值对形式
$config = [];
foreach ($configList as $item) {
$config[$item['config_name']] = $item['config_value'];
}
// 判断用户是否登录
$userInfo = [];
if (session('user_id')) {
// 从数据库获取最新用户信息
$user = Users::where('uid', session('user_id'))->find();
if ($user) {
$userInfo = [
'id' => $user->uid,
'name' => $user->name,
'account' => $user->account,
'avatar' => $user->avatar ?? '/static/images/avatar.png',
'is_login' => true,
'last_login_time' => $user->last_login_time
];
} else {
// 用户不存在,清除session
session('user_id', null);
session('user_name', null);
$userInfo = ['is_login' => false];
}
} else {
$userInfo = ['is_login' => false];
}
// 设置通用变量
View::assign([
'config' => $config,
'userInfo' => $userInfo
]);
}
/**
* 获取控制器名称(移除Controller后缀)
* @return string
*/
public function getControllerName()
{
$className = get_class($this);
$className = substr($className, strrpos($className, '\\') + 1);
return str_replace('Controller', '', $className);
}
/**
* 渲染模板输出
* @param string $template 模板文件
* @param array $vars 模板变量
* @return string
*/
protected function fetch($template = '', $vars = [])
{
return View::fetch($template, $vars);
}
/**
* 操作成功跳转
* @param string $msg 提示信息
* @param string $url 跳转地址
* @param mixed $data 返回数据
* @param integer $wait 跳转等待时间
* @return \think\response\Json|string
*/
protected function success($msg = '', $url = null, $data = '', $wait = 3)
{
if (Request::isAjax()) {
return json([
'code' => 1,
'msg' => $msg,
'data' => $data,
'url' => $url
]);
}
return View::fetch('common/success', [
'msg' => $msg,
'url' => $url,
'data' => $data,
'wait' => $wait
]);
}
/**
* 操作失败跳转
* @param string $msg 提示信息
* @param string $url 跳转地址
* @param mixed $data 返回数据
* @param integer $wait 跳转等待时间
* @return \think\response\Json|string
*/
protected function error($msg = '', $url = null, $data = '', $wait = 3)
{
if (Request::isAjax()) {
return json([
'code' => 0,
'msg' => $msg,
'data' => $data,
'url' => $url
]);
}
return View::fetch('common/error', [
'msg' => $msg,
'url' => $url,
'data' => $data,
'wait' => $wait
]);
}
protected function sendEmail($to, $content, $title)
{
// 获取邮件配置
$mailConfig = MailConfig::where('id', 1)->find();
if (!$mailConfig) {
return '邮件配置不存在';
}
//实例化PHPMailer核心类
$mail = new PHPMailer();
//是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式
$mail->SMTPDebug = 0;
//使用smtp鉴权方式发送邮件
$mail->isSMTP();
//smtp需要鉴权 这个必须是true
$mail->SMTPAuth = true;
//链接qq域名邮箱的服务器地址
$mail->Host = $mailConfig['smtp_host'];
//设置使用ssl加密方式登录鉴权
$mail->SMTPSecure = 'ssl';
//设置ssl连接smtp服务器的远程服务器端口号
$mail->Port = $mailConfig['smtp_port'];
//设置发件人的主机域
$mail->Hostname = $mailConfig['smtp_email'];
//设置发送的邮件的编码
$mail->CharSet = 'UTF-8';
//设置发件人姓名(昵称)
$mail->FromName = $mailConfig['smtp_name'];
//smtp登录的账号
$mail->Username = $mailConfig['smtp_email'];
//smtp登录的密码
$mail->Password = $mailConfig['smtp_password'];
//设置发件人邮箱地址
$mail->setFrom($mailConfig['smtp_email'], $mailConfig['smtp_name']);
//邮件正文是否为html编码
$mail->isHTML(true);
//设置收件人邮箱地址
$mail->addAddress($to);
//添加该邮件的主题
$mail->Subject = $title;
//添加邮件正文
$mail->Body = $content;
try {
$status = $mail->send();
if ($status) {
return '发送成功';
} else {
return '发送失败';
}
} catch (\Exception $e) {
return '发送失败:' . $e->getMessage();
}
}
}
+391
View File
@@ -0,0 +1,391 @@
<?php
/**
* 商业使用授权协议
*
* Copyright (c) 2025 [云泽网]. 保留所有权利.
*
* 本软件仅供评估使用。任何商业用途必须获得书面授权许可。
* 未经授权商业使用本软件属于侵权行为,将承担法律责任。
*
* 授权购买请联系: 357099073@qq.com
* 官方网站: https://www.yunzer.cn
*
* 评估用户须知:
* 1. 禁止移除版权声明
* 2. 禁止用于生产环境
* 3. 禁止转售或分发
*/
/**
* 游戏下载控制器
*/
namespace app\index\controller;
use app\index\controller\BaseController;
use think\facade\Db;
use think\facade\View;
use think\facade\Request;
use app\index\model\Resources\Resources;
use app\index\model\Resources\ResourcesCategory;
use app\index\model\Attachments;
class GameController extends BaseController
{
//资源中心
public function index()
{
// 获取前端传来的分类ID
$cateid = input('cateid/d', 0);
$page = input('page/d', 1);
$limit = input('limit/d', 10);
// 获取所有顶级分类
$categories = ResourcesCategory::where('cid', 0)
->where('delete_time', null)
->where('status', 1)
->select()
->toArray();
// 获取顶级分类信息
$category = null;
if ($cateid > 0) {
$category = ResourcesCategory::where('id', $cateid)
->where('delete_time', null)
->where('status', 1)
->find();
}
// 获取所有子分类
$subCategories = [];
if ($cateid > 0) {
$subCategories = ResourcesCategory::where('cid', $cateid)
->where('delete_time', null)
->where('status', 1)
->select()
->toArray();
}
// 获取所有子分类ID
$subCategoryIds = array_column($subCategories, 'id');
if ($cateid > 0) {
$subCategoryIds[] = $cateid;
}
// 构建游戏查询条件
$where = [
['delete_time', '=', null],
['status', '=', 1]
];
if (!empty($subCategoryIds)) {
$where[] = ['cate', 'in', $subCategoryIds];
}
// 查询游戏
$games = Resources::where($where)
->order('id DESC')
->page($page, $limit)
->select()
->toArray();
// 按子分类分组游戏
$groupedGames = [];
foreach ($subCategories as $subCategory) {
$groupedGames[$subCategory['id']] = [
'id' => $subCategory['id'],
'name' => $subCategory['name'],
'list' => []
];
}
// 将游戏分配到对应的子分类
foreach ($games as $game) {
if (isset($groupedGames[$game['cate']])) {
$groupedGames[$game['cate']]['list'][] = $game;
}
}
// 获取总数
$total = Resources::where($where)->count();
// 准备返回数据
$data = [
'cate' => [
'id' => $cateid,
'name' => $category ? $category['name'] : '',
'desc' => $category ? $category['desc'] : '',
'image' => $category ? $category['image'] : '',
'subCategories' => array_values($groupedGames),
'total' => $total,
'page' => $page,
'limit' => $limit
]
];
// 根据请求方式返回不同的输出
if (request()->isPost()) {
return json([
'code' => 1,
'msg' => '获取成功',
'data' => $data
]);
} else {
// 为视图准备数据
$viewData = [
'categories' => $categories,
'cate' => $data['cate']
];
return view('index', $viewData);
}
}
// 游戏列表页
public function list()
{
// 获取分类ID
$cateId = Request::param('cate/d', 0);
// 构建查询条件
$where = [
['a.delete_time', '=', null],
['a.status', '=', 1]
];
if ($cateId > 0) {
$where[] = ['a.cate', '=', $cateId];
}
// 获取游戏列表
$games = Resources::alias('a')
->join('resources_category c', 'a.cate = c.id')
->where($where)
->field([
'a.*',
'IF(a.icon IS NULL OR a.icon = "", c.icon, a.icon) as icon'
])
->order('a.id DESC')
->paginate([
'list_rows' => 10,
'query' => Request::instance()->param()
]);
// 获取分类信息
$category = null;
if ($cateId > 0) {
$category = ResourcesCategory::where('id', $cateId)
->where('delete_time', null)
->where('status', 1)
->find();
}
// 获取所有分类
$categories = ResourcesCategory::where('delete_time', null)
->where('status', 1)
->select()
->toArray();
// 如果是POST请求,返回JSON数据
if (Request::isPost()) {
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'games' => $games->items(),
'total' => $games->total(),
'current_page' => $games->currentPage(),
'per_page' => $games->listRows(),
'category' => $category
]
]);
}
// GET请求返回渲染的视图
View::assign([
'games' => $games,
'category' => $category,
'categories' => $categories
]);
return View::fetch('list');
}
// 游戏详情页
public function detail()
{
$id = Request::param('id/d', 0);
$game = Resources::where('id', $id)->find();
if (!$game) {
return json(['code' => 0, 'msg' => '游戏不存在或已被删除']);
}
// 如果size没有,从附件表中获取
if (empty($game['size']) && !empty($game['fileurl'])) {
$attachment = Attachments::where('src', $game['fileurl'])
->find();
if ($attachment && !empty($attachment['size'])) {
$size = $attachment['size'];
// 转换文件大小为合适的单位
if ($size >= 1073741824) { // 1GB = 1024MB = 1024*1024KB = 1024*1024*1024B
$game['size'] = round($size / 1073741824, 2) . 'GB';
} elseif ($size >= 1048576) { // 1MB = 1024KB = 1024*1024B
$game['size'] = round($size / 1048576, 2) . 'MB';
} else {
$game['size'] = round($size / 1024, 2) . 'KB';
}
}
}
// 获取分类名称
$cateName = ResourcesCategory::where('id', $game['cate'])
->value('name');
// 获取上一个和下一个游戏
$prevGame = Resources::where('id', '<', $id)
->where('delete_time', null)
->where('status', 1)
->where('cate', $game['cate'])
->field(['id', 'title'])
->order('id DESC')
->find();
$nextGame = Resources::where('id', '>', $id)
->where('delete_time', null)
->where('status', 1)
->where('cate', $game['cate'])
->field(['id', 'title'])
->order('id ASC')
->find();
// 获取相关游戏(同分类的其他游戏)
$relatedGames = Db::table('yz_resources')
->alias('g')
->join('yz_resources_category c', 'g.cate = c.id')
->where('g.cate', $game['cate'])
->where('g.id', '<>', $id)
->where('g.delete_time', null)
->where('g.status', 1)
->field([
'g.id',
'g.title',
'IF(g.icon IS NULL OR g.icon = "", c.icon, g.icon) as icon'
])
->order('g.id DESC')
->limit(3)
->select()
->toArray();
// 如果是 AJAX 请求,返回 JSON 数据
if (Request::isAjax()) {
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'game' => $game,
'cateName' => $cateName,
'prevGame' => $prevGame,
'nextGame' => $nextGame,
'relatedGames' => $relatedGames
]
]);
}
// 非 AJAX 请求返回视图
View::assign([
'game' => $game,
'cateName' => $cateName,
'prevGame' => $prevGame,
'nextGame' => $nextGame,
'relatedGames' => $relatedGames
]);
return View::fetch('detail');
}
// 游戏下载
public function downloadurl()
{
if (!Request::isAjax()) {
return json(['code' => 0, 'msg' => '非法请求']);
}
$id = Request::param('id/d', 0);
// 获取游戏信息
$game = Resources::where('id', $id)
->where('delete_time', null)
->find();
if (!$game) {
return json(['code' => 0, 'msg' => '游戏不存在']);
}
// 更新下载次数
$result = Resources::where('id', $id)
->where('delete_time', null)
->inc('downloads', 1)
->update();
if ($result) {
return json([
'code' => 1,
'msg' => '下载成功',
'data' => [
'url' => $game['url']
]
]);
} else {
return json(['code' => 0, 'msg' => '下载失败']);
}
}
// 获取访问统计
public function viewStats()
{
$id = Request::param('id/d', 0);
// 获取总访问量
$totalViews = Resources::where('id', $id)
->value('views');
return json([
'code' => 1,
'data' => [
'total' => $totalViews
]
]);
}
/**
* 更新游戏访问次数
*/
public function updateViews()
{
if (!Request::isPost()) {
return json(['code' => 0, 'msg' => '非法请求']);
}
$id = Request::post('id');
if (!$id) {
return json(['code' => 0, 'msg' => '参数错误']);
}
try {
// 更新访问次数
$game = Resources::where('id', $id)->find();
if (!$game) {
return json(['code' => 0, 'msg' => '游戏不存在']);
}
// 更新访问次数
Resources::where('id', $id)->inc('views')->update();
// 获取更新后的访问次数
$newViews = Resources::where('id', $id)->value('views');
return json(['code' => 1, 'msg' => '更新成功', 'data' => ['views' => $newViews]]);
} catch (\Exception $e) {
return json(['code' => 0, 'msg' => '更新失败:' . $e->getMessage()]);
}
}
}
+427
View File
@@ -0,0 +1,427 @@
<?php
/**
* 商业使用授权协议
*
* Copyright (c) 2025 [云泽网]. 保留所有权利.
*
* 本软件仅供评估使用。任何商业用途必须获得书面授权许可。
* 未经授权商业使用本软件属于侵权行为,将承担法律责任。
*
* 授权购买请联系: 357099073@qq.com
* 官方网站: https://www.yunzer.cn
*
* 评估用户须知:
* 1. 禁止移除版权声明
* 2. 禁止用于生产环境
* 3. 禁止转售或分发
*/
/**
* 后台管理系统-首页
*/
namespace app\index\controller;
use app\index\controller\BaseController;
use think\facade\Db;
use think\facade\View;
use think\facade\Env;
use think\facade\Config;
use app\index\model\Banner;
use app\index\model\Resources\ResourcesCategory;
use app\index\model\Articles\ArticlesCategory;
use app\index\model\Resources\Resources;
use app\index\model\Articles\Articles;
use app\index\model\MailConfig;
use \think\facade\Filesystem;
use app\index\model\Attachments;
class IndexController extends BaseController
{
/**
* 首页
*/
public function index()
{
// 获取banner列表
$bannerList = Banner::where('delete_time', null)
->order('sort DESC, id DESC')
->select()
->toArray();
View::assign('bannerList', $bannerList);
return View::fetch();
}
/**
* 获取站点资讯列表
*/
public function siteNewslist()
{
// 获取站点资讯分类(顶级分类id为1的子分类)
$categories = ArticlesCategory::where('cid', 1)
->where('delete_time', null)
->select()
->toArray();
$articles = [];
$categoryData = [];
// 提取分类名称和ID用于前端tab显示
foreach ($categories as $category) {
$categoryData[] = [
'id' => $category['id'],
'name' => $category['name']
];
// 获取该分类下的文章,限制4条
$articles = Articles::where('cate', $category['id'])
->where('delete_time', null)
->where('status', 2)
->order('id', 'desc')
->field('id, cate, title, image, author, publishdate, views')
->limit(4)
->select()
->toArray();
}
return json([
'code' => 1,
'msg' => '获取成功',
'articles' => $articles,
'categories' => $categoryData
]);
}
/**
* 获取技术文章列表
*/
public function technicalArticleslist()
{
// 获取技术文章分类(顶级分类id为3的子分类)
$categories = ArticlesCategory::where('cid', 3)
->where('delete_time', null)
->select()
->toArray();
// 组装分类数据,方便后续查找
$categoryData = [];
$categoryImageMap = [];
$articlesByCategory = [];
foreach ($categories as $category) {
$categoryData[] = [
'id' => $category['id'],
'name' => $category['name']
];
$categoryImageMap[$category['id']] = $category['image'] ?? '';
// 获取每个分类下的文章,限制12条
$articles = Articles::where('cate', $category['id'])
->where('delete_time', null)
->where('status', 2)
->order('id', 'desc')
->field('id, cate, title, image, author, publishdate, views')
->limit(12)
->select()
->toArray();
// 替换image为空的文章
foreach ($articles as &$article) {
if (empty($article['image']) && !empty($categoryImageMap[$article['cate']])) {
$article['image'] = $categoryImageMap[$article['cate']];
}
}
unset($article);
$articlesByCategory[$category['id']] = $articles;
}
return json([
'code' => 1,
'msg' => '获取成功',
'articles' => $articlesByCategory,
'categories' => $categoryData
]);
}
/**
* 获取banner列表
*/
public function bannerlist()
{
// 获取启用状态的banner列表,按排序倒序
$bannerList = Banner::where('delete_time', null)
->order('sort DESC, id DESC')
->select()
->toArray();
return json(['code' => 1, 'msg' => '获取成功', 'banner' => $bannerList]);
}
/**
* 获取资源下载列表
*/
public function resourcesList()
{
// 获取资源分类(顶级分类id为2的子分类)
$categories = ResourcesCategory::where('cid', 2)
->where('delete_time', null)
->select()
->toArray();
// 组装分类数据
$categoryData = [];
$categoryImageMap = [];
$resourcesByCategory = [];
foreach ($categories as $category) {
$categoryData[] = [
'id' => $category['id'],
'name' => $category['name']
];
$categoryImageMap[$category['id']] = $category['image'] ?? '';
// 获取每个分类下的资源,限制8条
$resources = Resources::where('cate', $category['id'])
->where('delete_time', null)
->where('status', 1)
->order('id', 'desc')
->field('id, cate, title, desc, downloads, create_time, icon, views, uploader')
->limit(8)
->select()
->toArray();
// 替换thumbnail为空的资源
foreach ($resources as &$resource) {
if (empty($resource['thumbnail']) && !empty($categoryImageMap[$resource['cate']])) {
$resource['thumbnail'] = $categoryImageMap[$resource['cate']];
}
}
unset($resource);
$resourcesByCategory[$category['id']] = $resources;
}
// 合并所有分类的资源
$allResources = [];
foreach ($resourcesByCategory as $resources) {
$allResources = array_merge($allResources, $resources);
}
// 按上传时间排序
usort($allResources, function ($a, $b) {
return $b['create_time'] - $a['create_time'];
});
// 只取最新的8条
$allResources = array_slice($allResources, 0, 8);
return json([
'code' => 1,
'msg' => '获取成功',
'resources' => $allResources,
'categories' => $categoryData
]);
}
/**
* 获取程序下载列表
*/
public function programList()
{
// 获取程序分类(顶级分类id为4的子分类)
$categories = ResourcesCategory::where('cid', 1)
->where('delete_time', null)
->select()
->toArray();
// 组装分类数据
$categoryData = [];
$categoryImageMap = [];
$programsByCategory = [];
foreach ($categories as $category) {
$categoryData[] = [
'id' => $category['id'],
'name' => $category['name']
];
$categoryImageMap[$category['id']] = $category['image'] ?? '';
// 获取每个分类下的程序,限制8条
$programs = Resources::where('cate', $category['id'])
->where('delete_time', null)
->where('status', 1)
->order('id', 'desc')
->field('id, cate, title, desc, downloads, create_time, icon, views, uploader')
->limit(8)
->select()
->toArray();
// 替换thumbnail为空的程序
foreach ($programs as &$program) {
if (empty($program['thumbnail']) && !empty($categoryImageMap[$program['cate']])) {
$program['thumbnail'] = $categoryImageMap[$program['cate']];
}
}
unset($program);
$programsByCategory[$category['id']] = $programs;
}
// 合并所有分类的程序
$allPrograms = [];
foreach ($programsByCategory as $programs) {
$allPrograms = array_merge($allPrograms, $programs);
}
// 按上传时间排序
usort($allPrograms, function ($a, $b) {
return $b['create_time'] - $a['create_time'];
});
// 只取最新的8条
$allPrograms = array_slice($allPrograms, 0, 8);
return json([
'code' => 1,
'msg' => '获取成功',
'programs' => $allPrograms,
'categories' => $categoryData
]);
}
/**
* 获取游戏下载列表
*/
public function gameList()
{
// 获取游戏分类(顶级分类id为8的子分类)
$categories = ResourcesCategory::where('cid', 8)
->where('delete_time', null)
->select()
->toArray();
// 组装分类数据
$categoryData = [];
$categoryImageMap = [];
$programsByCategory = [];
foreach ($categories as $category) {
$categoryData[] = [
'id' => $category['id'],
'name' => $category['name'],
'image' => $category['image'] ?? ''
];
// 获取每个分类下的游戏,限制8条
$programs = Resources::where('cate', $category['id'])
->where('delete_time', null)
->where('status', 1)
->order('id', 'desc')
->field('id, cate, title, desc, downloads, create_time, icon, views, uploader, number, url, code')
->limit(8)
->select()
->toArray();
// 处理游戏数据
foreach ($programs as &$program) {
// 如果没有图标,使用分类图片
if (empty($program['icon']) && !empty($category['image'])) {
$program['icon'] = $category['image'];
}
// 格式化时间
$program['create_time'] = date('Y-m-d H:i:s', $program['create_time']);
}
unset($program);
$programsByCategory[$category['id']] = $programs;
}
// 合并所有分类的游戏
$allPrograms = [];
foreach ($programsByCategory as $programs) {
$allPrograms = array_merge($allPrograms, $programs);
}
// 按上传时间排序
usort($allPrograms, function ($a, $b) {
return strtotime($b['create_time']) - strtotime($a['create_time']);
});
// 只取最新的8条
$allPrograms = array_slice($allPrograms, 0, 8);
return json([
'code' => 0,
'msg' => '获取成功',
'data' => [
'games' => $allPrograms,
'categories' => $categoryData
]
]);
}
//保存附件信息到数据库
private function saveAttachment($name, $type, $size, $src)
{
$data = [
'name' => $name,
'type' => $type,
'size' => $size,
'src' => $src,
'create_time' => time(),
'update_time' => time()
];
return Attachments::insertGetId($data);
}
//上传图片接口
public function update_imgs()
{
// 获取上传的文件
$file = request()->file();
$files = request()->file('file');
// 检查是否有文件上传
if (empty($file)) {
return json(['code' => 1, 'msg' => '没有文件上传']);
}
try {
// 验证上传的文件
validate([
'image' => 'filesize:51200|fileExt:jpg,png,gif,jpeg,webp'
])->check($file);
// 存储文件到public磁盘的uploads目录
$info = Filesystem::disk('public')->putFile('uploads', $files);
// 处理文件路径,统一使用正斜杠
$info = str_replace("\\", "/", $info);
$img = '/storage/' . $info;
// 保存附件信息
$fileName = $files->getOriginalName();
$fileSize = $files->getSize();
$attachmentId = $this->saveAttachment($fileName, 1, $fileSize, $img); // 1: 图片
// 返回成功信息
return json([
'code' => 0,
'data' => [
'url' => $img
],
'msg' => '上传成功'
]);
} catch (\think\exception\ValidateException $e) {
// 捕获验证异常并返回错误信息
return json(['code' => 1, 'msg' => $e->getMessage()]);
} catch (\Exception $e) {
// 捕获其他异常
return json(['code' => 1, 'msg' => '上传失败:' . $e->getMessage()]);
}
}
}
+427
View File
@@ -0,0 +1,427 @@
<?php
/**
* 商业使用授权协议
*
* Copyright (c) 2025 [云泽网]. 保留所有权利.
*
* 本软件仅供评估使用。任何商业用途必须获得书面授权许可。
* 未经授权商业使用本软件属于侵权行为,将承担法律责任。
*
* 授权购买请联系: 357099073@qq.com
* 官方网站: https://www.yunzer.cn
*
* 评估用户须知:
* 1. 禁止移除版权声明
* 2. 禁止用于生产环境
* 3. 禁止转售或分发
*/
/**
* 程序下载控制器
*/
namespace app\index\controller;
use app\index\controller\BaseController;
use think\Response;
use think\facade\Db;
use think\facade\View;
use think\facade\Request;
use app\index\model\Resources\Resources;
use app\index\model\Resources\ResourcesCategory;
use app\index\model\Attachments;
use app\index\model\Users;
use app\index\model\Articles\Articles;
class ProgramController extends BaseController
{
//资源中心
public function index()
{
// 获取前端传来的分类ID
$cateid = input('cateid/d', 0);
$page = input('page/d', 1);
$limit = input('limit/d', 10);
// 获取所有顶级分类
$categories = ResourcesCategory::where('cid', 0)
->where('delete_time', null)
->where('status', 1)
->select()
->toArray();
// 获取顶级分类信息
$category = null;
if ($cateid > 0) {
$category = ResourcesCategory::where('id', $cateid)
->where('delete_time', null)
->where('status', 1)
->find();
}
// 获取所有子分类
$subCategories = [];
if ($cateid > 0) {
$subCategories = ResourcesCategory::where('cid', $cateid)
->where('delete_time', null)
->where('status', 1)
->select()
->toArray();
}
// 获取所有子分类ID
$subCategoryIds = array_column($subCategories, 'id');
if ($cateid > 0) {
$subCategoryIds[] = $cateid;
}
// 构建资源查询条件
$where = [
['delete_time', '=', null],
['status', '=', 1]
];
if (!empty($subCategoryIds)) {
$where[] = ['cate', 'in', $subCategoryIds];
}
// 查询资源
$programs = Resources::where($where)
->order('id DESC')
->page($page, $limit)
->select()
->toArray();
// 处理每个资源的size
foreach ($programs as &$program) {
if (empty($program['size'])) {
// 从Attachments表中查找对应的src
$attachment = Attachments::where('src', $program['icon'])
->field('size')
->find();
if ($attachment) {
$program['size'] = $attachment['size'];
}
}
}
// 按子分类分组资源
$groupedPrograms = [];
foreach ($subCategories as $subCategory) {
$groupedPrograms[$subCategory['id']] = [
'id' => $subCategory['id'],
'name' => $subCategory['name'],
'list' => []
];
}
// 将资源分配到对应的子分类
foreach ($programs as $program) {
if (isset($groupedPrograms[$program['cate']])) {
$groupedPrograms[$program['cate']]['list'][] = $program;
}
}
// 获取总数
$total = Resources::where($where)->count();
// 准备返回数据
$data = [
'cate' => [
'id' => $cateid,
'name' => $category ? $category['name'] : '',
'desc' => $category ? $category['desc'] : '',
'image' => $category ? $category['image'] : '',
'subCategories' => array_values($groupedPrograms),
'total' => $total,
'page' => $page,
'limit' => $limit
]
];
// 根据请求方式返回不同的输出
if ($this->request->isPost()) {
return json([
'code' => 1,
'msg' => '获取成功',
'data' => $data
]);
}
// GET请求渲染页面
return view('index', [
'categories' => $categories,
'cate' => $data['cate']
]);
}
// 程序列表页
public function list()
{
// 获取分类ID
$cateId = Request::param('cate/d', 0);
// 构建查询条件
$where = [
['a.delete_time', '=', null],
['a.status', '=', 1]
];
if ($cateId > 0) {
$where[] = ['a.cate', '=', $cateId];
}
// 获取程序列表
$programs = Resources::alias('a')
->join('resources_category c', 'a.cate = c.id')
->where($where)
->field([
'a.*',
'IF(a.icon IS NULL OR a.icon = "", c.icon, a.icon) as icon'
])
->order('a.id DESC')
->paginate([
'list_rows' => 10,
'query' => Request::instance()->param()
]);
// 获取分类信息
$category = null;
if ($cateId > 0) {
$category = ResourcesCategory::where('id', $cateId)
->where('delete_time', null)
->where('status', 1)
->find();
}
// 获取所有分类
$categories = ResourcesCategory::where('delete_time', null)
->where('status', 1)
->select()
->toArray();
// 如果是POST请求,返回JSON数据
if (Request::isPost()) {
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'programs' => $programs->items(),
'total' => $programs->total(),
'current_page' => $programs->currentPage(),
'per_page' => $programs->listRows(),
'category' => $category
]
]);
}
// GET请求返回渲染的视图
View::assign([
'programs' => $programs,
'category' => $category,
'categories' => $categories
]);
return View::fetch('list');
}
// 程序详情页
public function detail($id)
{
// 获取资源详情
$program = Resources::where('id', $id)
->where('delete_time', null)
->where('status', 1)
->find();
if (!$program) {
if ($this->request->isPost()) {
return json(['code' => 0, 'msg' => '资源不存在']);
}
$this->error('资源不存在');
}
// 获取分类名称
$cateName = ResourcesCategory::where('id', $program['cate'])
->value('name');
// 获取上传者信息
$uploaderInfo = Users::where('name', $program['uploader'])
->field(['name', 'avatar'])
->find();
if ($uploaderInfo) {
$uploaderInfo = $uploaderInfo->toArray();
// 如果没有头像,使用默认头像
if (empty($uploaderInfo['avatar'])) {
$uploaderInfo['avatar'] = '/static/images/avatar.png';
}
} else {
$uploaderInfo = [
'name' => $program['uploader'],
'avatar' => '/static/images/avatar.png'
];
}
// 添加上传者的资源数和文章数统计
$uploaderInfo['resource_count'] = Resources::where('uploader', $program['uploader'])
->where('delete_time', null)
->where('status', 1)
->count();
$uploaderInfo['article_count'] = Articles::where('author', $program['uploader'])
->where('delete_time', null)
->where('status', 2)
->count();
// 处理资源size
if (empty($program['size'])) {
$attachment = Attachments::where('src', $program['icon'])
->field('size')
->find();
if ($attachment) {
$program['size'] = $attachment['size'];
}
}
// 转换文件大小为合适的单位
if (!empty($program['size']) && is_numeric($program['size'])) {
$size = $program['size'];
if ($size >= 1073741824) { // 1GB = 1024MB = 1024*1024KB = 1024*1024*1024B
$program['size'] = round($size / 1073741824, 2) . 'GB';
} elseif ($size >= 1048576) { // 1MB = 1024KB = 1024*1024B
$program['size'] = round($size / 1048576, 2) . 'MB';
} else {
$program['size'] = round($size / 1024, 2) . 'KB';
}
}
// 获取上一个和下一个程序
$prevProgram = Resources::where('id', '<', $id)
->where('delete_time', null)
->where('status', 1)
->where('cate', $program['cate'])
->field(['id', 'title'])
->order('id DESC')
->find();
$nextProgram = Resources::where('id', '>', $id)
->where('delete_time', null)
->where('status', 1)
->where('cate', $program['cate'])
->field(['id', 'title'])
->order('id ASC')
->find();
// 获取相关程序(同分类的其他程序)
$relatedPrograms = Resources::alias('p')
->join('yz_resources_category c', 'p.cate = c.id')
->where('p.cate', $program['cate'])
->where('p.id', '<>', $id)
->where('p.delete_time', null)
->where('p.status', 1)
->field([
'p.id',
'p.title',
'COALESCE(p.icon, c.icon) as icon'
])
->order('p.id DESC')
->limit(3)
->select()
->toArray();
// 准备返回数据
$data = [
'program' => $program,
'uploaderInfo' => $uploaderInfo,
'cateName' => $cateName,
'prevProgram' => $prevProgram,
'nextProgram' => $nextProgram,
'relatedPrograms' => $relatedPrograms
];
// 根据请求方式返回不同的输出
if ($this->request->isPost()) {
return json([
'code' => 1,
'msg' => '获取成功',
'data' => $data
]);
}
// GET请求渲染页面
return view('', $data);
}
// 程序下载
public function download()
{
$id = Request::param('id/d', 0);
$program = Resources::where('id', $id)
->where('delete_time', null)
->where('status', 1)
->find();
if (!$program) {
return json(['code' => 0, 'msg' => '程序不存在或已被删除']);
}
// 更新下载次数
Resources::where('id', $id)->inc('downloads')->update();
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'fileurl' => $program['fileurl']
]
]);
}
// 获取访问统计
public function viewStats()
{
$id = Request::param('id/d', 0);
// 获取总访问量
$totalViews = Resources::where('id', $id)
->value('views');
return json([
'code' => 1,
'data' => [
'total' => $totalViews
]
]);
}
/**
* 更新程序访问次数
*/
public function updateViews()
{
if (!Request::isPost()) {
return json(['code' => 0, 'msg' => '非法请求']);
}
$id = Request::post('id');
if (!$id) {
return json(['code' => 0, 'msg' => '参数错误']);
}
try {
// 更新访问次数
$program = Resources::where('id', $id)->find();
if (!$program) {
return json(['code' => 0, 'msg' => '程序不存在']);
}
// 更新访问次数
Resources::where('id', $id)->inc('views')->update();
// 获取更新后的访问次数
$newViews = Resources::where('id', $id)->value('views');
return json(['code' => 1, 'msg' => '更新成功', 'data' => ['views' => $newViews]]);
} catch (\Exception $e) {
return json(['code' => 0, 'msg' => '更新失败:' . $e->getMessage()]);
}
}
}
@@ -0,0 +1,309 @@
<?php
/**
* 商业使用授权协议
*
* Copyright (c) 2025 [云泽网]. 保留所有权利.
*
* 本软件仅供评估使用。任何商业用途必须获得书面授权许可。
* 未经授权商业使用本软件属于侵权行为,将承担法律责任。
*
* 授权购买请联系: 357099073@qq.com
* 官方网站: https://www.yunzer.cn
*
* 评估用户须知:
* 1. 禁止移除版权声明
* 2. 禁止用于生产环境
* 3. 禁止转售或分发
*/
/**
* 资源下载控制器
*/
namespace app\index\controller;
use app\index\controller\BaseController;
use think\facade\Db;
use think\facade\View;
use think\facade\Request;
use app\index\model\Resources\Resources;
use app\index\model\Resources\ResourcesCategory;
use app\index\model\Attachments;
use app\index\model\Users;
use app\index\model\Articles\Articles;
class ResourcesController extends BaseController
{
//资源中心
public function index()
{
// 获取所有顶级分类
$parentCategories = ResourcesCategory::where('cid', 0)
->where('status', 1)
->order('sort', 'asc')
->select();
// 获取每个顶级分类下的子分类
$categories = [];
foreach ($parentCategories as $parent) {
$subCategories = ResourcesCategory::where('cid', $parent->id)
->where('status', 1)
->order('sort', 'asc')
->select();
// 获取每个子分类下的资源数量
foreach ($subCategories as &$subCategory) {
$subCategory['resource_count'] = Resources::where('cate', $subCategory->id)
->where('status', 1)
->count();
}
$categories[] = [
'parent' => $parent,
'subCategories' => $subCategories
];
}
// 将数据传递给视图
View::assign('categories', $categories);
return View::fetch();
}
// 资源列表页
public function list()
{
$cid = input('cid/d', 0);
$page = input('page/d', 1);
// 获取分类信息
$category = ResourcesCategory::where('id', $cid)
->where('status', 1)
->find();
if (!$category) {
$this->error('分类不存在');
}
// 获取该分类下的资源,带分页
$resources = Resources::where('cate', $cid)
->where('status', 1)
->order('sort', 'asc')
->paginate([
'list_rows' => 20,
'page' => $page,
'query' => Request::instance()->param()
]);
// 将数据传递给视图
View::assign('category', $category);
View::assign('data', $resources);
View::assign('page', $resources->render()); // 新增这一行
return View::fetch('list');
}
// 资源详情页
public function detail()
{
$id = Request::param('id/d', 0);
$resources = Resources::where('id', $id)->find();
if (!$resources) {
return json(['code' => 0, 'msg' => '资源不存在或已被删除']);
}
// 如果size没有,从附件表中获取
if (empty($resources['size']) && !empty($resources['fileurl'])) {
$attachment = Attachments::where('src', $resources['fileurl'])
->find();
if ($attachment && !empty($attachment['size'])) {
$size = $attachment['size'];
// 转换文件大小为合适的单位
if ($size >= 1073741824) { // 1GB = 1024MB = 1024*1024KB = 1024*1024*1024B
$resources['size'] = round($size / 1073741824, 2) . 'GB';
} elseif ($size >= 1048576) { // 1MB = 1024KB = 1024*1024B
$resources['size'] = round($size / 1048576, 2) . 'MB';
} else {
$resources['size'] = round($size / 1024, 2) . 'KB';
}
}
}
// 获取分类名称
$cateName = ResourcesCategory::where('id', $resources['cate'])
->value('name');
// 获取作者信息
$authorInfo = Users::where('name', $resources['uploader'])->find();
// var_dump($authorInfo);
if ($authorInfo) {
// 统计作者的文章数
$resourcesCount = Articles::where('author', $resources['uploader'])->count();
// 统计作者的资源数
$resourceCount = Resources::where('uploader', $resources['uploader'])->count();
$authorData = [
'avatar' => $authorInfo['avatar'] ?: '/static/images/avatar.png',
'name' => $authorInfo['name'],
'resource_count' => $resourceCount,
'article_count' => $resourcesCount
];
} else {
$authorData = [
'avatar' => '/static/images/avatar.png',
'name' => $resources['author'],
'resource_count' => 0,
'article_count' => 0
];
}
// 获取上一个和下一个资源
$prevResources = Resources::where('id', '<', $id)
->where('delete_time', null)
->where('status', 1)
->where('cate', $resources['cate'])
->field(['id', 'title'])
->order('id DESC')
->find();
$nextResources = Resources::where('id', '>', $id)
->where('delete_time', null)
->where('status', 1)
->where('cate', $resources['cate'])
->field(['id', 'title'])
->order('id ASC')
->find();
// 获取相关资源(同分类的其他资源)
$relatedResourcess = Db::table('yz_resources')
->alias('g')
->join('yz_resources_category c', 'g.cate = c.id')
->where('g.cate', $resources['cate'])
->where('g.id', '<>', $id)
->where('g.delete_time', null)
->where('g.status', 1)
->field([
'g.id',
'g.title',
'IF(g.icon IS NULL OR g.icon = "", c.icon, g.icon) as icon'
])
->order('g.id DESC')
->limit(5)
->select()
->toArray();
// 如果是 AJAX 请求,返回 JSON 数据
if (Request::isAjax()) {
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'resources' => $resources,
'cateName' => $cateName,
'prevResources' => $prevResources,
'nextResources' => $nextResources,
'relatedResourcess' => $relatedResourcess
]
]);
}
// 非 AJAX 请求返回视图
View::assign([
'resources' => $resources,
'cateName' => $cateName,
'authorInfo' => $authorData,
'prevResources' => $prevResources,
'nextResources' => $nextResources,
'relatedResourcess' => $relatedResourcess
]);
return View::fetch('detail');
}
// 资源下载
public function downloadurl()
{
if (!Request::isAjax()) {
return json(['code' => 0, 'msg' => '非法请求']);
}
$id = Request::param('id/d', 0);
// 获取资源信息
$resources = Resources::where('id', $id)
->where('delete_time', null)
->find();
if (!$resources) {
return json(['code' => 0, 'msg' => '资源不存在']);
}
// 更新下载次数
$result = Resources::where('id', $id)
->where('delete_time', null)
->inc('downloads', 1)
->update();
if ($result) {
return json([
'code' => 1,
'msg' => '下载成功',
'data' => [
'url' => $resources['url']
]
]);
} else {
return json(['code' => 0, 'msg' => '下载失败']);
}
}
// 获取访问统计
public function viewStats()
{
$id = Request::param('id/d', 0);
// 获取总访问量
$totalViews = Resources::where('id', $id)
->value('views');
return json([
'code' => 1,
'data' => [
'total' => $totalViews
]
]);
}
/**
* 更新资源访问次数
*/
public function updateViews()
{
if (!Request::isPost()) {
return json(['code' => 0, 'msg' => '非法请求']);
}
$id = Request::post('id');
if (!$id) {
return json(['code' => 0, 'msg' => '参数错误']);
}
try {
// 更新访问次数
$resources = Resources::where('id', $id)->find();
if (!$resources) {
return json(['code' => 0, 'msg' => '资源不存在']);
}
// 更新访问次数
Resources::where('id', $id)->inc('views')->update();
// 获取更新后的访问次数
$newViews = Resources::where('id', $id)->value('views');
return json(['code' => 1, 'msg' => '更新成功', 'data' => ['views' => $newViews]]);
} catch (\Exception $e) {
return json(['code' => 0, 'msg' => '更新失败:' . $e->getMessage()]);
}
}
}
+128
View File
@@ -0,0 +1,128 @@
<?php
/**
* 商业使用授权协议
*
* Copyright (c) 2025 [云泽网]. 保留所有权利.
*
* 本软件仅供评估使用。任何商业用途必须获得书面授权许可。
* 未经授权商业使用本软件属于侵权行为,将承担法律责任。
*
* 授权购买请联系: 357099073@qq.com
* 官方网站: https://www.yunzer.cn
*
* 评估用户须知:
* 1. 禁止移除版权声明
* 2. 禁止用于生产环境
* 3. 禁止转售或分发
*/
namespace app\index\controller;
use think\Db;
use app\index\controller\BaseController;
use app\index\model\Articles\Articles;
use app\index\model\Articles\ArticlesCategory;
use app\index\model\Resources\Resources;
use app\index\model\Resources\ResourcesCategory;
class SearchController extends BaseController
{
public function index()
{
$keyword = input('keyword', '');
$type = input('type', 'articles'); // 搜索类型:articles-文章,resources-资源
$page = input('page', 1);
$limit = input('limit', 10);
if (empty($keyword)) {
$this->error('请输入搜索关键词');
}
// 根据类型选择对应的表和分类表
if ($type == 'articles') {
$model = new Articles();
$categoryModel = new ArticlesCategory();
$detailUrl = '/index/articles/detail';
$categoryUrl = '/index/articles/category';
$status = 2; // 文章状态为2
$fields = 'id, title, cate, image, author, FROM_UNIXTIME(create_time, "%Y-%m-%d") as publishdate';
} else if ($type == 'resources') {
$model = new Resources();
$categoryModel = new ResourcesCategory();
$detailUrl = '/index/resources/detail';
$categoryUrl = '/index/resources/category';
$status = 1; // 资源状态为1
$fields = 'id, title, cate, icon, uploader, FROM_UNIXTIME(create_time, "%Y-%m-%d") as publishdate';
} else {
$this->error('无效的搜索类型');
}
// 搜索内容
$items = $model->where('title', 'like', "%{$keyword}%")
->where('status', $status)
->field($fields)
->order('create_time desc')
->page($page, $limit)
->select();
// 获取总数
$count = $model->where('title', 'like', "%{$keyword}%")
->where('status', $status)
->count();
// 获取分类名称和图片
foreach ($items as &$item) {
if ($type == 'articles') {
$category = $categoryModel->where('id', $item['cate'])
->field('id, name, image')
->find();
$item['category'] = $category ?: ['id' => 0, 'name' => '未分类', 'image' => ''];
$item['cate'] = $item['category']['name']; // 使用分类名称替换分类ID
// 如果文章的图片为空,使用分类的图片
if (empty($item['image'])) {
$item['image'] = $item['category']['image'];
}
if (empty($item['image'])) {
$item['image'] = '/static/images/default.jpg';
}
} else {
$category = $categoryModel->where('id', $item['cate'])
->field('id, name, icon, cid')
->find();
$item['category'] = $category ?: ['id' => 0, 'name' => '未分类', 'icon' => '', 'cid' => 0];
$item['cate'] = $item['category']['name']; // 使用分类名称替换分类ID
// 如果资源的图片为空,使用分类的图片
if (empty($item['icon'])) {
$item['icon'] = $item['category']['icon'];
}
if (empty($item['icon'])) {
$item['icon'] = '/static/images/default.jpg';
}
// 根据分类cid判断资源类型
if ($item['category']['cid'] == 8) {
$item['detail_url'] = url('game/detail', ['id' => $item['id']]);
} else {
$item['detail_url'] = url('program/detail', ['id' => $item['id']]);
}
}
}
// 准备视图数据
$viewData = [
'keyword' => $keyword,
'type' => $type,
'items' => $items,
'detailUrl' => $detailUrl,
'count' => $count,
'page' => $page,
'limit' => $limit
];
return view('index', $viewData);
}
}
@@ -0,0 +1,70 @@
<?php
/**
* 商业使用授权协议
*
* Copyright (c) 2025 [云泽网]. 保留所有权利.
*
* 本软件仅供评估使用。任何商业用途必须获得书面授权许可。
* 未经授权商业使用本软件属于侵权行为,将承担法律责任。
*
* 授权购买请联系: 357099073@qq.com
* 官方网站: https://www.yunzer.cn
*
* 评估用户须知:
* 1. 禁止移除版权声明
* 2. 禁止用于生产环境
* 3. 禁止转售或分发
*/
namespace app\index\controller;
use think\facade\Request;
use think\facade\Filesystem;
use think\Response;
use app\index\model\Resources\Resources;
class StorageController extends BaseController
{
/**
* 处理文件下载
* @return \think\Response
*/
public function download()
{
// 获取请求的文件路径
$path = Request::pathinfo();
// 移除 'storage/' 前缀
$path = str_replace('storage/', '', $path);
// 构建完整的文件路径
$filePath = public_path() . 'storage/' . $path;
// 检查文件是否存在
if (!file_exists($filePath)) {
return Response::create('文件不存在', 'html', 404);
}
// 获取文件信息
$fileInfo = pathinfo($filePath);
$fileName = $fileInfo['basename'];
$fileSize = filesize($filePath);
$fileType = mime_content_type($filePath);
// 设置响应头
$headers = [
'Content-Type' => $fileType,
'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
'Content-Length' => $fileSize,
'Cache-Control' => 'no-cache, must-revalidate',
'Pragma' => 'no-cache',
'Expires' => '0'
];
// 读取文件内容
$content = file_get_contents($filePath);
// 返回文件下载响应
return Response::create($content, 'file', 200, $headers);
}
}
+754
View File
@@ -0,0 +1,754 @@
<?php
/**
* 商业使用授权协议
*
* Copyright (c) 2025 [云泽网]. 保留所有权利.
*
* 本软件仅供评估使用。任何商业用途必须获得书面授权许可。
* 未经授权商业使用本软件属于侵权行为,将承担法律责任。
*
* 授权购买请联系: 357099073@qq.com
* 官方网站: https://www.yunzer.cn
*
* 评估用户须知:
* 1. 禁止移除版权声明
* 2. 禁止用于生产环境
* 3. 禁止转售或分发
*/
namespace app\index\controller;
use think\Controller;
use app\index\model\Users;
use think\facade\Redirect;
use think\facade\View;
use \think\facade\Log;
use \think\facade\Cache;
use PHPMailer\PHPMailer\PHPMailer;
use think\Response;
use app\index\model\UserMessage;
use app\index\model\SystemNotice;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
class UserController extends BaseController
{
/**
* 用户登录
*
* @return \think\Response
*/
public function login()
{
if ($this->request->isPost()) {
$data = $this->request->post();
try {
// 验证数据
$validate = validate([
'account' => 'require|email',
'password' => 'require'
]);
if (!$validate->check($data)) {
return json(['code' => 1, 'msg' => $validate->getError()]);
}
// 查询用户
$user = Users::where('account', $data['account'])->find();
if (!$user) {
return json(['code' => 1, 'msg' => '用户不存在']);
}
// 验证密码
if ($user->password !== md5($data['password'])) {
return json(['code' => 1, 'msg' => '密码错误']);
}
// 登录成功,设置session
session('user_id', $user->id);
session('user_name', $user->name);
session('user_avatar', $user->avatar ?? '/static/images/avatar.png');
// 设置cookie,有效期7天
$expire = 7 * 24 * 3600;
cookie('user_id', $user->id, ['expire' => $expire]);
cookie('user_account', $user->account, ['expire' => $expire]);
cookie('user_name', $user->name, ['expire' => $expire]);
cookie('user_avatar', $user->avatar ?? '/static/images/avatar.png', ['expire' => $expire]);
// 记录登录日志
Log::record('用户登录成功:' . $user->account, 'info');
return json(['code' => 0, 'msg' => '登录成功']);
} catch (\Exception $e) {
Log::record('登录失败:' . $e->getMessage(), 'error');
return json(['code' => 1, 'msg' => '登录失败:' . $e->getMessage()]);
}
}
return view('login');
}
/**
* 用户注册
*
* @return \think\Response
*/
public function register()
{
if ($this->request->isPost()) {
$data = $this->request->post();
try {
// 验证数据
$validate = validate([
'account' => 'require|email|unique:users',
'code' => 'require|number|length:6',
'password' => 'require|min:6|max:20',
'repassword' => 'require|confirm:password'
], [
'account.require' => '账户不能为空',
'account.email' => '邮箱格式不正确',
'account.unique' => '该邮箱已注册',
'code.require' => '验证码不能为空',
'code.number' => '验证码必须为数字',
'code.length' => '验证码长度必须为6位',
'password.require' => '密码不能为空',
'password.min' => '密码长度不能小于6个字符',
'password.max' => '密码长度不能超过20个字符',
'repassword.require' => '确认密码不能为空',
'repassword.confirm' => '两次输入的密码不一致'
]);
if (!$validate->check($data)) {
return json(['code' => 1, 'msg' => $validate->getError()]);
}
// 验证邮箱验证码
$emailCode = cache('email_code_' . $data['account']);
if (!$emailCode || $emailCode != $data['code']) {
return json(['code' => 1, 'msg' => '验证码错误或已过期']);
}
// 创建用户
$user = new Users;
$user->account = $data['account'];
$user->password = md5($data['password']);
$user->name = $this->generateRandomName();
$user->create_time = time();
$user->save();
// 清除验证码缓存
cache('email_code_' . $data['account'], null);
return json(['code' => 0, 'msg' => '注册成功']);
} catch (\Exception $e) {
return json(['code' => 1, 'msg' => '注册失败:' . $e->getMessage()]);
}
}
return view('register');
}
/**
* 退出登录
*
* @return \think\Response
*/
public function logout()
{
try {
Log::record('用户退出登录', 'info');
// 清除所有会话和缓存数据
session(null);
Cache::tag('user_cache')->clear();
// 清除所有cookie
$cookies = [
'user_id',
'user_account',
'user_name',
'user_avatar',
'expire_time',
'is_auto_login',
'auto_login_attempted',
'PHPSESSID'
];
foreach ($cookies as $cookie) {
cookie($cookie, null, ['expire' => -1]);
}
return json(['code' => 0, 'msg' => '退出成功', 'data' => ['clear_storage' => true]]);
} catch (\Exception $e) {
Log::record('退出登录失败:' . $e->getMessage(), 'error');
return json(['code' => 1, 'msg' => '退出失败:' . $e->getMessage()]);
}
}
// 生成随机用户名
private function generateRandomName()
{
return '云朵_' . mt_rand(100000, 999999);
}
// 发送短信验证码
public function sendSmsCode()
{
if ($this->request->isPost()) {
$phone = $this->request->post('phone');
// 验证手机号
$validate = validate([
'phone' => 'require|mobile|unique:user'
], [
'phone.require' => '手机号不能为空',
'phone.mobile' => '手机号格式不正确',
'phone.unique' => '该手机号已注册'
]);
if (!$validate->check(['phone' => $phone])) {
return json(['code' => 0, 'msg' => $validate->getError()]);
}
// 生成6位随机验证码
$code = mt_rand(100000, 999999);
// 这里应该调用短信服务商API发送验证码
// 示例代码,实际使用时需要替换为真实的短信发送逻辑
try {
// TODO: 调用短信服务商API发送验证码
// $result = sendSms($phone, $code);
// 将验证码保存到缓存,有效期5分钟
cache('sms_code_' . $phone, $code, 300);
return json(['code' => 1, 'msg' => '验证码发送成功']);
} catch (\Exception $e) {
return json(['code' => 0, 'msg' => '验证码发送失败:' . $e->getMessage()]);
}
}
return json(['code' => 0, 'msg' => '非法请求']);
}
// 微信授权回调
// public function wechatCallback()
// {
// $code = $this->request->get('code');
// if (!$code) {
// return json(['code' => 0, 'msg' => '微信授权失败']);
// }
// try {
// // 这里应该调用微信API获取用户信息
// // 示例代码,实际使用时需要替换为真实的微信API调用逻辑
// // $wechatUser = getWechatUserInfo($code);
// // 模拟获取到的微信用户信息
// $wechatUser = [
// 'openid' => 'test_openid_' . time(),
// 'nickname' => '微信用户',
// 'avatar' => ''
// ];
// // 检查用户是否已注册
// $user = Users::where('openid', $wechatUser['openid'])->find();
// if ($user) {
// // 已注册,直接登录
// session('user_id', $user->id);
// return json(['code' => 1, 'msg' => '登录成功']);
// }
// // 未注册,返回注册所需信息
// return json([
// 'code' => 2,
// 'msg' => '需要注册',
// 'data' => $wechatUser
// ]);
// } catch (\Exception $e) {
// return json(['code' => 0, 'msg' => '微信授权失败:' . $e->getMessage()]);
// }
// }
// 发送邮箱验证码
public function sendEmailCode()
{
// 设置响应头
header('Content-Type: application/json; charset=utf-8');
if (!$this->request->isPost()) {
return json(['code' => 1, 'msg' => '请求方法无效']);
}
$email = $this->request->post('account');
if (empty($email)) {
return json(['code' => 1, 'msg' => '邮箱不能为空']);
}
// 验证邮箱格式
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return json(['code' => 1, 'msg' => '邮箱格式不正确']);
}
// 检查邮箱是否已注册
$exists = Users::where('account', $email)->find();
if ($exists) {
return json(['code' => 1, 'msg' => '该邮箱已注册']);
}
// 生成6位随机验证码
$code = mt_rand(100000, 999999);
// 发送验证码邮件
$result = parent::sendEmail($email, "您的注册验证码是:{$code},有效期为5分钟。", '注册验证码');
if ($result === '发送成功') { // 修改这里的判断条件
// 将验证码存入缓存,有效期5分钟
cache('email_code_' . $email, $code, 300);
return json(['code' => 0, 'msg' => '验证码已发送']);
} else {
return json(['code' => 1, 'msg' => '发送失败:' . $result]);
}
}
//个人中心
public function profile()
{
// 检查用户是否登录
if (!cookie('user_account')) {
return redirect('/index/user/login');
}
// 获取用户信息
$user = Users::where('account', cookie('user_account'))->find();
// var_dump($user);
if (!$user) {
return redirect('/index/user/login');
}
View::assign('user', $user);
return $this->fetch();
}
//个人资料
public function saveBasic()
{
// 检查用户是否登录
if (!cookie('user_account')) {
return json(['code' => 1, 'msg' => '请先登录']);
}
// 获取用户信息
$user = Users::where('account', cookie('user_account'))->find();
if (!$user) {
return json(['code' => 1, 'msg' => '用户不存在']);
}
// 获取表单数据
$data = $this->request->post();
// 验证用户名
if (empty($data['name'])) {
return json(['code' => 1, 'msg' => '用户名不能为空']);
}
// 验证手机号格式
if (!empty($data['phone']) && !preg_match('/^1[3-9]\d{9}$/', $data['phone'])) {
return json(['code' => 1, 'msg' => '请检查手机号']);
}
// 检查用户名是否已被使用(排除当前用户)
$existingUser = Users::where('name', $data['name'])
->where('uid', '<>', $user->uid) // 排除当前用户
->find();
if ($existingUser) {
return json(['code' => 1, 'msg' => '该用户名已被使用']);
}
// 更新用户信息
$user->name = $data['name'];
$user->phone = $data['phone'] ?? '';
$user->sex = $data['sex'] ?? 0;
$user->qq = $data['qq'] ?? '';
$user->wechat = $data['wechat'] ?? '';
$user->update_time = time();
if ($user->save()) {
return json(['code' => 0, 'msg' => '保存成功']);
} else {
return json(['code' => 1, 'msg' => '保存失败']);
}
}
//更新头像
public function update_avatar()
{
// 检查用户是否登录
if (!cookie('user_account')) {
return json(['code' => 1, 'msg' => '请先登录']);
}
// 获取用户信息
$user = Users::where('account', cookie('user_account'))->find();
if (!$user) {
return json(['code' => 1, 'msg' => '用户不存在']);
}
// 获取上传的文件
$file = $this->request->file('avatar');
if (!$file) {
return json(['code' => 1, 'msg' => '请选择要上传的头像']);
}
try {
// 验证文件大小和类型
if ($file->getSize() > 2097152) { // 2MB
return json(['code' => 1, 'msg' => '图片大小不能超过2MB']);
}
$ext = strtolower($file->getOriginalExtension());
if (!in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) {
return json(['code' => 1, 'msg' => '只支持jpg、jpeg、png、gif、webp格式的图片']);
}
// 移动到指定目录
$savename = \think\facade\Filesystem::disk('public')->putFile('avatar', $file);
if (!$savename) {
return json(['code' => 1, 'msg' => '图片上传失败']);
}
// 获取文件URL
$avatarUrl = '/storage/' . $savename;
// 更新用户头像
$user->avatar = $avatarUrl;
$user->update_time = time();
if ($user->save()) {
return json(['code' => 0, 'msg' => '头像更新成功', 'data' => ['url' => $avatarUrl]]);
} else {
return json(['code' => 1, 'msg' => '头像更新失败']);
}
} catch (\Exception $e) {
return json(['code' => 1, 'msg' => '系统错误:' . $e->getMessage()]);
}
}
/**
* 获取系统通知列表
*/
public function getNotifications()
{
// 检查用户是否登录
if (!cookie('user_account')) {
return json(['code' => 1, 'msg' => '请先登录']);
}
$type = $this->request->get('type', 'all'); // 获取通知类型:all, unread, read
$userId = cookie('user_id');
try {
// 构建查询条件
$where = [
['status', '=', 1] // 只获取启用的通知
];
// 查询系统通知
$notices = SystemNotice::where($where)
->order('is_top', 'desc') // 置顶的排在前面
->order('create_time', 'desc')
->select();
// 格式化数据
$data = [];
foreach ($notices as $notice) {
// 检查用户是否已读该通知
$isRead = SystemNotice::where([
['user_id', '=', $userId],
['notice_id', '=', $notice->id],
['is_read', '=', 1]
])->find();
// 根据type过滤
if ($type == 'unread' && $isRead)
continue;
if ($type == 'read' && !$isRead)
continue;
$data[] = [
'id' => $notice->id,
'title' => $notice->title,
'content' => $notice->content,
'type' => $notice->type,
'is_top' => $notice->is_top,
'is_read' => $isRead ? 1 : 0,
'create_time' => date('Y-m-d H:i:s', $notice->create_time)
];
}
return json(['code' => 0, 'msg' => '获取成功', 'data' => $data]);
} catch (\Exception $e) {
return json(['code' => 1, 'msg' => '获取失败:' . $e->getMessage()]);
}
}
/**
* 查看通知详情
*/
public function readNotification()
{
// 检查用户是否登录
if (!cookie('user_account')) {
return json(['code' => 1, 'msg' => '请先登录']);
}
$data = $this->request->post();
$noticeId = $data['id'] ?? 0;
$userId = cookie('user_id');
try {
// 查询通知
$notice = SystemNotice::where('id', $noticeId)
->where('status', 1)
->find();
if (!$notice) {
return json(['code' => 1, 'msg' => '通知不存在']);
}
// 记录用户已读状态
$message = SystemNotice::where([
['user_id', '=', $userId],
['notice_id', '=', $noticeId]
])->find();
if (!$message) {
// 创建新的已读记录
$message = new SystemNotice;
$message->user_id = $userId;
$message->notice_id = $noticeId;
$message->is_read = 1;
$message->read_time = time();
$message->save();
} elseif (!$message->is_read) {
// 更新已读状态
$message->is_read = 1;
$message->read_time = time();
$message->save();
}
return json(['code' => 0, 'msg' => '操作成功']);
} catch (\Exception $e) {
return json(['code' => 1, 'msg' => '操作失败:' . $e->getMessage()]);
}
}
/**
* 通知详情页面
*/
public function notificationDetail()
{
// 检查用户是否登录
if (!cookie('user_account')) {
return redirect('/index/user/login');
}
$noticeId = $this->request->get('id');
$userId = cookie('user_id');
try {
// 查询通知
$notice = SystemNotice::where('id', $noticeId)
->where('status', 1)
->find();
if (!$notice) {
return $this->error('通知不存在');
}
// 记录用户已读状态
$message = SystemNotice::where([
['user_id', '=', $userId],
['notice_id', '=', $noticeId]
])->find();
if (!$message) {
// 创建新的已读记录
$message = new SystemNotice;
$message->user_id = $userId;
$message->notice_id = $noticeId;
$message->is_read = 1;
$message->read_time = time();
$message->save();
} elseif (!$message->is_read) {
// 更新已读状态
$message->is_read = 1;
$message->read_time = time();
$message->save();
}
// 增加查看次数
$notice->view_count = $notice->view_count + 1;
$notice->save();
View::assign('notice', $notice);
return $this->fetch('notification_detail');
} catch (\Exception $e) {
return $this->error('获取通知详情失败:' . $e->getMessage());
}
}
/**
* 获取系统通知列表
*/
public function getMessages()
{
// 检查用户是否登录
if (!cookie('user_account')) {
return json(['code' => 1, 'msg' => '请先登录']);
}
$type = $this->request->get('type', 'all'); // 获取通知类型:all, unread, read
$userId = cookie('user_id');
try {
// 构建查询条件
$where = [
['status', '=', 1] // 只获取启用的通知
];
// 查询系统通知
$notices = UserMessage::where($where)
->order('is_top', 'desc') // 置顶的排在前面
->order('create_time', 'desc')
->select();
// 格式化数据
$data = [];
foreach ($notices as $notice) {
// 检查用户是否已读该通知
$isRead = UserMessage::where([
['user_id', '=', $userId],
['notice_id', '=', $notice->id],
['is_read', '=', 1]
])->find();
// 根据type过滤
if ($type == 'unread' && $isRead)
continue;
if ($type == 'read' && !$isRead)
continue;
$data[] = [
'id' => $notice->id,
'title' => $notice->title,
'content' => $notice->content,
'type' => $notice->type,
'is_top' => $notice->is_top,
'is_read' => $isRead ? 1 : 0,
'create_time' => date('Y-m-d H:i:s', $notice->create_time)
];
}
return json(['code' => 0, 'msg' => '获取成功', 'data' => $data]);
} catch (\Exception $e) {
return json(['code' => 1, 'msg' => '获取失败:' . $e->getMessage()]);
}
}
//修改密码
public function updatePassword()
{
// 检查用户是否登录
if (!cookie('user_account')) {
return redirect('/index/user/login');
}
// 获取用户信息
$user = Users::where('account', cookie('user_account'))->find();
if (!$user) {
return redirect('/index/user/login');
}
// 如果是GET请求,显示修改密码页面
if ($this->request->isGet()) {
return $this->fetch();
}
// 如果是POST请求,处理密码修改
if ($this->request->isPost()) {
$data = $this->request->post();
// 验证旧密码
if ($user->password !== md5($data['old_password'])) {
return json(['code' => 1, 'msg' => '旧密码错误']);
}
// 验证新密码
if ($data['new_password'] !== $data['confirm_password']) {
return json(['code' => 1, 'msg' => '两次输入的密码不一致']);
}
// 更新密码
$user->password = md5($data['new_password']);
$user->update_time = time();
if ($user->save()) {
// 清除登录状态
cookie('user_id', null, ['expire' => -1]);
cookie('user_account', null, ['expire' => -1]);
cookie('user_name', null, ['expire' => -1]);
cookie('user_avatar', null, ['expire' => -1]);
return json(['code' => 0, 'msg' => '密码修改成功,请重新登录']);
} else {
return json(['code' => 1, 'msg' => '密码修改失败']);
}
}
}
//生成二维码绑定微信
public function qrcode()
{
// 检查用户是否登录
if (!cookie('user_account')) {
return json(['code'=> -1,'msg'=> '请先登录']);
}
// 获取当前用户信息
$user = Users::where('account', cookie('user_account'))->find();
if (!$user) {
return json(['code' => -1, 'msg' => '用户信息获取失败']);
}
// 假设这里生成一个唯一的绑定标识,例如使用用户ID和时间戳组合
$bindToken = md5($user->id . time());
// 生成实际的绑定 URL
$domain = $this->request->domain();
$bindUrl = "{$domain}/wechat_bind?token={$bindToken}";
// 将绑定标识存入缓存,设置有效期,例如30分钟
cache('wechat_bind_token_' . $user->id, $bindToken, 1800);
try {
// 创建二维码实例
$qrCode = QrCode::create($bindUrl);
$writer = new PngWriter();
// 生成二维码图片
$result = $writer->write($qrCode);
$qrCodeDataUri = $result->getDataUri();
return json(['code' => 0, 'msg' => '二维码生成成功', 'data' => ['qrcode_url' => $qrCodeDataUri]]);
} catch (\Exception $e) {
return json(['code' => -1, 'msg' => '二维码生成失败: ' . $e->getMessage()]);
}
}
}
+867
View File
@@ -0,0 +1,867 @@
<?php
/**
* 商业使用授权协议
*
* Copyright (c) 2025 [云泽网]. 保留所有权利.
*
* 本软件仅供评估使用。任何商业用途必须获得书面授权许可。
* 未经授权商业使用本软件属于侵权行为,将承担法律责任。
*
* 授权购买请联系: 357099073@qq.com
* 官方网站: https://www.yunzer.cn
*
* 评估用户须知:
* 1. 禁止移除版权声明
* 2. 禁止用于生产环境
* 3. 禁止转售或分发
*/
namespace app\index\controller;
use think\facade\Request;
use think\facade\Log;
use think\facade\Cache;
use GuzzleHttp\Client;
use app\index\model\Users;
use app\index\model\AdminConfig;
class WechatController extends BaseController
{
/**
* 测试接口是否正常工作
*/
public function test()
{
try {
// 设置响应头
header('Content-Type: application/json; charset=utf-8');
$data = [
'time' => date('Y-m-d H:i:s'),
'status' => 'ok',
'server' => [
'REQUEST_METHOD' => $_SERVER['REQUEST_METHOD'] ?? '',
'REQUEST_URI' => $_SERVER['REQUEST_URI'] ?? '',
'HTTP_HOST' => $_SERVER['HTTP_HOST'] ?? '',
'REMOTE_ADDR' => $_SERVER['REMOTE_ADDR'] ?? '',
]
];
// 记录详细日志
Log::info('接口测试 - 请求信息:' . json_encode($data, JSON_UNESCAPED_UNICODE));
return json($data, JSON_UNESCAPED_UNICODE);
} catch (\Exception $e) {
$error = [
'error' => $e->getMessage(),
'time' => date('Y-m-d H:i:s')
];
Log::error('接口测试错误:' . json_encode($error, JSON_UNESCAPED_UNICODE));
return json($error, JSON_UNESCAPED_UNICODE);
}
}
public function index()
{
try {
// 设置响应头
header('Content-Type: text/html; charset=utf-8');
// 记录原始请求信息
$requestInfo = [
'time' => date('Y-m-d H:i:s'),
'method' => Request::method(),
'url' => Request::url(true),
'ip' => Request::ip(),
'real_ip' => Request::server('HTTP_X_REAL_IP'),
'forwarded_ip' => Request::server('HTTP_X_FORWARDED_FOR'),
'params' => Request::param(),
'headers' => getallheaders(),
'server' => [
'REQUEST_METHOD' => $_SERVER['REQUEST_METHOD'] ?? '',
'REQUEST_URI' => $_SERVER['REQUEST_URI'] ?? '',
'HTTP_HOST' => $_SERVER['HTTP_HOST'] ?? '',
'REMOTE_ADDR' => $_SERVER['REMOTE_ADDR'] ?? '',
'QUERY_STRING' => $_SERVER['QUERY_STRING'] ?? '',
'HTTP_USER_AGENT' => $_SERVER['HTTP_USER_AGENT'] ?? '',
'HTTP_REFERER' => $_SERVER['HTTP_REFERER'] ?? '',
'CONTENT_TYPE' => $_SERVER['CONTENT_TYPE'] ?? '',
'CONTENT_LENGTH' => $_SERVER['CONTENT_LENGTH'] ?? '',
'SERVER_NAME' => $_SERVER['SERVER_NAME'] ?? '',
'SERVER_ADDR' => $_SERVER['SERVER_ADDR'] ?? '',
'SERVER_PORT' => $_SERVER['SERVER_PORT'] ?? '',
'REQUEST_SCHEME' => $_SERVER['REQUEST_SCHEME'] ?? '',
],
'env' => [
'app_debug' => config('app.debug'),
'app_env' => config('app.env'),
'domain' => config('app.domain'),
]
];
Log::info('微信接口访问请求信息:' . json_encode($requestInfo, JSON_UNESCAPED_UNICODE));
// 获取原始数据
$rawData = file_get_contents("php://input");
if (!empty($rawData)) {
$rawData = mb_convert_encoding($rawData, 'UTF-8', 'UTF-8,GBK,GB2312');
Log::info('微信接口原始数据:' . $rawData);
}
// 检查请求方法
if (Request::method() == 'GET') {
Log::info('微信接口:GET请求,进行签名验证');
// 首次验证服务器地址的有效性
$this->checkSignature();
} elseif (Request::method() == 'POST') {
Log::info('微信接口:POST请求,处理消息');
// 接收消息并回复
$response = $this->receiveMessage();
// 直接输出回复的XML字符串
echo $response;
exit;
} else {
Log::error('微信接口:不支持的请求方法 - ' . Request::method());
echo '';
exit;
}
} catch (\Exception $e) {
Log::error('微信接口错误:' . $e->getMessage());
Log::error('错误堆栈:' . $e->getTraceAsString());
// 返回空字符串,避免微信服务器重试
echo '';
exit;
}
}
// 验证签名
protected function checkSignature()
{
try {
$signature = Request::get('signature');
$timestamp = Request::get('timestamp');
$nonce = Request::get('nonce');
$echostr = Request::get('echostr');
$debugInfo = [
'signature' => $signature,
'timestamp' => $timestamp,
'nonce' => $nonce,
'echostr' => $echostr,
'url' => Request::url(true),
'time' => date('Y-m-d H:i:s'),
'ip' => Request::ip(),
'headers' => getallheaders()
];
Log::info('微信验证参数:' . json_encode($debugInfo, JSON_UNESCAPED_UNICODE));
if (empty($signature) || empty($timestamp) || empty($nonce)) {
Log::error('微信验证参数缺失', $debugInfo);
exit;
}
$token = AdminConfig::where('config_name', 'wechat_token')->value('config_value');
if (empty($token)) {
Log::error('微信token未配置');
exit;
}
Log::info('微信token' . $token);
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
$verifyInfo = [
'tmpStr' => $tmpStr,
'signature' => $signature,
'token' => $token,
'timestamp' => $timestamp,
'nonce' => $nonce
];
Log::info('签名验证:' . json_encode($verifyInfo, JSON_UNESCAPED_UNICODE));
if ($tmpStr == $signature) {
Log::info('微信签名验证成功');
echo $echostr;
exit;
} else {
Log::error('微信签名验证失败', $verifyInfo);
exit;
}
} catch (\Exception $e) {
Log::error('微信验证签名错误:' . $e->getMessage());
Log::error('错误堆栈:' . $e->getTraceAsString());
exit;
}
}
// 接收消息
protected function receiveMessage()
{
try {
$postStr = file_get_contents("php://input");
if (empty($postStr)) {
Log::error('微信消息:接收数据为空');
return '';
}
// 转换编码
$postStr = mb_convert_encoding($postStr, 'UTF-8', 'UTF-8,GBK,GB2312');
Log::info('微信消息原始数据:' . $postStr);
// 使用DOMDocument替代simplexml_load_string
$dom = new \DOMDocument();
$dom->loadXML($postStr, LIBXML_NOCDATA | LIBXML_NOBLANKS);
$postObj = simplexml_import_dom($dom);
if ($postObj === false) {
Log::error('微信消息:XML解析失败');
return '';
}
// 检查消息类型
$msgType = strtolower((string) $postObj->MsgType);
Log::info('微信消息类型:' . $msgType);
// 处理事件消息
if ($msgType == 'event') {
$event = strtolower((string) $postObj->Event);
Log::info('微信事件类型:' . $event);
// 处理扫码事件和关注事件
if ($event == 'scan' || $event == 'subscribe') {
try {
$scene_str = trim((string) $postObj->EventKey);
// 如果是关注事件,需要去掉前缀 'qrscene_'
if ($event == 'subscribe' && strpos($scene_str, 'qrscene_') === 0) {
$scene_str = substr($scene_str, 8);
}
$fromUsername = trim((string) $postObj->FromUserName);
$toUsername = trim((string) $postObj->ToUserName);
$ticket = (string) $postObj->Ticket;
Log::info('微信扫码/关注事件详情', [
'event' => $event,
'scene_str' => $scene_str,
'fromUsername' => $fromUsername,
'toUsername' => $toUsername,
'ticket' => $ticket,
'time' => date('Y-m-d H:i:s'),
'raw_data' => $postStr
]);
// 创建票据保存目录
$upload_dir = 'public/storage/uploads/ticket/';
if (!is_dir($upload_dir)) {
if (!mkdir($upload_dir, 0755, true)) {
Log::error('创建票据保存目录失败:' . $upload_dir);
return 'success';
}
Log::info('创建票据保存目录成功:' . $upload_dir);
}
// 保存扫码数据
$data = [
'openid' => $fromUsername,
'scene_str' => $scene_str,
'ticket' => $ticket,
'scan_time' => time(),
'event' => $event,
'raw_data' => $postStr
];
$content = json_encode($data, JSON_UNESCAPED_UNICODE);
$file = $upload_dir . $scene_str . "_" . $ticket . ".json";
if (file_put_contents($file, $content) === false) {
Log::error('保存扫码数据失败:' . $file);
return 'success';
}
Log::info('保存扫码数据成功:' . $file);
// 获取用户信息
try {
$accessToken = $this->getGZHAccessToken();
Log::info('获取access_token成功:' . $accessToken);
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$accessToken}&openid={$fromUsername}&lang=zh_CN";
$client = new Client(['verify' => false]);
$response = $client->get($url);
$userInfo = json_decode($response->getBody(), true);
Log::info('获取用户信息结果:' . json_encode($userInfo, JSON_UNESCAPED_UNICODE));
if (isset($userInfo['openid'])) {
// 先检查是否存在该openid的用户
$user = Users::where('openid', $fromUsername)->find();
if ($user) {
// 已存在用户,直接登录
$user->login_count = $user->login_count + 1; // 增加登录次数
$user->update_time = time(); // 更新登录时间
// 只在头像为空或为默认头像时更新
if (empty($user->avatar) || $user->avatar === '/static/images/avatar.png') {
if (!empty($userInfo['headimgurl'])) {
$user->avatar = $userInfo['headimgurl'];
} elseif (empty($user->avatar)) {
$user->avatar = '/static/images/avatar.png';
}
}
if (!$user->save()) {
Log::error('更新用户登录信息失败:' . json_encode($user->getError(), JSON_UNESCAPED_UNICODE));
return 'success';
}
Log::info('用户登录成功:' . json_encode($user->toArray(), JSON_UNESCAPED_UNICODE));
} else {
// 不存在用户,创建新用户
$user = new Users;
$user->openid = $fromUsername;
// 生成默认账号
$defaultAccount = 'wx_' . substr(md5($fromUsername), 0, 8);
$user->account = $defaultAccount;
$user->name = $defaultAccount; // 将默认账号同时设置为用户名
// 设置头像,确保有值
$user->avatar = !empty($userInfo['headimgurl']) ? $userInfo['headimgurl'] : '/static/images/avatar.png';
// 生成随机密码
$user->password = md5(uniqid() . rand(1000, 9999));
$user->create_time = time(); // 设置创建时间
$user->login_count = 1; // 首次登录,设置登录次数为1
if (!$user->save()) {
Log::error('创建用户失败:' . json_encode($user->getError(), JSON_UNESCAPED_UNICODE));
return 'success';
}
Log::info('创建新用户成功:' . json_encode($user->toArray(), JSON_UNESCAPED_UNICODE));
}
// 更新票据文件
$data = [
'uid' => (int)$user->uid, // 确保uid是整数
'name' => $user->name,
'avatar' => $user->avatar ?: '/static/images/avatar.png', // 确保avatar不为空
'openid' => $user->openid,
'user_account' => $user->account,
'user_password' => $user->password,
'expire_time' => time() + (7 * 24 * 3600), // 7天过期
'is_auto_login' => true,
'login_status' => 'success'
];
if (file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE)) === false) {
Log::error('更新票据文件失败:' . $file);
} else {
Log::info('更新票据文件成功:' . json_encode($data, JSON_UNESCAPED_UNICODE));
}
// 设置cookie
$expire = 7 * 24 * 3600; // 7天过期
cookie('user_account', $user->account, ['expire' => $expire]);
cookie('user_avatar', $user->avatar ?: '/static/images/avatar.png', ['expire' => $expire]);
cookie('user_name', $user->name, ['expire' => $expire]);
cookie('open_id', $user->openid, ['expire' => $expire]);
// 发送登录成功消息
$messageContent = [
'content' => "您好!\n您已成功登录系统。\n登录时间:" . date('Y-m-d H:i:s')
];
$this->sendCustomMessage($fromUsername, 'text', $messageContent);
Log::info('用户登录成功:' . json_encode([
'uid' => (int)$user->uid,
'name' => $user->name,
'openid' => $user->openid,
'account' => $user->account,
'cookies' => [
'user_account' => $user->account,
'user_avatar' => $user->avatar,
'user_name' => $user->name,
'open_id' => $user->openid
]
], JSON_UNESCAPED_UNICODE));
} else {
Log::error('获取用户信息失败:' . json_encode($userInfo, JSON_UNESCAPED_UNICODE));
}
} catch (\Exception $e) {
Log::error('获取用户信息失败:' . $e->getMessage());
Log::error('错误堆栈:' . $e->getTraceAsString());
}
} catch (\Exception $e) {
Log::error('处理扫码事件失败:' . $e->getMessage());
Log::error('错误堆栈:' . $e->getTraceAsString());
}
}
}
return 'success';
} catch (\Exception $e) {
Log::error('处理微信消息错误:' . $e->getMessage());
Log::error('错误堆栈:' . $e->getTraceAsString());
return 'success';
}
}
// 发送小程序卡片消息的方法
private function sendMiniProgramCard($openid)
{
$accessToken = $this->getGZHAccessToken();
print_r($accessToken);
if (!$accessToken) {
// 处理获取access_token失败的情况
return;
}
$postData = json_encode([
'touser' => $openid, // 接收者(用户)的openid
'msgtype' => 'miniprogrampage',
'miniprogrampage' => [
'title' => '小程序标题',
'appid' => '小程序appid',
'pagepath' => '小程序路径',
'thumb_media_id' => '你的thumb_media_id'
]
], JSON_UNESCAPED_UNICODE);
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$accessToken}";
$result = json_decode(file_get_contents($url, false, stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-type: application/json\r\n",
'content' => $postData,
'timeout' => 60 // 超时时间(单位:s
]
])), true);
// 处理返回结果
if ($result['errcode'] == 0) {
// 发送成功
} else {
// 发送失败
}
}
// 获取公众号Access token
public function getGZHAccessToken()
{
// 从数据库获取配置
$appid = AdminConfig::where('config_name', 'wechat_appid')->value('config_value');
$secret = AdminConfig::where('config_name', 'wechat_appsecret')->value('config_value');
if (empty($appid) || empty($secret)) {
throw new \Exception('微信配置信息未设置');
}
// 构建请求URL
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
try {
// 使用 GuzzleHttp 发送请求,禁用SSL验证
$client = new Client([
'verify' => false
]);
$response = $client->get($url);
$data = json_decode($response->getBody(), true);
if (!isset($data['access_token'])) {
throw new \Exception("获取access_token失败: {$data['errmsg']}", $data['errcode'] ?? -1);
}
return $data['access_token'];
} catch (\Exception $e) {
Log::error('获取access_token失败:' . $e->getMessage());
throw $e;
}
}
/**
* 获取微信登录二维码
* @return \think\response\Json
*/
public function getLoginTicket()
{
try {
Log::info('开始获取微信登录二维码');
// 获取access_token
$access_token = $this->getGZHAccessToken();
Log::info('获取access_token成功:' . $access_token);
// 构建请求URL - 使用正确的接口生成临时二维码
$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$access_token}";
// 生成唯一场景值
$scene_str = md5(uniqid() . time());
Log::info('生成场景值:' . $scene_str);
// 准备请求数据 - 生成临时二维码,有效期5分钟
$postData = json_encode([
'expire_seconds' => 300, // 5分钟有效期
'action_name' => 'QR_STR_SCENE',
'action_info' => [
'scene' => [
'scene_str' => $scene_str
]
]
]);
// 发送请求获取ticket
$client = new Client(['verify' => false]);
$response = $client->post($url, [
'body' => $postData,
'headers' => [
'Content-Type' => 'application/json'
]
]);
$result = json_decode($response->getBody(), true);
Log::info('微信返回结果:' . json_encode($result, JSON_UNESCAPED_UNICODE));
if (isset($result['errcode']) && $result['errcode'] != 0) {
Log::error('获取二维码失败:' . $result['errmsg']);
return json(['code' => 1, 'msg' => '获取二维码失败:' . $result['errmsg']]);
}
// 使用ticket获取二维码图片URL
$ticket = urlencode($result['ticket']);
$qrcodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={$ticket}";
// 将场景值保存到缓存中,用于后续验证
Cache::set('wx_login_scene_' . $result['ticket'], [
'scene_str' => $scene_str,
'create_time' => time(),
'expire_time' => time() + 300
], 300);
Log::info('二维码生成成功', [
'ticket' => $result['ticket'],
'scene_str' => $scene_str,
'expire_time' => time() + 300
]);
return json([
'code' => 0,
'msg' => '获取二维码成功',
'data' => [
'ticket' => $result['ticket'],
'expire_seconds' => $result['expire_seconds'],
'url' => $qrcodeUrl,
'scene_str' => $scene_str
]
]);
} catch (\Exception $e) {
Log::error('获取微信登录二维码失败:' . $e->getMessage());
Log::error('错误堆栈:' . $e->getTraceAsString());
return json(['code' => 1, 'msg' => '获取二维码失败:' . $e->getMessage()]);
}
}
/**
* 重新生成二维码
* @return \think\response\Json
*/
public function reGenerateQrcode()
{
try {
$scene_str = Request::post('scene_str');
if (empty($scene_str)) {
return json(['code' => 1, 'msg' => '参数错误']);
}
// 清除旧的缓存
Cache::delete('wx_login_scene_' . $scene_str);
// 获取access_token
$access_token = $this->getGZHAccessToken();
// 构建请求URL
$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$access_token}";
// 生成新的场景值
$new_scene_str = md5(uniqid() . time());
// 准备请求数据
$postData = json_encode([
'expire_seconds' => 300,
'action_name' => 'QR_STR_SCENE',
'action_info' => [
'scene' => [
'scene_str' => $new_scene_str
]
]
]);
// 发送请求获取ticket
$client = new Client(['verify' => false]);
$response = $client->post($url, [
'body' => $postData,
'headers' => [
'Content-Type' => 'application/json'
]
]);
$result = json_decode($response->getBody(), true);
if (isset($result['errcode']) && $result['errcode'] != 0) {
return json(['code' => 1, 'msg' => '获取二维码失败:' . $result['errmsg']]);
}
// 使用ticket获取二维码图片URL
$ticket = urlencode($result['ticket']);
$qrcodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={$ticket}";
// 将新的场景值保存到缓存中
Cache::set('wx_login_scene_' . $new_scene_str, [
'scene_str' => $new_scene_str,
'create_time' => time(),
'expire_time' => time() + 300
], 300);
return json([
'code' => 0,
'msg' => '获取二维码成功',
'data' => [
'ticket' => $result['ticket'],
'expire_seconds' => $result['expire_seconds'],
'url' => $qrcodeUrl,
'scene_str' => $new_scene_str
]
]);
} catch (\Exception $e) {
Log::error('重新生成二维码失败:' . $e->getMessage());
return json(['code' => 1, 'msg' => '重新生成二维码失败:' . $e->getMessage()]);
}
}
/**
* 检查微信扫码登录状态
* @return \think\response\Json
*/
public function checkLoginStatus()
{
try {
$scene_str = Request::post('scene_str');
$ticket = Request::post('ticket');
if (empty($scene_str) || empty($ticket)) {
return json(['code' => 0, 'msg' => '参数错误']);
}
// 检查票据文件
$file = 'public/storage/uploads/ticket/' . $scene_str . "_" . $ticket . ".json";
if (!file_exists($file)) {
return json(['code' => 0, 'msg' => '等待扫码']);
}
$loginData = json_decode(file_get_contents($file), true);
if (!$loginData) {
return json(['code' => 0, 'msg' => '等待扫码']);
}
// 检查是否已经扫码
if (!isset($loginData['openid'])) {
return json(['code' => 0, 'msg' => '等待扫码']);
}
// 检查登录状态
if (!isset($loginData['login_status']) || $loginData['login_status'] !== 'success') {
return json(['code' => 0, 'msg' => '正在处理登录,请稍候...']);
}
// 登录成功,设置session
session('user_id', $loginData['uid']);
session('user_name', $loginData['name']);
session('user_avatar', $loginData['avatar']);
session('user_account', $loginData['user_account']);
session('openid', $loginData['openid']);
// 删除临时文件
@unlink($file);
// 返回用户信息
return json([
'code' => 1,
'msg' => '登录成功',
'data' => [
'uid' => $loginData['uid'],
'name' => $loginData['name'],
'avatar' => $loginData['avatar'],
'openid' => $loginData['openid'],
'user_account' => $loginData['user_account'],
'user_password' => $loginData['user_password'],
'expire_time' => $loginData['expire_time'],
'is_auto_login' => $loginData['is_auto_login']
]
]);
} catch (\Exception $e) {
Log::error('检查登录状态失败:' . $e->getMessage());
return json(['code' => 0, 'msg' => '系统错误']);
}
}
/**
* 根据openid获取用户信息
* @param string $openid
* @return array|null
*/
private function getUserInfoByOpenid($openid)
{
try {
// 这里需要根据你的用户表结构来实现
// 示例:从用户表中查询openid对应的用户信息
$user = Users::where('openid', $openid)->find();
if ($user) {
return $user->toArray();
}
return null;
} catch (\Exception $e) {
Log::error('获取用户信息失败:' . $e->getMessage());
return null;
}
}
/**
* 测试微信服务器访问
*/
public function testWechat()
{
try {
// 记录所有请求信息
$requestInfo = [
'time' => date('Y-m-d H:i:s'),
'method' => Request::method(),
'url' => Request::url(true),
'ip' => Request::ip(),
'real_ip' => Request::server('HTTP_X_REAL_IP'),
'forwarded_ip' => Request::server('HTTP_X_FORWARDED_FOR'),
'params' => Request::param(),
'headers' => getallheaders(),
'server' => [
'REQUEST_METHOD' => $_SERVER['REQUEST_METHOD'] ?? '',
'REQUEST_URI' => $_SERVER['REQUEST_URI'] ?? '',
'HTTP_HOST' => $_SERVER['HTTP_HOST'] ?? '',
'REMOTE_ADDR' => $_SERVER['REMOTE_ADDR'] ?? '',
'QUERY_STRING' => $_SERVER['QUERY_STRING'] ?? '',
'HTTP_USER_AGENT' => $_SERVER['HTTP_USER_AGENT'] ?? '',
'HTTP_REFERER' => $_SERVER['HTTP_REFERER'] ?? '',
'CONTENT_TYPE' => $_SERVER['CONTENT_TYPE'] ?? '',
'CONTENT_LENGTH' => $_SERVER['CONTENT_LENGTH'] ?? '',
'SERVER_NAME' => $_SERVER['SERVER_NAME'] ?? '',
'SERVER_ADDR' => $_SERVER['SERVER_ADDR'] ?? '',
'SERVER_PORT' => $_SERVER['SERVER_PORT'] ?? '',
'REQUEST_SCHEME' => $_SERVER['REQUEST_SCHEME'] ?? '',
]
];
Log::info('微信测试接口访问:' . json_encode($requestInfo, JSON_UNESCAPED_UNICODE));
// 获取原始数据
$rawData = file_get_contents("php://input");
if (!empty($rawData)) {
$rawData = mb_convert_encoding($rawData, 'UTF-8', 'UTF-8,GBK,GB2312');
Log::info('微信测试接口原始数据:' . $rawData);
}
// 如果是GET请求,进行签名验证
if (Request::method() == 'GET') {
$signature = Request::get('signature');
$timestamp = Request::get('timestamp');
$nonce = Request::get('nonce');
$echostr = Request::get('echostr');
$verifyInfo = [
'signature' => $signature,
'timestamp' => $timestamp,
'nonce' => $nonce,
'echostr' => $echostr,
'time' => date('Y-m-d H:i:s'),
'ip' => Request::ip(),
'headers' => getallheaders()
];
Log::info('微信测试接口验证参数:' . json_encode($verifyInfo, JSON_UNESCAPED_UNICODE));
if (!empty($signature) && !empty($timestamp) && !empty($nonce)) {
$token = AdminConfig::where('config_name', 'wechat_token')->value('config_value');
if (empty($token)) {
Log::error('微信token未配置');
return 'token not configured';
}
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
if ($tmpStr == $signature) {
Log::info('微信测试接口验证成功');
return $echostr;
} else {
Log::error('微信测试接口验证失败');
return 'signature verification failed';
}
}
}
return 'success';
} catch (\Exception $e) {
Log::error('微信测试接口错误:' . $e->getMessage());
Log::error('错误堆栈:' . $e->getTraceAsString());
return 'error';
}
}
/**
* 发送客服消息
* @param string $openid 接收者openid
* @param string $type 消息类型
* @param array $content 消息内容
* @return bool
*/
private function sendCustomMessage($openid, $type = 'text', $content = [])
{
try {
$accessToken = $this->getGZHAccessToken();
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$accessToken}";
$data = [
'touser' => $openid,
'msgtype' => $type
];
if ($type === 'text') {
$data['text'] = ['content' => $content['content'] ?? '登录成功'];
}
$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
$client = new Client(['verify' => false]);
$response = $client->post($url, [
'body' => $jsonData,
'headers' => [
'Content-Type' => 'application/json; charset=utf-8'
]
]);
$result = json_decode($response->getBody(), true);
if (isset($result['errcode']) && $result['errcode'] == 0) {
Log::info('发送客服消息成功:' . json_encode($result, JSON_UNESCAPED_UNICODE));
return true;
} else {
Log::error('发送客服消息失败:' . json_encode($result, JSON_UNESCAPED_UNICODE));
return false;
}
} catch (\Exception $e) {
Log::error('发送客服消息异常:' . $e->getMessage());
return false;
}
}
}