Files
lgp-admin-plus-api/app/Service/wx/WxUploadService.php
LQ bcf54c2727 初始化
缺陷:主题配色需要优化整体的同风格
2026-08-14 23:21:21 +08:00

71 lines
2.5 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Service\wx;
use App\BaseApp\BaseWxService;
use App\Models\FileModel;
use App\Service\common\oss\OssRuntimeConfigService;
use App\Service\common\oss\OssStorageFactory;
use Illuminate\Support\Str;
/**
* 小程序上传入口(转账凭证等)。
*
* 不直接复用后台 UploadService后者继承 BaseService构造期会解后台 JWT
* 在 wx 组里走 BaseService 等于拿不到小程序身份、还会触发后台 token 校验。
* 这里只复用底层工厂 OssRuntimeConfigService / OssStorageFactory
* 保证存储实现与后台一致、身份走 BaseWxService 的 cc_wx_user。
*/
class WxUploadService extends BaseWxService
{
/**
* 上传图片到当前启用的 OSS / 本地存储。
*
* 返回结构与后台 UploadService::uploadImage 对齐url 键),
* 小程序拿到 url 后塞进 voucher 字段,再调 wx/order/voucher 提交。
*
* @param mixed $file UploadedFile
*/
public function uploadImage($file): array|bool
{
if (empty($file)) {
$this->utils->errorThrow('请选择图片');
}
$ext = $file->getClientOriginalExtension();
// 单独走 wx 命名空间避免与后台素材库扫描混目录
$key = 'wx/voucher/' . date('Ymd') . '/' . 'wx_' . Str::random() . uniqid() . '.' . $ext;
$storage = $this->resolveStorage();
$result = $storage->uploadVideo($file, $key);
if (!$result) {
$this->utils->errorThrow('图片上传失败');
}
// 落一份上传流水到 nl_filetype=image方便后台审计小程序上传的凭证
FileModel::insert([
'user_id' => $this->userId,
'url' => $result['url'],
'type' => FileModel::TYPE_IMAGE,
'source' => FileModel::SOURCE_UPLOAD,
'created_at' => time(),
'updated_at' => time(),
]);
return $result;
}
/**
* 解析当前启用的存储实现;配置异常时回退本地,避免整站上传不可用
*/
private function resolveStorage()
{
try {
$config = OssRuntimeConfigService::getInstance()->getActiveConfig();
return OssStorageFactory::getInstance()->make($config);
} catch (\Throwable $e) {
return OssStorageFactory::getInstance()->make([
'driver' => 'local',
'path_prefix' => 'uploads',
'domain' => '',
]);
}
}
}