提交
This commit is contained in:
126
app/service/AwsUploadService.php
Normal file
126
app/service/AwsUploadService.php
Normal file
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
namespace app\service;
|
||||
use Aws\S3\S3Client;
|
||||
use think\facade\Log;
|
||||
use think\File;
|
||||
|
||||
class AwsUploadService
|
||||
{
|
||||
/**
|
||||
* 处理表单文件上传并转发到目标服务器
|
||||
*
|
||||
* @param string $fileField 表单文件字段名
|
||||
* @param array $extraFields 额外传递的字段
|
||||
* @return array 包含上传结果的数组
|
||||
*/
|
||||
public function uploadAndForward( File $file, string $fileField,array $extraFields = []): array
|
||||
{
|
||||
|
||||
$mimeType = $file->getMime();
|
||||
$s3config = config('filesystem.disks.s3');
|
||||
$s3 = new S3Client($s3config);
|
||||
try {
|
||||
$config = config('app.upload_conf');
|
||||
$configs=[];
|
||||
foreach ($config as $key=>$con){
|
||||
$configs[] = $key.':'.$con;
|
||||
}
|
||||
|
||||
// 验证文件
|
||||
$validate = validate([
|
||||
$fileField =>implode('|',$configs),
|
||||
]);
|
||||
|
||||
if (!$validate->check([$fileField => $file])) {
|
||||
return $this->createErrorResult($validate->getError());
|
||||
}
|
||||
|
||||
// 根据文件类型设置 Content-Type
|
||||
if (in_array($mimeType, config('app.imageMimeTypes'))) {
|
||||
$contentType = $mimeType; // 使用图片的实际 MIME 类型
|
||||
} else {
|
||||
$contentType = 'application/octet-stream'; // 非图片文件使用默认类型
|
||||
}
|
||||
$checkBucket = $this->checkBucket($s3, $extraFields['Bucket']);
|
||||
if (!$checkBucket) {
|
||||
return $this->createErrorResult('Bucket error');
|
||||
}
|
||||
$s3->putObject([
|
||||
'Bucket' => $extraFields['Bucket'],
|
||||
'Key' => $extraFields['Key'],
|
||||
'Body' => fopen($file->getRealPath(), 'r'),
|
||||
'ACL' => 'public-read',
|
||||
'ContentType' => $contentType, // 设置检测到的 Content-Type
|
||||
]);
|
||||
return [
|
||||
'code' => 1,
|
||||
'data' =>[
|
||||
'savename'=>$s3config['endpoint'].'/'.$extraFields['Bucket'].'/'.$extraFields['Key']
|
||||
] ,
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
return $this->createErrorResult('上传过程中发生异常: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
public function checkBucket($s3, $bucket)
|
||||
{
|
||||
try {
|
||||
$buckets = $s3->listBuckets()->get('Buckets');
|
||||
$buckets_arr = array_column($buckets, 'Name');
|
||||
if (!in_array($bucket, $buckets_arr)) {
|
||||
$s3->createBucket([
|
||||
'Bucket' => $bucket,
|
||||
]);
|
||||
$policy = [
|
||||
'Version' => '2012-10-17',
|
||||
'Statement' => [
|
||||
[
|
||||
'Effect' => 'Allow',
|
||||
'Principal' => ['AWS' => ['*']],
|
||||
'Action' => [
|
||||
's3:GetBucketLocation',
|
||||
's3:ListBucket',
|
||||
's3:ListBucketMultipartUploads',
|
||||
],
|
||||
'Resource' => "arn:aws:s3:::$bucket",
|
||||
],
|
||||
[
|
||||
'Effect' => 'Allow',
|
||||
'Principal' => ['AWS' => ['*']],
|
||||
'Action' => [
|
||||
's3:DeleteObject',
|
||||
's3:GetObject',
|
||||
's3:ListMultipartUploadParts',
|
||||
's3:PutObject',
|
||||
's3:AbortMultipartUpload',
|
||||
],
|
||||
'Resource' => "arn:aws:s3:::$bucket/*",
|
||||
],
|
||||
],
|
||||
];
|
||||
$s3->putBucketPolicy([
|
||||
'Bucket' => $bucket,
|
||||
'Policy' => json_encode($policy),
|
||||
]);
|
||||
}
|
||||
return true;
|
||||
} catch (\Exception $e) {
|
||||
Log::info('checkBucket error:' . $e->getMessage());
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
/**
|
||||
* 创建错误结果数组
|
||||
*
|
||||
* @param string $message 错误信息
|
||||
* @return array 错误结果
|
||||
*/
|
||||
private function createErrorResult(string $message): array
|
||||
{
|
||||
return [
|
||||
'code' => 0,
|
||||
'error' => $message
|
||||
];
|
||||
}
|
||||
}
|
||||
122
app/service/BaiduOcrService.php
Normal file
122
app/service/BaiduOcrService.php
Normal file
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
namespace app\service;
|
||||
|
||||
use Curl\Curl;
|
||||
|
||||
class BaiduOcrService
|
||||
{
|
||||
private $url = 'https://uniuser.evus.cn/home/upload/';
|
||||
/**
|
||||
*
|
||||
*护照识别
|
||||
* @param string $fileData 图片的二进制数据
|
||||
* @return array
|
||||
*/
|
||||
function passport($fileData)
|
||||
{
|
||||
if ($fileData === false) {
|
||||
return [
|
||||
'code' => 0,
|
||||
'msg' => '无法读取上传的文件',
|
||||
];
|
||||
}
|
||||
$curl = new Curl();
|
||||
$curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
|
||||
$curl->setOpt(CURLOPT_SSL_VERIFYHOST, 0);
|
||||
|
||||
$curl->post($this->url.'passport', [
|
||||
'image' => $fileData,
|
||||
]);
|
||||
if ($curl->error) {
|
||||
return [
|
||||
'code' => 0,
|
||||
'msg' => $curl->errorMessage,
|
||||
];
|
||||
} else {
|
||||
if (!$curl->response->code){
|
||||
return [
|
||||
'code' => 0,
|
||||
'msg' => '解析失败',
|
||||
];
|
||||
}
|
||||
return [
|
||||
'code' => 1,
|
||||
'data' => $curl->response->data,
|
||||
];
|
||||
}
|
||||
}
|
||||
/**
|
||||
*
|
||||
*身份证识别
|
||||
* @param string $fileData 图片的二进制数据
|
||||
* @return array
|
||||
*/
|
||||
function identification($fileData)
|
||||
{
|
||||
if ($fileData === false) {
|
||||
return [
|
||||
'code' => 0,
|
||||
'msg' => '无法读取上传的文件',
|
||||
];
|
||||
}
|
||||
$curl = new Curl();
|
||||
$curl->post($this->url.'identification', [
|
||||
'image' => $fileData,
|
||||
]);
|
||||
if ($curl->error) {
|
||||
return [
|
||||
'code' => 0,
|
||||
'msg' => $curl->errorMessage,
|
||||
];
|
||||
} else {
|
||||
if (!$curl->response->code){
|
||||
return [
|
||||
'code' => 0,
|
||||
'msg' => '解析失败',
|
||||
];
|
||||
}
|
||||
return [
|
||||
'code' => 1,
|
||||
'data' => $curl->response->data,
|
||||
];
|
||||
}
|
||||
}
|
||||
/**
|
||||
*
|
||||
*护照识别
|
||||
* @param string $fileData 图片的二进制数据
|
||||
* @return array 包含压缩后图片信息的数组
|
||||
*/
|
||||
function visa($fileData)
|
||||
{
|
||||
if ($fileData === false) {
|
||||
return [
|
||||
'code' => 0,
|
||||
'msg' => '无法读取上传的文件',
|
||||
];
|
||||
}
|
||||
$curl = new Curl();
|
||||
$curl->post($this->url.'visa', [
|
||||
'image' => $fileData,
|
||||
]);
|
||||
if ($curl->error) {
|
||||
return [
|
||||
'code' => 0,
|
||||
'msg' => $curl->errorMessage,
|
||||
];
|
||||
} else {
|
||||
if (!$curl->response->code){
|
||||
return [
|
||||
'code' => 0,
|
||||
'msg' => '解析失败',
|
||||
];
|
||||
}
|
||||
return [
|
||||
'code' => 1,
|
||||
'data' => $curl->response->data,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
185
app/service/CompressImgService.php
Normal file
185
app/service/CompressImgService.php
Normal file
@@ -0,0 +1,185 @@
|
||||
<?php
|
||||
|
||||
namespace app\service;
|
||||
/**
|
||||
* 压缩二进制流图片
|
||||
*/
|
||||
class CompressImgService
|
||||
{
|
||||
/**
|
||||
* 压缩通过表单上传的图片
|
||||
*
|
||||
* @param string $fileData 图片的二进制数据
|
||||
* @param int $quality 压缩质量(0-100,仅适用于JPEG和WebP)
|
||||
* @param string|null $targetFormat 目标格式('jpeg', 'png', 'webp',默认使用原格式)
|
||||
* @return array 包含压缩后图片信息的数组
|
||||
*/
|
||||
function compress($fileData, $quality = 80, $targetFormat = null)
|
||||
{
|
||||
|
||||
// 读取上传的二进制数据
|
||||
$imageData = file_get_contents($fileData);
|
||||
if ($imageData === false) {
|
||||
return [
|
||||
'code' => 0,
|
||||
'message' => '无法读取上传的文件',
|
||||
];
|
||||
}
|
||||
|
||||
// 获取图片信息
|
||||
$imageInfo = getimagesizefromstring($imageData);
|
||||
if (!$imageInfo) {
|
||||
return [
|
||||
'code' => 0,
|
||||
'message' => '无法解析图片信息',
|
||||
];
|
||||
}
|
||||
|
||||
// 确定原始和目标格式
|
||||
$originalMimeType = $imageInfo['mime'];
|
||||
$originalExtension = image_type_to_extension($imageInfo[2], false);
|
||||
|
||||
if ($targetFormat === null) {
|
||||
$targetFormat = $originalExtension;
|
||||
}
|
||||
|
||||
// 创建图片资源
|
||||
switch (strtolower($originalExtension)) {
|
||||
case 'jpeg':
|
||||
case 'jpg':
|
||||
$image = imagecreatefromstring($imageData);
|
||||
break;
|
||||
case 'png':
|
||||
$image = imagecreatefromstring($imageData);
|
||||
break;
|
||||
case 'webp':
|
||||
$image = imagecreatefromstring($imageData);
|
||||
break;
|
||||
default:
|
||||
return [
|
||||
'code' => 0,
|
||||
'message' => '不支持的图片格式',
|
||||
];
|
||||
}
|
||||
|
||||
if (!$image) {
|
||||
return [
|
||||
'code' => 0,
|
||||
'message' => '无法创建图片资源',
|
||||
];
|
||||
}
|
||||
|
||||
// 压缩并转换图片
|
||||
ob_start();
|
||||
switch (strtolower($targetFormat)) {
|
||||
case 'jpeg':
|
||||
case 'jpg':
|
||||
imagejpeg($image, null, $quality);
|
||||
$compressedMimeType = 'image/jpeg';
|
||||
break;
|
||||
case 'png':
|
||||
$pngQuality = 9 - floor($quality / 11);
|
||||
imagepng($image, null, $pngQuality);
|
||||
$compressedMimeType = 'image/png';
|
||||
break;
|
||||
case 'webp':
|
||||
if (function_exists('imagewebp')) {
|
||||
imagewebp($image, null, $quality);
|
||||
$compressedMimeType = 'image/webp';
|
||||
} else {
|
||||
imagejpeg($image, null, $quality);
|
||||
$compressedMimeType = 'image/jpeg';
|
||||
}
|
||||
break;
|
||||
default:
|
||||
imagedestroy($image);
|
||||
ob_end_clean();
|
||||
return [
|
||||
'code' => 0,
|
||||
'message' => "不支持的目标格式: {$targetFormat}",
|
||||
];
|
||||
}
|
||||
|
||||
$compressedData = ob_get_clean();
|
||||
imagedestroy($image);
|
||||
// 返回结果
|
||||
return [
|
||||
'code' => 1,
|
||||
'compressed_data' => $compressedData,
|
||||
'base64' => 'data:' . $compressedMimeType . ';base64,' . base64_encode($compressedData),
|
||||
];
|
||||
}
|
||||
|
||||
public function compressImage($filePath, $fileSize)
|
||||
{
|
||||
// 获取图片信息
|
||||
$imageInfo = getimagesize($filePath);
|
||||
if (!$imageInfo) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$mime = $imageInfo['mime'];
|
||||
|
||||
// 根据MIME类型创建图像资源
|
||||
switch ($mime) {
|
||||
case 'image/jpeg':
|
||||
$image = imagecreatefromjpeg($filePath);
|
||||
break;
|
||||
case 'image/png':
|
||||
$image = imagecreatefrompng($filePath);
|
||||
break;
|
||||
case 'image/gif':
|
||||
$image = imagecreatefromgif($filePath);
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$image) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 计算压缩质量(根据文件大小动态调整)
|
||||
$originalQuality = 85; // 初始质量
|
||||
$targetSize = 2.5 * 1024 * 1024; // 目标大小2.5MB
|
||||
|
||||
// 如果文件很大,降低初始质量
|
||||
if ($fileSize > 5 * 1024 * 1024) {
|
||||
$quality = 75;
|
||||
} elseif ($fileSize > 10 * 1024 * 1024) {
|
||||
$quality = 65;
|
||||
} else {
|
||||
$quality = $originalQuality;
|
||||
}
|
||||
|
||||
// 创建临时文件
|
||||
$tempFile = tempnam(sys_get_temp_dir(), 'compressed_');
|
||||
|
||||
// 保存压缩后的图片
|
||||
switch ($mime) {
|
||||
case 'image/jpeg':
|
||||
imagejpeg($image, $tempFile, $quality);
|
||||
break;
|
||||
case 'image/png':
|
||||
// PNG使用压缩级别(0-9),需要转换
|
||||
$pngQuality = 9 - round(($quality / 100) * 9);
|
||||
imagepng($image, $tempFile, $pngQuality);
|
||||
break;
|
||||
case 'image/gif':
|
||||
imagegif($image, $tempFile);
|
||||
break;
|
||||
}
|
||||
|
||||
// 释放内存
|
||||
imagedestroy($image);
|
||||
|
||||
// 检查压缩后文件大小,如果仍然大于3MB,继续压缩
|
||||
$compressedSize = filesize($tempFile);
|
||||
if ($compressedSize > 3 * 1024 * 1024) {
|
||||
// 递归压缩直到满足要求
|
||||
return $this->compressImage($tempFile, $compressedSize);
|
||||
}
|
||||
|
||||
return $tempFile;
|
||||
}
|
||||
}
|
||||
127
app/service/MiniProgramWechatService.php
Normal file
127
app/service/MiniProgramWechatService.php
Normal file
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
declare (strict_types=1);
|
||||
|
||||
namespace app\service;
|
||||
|
||||
use api\Httpcurl;
|
||||
use think\facade\Cache;
|
||||
use think\facade\Log;
|
||||
|
||||
class MiniProgramWechatService
|
||||
{
|
||||
private string $miniAppCode;
|
||||
private array $miniApp;
|
||||
|
||||
public function __construct(string $miniAppCode, array $miniApp)
|
||||
{
|
||||
$this->miniAppCode = $miniAppCode;
|
||||
$this->miniApp = $miniApp;
|
||||
}
|
||||
|
||||
public function openidByLoginCode(string $loginCode, bool $required = false): string
|
||||
{
|
||||
$config = $this->wechatConfig();
|
||||
if ($loginCode === '' || $config['appid'] === '' || $config['secret'] === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$response = Httpcurl::request('https://api.weixin.qq.com/sns/jscode2session', 'get', [
|
||||
'appid' => $config['appid'],
|
||||
'secret' => $config['secret'],
|
||||
'js_code' => $loginCode,
|
||||
'grant_type' => 'authorization_code',
|
||||
], [], 8);
|
||||
$result = $this->decodeWechatResponse($response, 'miniapi wx code2session');
|
||||
if (!empty($result['openid'])) {
|
||||
return (string)$result['openid'];
|
||||
}
|
||||
|
||||
if ($required) {
|
||||
Log::warning('miniapi wx openid missing: ' . json_encode($result, JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
public function mobileByPhoneCode(string $phoneCode): string
|
||||
{
|
||||
$accessToken = $this->wechatAccessToken();
|
||||
if ($phoneCode === '' || $accessToken === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$response = Httpcurl::request(
|
||||
'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . urlencode($accessToken),
|
||||
'post',
|
||||
json_encode(['code' => $phoneCode], JSON_UNESCAPED_UNICODE),
|
||||
['Content-Type: application/json'],
|
||||
8
|
||||
);
|
||||
$result = $this->decodeWechatResponse($response, 'miniapi wx get phone number');
|
||||
$phoneInfo = $result['phone_info'] ?? [];
|
||||
return (string)($phoneInfo['purePhoneNumber'] ?? $phoneInfo['phoneNumber'] ?? '');
|
||||
}
|
||||
|
||||
private function wechatAccessToken(): string
|
||||
{
|
||||
$config = $this->wechatConfig();
|
||||
if ($config['appid'] === '' || $config['secret'] === '') {
|
||||
Log::warning('miniapi wx config missing: ' . $this->miniAppCode);
|
||||
return '';
|
||||
}
|
||||
|
||||
$cacheKey = 'miniapp_access_token_' . $this->miniAppCode;
|
||||
$cached = Cache::get($cacheKey);
|
||||
if (!empty($cached)) {
|
||||
return (string)$cached;
|
||||
}
|
||||
|
||||
$response = Httpcurl::request('https://api.weixin.qq.com/cgi-bin/token', 'get', [
|
||||
'grant_type' => 'client_credential',
|
||||
'appid' => $config['appid'],
|
||||
'secret' => $config['secret'],
|
||||
], [], 8);
|
||||
$result = $this->decodeWechatResponse($response, 'miniapi wx access token');
|
||||
if (empty($result['access_token'])) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$ttl = max(60, intval($result['expires_in'] ?? 7200) - 300);
|
||||
Cache::set($cacheKey, $result['access_token'], $ttl);
|
||||
return (string)$result['access_token'];
|
||||
}
|
||||
|
||||
private function wechatConfig(): array
|
||||
{
|
||||
return [
|
||||
'appid' => trim((string)($this->miniApp['wechat_appid'] ?? '')),
|
||||
'secret' => trim((string)($this->miniApp['wechat_secret'] ?? '')),
|
||||
];
|
||||
}
|
||||
|
||||
private function decodeWechatResponse($response, string $scene): array
|
||||
{
|
||||
$result = $this->decodeResponse($response, $scene);
|
||||
if (isset($result['errcode']) && intval($result['errcode']) !== 0) {
|
||||
Log::warning($scene . ' failed: ' . json_encode($result, JSON_UNESCAPED_UNICODE));
|
||||
return [];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function decodeResponse($response, string $scene): array
|
||||
{
|
||||
if (!is_array($response) || !isset($response[0]) || !empty($response[3])) {
|
||||
Log::error($scene . ' request failed: ' . json_encode($response, JSON_UNESCAPED_UNICODE));
|
||||
return [];
|
||||
}
|
||||
|
||||
$result = json_decode($response[0], true);
|
||||
if (!is_array($result)) {
|
||||
Log::error($scene . ' response decode failed: ' . $response[0]);
|
||||
return [];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
301
app/service/OssService.php
Normal file
301
app/service/OssService.php
Normal file
@@ -0,0 +1,301 @@
|
||||
<?php
|
||||
namespace app\service;
|
||||
|
||||
use AlibabaCloud\Oss\V2 as Oss;
|
||||
use Exception;
|
||||
|
||||
final class OssService
|
||||
{
|
||||
private Oss\Client $client;
|
||||
private string $bucket;
|
||||
private string $region;
|
||||
private ?string $endpoint;
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* region: string,
|
||||
* bucket: string,
|
||||
* endpoint?: string,
|
||||
* access_key_id?: string,
|
||||
* access_key_secret?: string,
|
||||
* session_token?: string
|
||||
* } $config
|
||||
*/
|
||||
public function __construct(array $config)
|
||||
{
|
||||
$this->region = $config['region'] ?? '';
|
||||
$this->bucket = $config['bucket'] ?? '';
|
||||
$this->endpoint = $config['endpoint'] ?? null;
|
||||
|
||||
if ($this->region === '' || $this->bucket === '') {
|
||||
throw new Exception('OSS config missing: region/bucket');
|
||||
}
|
||||
|
||||
if (!empty($config['access_key_id']) && !empty($config['access_key_secret'])) {
|
||||
$credentialsProvider = new FixedCredentialsProvider(
|
||||
(string)$config['access_key_id'],
|
||||
(string)$config['access_key_secret'],
|
||||
$config['session_token'] ?? null
|
||||
);
|
||||
} else {
|
||||
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
|
||||
}
|
||||
|
||||
$cfg = Oss\Config::loadDefault();
|
||||
$cfg->setCredentialsProvider($credentialsProvider);
|
||||
$cfg->setRegion($this->region);
|
||||
if ($this->endpoint) {
|
||||
$cfg->setEndpoint($this->endpoint);
|
||||
if ($this->shouldUseCname($this->endpoint)) {
|
||||
$cfg->setUseCname(true);
|
||||
}
|
||||
}
|
||||
|
||||
$this->client = new Oss\Client($cfg);
|
||||
$this->assertCredentialsVisible($config);
|
||||
}
|
||||
|
||||
public function upload(string $source, string $key, ?string $bucket = null, array $options = []): array
|
||||
{
|
||||
if ($this->isBase64DataUri($source)) {
|
||||
return $this->uploadFromBase64($source, $key, $bucket, $options);
|
||||
}
|
||||
|
||||
if ($this->isUrl($source)) {
|
||||
return $this->uploadFromUrl($source, $key, $bucket, $options);
|
||||
}
|
||||
|
||||
return $this->uploadFromFile($source, $key, $bucket, $options);
|
||||
}
|
||||
|
||||
public function uploadFromBase64(string $base64, string $key, ?string $bucket = null, array $options = []): array
|
||||
{
|
||||
$contentType = null;
|
||||
$payload = $base64;
|
||||
|
||||
if (preg_match('/^data:([a-zA-Z0-9.+\\/-]+);base64,(.*)$/s', $base64, $m)) {
|
||||
$contentType = strtolower((string)$m[1]);
|
||||
$payload = (string)$m[2];
|
||||
}
|
||||
|
||||
$payload = preg_replace('/\\s+/', '', $payload ?? '');
|
||||
if ($payload === '') {
|
||||
throw new Exception('Base64 payload is empty');
|
||||
}
|
||||
|
||||
$binary = base64_decode($payload, true);
|
||||
if ($binary === false) {
|
||||
throw new Exception('Invalid base64 payload');
|
||||
}
|
||||
|
||||
if ($contentType && empty($options['contentType'])) {
|
||||
$options['contentType'] = $contentType;
|
||||
}
|
||||
|
||||
return $this->uploadFromBinary($binary, $key, $bucket, $options);
|
||||
}
|
||||
|
||||
public function uploadFromBinary(string $binary, string $key, ?string $bucket = null, array $options = []): array
|
||||
{
|
||||
if ($binary === '') {
|
||||
throw new Exception('Binary payload is empty');
|
||||
}
|
||||
|
||||
$stream = fopen('php://temp', 'wb+');
|
||||
if ($stream === false) {
|
||||
throw new Exception('Unable to create temporary stream for binary upload');
|
||||
}
|
||||
|
||||
fwrite($stream, $binary);
|
||||
rewind($stream);
|
||||
|
||||
return $this->putObjectFromResource($stream, $key, $bucket, $options);
|
||||
}
|
||||
|
||||
public function uploadFromFile(string $filePath, string $key, ?string $bucket = null, array $options = []): array
|
||||
{
|
||||
if (!is_file($filePath)) {
|
||||
throw new Exception("Local file not found: {$filePath}");
|
||||
}
|
||||
|
||||
$fp = fopen($filePath, 'rb');
|
||||
if ($fp === false) {
|
||||
throw new Exception("Unable to open local file: {$filePath}");
|
||||
}
|
||||
|
||||
return $this->putObjectFromResource($fp, $key, $bucket, $options);
|
||||
}
|
||||
|
||||
public function uploadFromUrl(string $url, string $key, ?string $bucket = null, array $options = []): array
|
||||
{
|
||||
$fp = @fopen($url, 'rb');
|
||||
if ($fp !== false) {
|
||||
return $this->putObjectFromResource($fp, $key, $bucket, $options);
|
||||
}
|
||||
|
||||
$tmp = tmpfile();
|
||||
if ($tmp === false) {
|
||||
throw new Exception('Unable to create tmpfile() for remote download');
|
||||
}
|
||||
|
||||
$this->downloadToStreamByCurl($url, $tmp);
|
||||
rewind($tmp);
|
||||
|
||||
return $this->putObjectFromResource($tmp, $key, $bucket, $options);
|
||||
}
|
||||
|
||||
public function buildObjectUrl(string $key, ?string $bucket = null, bool $useHttps = true): string
|
||||
{
|
||||
$bucket = $bucket ?: $this->bucket;
|
||||
$key = ltrim($key, '/');
|
||||
$endpoint = $this->endpoint ?: sprintf('oss-%s.aliyuncs.com', $this->region);
|
||||
$host = $this->extractEndpointHost($endpoint);
|
||||
$scheme = $useHttps ? 'https' : 'http';
|
||||
$encodedKey = implode('/', array_map('rawurlencode', explode('/', $key)));
|
||||
|
||||
if ($this->shouldUseCname($endpoint)) {
|
||||
return sprintf('%s://%s/%s', $scheme, $host, $encodedKey);
|
||||
}
|
||||
|
||||
return sprintf('%s://%s.%s/%s', $scheme, $bucket, $host, $encodedKey);
|
||||
}
|
||||
|
||||
private function putObjectFromResource($resource, string $key, ?string $bucket = null, array $options = []): array
|
||||
{
|
||||
$bucket = $bucket ?: $this->bucket;
|
||||
$key = ltrim($key, '/');
|
||||
$metadata = $options['metadata'] ?? [];
|
||||
$contentType = $options['contentType'] ?? null;
|
||||
$acl = $options['acl'] ?? null;
|
||||
|
||||
$body = Oss\Utils::streamFor($resource);
|
||||
$request = new Oss\Models\PutObjectRequest(
|
||||
bucket: $bucket,
|
||||
key: $key,
|
||||
metadata: $metadata ?: null,
|
||||
contentType: $contentType,
|
||||
objectAcl: $acl
|
||||
);
|
||||
$request->body = $body;
|
||||
|
||||
$result = $this->client->putObject($request);
|
||||
|
||||
return [
|
||||
'statusCode' => $result->statusCode,
|
||||
'requestId' => $result->requestId,
|
||||
'etag' => $result->etag,
|
||||
'bucket' => $bucket,
|
||||
'key' => $key,
|
||||
];
|
||||
}
|
||||
|
||||
private function downloadToStreamByCurl(string $url, $destStream): void
|
||||
{
|
||||
if (!function_exists('curl_init')) {
|
||||
throw new Exception('cURL extension is required when allow_url_fopen is disabled.');
|
||||
}
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_FILE => $destStream,
|
||||
CURLOPT_FOLLOWLOCATION => true,
|
||||
CURLOPT_MAXREDIRS => 5,
|
||||
CURLOPT_CONNECTTIMEOUT => 10,
|
||||
CURLOPT_TIMEOUT => 60,
|
||||
CURLOPT_FAILONERROR => true,
|
||||
CURLOPT_USERAGENT => 'OssService/1.0',
|
||||
]);
|
||||
|
||||
$ok = curl_exec($ch);
|
||||
if ($ok !== true) {
|
||||
$err = curl_error($ch);
|
||||
$code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
|
||||
curl_close($ch);
|
||||
throw new Exception("Failed to download remote file. HTTP={$code}, error={$err}");
|
||||
}
|
||||
|
||||
curl_close($ch);
|
||||
}
|
||||
|
||||
private function isUrl(string $value): bool
|
||||
{
|
||||
return (bool)filter_var($value, FILTER_VALIDATE_URL);
|
||||
}
|
||||
|
||||
private function isBase64DataUri(string $value): bool
|
||||
{
|
||||
return (bool)preg_match('/^data:[a-zA-Z0-9.+\\/-]+;base64,/i', $value);
|
||||
}
|
||||
|
||||
private function assertCredentialsVisible(array $config): void
|
||||
{
|
||||
if (!empty($config['access_key_id']) && !empty($config['access_key_secret'])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$ak = getenv('OSS_ACCESS_KEY_ID');
|
||||
$sk = getenv('OSS_ACCESS_KEY_SECRET');
|
||||
|
||||
if (empty($ak) || empty($sk)) {
|
||||
throw new Exception(
|
||||
"OSS credentials missing in PHP process env. " .
|
||||
"getenv('OSS_ACCESS_KEY_ID')/getenv('OSS_ACCESS_KEY_SECRET') is empty. " .
|
||||
"Fix: make sure the PHP runtime process can see env vars, or pass access_key_id/access_key_secret into OssService config."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function shouldUseCname(string $endpoint): bool
|
||||
{
|
||||
$host = strtolower($this->extractEndpointHost($endpoint));
|
||||
|
||||
if ($host === '' || str_contains($host, 'aliyuncs.com') || str_contains($host, '.oss-')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function extractEndpointHost(string $endpoint): string
|
||||
{
|
||||
$normalized = preg_match('#^https?://#i', $endpoint) ? $endpoint : 'https://' . ltrim($endpoint, '/');
|
||||
return (string)(parse_url($normalized, PHP_URL_HOST) ?: '');
|
||||
}
|
||||
|
||||
public function presignGetObjectUrl(string $key, ?string $bucket = null, int $expireSeconds = 900): array
|
||||
{
|
||||
$bucket = $bucket ?: $this->bucket;
|
||||
$key = ltrim($key, '/');
|
||||
|
||||
$request = new Oss\Models\GetObjectRequest(bucket: $bucket, key: $key);
|
||||
$result = $this->client->presign($request, [
|
||||
'expires' => new \DateInterval("PT{$expireSeconds}S"),
|
||||
]);
|
||||
|
||||
return [
|
||||
'url' => $result->url,
|
||||
'expire' => $expireSeconds,
|
||||
'bucket' => $bucket,
|
||||
'key' => $key,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
final class FixedCredentialsProvider implements Oss\Credentials\CredentialsProvider
|
||||
{
|
||||
private string $ak;
|
||||
private string $sk;
|
||||
private ?string $token;
|
||||
|
||||
public function __construct(string $ak, string $sk, ?string $token = null)
|
||||
{
|
||||
$this->ak = $ak;
|
||||
$this->sk = $sk;
|
||||
$this->token = $token;
|
||||
}
|
||||
|
||||
public function getCredentials(): Oss\Credentials\Credentials
|
||||
{
|
||||
return new Oss\Credentials\Credentials($this->ak, $this->sk, $this->token);
|
||||
}
|
||||
}
|
||||
203
app/service/OssUploadService.php
Normal file
203
app/service/OssUploadService.php
Normal file
@@ -0,0 +1,203 @@
|
||||
<?php
|
||||
namespace app\service;
|
||||
|
||||
use Throwable;
|
||||
|
||||
class OssUploadService
|
||||
{
|
||||
public function uploadBase64(string $fileName, string $base64File, array $extraFields = []): array
|
||||
{
|
||||
$fileContent = base64_decode($base64File, true);
|
||||
if ($fileContent === false || $fileContent === '') {
|
||||
return $this->createErrorResult('文件解析错误');
|
||||
}
|
||||
|
||||
return $this->uploadBinaryContent($fileName, $fileContent, $extraFields);
|
||||
}
|
||||
|
||||
public function uploadBinary(string $fileName, string $fileContent, array $extraFields = []): array
|
||||
{
|
||||
if ($fileContent === '') {
|
||||
return $this->createErrorResult('Binary payload is empty');
|
||||
}
|
||||
|
||||
return $this->uploadBinaryContent($fileName, $fileContent, $extraFields);
|
||||
}
|
||||
|
||||
private function uploadBinaryContent(string $fileName, string $fileContent, array $extraFields = []): array
|
||||
{
|
||||
$uploadConfig = config('filesystem.upload_conf') ?: [];
|
||||
$maxSize = (int)($uploadConfig['fileSize'] ?? 10 * 1024 * 1024);
|
||||
if (strlen($fileContent) > $maxSize) {
|
||||
return $this->createErrorResult('File size exceeds limit');
|
||||
}
|
||||
|
||||
$ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
|
||||
$allowedExts = $uploadConfig['fileExt'] ?? [];
|
||||
if ($ext === '' || (!empty($allowedExts) && !in_array($ext, $allowedExts, true))) {
|
||||
return $this->createErrorResult('File extension not allowed');
|
||||
}
|
||||
|
||||
$bucket = (string)config('oss.bucket');
|
||||
$folder = (string)($extraFields['Folder'] ?? ($extraFields['Bucket'] ?? ''));
|
||||
$key = $extraFields['Key'] ?? basename($fileName);
|
||||
$objectKey = $this->buildObjectKey($folder, (string)$key);
|
||||
if ($bucket === '' || $objectKey === '') {
|
||||
return $this->createErrorResult('Bucket or key missing');
|
||||
}
|
||||
|
||||
$finfo = new \finfo(FILEINFO_MIME_TYPE);
|
||||
$mimeType = (string)$finfo->buffer($fileContent);
|
||||
|
||||
try {
|
||||
$service = new OssService(config('oss'));
|
||||
$result = $service->uploadFromBinary($fileContent, $objectKey, $bucket, [
|
||||
'contentType' => $this->resolveContentType($mimeType, $ext),
|
||||
]);
|
||||
$result['url'] = $service->buildObjectUrl($objectKey, $bucket);
|
||||
$result['folder'] = $folder;
|
||||
|
||||
return [
|
||||
'code' => 1,
|
||||
'msg' => 'upload ok',
|
||||
'data' => $result,
|
||||
];
|
||||
} catch (Throwable $e) {
|
||||
$fallback = $this->saveToLocalFallback($fileContent, $bucket, $objectKey);
|
||||
|
||||
return $this->createErrorResult(
|
||||
'OSS upload failed: ' . $e->getMessage(),
|
||||
[
|
||||
'bucket' => $bucket,
|
||||
'key' => $objectKey,
|
||||
'folder' => $folder,
|
||||
'fallback_saved' => $fallback['saved'],
|
||||
'fallback_path' => $fallback['path'],
|
||||
'fallback_error' => $fallback['error'],
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function buildObjectKey(string $folder, string $key): string
|
||||
{
|
||||
$folder = trim(str_replace('\\', '/', $folder), '/');
|
||||
$key = trim(str_replace('\\', '/', $key), '/');
|
||||
|
||||
if ($folder === '') {
|
||||
return $key;
|
||||
}
|
||||
|
||||
if ($key === '') {
|
||||
return $folder;
|
||||
}
|
||||
|
||||
if (str_starts_with($key . '/', $folder . '/')) {
|
||||
return $key;
|
||||
}
|
||||
|
||||
return $folder . '/' . $key;
|
||||
}
|
||||
|
||||
private function saveToLocalFallback(string $fileContent, string $bucket, string $key): array
|
||||
{
|
||||
$baseDir = $this->resolveFallbackBaseDir();
|
||||
$safeBucket = $this->sanitizePathSegment($bucket);
|
||||
$safeKey = $this->sanitizeObjectKey($key);
|
||||
$fullPath = $baseDir . DIRECTORY_SEPARATOR . $safeBucket . DIRECTORY_SEPARATOR . $safeKey;
|
||||
$directory = dirname($fullPath);
|
||||
|
||||
try {
|
||||
if (!is_dir($directory) && !mkdir($directory, 0777, true) && !is_dir($directory)) {
|
||||
throw new \RuntimeException('Unable to create fallback directory');
|
||||
}
|
||||
|
||||
if (file_put_contents($fullPath, $fileContent) === false) {
|
||||
throw new \RuntimeException('Unable to write fallback file');
|
||||
}
|
||||
|
||||
return [
|
||||
'saved' => true,
|
||||
'path' => $fullPath,
|
||||
'error' => null,
|
||||
];
|
||||
} catch (Throwable $e) {
|
||||
return [
|
||||
'saved' => false,
|
||||
'path' => $fullPath,
|
||||
'error' => $e->getMessage(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
private function resolveFallbackBaseDir(): string
|
||||
{
|
||||
$uploadConfig = config('filesystem.upload_conf') ?: [];
|
||||
$configured = (string)($uploadConfig['fallbackDir'] ?? '');
|
||||
if ($configured !== '') {
|
||||
return rtrim($configured, "\\/");
|
||||
}
|
||||
|
||||
$localRoot = (string)(config('filesystem.disks.local.root') ?? '');
|
||||
if ($localRoot !== '') {
|
||||
return rtrim($localRoot, "\\/") . DIRECTORY_SEPARATOR . 'oss-fallback';
|
||||
}
|
||||
|
||||
return app()->getRuntimePath() . 'storage' . DIRECTORY_SEPARATOR . 'oss-fallback';
|
||||
}
|
||||
|
||||
private function sanitizeObjectKey(string $key): string
|
||||
{
|
||||
$normalized = str_replace('\\', '/', $key);
|
||||
$segments = array_filter(explode('/', $normalized), static function (string $segment): bool {
|
||||
return $segment !== '' && $segment !== '.' && $segment !== '..';
|
||||
});
|
||||
|
||||
if ($segments === []) {
|
||||
return 'unnamed-file';
|
||||
}
|
||||
|
||||
$safeSegments = array_map([$this, 'sanitizePathSegment'], $segments);
|
||||
return implode(DIRECTORY_SEPARATOR, $safeSegments);
|
||||
}
|
||||
|
||||
private function sanitizePathSegment(string $segment): string
|
||||
{
|
||||
$cleaned = preg_replace('/[^A-Za-z0-9._-]/', '_', $segment) ?? '';
|
||||
return $cleaned !== '' ? $cleaned : 'unknown';
|
||||
}
|
||||
|
||||
private function resolveContentType(string $mimeType, string $ext): string
|
||||
{
|
||||
if ($mimeType !== '' && $mimeType !== 'application/octet-stream') {
|
||||
return $mimeType;
|
||||
}
|
||||
|
||||
return match ($ext) {
|
||||
'jpg', 'jpeg' => 'image/jpeg',
|
||||
'png' => 'image/png',
|
||||
'gif' => 'image/gif',
|
||||
'webp' => 'image/webp',
|
||||
'bmp' => 'image/bmp',
|
||||
'svg' => 'image/svg+xml',
|
||||
'pdf' => 'application/pdf',
|
||||
'doc' => 'application/msword',
|
||||
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
default => 'application/octet-stream',
|
||||
};
|
||||
}
|
||||
|
||||
private function createErrorResult(string $message, array $data = []): array
|
||||
{
|
||||
$result = [
|
||||
'code' => 0,
|
||||
'msg' => $message,
|
||||
];
|
||||
|
||||
if ($data !== []) {
|
||||
$result['data'] = $data;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
233
app/service/PassportOcrService.php
Normal file
233
app/service/PassportOcrService.php
Normal file
@@ -0,0 +1,233 @@
|
||||
<?php
|
||||
|
||||
namespace app\service;
|
||||
|
||||
use Throwable;
|
||||
|
||||
class PassportOcrService
|
||||
{
|
||||
private const PASSPORT_ENDPOINT = '/ocr/passport/base64';
|
||||
private const IDCARD_ENDPOINT = '/ocr/idcard/base64';
|
||||
private const VISA_ENDPOINT = '/ocr/visa-number/base64';
|
||||
|
||||
public function passport($fileData): array
|
||||
{
|
||||
return $this->request(self::PASSPORT_ENDPOINT, $fileData);
|
||||
}
|
||||
|
||||
public function identification($fileData): array
|
||||
{
|
||||
return $this->request(self::IDCARD_ENDPOINT, $fileData);
|
||||
}
|
||||
|
||||
public function visa($fileData): array
|
||||
{
|
||||
return $this->request(self::VISA_ENDPOINT, $fileData);
|
||||
}
|
||||
|
||||
private function request(string $endpoint, $fileData): array
|
||||
{
|
||||
if (!is_string($fileData) || $fileData === '') {
|
||||
return $this->error('Unable to read uploaded file');
|
||||
}
|
||||
|
||||
$config = $this->loadConfig();
|
||||
if ($config['base_url'] === '' || $config['app_id'] === '' || $config['secret'] === '') {
|
||||
return $this->error('OCR config missing: app.OCR_BASE_URL, app.OCR_APP_ID and app.OCR_SECRET are required');
|
||||
}
|
||||
|
||||
try {
|
||||
$payload = $this->buildPayload($fileData, $config);
|
||||
} catch (Throwable $e) {
|
||||
return $this->error('Unable to build OCR payload: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
$timestamp = (string) time();
|
||||
$signature = hash_hmac('sha256', $config['app_id'] . "\n" . $timestamp, $config['secret']);
|
||||
$headers = [
|
||||
'Content-Type: application/json',
|
||||
'Accept: application/json',
|
||||
'X-App-Id: ' . $config['app_id'],
|
||||
'X-Timestamp: ' . $timestamp,
|
||||
'X-Signature: ' . $signature,
|
||||
];
|
||||
|
||||
if ($config['origin'] !== '') {
|
||||
$headers[] = 'Origin: ' . $config['origin'];
|
||||
}
|
||||
|
||||
$ch = curl_init($config['base_url'] . $endpoint);
|
||||
if ($ch === false) {
|
||||
return $this->error('Unable to initialize cURL');
|
||||
}
|
||||
|
||||
try {
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
|
||||
CURLOPT_TIMEOUT => $config['timeout'],
|
||||
CURLOPT_CONNECTTIMEOUT => $config['connect_timeout'],
|
||||
]);
|
||||
|
||||
if (!$config['verify_ssl']) {
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
|
||||
}
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
if ($response === false) {
|
||||
return $this->error('OCR request failed: ' . curl_error($ch));
|
||||
}
|
||||
|
||||
$decoded = json_decode((string) $response, true);
|
||||
if (!is_array($decoded)) {
|
||||
return $this->error('OCR response is not valid JSON', [
|
||||
'http_code' => $httpCode,
|
||||
'response' => substr((string) $response, 0, 300),
|
||||
]);
|
||||
}
|
||||
|
||||
return $decoded;
|
||||
} finally {
|
||||
curl_close($ch);
|
||||
}
|
||||
}
|
||||
|
||||
private function buildPayload(string $fileData, array $config): array
|
||||
{
|
||||
$mimeType = $this->detectMimeType($fileData);
|
||||
$extension = $this->extensionForMimeType($mimeType);
|
||||
|
||||
return [
|
||||
'filename' => 'upload.' . $extension,
|
||||
'content_type' => $mimeType,
|
||||
'image_base64' => 'data:' . $mimeType . ';base64,' . base64_encode($fileData),
|
||||
'auto_rotate' => $config['auto_rotate'],
|
||||
'return_debug' => $config['return_debug'],
|
||||
];
|
||||
}
|
||||
|
||||
private function loadConfig(): array
|
||||
{
|
||||
$config = config('ocr') ?: [];
|
||||
|
||||
return [
|
||||
'base_url' => rtrim((string) (config('app.OCR_BASE_URL') ?? ''), '/'),
|
||||
'app_id' => (string) (config('app.OCR_APP_ID') ?? ''),
|
||||
'secret' => (string) (config('app.OCR_SECRET') ?? ''),
|
||||
'origin' => $this->resolveOrigin((string) (config('app.OCR_ORIGIN') ?? ($config['origin'] ?? ''))),
|
||||
'timeout' => max(1, (int) ($config['timeout'] ?? 60)),
|
||||
'connect_timeout' => max(1, (int) ($config['connect_timeout'] ?? 10)),
|
||||
'auto_rotate' => $this->boolValue($config['auto_rotate'] ?? true),
|
||||
'return_debug' => $this->boolValue($config['return_debug'] ?? false),
|
||||
'verify_ssl' => $this->boolValue($config['verify_ssl'] ?? true),
|
||||
];
|
||||
}
|
||||
|
||||
private function resolveOrigin(string $configuredOrigin): string
|
||||
{
|
||||
$configuredOrigin = trim($configuredOrigin);
|
||||
if ($configuredOrigin !== '') {
|
||||
return rtrim($configuredOrigin, '/');
|
||||
}
|
||||
|
||||
$requestOrigin = trim((string) ($_SERVER['HTTP_ORIGIN'] ?? ''));
|
||||
if ($this->isValidOrigin($requestOrigin)) {
|
||||
return rtrim($requestOrigin, '/');
|
||||
}
|
||||
|
||||
$host = trim((string) ($_SERVER['HTTP_HOST'] ?? ''));
|
||||
if ($host === '' || !preg_match('/^[A-Za-z0-9.-]+(?::\d+)?$/', $host)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return $this->currentScheme() . '://' . $host;
|
||||
}
|
||||
|
||||
private function isValidOrigin(string $origin): bool
|
||||
{
|
||||
if ($origin === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$parts = parse_url($origin);
|
||||
if (!is_array($parts)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$scheme = strtolower((string) ($parts['scheme'] ?? ''));
|
||||
return in_array($scheme, ['http', 'https'], true)
|
||||
&& !empty($parts['host'])
|
||||
&& empty($parts['path'])
|
||||
&& empty($parts['query'])
|
||||
&& empty($parts['fragment']);
|
||||
}
|
||||
|
||||
private function currentScheme(): string
|
||||
{
|
||||
$forwardedProto = trim((string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? ''));
|
||||
if ($forwardedProto !== '') {
|
||||
$forwardedProto = strtolower(trim(explode(',', $forwardedProto)[0]));
|
||||
if (in_array($forwardedProto, ['http', 'https'], true)) {
|
||||
return $forwardedProto;
|
||||
}
|
||||
}
|
||||
|
||||
$requestScheme = strtolower((string) ($_SERVER['REQUEST_SCHEME'] ?? ''));
|
||||
if (in_array($requestScheme, ['http', 'https'], true)) {
|
||||
return $requestScheme;
|
||||
}
|
||||
|
||||
$https = strtolower((string) ($_SERVER['HTTPS'] ?? ''));
|
||||
return $https !== '' && $https !== 'off' ? 'https' : 'http';
|
||||
}
|
||||
|
||||
private function detectMimeType(string $fileData): string
|
||||
{
|
||||
if (!class_exists(\finfo::class)) {
|
||||
return 'image/jpeg';
|
||||
}
|
||||
|
||||
$finfo = new \finfo(FILEINFO_MIME_TYPE);
|
||||
$mimeType = $finfo->buffer($fileData);
|
||||
if (is_string($mimeType) && $mimeType !== '' && $mimeType !== 'application/octet-stream') {
|
||||
return $mimeType;
|
||||
}
|
||||
|
||||
return 'image/jpeg';
|
||||
}
|
||||
|
||||
private function extensionForMimeType(string $mimeType): string
|
||||
{
|
||||
return match ($mimeType) {
|
||||
'image/png' => 'png',
|
||||
'image/gif' => 'gif',
|
||||
'image/webp' => 'webp',
|
||||
'image/bmp', 'image/x-ms-bmp' => 'bmp',
|
||||
default => 'jpg',
|
||||
};
|
||||
}
|
||||
|
||||
private function boolValue($value): bool
|
||||
{
|
||||
$parsed = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
|
||||
return $parsed ?? (bool) $value;
|
||||
}
|
||||
|
||||
private function error(string $message, array $data = []): array
|
||||
{
|
||||
$result = [
|
||||
'code' => 0,
|
||||
'msg' => $message,
|
||||
];
|
||||
|
||||
if ($data !== []) {
|
||||
$result['data'] = $data;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
63
app/service/SwooleService.php
Normal file
63
app/service/SwooleService.php
Normal file
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
namespace app\service;
|
||||
|
||||
use Swoole\Client;
|
||||
|
||||
class SwooleService
|
||||
{
|
||||
private static ?self $instance = null;
|
||||
|
||||
private string $host = 'ossup.jzvisa.com';
|
||||
private int $port = 19501;
|
||||
private float $timeout = 3.0;
|
||||
|
||||
// 私有化构造函数,保留原来的单例调用方式
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
// 获取单例
|
||||
public static function getInstance(): self
|
||||
{
|
||||
if (self::$instance === null) {
|
||||
self::$instance = new self();
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
// 发送任务:短连接模式,每次连接、发送、关闭
|
||||
public function sendTask(array $task): bool
|
||||
{
|
||||
$client = new Client(SWOOLE_SOCK_TCP);
|
||||
|
||||
try {
|
||||
if (!$client->connect($this->host, $this->port, $this->timeout)) {
|
||||
throw new \RuntimeException(
|
||||
"Cannot connect to Swoole Server {$this->host}:{$this->port}, error: {$client->errCode}"
|
||||
);
|
||||
}
|
||||
|
||||
$data = json_encode($task, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
|
||||
if ($data === false) {
|
||||
throw new \RuntimeException('JSON encode failed: ' . json_last_error_msg());
|
||||
}
|
||||
|
||||
// 你的服务端使用 \r\n 作为 package_eof,所以这里必须加 \r\n
|
||||
$sendResult = $client->send($data . "\r\n");
|
||||
|
||||
return $sendResult !== false;
|
||||
} finally {
|
||||
if ($client->isConnected()) {
|
||||
$client->close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 保留 close 方法,避免旧代码调用时报错
|
||||
public function close(): void
|
||||
{
|
||||
self::$instance = null;
|
||||
}
|
||||
}
|
||||
133
app/service/UploadService.php
Normal file
133
app/service/UploadService.php
Normal file
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
namespace app\service;
|
||||
use think\Exception;
|
||||
|
||||
class UploadService
|
||||
{
|
||||
/**
|
||||
* 处理表单文件上传并转发到目标服务器
|
||||
*
|
||||
* @param string $fileField 表单文件字段名
|
||||
* @param string $targetUrl 目标服务器URL
|
||||
* @param array $extraFields 额外传递的字段
|
||||
* @param array $headers 额外的请求头
|
||||
* @return array 包含上传结果的数组
|
||||
*/
|
||||
public function uploadAndForward(string $fileField, string $targetUrl, array $extraFields = [], array $headers = []): array
|
||||
{
|
||||
// 获取上传的文件
|
||||
$file = request()->file($fileField);
|
||||
|
||||
if (!$file) {
|
||||
return $this->createErrorResult('未上传文件或上传失败');
|
||||
}
|
||||
try {
|
||||
$config = config('app.upload_conf');
|
||||
$configs=[];
|
||||
foreach ($config as $key=>$con){
|
||||
$configs[] = $key.':'.$con;
|
||||
}
|
||||
|
||||
// 验证文件
|
||||
$validate = validate([
|
||||
$fileField =>implode('|',$configs),
|
||||
]);
|
||||
|
||||
if (!$validate->check([$fileField => $file])) {
|
||||
return $this->createErrorResult($validate->getError());
|
||||
}
|
||||
|
||||
// 使用cURL转发到目标服务器
|
||||
$result = $this->forwardToTargetServer($file, $targetUrl, $extraFields, $headers);
|
||||
|
||||
return $result;
|
||||
} catch (\Exception $e) {
|
||||
return $this->createErrorResult('上传过程中发生异常: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用cURL将文件转发到目标服务器
|
||||
*
|
||||
* @param \think\File $file 文件对象
|
||||
* @param string $targetUrl 目标URL
|
||||
* @param array $extraFields 额外字段
|
||||
* @param array $headers 请求头
|
||||
* @return array 包含响应信息的数组
|
||||
*/
|
||||
private function forwardToTargetServer(\think\File $file, string $targetUrl, array $extraFields = [], array $headers = []): array
|
||||
{
|
||||
$ch = curl_init();
|
||||
|
||||
try {
|
||||
// 设置基本选项
|
||||
curl_setopt($ch, CURLOPT_URL, $targetUrl);
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_HEADER, false);
|
||||
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, 300); // 5分钟超时
|
||||
|
||||
// 构建上传数据
|
||||
$postData = [
|
||||
'file' => new \CURLFile(
|
||||
$file->getPathname(),
|
||||
$file->getOriginalMime(),
|
||||
$file->getOriginalName()
|
||||
)
|
||||
];
|
||||
|
||||
// 添加额外字段
|
||||
$postData = array_merge($postData, $extraFields);
|
||||
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
|
||||
|
||||
// 设置请求头
|
||||
$httpHeaders = [];
|
||||
foreach ($headers as $headerName => $headerValue) {
|
||||
$httpHeaders[] = "$headerName: $headerValue";
|
||||
}
|
||||
|
||||
if (!empty($httpHeaders)) {
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders);
|
||||
}
|
||||
|
||||
// 执行请求
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$curlInfo = curl_getinfo($ch);
|
||||
|
||||
// 检查错误
|
||||
if ($response === false) {
|
||||
throw new Exception('cURL错误: ' . curl_error($ch));
|
||||
}
|
||||
|
||||
return [
|
||||
'code' => 1,
|
||||
'http_code' => $httpCode,
|
||||
'response' => $response,
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
return [
|
||||
'code' => 0,
|
||||
'error' => $e->getMessage()
|
||||
];
|
||||
} finally {
|
||||
curl_close($ch);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建错误结果数组
|
||||
*
|
||||
* @param string $message 错误信息
|
||||
* @return array 错误结果
|
||||
*/
|
||||
private function createErrorResult(string $message): array
|
||||
{
|
||||
return [
|
||||
'code' => 0,
|
||||
'error' => $message
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user