Files
lgp-admin-plus-api/app/Http/Middleware/WxHttpsRewriteMiddleware.php
2026-08-19 08:16:49 +08:00

64 lines
1.9 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\Http\Middleware;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* 小程序响应 HTTPS 改写
*
* 对齐老 lgp-wx-api ApiMiddleware::checkHttp成功包code=0里递归把
* result 中的 http:// 换成 https://,满足微信小程序对图片等资源的 HTTPS 要求。
* 仅挂在 /api/wx/*,不改管理端接口;不写库,只做出站改写。
*/
class WxHttpsRewriteMiddleware
{
/**
* 处理完控制器后改写成功响应的 result
*/
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
if (!$response instanceof JsonResponse) {
return $response;
}
$payload = $response->getData(true);
if (!is_array($payload)) {
return $response;
}
// 与 jok 约定一致:成功 code 为 0字符串 "0" 一并兼容
if (($payload['code'] ?? null) != 0 || !array_key_exists('result', $payload)) {
return $response;
}
$payload['result'] = $this->checkHttp($payload['result']);
$response->setData($payload);
return $response;
}
/**
* 递归把字符串/数组/对象中的 http:// 换成 https://
* 不用 PHPUnit 的 isObject对象先转数组再走
*/
private function checkHttp(mixed $data): mixed
{
if (is_object($data)) {
$data = json_decode(json_encode($data), true);
}
if (is_string($data)) {
return str_replace('http://', 'https://', $data);
}
if (is_array($data)) {
array_walk_recursive($data, function (&$value) {
if (is_string($value)) {
$value = str_replace('http://', 'https://', $value);
}
});
return $data;
}
return $data;
}
}