64 lines
1.9 KiB
PHP
64 lines
1.9 KiB
PHP
|
|
<?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;
|
|||
|
|
}
|
|||
|
|
}
|